//package globalround1;
import java.util.*;

public class ProblemH {
    public static void main(String[] args) {
        new ProblemH().solve();
    }

    int N = 1111, M=20111;
    Scanner in = new Scanner(System.in);
    char[] l = new char[N];
    char[] r = new char[N];
    int n, nl, nr, rt, tot, fr, rr;
    int[][] go = new int[M][10];
    int[][] wild = new int[M][811];
    int[] q = new int[M];
    int[] fail = new int[M];
    int[][] dp = new int[2111][M];

    void solve() {
        String tl = in.next();
        String tr = in.next();
        n = in.nextInt();
        nl = tl.length();
        nr = tr.length();
        for(int i = 0 ; i < nl ; i++){
            l[i] = tl.charAt(i);
        }
        for(int i = 0 ; i < nr ; i++){
            r[i] = tr.charAt(i);
        }
        rt = ++tot;
        insert(l);
        insert(r);
        if(nl == nr){
            int k1 = rt, k2 = rt;
            for(int i = 0 ; i < nl ; i++){
                if(k1 == k2 && l[i] !=r[i]){
                    for(int c = l[i]+1 ; c < r[i] ; c++){
                        if(go[k1][c-'0'] == 0){
                            go[k1][c-'0'] = ++tot;
                        }
                        wild[go[k1][c-'0']][nl-i-1]++;
                    }
                }
                else if(k1 != k2){
                    for(int c = l[i]+1 ; c < '0'+10 ; c++){
                        if(go[k1][c-'0'] == 0){
                            go[k1][c-'0'] = ++tot;
                        }
                        wild[go[k1][c-'0']][nl-i-1]++;
                    }
                    for(int c = '0'+ (i == 0 ? 1 : 0) ; c < r[i] ; c++){
                        if(go[k2][c-'0'] == 0){
                            go[k2][c-'0'] = ++tot;
                        }
                        wild[go[k2][c-'0']][nl-i-1]++;
                    }
                }
                k1 = go[k1][l[i]-'0'];
                k2 = go[k2][r[i]-'0'];
            }
            wild[k1][0]++;
            if(k1 != k2){
                wild[k2][0]++;
            }
        }
        else{
            int k1 = rt,k2 = rt;
            for(int i = 0 ; i < nl ; i++){
                for(int c = l[i]+1 ; c < '0'+10 ; c++){
                    if(go[k1][c-'0'] == 0){
                        go[k1][c-'0'] = ++tot;
                    }
                    wild[go[k1][c-'0']][nl-i-1]++;
                }
                k1 = go[k1][l[i]-'0'];
            }
            for(int i = 0 ; i < nr ; i++){
                for(int c = '0'+ (i == 0 ? 1 : 0) ; c < r[i] ; c++){
                    if(go[k2][c-'0'] == 0){
                        go[k2][c-'0'] = ++tot;
                    }
                    wild[go[k2][c-'0']][nr-i-1]++;
                }
                k2 = go[k2][r[i]-'0'];
            }
            wild[k1][0]++;
            wild[k2][0]++;
            for(int i = 1 ; i < 10 ; i++){
                if(go[rt][i] == 0){
                    go[rt][i] = ++tot;
                }
                for(int j = nl+1 ; j < nr ; j++){
                    wild[go[rt][i]][j-1]++;
                }
            }
        }
        construct();
        for(int i = 1 ; i < rr ; i++){
            int x = q[i];
            for(int j = 0 ; j < nr ; j++){
                wild[x][j] += wild[fail[x]][j];
            }
        }
        for(int i = 1 ; i <= tot ; i++){
            for(int j = 1 ; j < nr ; j++){
                wild[i][j] += wild[i][j-1];
            }
        }
        DP();
        in.close();
    }

    void insert(char s[]){
        int cur = rt;
        for(int i = 0 ; s[i] != 0  ; i++){
            if(go[cur][s[i]-'0'] == 0){
                go[cur][s[i]-'0'] = ++tot;
            }
            cur = go[cur][s[i]-'0'];
        }
    }

    void construct(){
        fr = rr = 0;
        q[rr++] = rt;
        for(; fr < rr ; fr++){
            int x = q[fr];
            for(int i = 0 ; i < 10 ; i++){
                if(go[x][i] != 0){
                    if(x == rt){
                        fail[go[x][i]] = x;
                    }
                    else{
                        fail[go[x][i]] = fail[x];
                        while(fail[go[x][i]] != rt && go[fail[go[x][i]]][i] == 0){
                            fail[go[x][i]] = fail[fail[go[x][i]]];
                        }
                        if(go[fail[go[x][i]]][i] != 0){
                            fail[go[x][i]] = go[fail[go[x][i]]][i];
                        }
                    }
                    q[rr++] = go[x][i];
                }
            }
        }
        for(int i = 0 ; i < 10 ; i++){
            if(go[rt][i] == 0){
                go[rt][i] = rt;
            }
        }
        for(int j = 1 ; j < rr ; j++){
            int x = q[j];
            for(int i = 0 ; i < 10 ; i++){
                if(go[x][i] == 0){
                    go[x][i] = go[fail[x]][i];
                }
            }
        }
    }

    void DP(){
        for(int i = 1 ; i <= tot ; i++){
            dp[0][i] = wild[i][0];
        }
        for(int i = 1 ; i <= n ; i++){
            for(int j = 1 ; j <= tot ; j++){
                for(int k = 0 ; k < 10 ; k++){
                    dp[i][j] = Math.max(dp[i][j], dp[i-1][go[j][k]]);
                }
                dp[i][j] += wild[j][Math.min(i, nr-1)];
            }
        }
        System.out.println(dp[n][rt]);
        int cur = rt;
        for(int i = n ; i >= 1 ; i--){
            int val = dp[i][cur]-wild[cur][Math.min(i, nr-1)];
            for(int next = 0 ; next < 10 ; next++){
                if(dp[i-1][go[cur][next]]==val){
                    System.out.print(next);
                    cur = go[cur][next];
                    break;
                }
            }
        }
    }
}


import java.io.*;
import java.util.*;
import java.awt.Point;

public class CF_1204E {
    public static void main(String args[]) throws Exception {
        BufferedScanner in = new BufferedScanner(System.in);
        BufferedPrinter out = new BufferedPrinter(System.out);

        long MOD = 998244853;
        int n = in.nextInt(), m = in.nextInt();

        long[][] dp = new long[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            dp[i][0] = i % MOD;
        }

        long[][] zs = new long[n + 1][m + 1];
        for (int i = 0; i <= m; i++) zs[0][i] = 1;

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i && j <= m; j++) {
                zs[i][j] = zs[i][j - 1] + zs[i - 1][j];
            }
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                dp[i][j] = zs[i][j] + dp[i][j - 1] + dp[i-1][j];
            }
        }
        out.println(dp[n][m]);

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

    /**
     * My template below. FastIO and utility functions.
     * Minimized with https://codebeautify.org/javaviewer.
     */

    // @formatter:off
    static<T>ArrayList<ArrayList<T>>get2D(int n){ArrayList<ArrayList<T>>ret=new ArrayList<>();for(int i=0;i<n;i++)ret.add(new ArrayList<>());return ret;}
    static void force(boolean condition){if(!condition)throw new IllegalStateException();}
    static class BufferedPrinter{PrintWriter out;BufferedPrinter(OutputStream out){this(new OutputStreamWriter(out));}
    BufferedPrinter(Writer out){this.out=new PrintWriter(new BufferedWriter(out));}
    void print(Object...os){for(int i=0;i<os.length;i++){if(i!=0)out.print(' ');out.print(os[i]);}}
    void println(Object...os){print(os);out.println();}
    void close(){out.close();}
    void flush(){out.flush();}}
    static class BufferedScanner{private final InputStream in;private final byte[]buf=new byte[1<<13];int pos,count;BufferedScanner(InputStream in)throws IOException{this.in=in;}
    long nextLong()throws IOException{return Long.parseLong(next());}
    int[]nextN(int n)throws IOException{int[]ret=new int[n];for(int i=0;i<n;i++)ret[i]=this.nextInt();return ret;}
    long[]nextNL(int n)throws IOException{long[]ret=new long[n];for(int i=0;i<n;i++)ret[i]=this.nextLong();return ret;}
    private int read(){if(count==-1)err();try{if(pos>=count){pos=0;count=in.read(buf);if(count<=0)return-1;}}catch(IOException e){err();}
    return buf[pos++];}
    private static boolean isSpace(int c){return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;}
    private int readSkipSpace(){int ret;do{ret=read();}while(isSpace(ret));return ret;}
    int nextInt(){int sign=1;int c=readSkipSpace();if(c=='-'){sign=-1;c=read();}
    int ret=0;do{if(c<'0'||c>'9')err();ret=ret*10+c-'0';c=read();}while(!isSpace(c));return sign*ret;}
    String next(){StringBuilder sb=new StringBuilder();int c=readSkipSpace();do{sb.append((char)c);c=read();}while(!isSpace(c));return sb.toString();}
    private void err(){throw new InputMismatchException();}
    void close()throws IOException{in.close();}}
    // @formatter:on
}


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

public class E {

	static final int[] DX = { -1, 0, 1, 0 };
	static final int[] DY = { 0, -1, 0, 1 };

	static final int P = 1_000_000_007;

	static final int CACHE_SIZE = 1 << 19;
	int[] cacheInv = new int[CACHE_SIZE];
	{
		cacheInv[1] = 1;
		for (int i = 2; i < CACHE_SIZE; i++) {
			cacheInv[i] = P - (int) ((long) (P / i) * cacheInv[P % i] % P);
		}
	}

	int inv(int x) {
		return x < CACHE_SIZE ? cacheInv[x] : P
				- (int) ((long) (P / x) * inv(P % x) % P);
	}

	void submit() {
		// long start = System.currentTimeMillis();
		int r = nextInt();
		int[] byDir = new int[4];
		int sum = 0;
		for (int i = 0; i < 4; i++) {
			byDir[i] = nextInt();
			sum += byDir[i];
		}

		int invSum = inv(sum);

		for (int i = 0; i < 4; i++) {
			byDir[i] = (int) ((long) byDir[i] * invSum % P);
		}

		int s = 2 * r + 3;

		int[][] f = new int[s][s];
		int[] cx = new int[s * s];
		int[] cy = new int[s * s];
		int vars = 0;
		for (int i = 0; i < s; i++) {
			for (int j = 0; j < s; j++) {
				int sum2 = (i - r - 1) * (i - r - 1) + (j - r - 1)
						* (j - r - 1);
				if (sum2 <= r * r) {
					cx[vars] = i;
					cy[vars] = j;
					f[i][j] = vars++;
				} else {
					f[i][j] = -1;
				}
			}
		}

		int band = 0;

		for (int i = 0; i < vars; i++) {
			int x0 = cx[i];
			int y0 = cy[i];
			for (int dir = 0; dir < 4; dir++) {
				int x1 = x0 + DX[dir];
				int y1 = y0 + DY[dir];
				if (f[x1][y1] == -1) {
					continue;
				}
				int j = f[x1][y1];
				band = Math.max(band, Math.abs(i - j));
			}
		}

		int[][] bandM = new int[vars][2 * band + 1];

		for (int i = 0; i < vars; i++) {
			int x0 = cx[i];
			int y0 = cy[i];
			for (int dir = 0; dir < 4; dir++) {
				int x1 = x0 + DX[dir];
				int y1 = y0 + DY[dir];
				if (f[x1][y1] == -1) {
					continue;
				}
				int j = f[x1][y1];

				updateBandedMatrix(i, j, band, bandM, byDir[dir]);

			}
		}

		for (int i = 0; i < vars; i++) {
			for (int d = 0; d <= 2 * band; d++) {
				int j = i + d - band;
				bandM[i][d] = (i == j ? 1 : 0) - bandM[i][d];
				if (bandM[i][d] < 0) {
					bandM[i][d] += P;
				}
			}
		}

		// out.println(System.currentTimeMillis() - start);

		int[] ans = inverseBanded(bandM, band, f[r + 1][r + 1]);

		// out.println(System.currentTimeMillis() - start);

		int ret = 0;
		for (int x : ans) {
			ret += x;
			if (ret >= P) {
				ret -= P;
			}
		}

		out.println(ret);

	}

	void updateBandedMatrix(int row, int col, int width, int[][] m, double delta) {
		if (Math.abs(row - col) > width) {
			throw new AssertionError();
		}
		m[row][col - row + width] += delta;
	}

	int[] inverseBanded(int[][] a, int w, int whatCol) {
		int n = a.length;
		if (whatCol > n) {
			throw new AssertionError();
		}
		int[] b = new int[n];
		b[whatCol] = 1;

		for (int j = 0; j < n; j++) {
			int[] aj = a[j];
			for (int i = j + 1; i <= j + w && i < n; i++) {
				int[] ai = a[i];
				int coef = (int) ((long) ai[j - i + w] * inv(aj[w]) % P);

				for (int k = j + 1; k < n && k <= j + w; k++) {
					int kek = ai[k - i + w]
							- (int) ((long) aj[k - j + w] * coef % P);
					if (kek < 0) {
						kek += P;
					}
					ai[k - i + w] = kek;
				}
				b[i] -= (int) ((long) b[j] * coef % P);
				if (b[i] < 0) {
					b[i] += P;
				}
			}
		}

		// for (int i = n - 1; i >= 0; i--) {
		// for (int j = i + 1; j < n && j <= i + w; j++) {
		// b[i] -= (int) ((long) b[j] * a[i][j - i + w] % P);
		// if (b[i] < 0) {
		// b[i] += P;
		// }
		// }
		// b[i] = (int) ((long) b[i] * inv(a[i][w]) % P);
		// }

		for (int i = n - 1; i >= 0; i--) {
			long tot = 0;
			for (int j = i + 1; j < n && j <= i + w; j++) {
				tot += (long) b[j] * a[i][j - i + w];
				if (tot >= P2) {
					tot -= P2;
				}
			}
			b[i] -= (int) (tot % P);
			if (b[i] < 0) {
				b[i] += P;
			}
			b[i] = (int) ((long) b[i] * inv(a[i][w]) % P);
		}

		return b;
	}

	static final long P2 = (long) P * P;

	void preCalc() {

	}

	void test() {

	}

	void stress() {
		for (int tst = 0;; tst++) {
			if (false) {
				throw new AssertionError();
			}
			System.err.println(tst);
		}
	}

	E() throws IOException {
		is = System.in;
		out = new PrintWriter(System.out);
		preCalc();
		submit();
		// stress();
		// test();
		out.close();
	}

	static final Random rng = new Random();
	static final int C = 5;

	static int rand(int l, int r) {
		return l + rng.nextInt(r - l + 1);
	}

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

	private InputStream is;
	PrintWriter out;

	private byte[] buf = new byte[1 << 14];
	private int bufSz = 0, bufPtr = 0;

	private int readByte() {
		if (bufSz == -1)
			throw new RuntimeException("Reading past EOF");
		if (bufPtr >= bufSz) {
			bufPtr = 0;
			try {
				bufSz = is.read(buf);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			if (bufSz <= 0)
				return -1;
		}
		return buf[bufPtr++];
	}

	private boolean isTrash(int c) {
		return c < 33 || c > 126;
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isTrash(b))
			;
		return b;
	}

	String nextToken() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!isTrash(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	String nextString() {
		int b = readByte();
		StringBuilder sb = new StringBuilder();
		while (!isTrash(b) || b == ' ') {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

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

	char nextChar() {
		return (char) skip();
	}

	int nextInt() {
		int ret = 0;
		int b = skip();
		if (b != '-' && (b < '0' || b > '9')) {
			throw new InputMismatchException();
		}
		boolean neg = false;
		if (b == '-') {
			neg = true;
			b = readByte();
		}
		while (true) {
			if (b >= '0' && b <= '9') {
				ret = ret * 10 + (b - '0');
			} else {
				if (b != -1 && !isTrash(b)) {
					throw new InputMismatchException();
				}
				return neg ? -ret : ret;
			}
			b = readByte();
		}
	}

	long nextLong() {
		long ret = 0;
		int b = skip();
		if (b != '-' && (b < '0' || b > '9')) {
			throw new InputMismatchException();
		}
		boolean neg = false;
		if (b == '-') {
			neg = true;
			b = readByte();
		}
		while (true) {
			if (b >= '0' && b <= '9') {
				ret = ret * 10 + (b - '0');
			} else {
				if (b != -1 && !isTrash(b)) {
					throw new InputMismatchException();
				}
				return neg ? -ret : ret;
			}
			b = readByte();
		}
	}
}


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

public class E {

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

	int n;
	int[] p;
	int[] sz;
	int[] who;

	int[] to;
	int[] head;
	int[] next;

	void addEdge(int v, int u, int idx) {
		to[idx] = u;
		next[idx] = head[v];
		head[v] = idx;
	}

	boolean cool(int a, int b, int c, int d) {
		// CAN ONLY EVEN!!!
		// SO COOL OPTIMIZATION
		// VERY MUCH
		boolean[] can = new boolean[n / 2 + 3];
		can[0] = true;

		int base = 0;

		for (int v = p[a]; v != 0; v = p[v]) {
			base++; // need to take this edge

			for (int e = head[v]; e >= 0; e = next[e]) {
				int u = to[e];
				if (who[u] == a) {
					// System.err.println(v + " a " + u);
					continue;
				}

				int nowSz = sz[u];

				for (int i = can.length - 1; i >= nowSz; i--) {
					can[i] |= can[i - nowSz];
				}
			}
		}

		for (int v = p[b]; v != 0; v = p[v]) {
			base++; // need to take this edge

			for (int e = head[v]; e >= 0; e = next[e]) {
				int u = to[e];
				if (who[u] == b) {
					// System.err.println(v + " b " + u);
					continue;
				}

				int nowSz = sz[u];

				for (int i = can.length - 1; i >= nowSz; i--) {
					can[i] |= can[i - nowSz];
				}
			}
		}

		int szC = -1;
		int szD = -1;
		for (int e = head[0]; e >= 0; e = next[e]) {
			int u = to[e];
			if (who[u] == c) {
				szC = sz[u];
			} else if (who[u] == d) {
				szD = sz[u];
			} else if (who[u] == -1) {
				int nowSz = sz[u];
				for (int i = can.length - 1; i >= nowSz; i--) {
					can[i] |= can[i - nowSz];
				}
			}
		}

		if (szC == -1 || szD == -1) {
			throw new AssertionError();
		}

		// System.err.println(Arrays.toString(can));
		// System.err.println(base);
		// System.err.println(szC + " " + szD);

		base += 2; // edges from root

		{
			int need = n - 1 - 2 * szC;
			if ((need - base) % 2 != 0) {
				return false;
			}

			int lookFor = (need - base) / 2;
			if (lookFor < 0 || lookFor >= can.length || !can[lookFor]) {
				return false;
			}
		}

		{
			int need = n - 1 - 2 * szD;
			if ((need - base) % 2 != 0) {
				return false;
			}

			int lookFor = (need - base) / 2;
			if (lookFor < 0 || lookFor >= can.length || !can[lookFor]) {
				return false;
			}
		}

		return true;
	}

	void solve() throws IOException {
		n = nextInt();
		int a = nextInt() - 1;
		int b = nextInt() - 1;
		int c = nextInt() - 1;
		int d = nextInt() - 1;

		head = new int[n];
		Arrays.fill(head, -1);
		to = new int[n - 1];
		next = new int[n - 1];

		p = new int[n];
		p[0] = -1;
		for (int i = 1; i < n; i++) {
			p[i] = nextInt() - 1;
			addEdge(p[i], i, i - 1);
		}

		sz = new int[n];
		who = new int[n];

		Arrays.fill(who, -1);
		who[a] = a;
		who[b] = b;
		who[c] = c;
		who[d] = d;

		Arrays.fill(sz, 1);
		for (int i = n - 1; i >= 1; i--) {
			sz[p[i]] += sz[i];
			if (who[i] != -1) {
				who[p[i]] = who[i];
			}
		}

		out.println(cool(a, b, c, d) && cool(c, d, a, b) ? "YES" : "NO");

	}

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

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

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

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


/*Author: Satyajeet Singh, Delhi Technological University*/
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.lang.*;
    import java.math.*;
public class Main{
/*********************************************Constants******************************************/
    static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static long mod=(long)1e9+7;
    static long mod1=998244353;
    static boolean sieve[];
    static ArrayList<Integer> primes;
    static long factorial[],invFactorial[];
    static ArrayList<Pair> graph[];
    static int pptr=0;
    static String st[];
/****************************************Solutions Begins***************************************/
    static void fact(int n){
        factorial=new long[n+1];
        invFactorial=new long [n+1];
        factorial[0]=1l;
        invFactorial[0]=1l;
        for(int i=1;i<=n;i++){
            factorial[i]=(factorial[i-1]*i)%mod;
            invFactorial[i]=modulo(factorial[i],mod-2,mod);
        }
    }
/*******************************************ncr*********************************************************/
    static long ncr(int n,int k){
        long aa=invFactorial[n-k];
        long bb=invFactorial[k];
        long cc=factorial[n];
        long ans=(aa*cc)%mod;
        ans=(ans*bb)%mod;
        return ans;
    }
    static int nx(int i){
        i++;
        if(i>=n)return i-=n;
        return i;
    }
    static int n;
    public static void main(String[] args) throws Exception{
        nl();
        n=pi();
        long k=pi();
        mod=mod1;
        fact(n+5);
        long t=0;
        int input[]=new int[n];
        nl();
        for(int i=0;i<n;i++){
            input[i]=pi();
        }
        for(int i=0;i<n;i++){
            if(input[i]!=input[nx(i)])t++;
        }
        long inv=modulo(2,mod-2,mod);
        long cur=0;
        long ans=modulo(k,n-t,mod);
        for(int i=0;i<=t-1;i++){
            long c=(modulo(k-2,i,mod)*ncr((int)t,i))%mod;
            long rem=t-i;
            long d=0;
            if(rem%2==0){
                d=modulo(2,t-i,mod)-ncr((int)rem,(int)(rem/2));
                if(d<0)d+=mod;
                d=(d*inv)%mod;
            }
            else{
                d=modulo(2,t-i-1,mod);
            }
            c=(c*d)%mod;
            cur+=c;
            if(cur>=mod)cur-=mod;
        }
        ans=(ans*cur)%mod;
        out.println(ans);
/****************************************Solutions Ends**************************************************/
        out.flush();
        out.close();
    }
/****************************************Template Begins************************************************/
    static void nl() throws Exception{
        pptr=0;
        st=br.readLine().split(" ");
    }
    static void nls() throws Exception{
        pptr=0;
        st=br.readLine().split("");
    }
    static int pi(){
        return Integer.parseInt(st[pptr++]);
    }
    static long pl(){
        return Long.parseLong(st[pptr++]);
    }
    static double pd(){
        return Double.parseDouble(st[pptr++]);
    }
    static String ps(){
        return st[pptr++];
    }
/***************************************Precision Printing**********************************************/
    static void printPrecision(double d){
        DecimalFormat ft = new DecimalFormat("0.000000000000000000000");
        out.print(ft.format(d));
    }
/**************************************Bit Manipulation**************************************************/
    static void printMask(long mask){
        System.out.println(Long.toBinaryString(mask));
    }
    static int countBit(long mask){
        int ans=0;
        while(mask!=0){
            mask&=(mask-1);
            ans++;
        }
        return ans;
    }
/******************************************Graph*********************************************************/
    static void Makegraph(int n){
        graph=new ArrayList[n];
        for(int i=0;i<n;i++){
            graph[i]=new ArrayList<>();
        }
    }
    static void addEdge(int a,int b){
        graph[a].add(new Pair(b,1));
    }
    static void addEdge(int a,int b,int c){
        graph[a].add(new Pair(b,c));
    }
/*********************************************PAIR********************************************************/
    static class Pair implements Comparable<Pair> {
        int u;
        int v;
        int index=-1;
        public Pair(int u, int v) {
            this.u = u;
            this.v = v;
        }
        public int hashCode() {
            int hu = (int) (u ^ (u >>> 32));
            int hv = (int) (v ^ (v >>> 32));
            return 31 * hu + hv;
        }
        public boolean equals(Object o) {
            Pair other = (Pair) o;
            return u == other.u && v == other.v;
        }
        public int compareTo(Pair other) {
            if(index!=other.index)
                return Long.compare(index, other.index);
            return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
        }
        public String toString() {
            return "[u=" + u + ", v=" + v + "]";
        }
    }
/******************************************Long Pair*******************************************************/
    static class Pairl implements Comparable<Pairl> {
            long u;
            long v;
            int index=-1;
            public Pairl(long u, long v) {
                this.u = u;
                this.v = v;
            }
            public int hashCode() {
                int hu = (int) (u ^ (u >>> 32));
                int hv = (int) (v ^ (v >>> 32));
                return 31 * hu + hv;
            }
            public boolean equals(Object o) {
                Pairl other = (Pairl) o;
                return u == other.u && v == other.v;
            }
            public int compareTo(Pairl other) {
                if(index!=other.index)
                    return Long.compare(index, other.index);
                return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
            }
            public String toString() {
                return "[u=" + u + ", v=" + v + "]";
            }
        }
/*****************************************DEBUG***********************************************************/
    public static void debug(Object... o){
        System.out.println(Arrays.deepToString(o));
    }
/************************************MODULAR EXPONENTIATION***********************************************/
    static long modulo(long a,long b,long c){
        long x=1;
        long y=a%c;
        while(b > 0){
            if(b%2 == 1){
                x=(x*y)%c;
            }
            y = (y*y)%c; // squaring the base
            b /= 2;
        }
        return  x%c;
    }
/********************************************GCD**********************************************************/
    static long gcd(long x, long y){
        if(x==0)
            return y;
        if(y==0)
            return x;
        long r=0, a, b;
        a = (x > y) ? x : y; // a is greater number
        b = (x < y) ? x : y; // b is smaller number
        r = b;
        while(a % b != 0){
            r = a % b;
            a = b;
            b = r;
        }
        return r;
    }
/******************************************SIEVE**********************************************************/
    static void sieveMake(int n){
        sieve=new boolean[n];
        Arrays.fill(sieve,true);
        sieve[0]=false;
        sieve[1]=false;
        for(int i=2;i*i<n;i++){
            if(sieve[i]){
                for(int j=i*i;j<n;j+=i){
                    sieve[j]=false;
                }
            }
        }
        primes=new ArrayList<Integer>();
        for(int i=0;i<n;i++){
            if(sieve[i]){
                primes.add(i);
            }
        }
    }
/********************************************End***********************************************************/
}


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

public class Sol{
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static FastReader in=new FastReader(inputStream);
static PrintWriter out=new PrintWriter(outputStream);

static class FastReader
{
  BufferedReader br;
  StringTokenizer st;

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

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

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

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

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

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

//----------------------------------------------------------------------------------------------//

//----------------S  T  A  R  T  ---------------------------------------------------------------//

//----------------------------------------------------------------------------------------------//

/*linear sieve nlogn
int n=(int)Math.pow(10,6)+100;
long mod=998244353;
long d[]=new long[n];

for(int i=1;i<n;i++){ for(int j=i; j<n; j+=i){ d[j] += 1; }}

long pre[]=new long[n];

pre[1]=1;d[1]=1;
for(int i=2;i<n;i++){d[i]+=pre[i-1]%mod;pre[i] += (pre[i-1]+d[i])%mod;}*/

static class Pair {
        int id;long val;
        public Pair(int id,long val) {

          this.id=id;
         this.val=val;
        }

      }

/*----------nCx---------------
long Comb[][]=new long[61][61];

for(int i=1;i<=60;i++){Comb[i][0]=1;}
for(int i=1;i<=60;i++){Comb[i][1]=i;Comb[i][i]=1;}
for(int i=2;i<=60;i++){for(int j=1;j<i;j++){Comb[i][j]=Comb[i-1][j]+Comb[i-1][j-1];}}
----------nCx------------------
*/

/*----------DFS-------------
static void DFS(int v,int p){
dp[0][v]=0;dp[1][v]=0;
for(int u:adj[v]){
if(u==p)continue;
DFS(u,v);
dp[0][v]+=Math.max(Math.abs(A[0][u]-A[0][v]) + dp[0][u], Math.abs(A[1][u]-A[0][v]) + dp[1][u] );
dp[1][v]+=Math.max(Math.abs(A[0][u]-A[1][v]) + dp[0][u], Math.abs(A[1][u]-A[1][v]) + dp[1][u] );
}

}

static int N=(int)Math.pow(10,5)+10;
static ArrayList<Integer> adj[]=new ArrayList[N];
static long dp[][]=new long[2][N];
static long A[][]=new long[2][N];

-----------DFS--------------
*/
/*static class Edge implements Comparable<Edge>{
int destination;long cost;
Edge(int destination,long cost){this.cost=cost;this.destination=destination;}

@Override

		public int compareTo(Edge o) {
			return Long.compare(cost, o.cost);
		}
}

*/

public static void main(String []args){

int t=1;

while(t-->0){
int n=in.nextInt();int m=in.nextInt();

HashSet<Integer> hs=new HashSet<Integer>();boolean ans=true;
while(n>0){if(hs.contains(n%m)){ans=false;}else{hs.add(n%m);}n/=m;         }
if(ans)out.println("YES");
else out.println("NO");
 }

out.close();
}}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class ComputerGame {

	static double[][] identity;
	static double INF = 1e18D;
	static int MAXPOW = 40;
	public static void main(String[] args) {
		FS in = new FS();
		PrintWriter out = new PrintWriter(System.out);
		int N = in.nextInt();
		long T = in.nextLong();
		double[] A = new double[N];
		double[] B = new double[N];
		double[] P = new double[N];
		double V = 0;
		for(int i = 0; i < N; i++) {
			A[i] = in.nextDouble();
			B[i] = in.nextDouble();
			P[i] = in.nextDouble();
			V = Math.max(V, P[i]*B[i]);
		}

		CHT cht = new CHT(1);
		for(int i = 0; i < N; i++) {
			cht.add(P[i], P[i]*A[i], i);
		}
		identity = identity(3);
		double vec[][] = new double[][]{{0}, {0}, {1}}; //prevDp, prevT, prev1
		for(CHT.Line l : cht.hull) {
			CHT.Line higherLine = cht.hull.higher(l);
			double stopAt = higherLine == null ? INF : l.inter(higherLine);

			double mat[][] = new double[][] {
				{1-P[l.id], P[l.id]*V, P[l.id]*A[l.id]},
				{0, 1, 1},
				{0, 0, 1},
			};

			double matToPowerOf2[][][] = new double[MAXPOW][][];
			matToPowerOf2[0] = identity;
			matToPowerOf2[1] = mat;
			for(int i = 2; i < MAXPOW; i++) matToPowerOf2[i] = mult(matToPowerOf2[i-1], matToPowerOf2[i-1]);

//			print(mat);

			// Find how long we will use this line for
			double cur[][] = identity;
			for(int i = MAXPOW-1; i >= 0; i--) {
				double next[][] = mult(cur, matToPowerOf2[i]);
				double nextVec[][] = mult(next, vec);

				long t = (long)(nextVec[1][0]);
				double query = V*t-nextVec[0][0];

				boolean bad = (t > T) || (query > stopAt);
				if(!bad) {
					// Take this expo
					cur = next;
				}
			}
			vec = mult(cur, vec);
		}
		System.out.println(vec[0][0]);
	}

	static void print(double a[][]) {
		for(int i = 0; i < a.length; i++) {
			System.out.println(Arrays.toString(a[i]));
		}
		System.out.println();
	}

	static double [][] pow(double m[][], long p) {
		if(p == 0) return identity;
		if(p == 1) return m;
		if((p&1) == 0) {
			double res[][] = pow(m, p>>1);
			return mult(res,res);
		}
		else {
			return mult(m, pow(m, p-1));
		}
	}

	static double[][] mult(double a[][], double b[][]){
		double res[][] = new double[a.length][b[0].length];
		for(int i = 0; i < a.length; i++) {
			for(int j = 0; j < b[0].length; j++) {
				for(int k = 0; k < a[i].length; k++) {
					res[i][j] += a[i][k]*b[k][j];
				}
			}
		}
		return res;
	}
	static double[][] identity(int sz) {
		double res[][] = new double[sz][sz];
		for(int i = 0; i < sz; i++) res[i][i] = 1;
		return res;
	}

	static class CHT {
		TreeSet<Line> hull;
		int type;  boolean query  = false;
		Comparator<Line> comp = new Comparator<Line>() {
			public int compare(Line a, Line b) {
				if (!query) return type * Double.compare(a.m, b.m);
				if (a.left == b.left) return Double.compare(a.m, b.m);
				return Double.compare(a.left, b.left);
			}
		};
		// -1 for min; +1 for max
		public CHT(int typee) { type = typee;  hull = new TreeSet<>(comp); }

		public void add(double m, double b, int id) { add(new Line(m, b, id)); }

		public void add(Line a) {
			Line[] LR = { hull.lower(a), hull.ceiling(a) };
			for (int i = 0; i < 2; i++)
				if (LR[i] != null && LR[i].m == a.m) {
					if (type == 1 && LR[i].b >= a.b) return;
					if (type == -1 && LR[i].b <= a.b) return;
					remove(LR[i]);
				}
			hull.add(a);
			Line L = hull.lower(a), R = hull.higher(a);
			if (L != null && R != null && a.inter(R) <= R.left) {
				hull.remove(a);
				return;
			}
			Line LL = (L != null) ? hull.lower(L) : null;
			Line RR = (R != null) ? hull.higher(R) : null;
			if (L != null) a.left = a.inter(L);
			if (R != null) R.left = a.inter(R);
			while (LL != null && L.left >= a.inter(LL)) {
				remove(L);
				a.left = a.inter(L = LL);
				LL = hull.lower(L);
			}
			while (RR != null && R.inter(RR) <= a.inter(RR)) {
				remove(R);
				RR.left = a.inter(R = RR);
				RR = hull.higher(R);
			}
		}

		public long query(long x) {
			if(hull.size() == 0) return 0;
			Line temp = new Line(0, 0);
			temp.left = x;  query = true;
			long ans = (long) hull.floor(temp).eval(x);
			query = false;  return ans;
		}

		private void remove(Line x) { hull.remove(x); }

		public int size() { return hull.size(); }

		static class Line {
			double m, b; double left = Long.MIN_VALUE;
			int id;
			public Line(double mm, double bb, int ii) { m = mm; b = bb; id = ii;}
			public Line(double mm, double bb) { m = mm; b = bb; }
			public double eval(double x) { return m * x + b; }
			public double inter(Line x) {
				return (double) (x.b - this.b) / (double) (this.m - x.m);
			}
		}
	}

	static class FS{
		BufferedReader br;
		StringTokenizer st;
		public FS() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try { st = new StringTokenizer(br.readLine());}
				catch(Exception e) { throw null;}
			}
			return st.nextToken();
		}
		int nextInt() { return Integer.parseInt(next());}
		double nextDouble() { return Double.parseDouble(next());}
		long nextLong() { return Long.parseLong(next());}
	}

}


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

public class G {
	int oo = (int)1e8;

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

	int SQRT;
	int[] minTandemStart, minTandemEnd, sa, rsa, lcp;
	boolean[] primes;
	RMQ query3RMQ, lcpRMQ;
	String str;

	public G() {
		FastScanner fs = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		System.err.println("");

		doPrimes();

		int n = fs.nextInt();
		SQRT = (int)Math.sqrt(n);
		str = fs.next();
		FastSuffixArray fsa = new FastSuffixArray();
		sa = fsa.suffixArray(str.toCharArray());
		rsa = new int[sa.length];
		lcp = fsa.lcp(sa, str.toCharArray());
		lcpRMQ = new RMQ(lcp);
		for(int i = 0; i < sa.length; i++) rsa[sa[i]] = i;

		TandemRepeats tr = new TandemRepeats(str);
		minTandemStart = tr.min;
		TandemRepeats tr2 = new TandemRepeats(reverse(str));
		minTandemEnd = reverse(tr2.min);

//		System.out.println(Arrays.toString(minTandemStart));
//		System.out.println(Arrays.toString(minTandemEnd));
//		System.out.println();

		int[] query3Values = new int[n];
		for(int i = 0; i < n; i++) {
			query3Values[i] = i+2*minTandemStart[i];
		}
		query3RMQ = new RMQ(query3Values);

		int[][] pref = new int[26][n];
		for(int i = n-1; i >= 0; i--) {
			for(int j = 0; j < 26 && i+1 < n; j++) pref[j][i] = pref[j][i+1];
			pref[str.charAt(i)-'a'][i]++;
		}

		int Q = fs.nextInt();
		for(int qq = 1; qq <= Q; qq++) {
			int L = fs.nextInt()-1, R = fs.nextInt()-1;

			//case -1
			boolean good = false;
			for(int i = 0; i < 26; i++) {
				int sum = pref[i][L];
				if(R + 1 < n) sum -= pref[i][R+1];
				if(sum > 1) good = true;
			}
			if(!good) {
				out.println(-1);
				continue;
			}

			//case 1:
			boolean ans1 = false;
			int N = R-L+1;
			for(int div = 1; div * div <= N; div++) {
				if(N % div != 0) continue;
				if(!primes[N/div]) continue;

				if(check(L, R, div)) ans1 = true;
				else if(primes[div] && check(L, R, N/div)) ans1 = true;
				if(ans1) break;
			}
			if(ans1) {
				out.println(1);
				continue;
			}

			//case 2:
			boolean ans2 = false;
			if(minTandemStart[L] != oo && L+minTandemStart[L]*2-1 <= R) {
				ans2 = true;
			}
			if(minTandemEnd[R] != oo && R-minTandemEnd[R]*2+1 >= L) {
				ans2 = true;
			}
			if(isBorder(L, R)) {
				ans2 = true;
			}
			if(ans2) {
				out.println(2);
				continue;
			}

			//case 3:
			boolean ans3 = false;
			{ //first character
				int idx = str.charAt(L)-'a';
				int sum = pref[idx][L];
				if(R+1 < n) sum -= pref[idx][R+1];
				if(sum > 1) ans3 = true;
			}
			{ //last character
				int idx = str.charAt(R)-'a';
				int sum = pref[idx][L];
				if(R+1 < n) sum -= pref[idx][R+1];
				if(sum > 1) ans3 = true;
			}
			{ //BAAC
				int min = query3RMQ.query(L, R);
				if(min <= R) ans3 = true;
			}
			if(ans3) {
				out.println(3);
				continue;
			}

			out.println(4);
		}

		out.close();
	}

	boolean check(int L, int R, int div) {
		int minPos = rsa[L], maxPos = rsa[L];
		for(int j = L+div; j <= R; j += div) {
			minPos = Math.min(minPos, rsa[j]);
			maxPos = Math.max(maxPos, rsa[j]);
		}
		int lcp = lcpRMQ.query(minPos, maxPos-1);
		if(lcp >= div) {
			return true;
		}
		return false;
	}

	boolean isBorder(int L, int R) {
		for(int len = 1; len < SQRT; len++) {
			int ptsTo = R-len+1;
			if(ptsTo <= L+len-1) continue;
			int min = Math.min(rsa[L], rsa[ptsTo]);
			int max = Math.max(rsa[L], rsa[ptsTo]);
			int lcp = lcpRMQ.query(min, max-1);
			if(lcp >= len) {
				return true;
			}
		}
		int st = Math.max(0, rsa[L]-SQRT-1);
		int en = Math.min(sa.length-1, rsa[L]+SQRT+1);
		int him = rsa[L];

		for(int i = st; i <= en; i++) {
			int idx = sa[i];
			if(L <= idx && idx <= R) {}
			else continue;
			int min = Math.min(i, him);
			int max = Math.max(i, him);
			int lcp = lcpRMQ.query(min, max-1);
			if(lcp < SQRT) continue;

			if(idx+lcp-1 < R) continue;
			int size = R-idx+1;
			if(L+size-1 >= idx) continue;
			return true;
		}

		return false;
	}

	class RMQ {
		int[] vs;
		int[][] lift;

		public RMQ(int[] vs) {
			this.vs = vs;
			int n = vs.length;
			int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2;
			lift = new int[maxlog][n];
			for (int i = 0; i < n; i++)
				lift[0][i] = vs[i];
			int lastRange = 1;
			for (int lg = 1; lg < maxlog; lg++) {
				for (int i = 0; i < n; i++) {
					lift[lg][i] = Math.min(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]);
				}
				lastRange *= 2;
			}
		}

		public int query(int low, int hi) {
			if(hi < low) return 0;
			int range = hi - low + 1;
			int exp = Integer.highestOneBit(range);
			int lg = Integer.numberOfTrailingZeros(exp);
			return Math.min(lift[lg][low], lift[lg][hi - exp + 1]);
		}
	}

	class FastSuffixArray {
		public int[] suffixArray(char[] S) {
			int n = S.length;
			Integer[] order = new Integer[n];
			for (int i = 0; i < n; i++)
				order[i] = n - 1 - i;

			Arrays.sort(order, (a, b) -> Character.compare(S[a], S[b]));

			int[] sa = new int[n];
			int[] classes = new int[n];
			for (int i = 0; i < n; i++) {
				sa[i] = order[i];
				classes[i] = S[i];
			}

			for (int len = 1; len < n; len *= 2) {
				int[] c = classes.clone();
				for (int i = 0; i < n; i++) {
					classes[sa[i]] = i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + len / 2] == c[sa[i] + len / 2] ? classes[sa[i - 1]] : i;
				}
				int[] cnt = new int[n];
				for (int i = 0; i < n; i++)
					cnt[i] = i;
				int[] s = sa.clone();
				for (int i = 0; i < n; i++) {
					int s1 = s[i] - len;
					if (s1 >= 0)
						sa[cnt[classes[s1]]++] = s1;
				}
			}
			return sa;
		}

		public int[] lcp(int[] sa, char[] s) {
			int n = sa.length;
			int[] rank = new int[n];
			for (int i = 0; i < n; i++)
				rank[sa[i]] = i;
			int[] lcp = new int[n - 1];
			for (int i = 0, h = 0; i < n; i++) {
				if (rank[i] < n - 1) {
					for (int j = sa[rank[i] + 1]; Math.max(i, j) + h < s.length && s[i + h] == s[j + h]; ++h)
						;
					lcp[rank[i]] = h;
					if (h > 0)
						--h;
				}
			}
			return lcp;
		}
	}

	class TandemRepeats {
		int[] min;
		TandemRepeats(String str) {
			list = new ArrayList<>();
			findRepetitions(str, 0, str.length()-1);
			Collections.sort(list);
			min = new int[str.length()];
			Arrays.fill(min, oo);

			TreeMap<Integer, Integer> map = new TreeMap<>();
			int ptr = 0;
			for(int i = 0; i < str.length(); i++) {
				while(ptr < list.size()) {
					Event now = list.get(ptr);
					if(now.pos <= i) {
						if(now.type == 0) add(map, now.val);
						else rem(map, now.val);
						ptr++;
					} else break;
				}
				if(!map.isEmpty())
					min[i] = Math.min(min[i], map.firstKey());
			}
		}

		ArrayList<Event> list;
		//Main-Lorentz algorithm
		void findRepetitions(String str, int L, int R) {
			int n = R-L+1;
			if(n < 2 || R < L) return;

			String u = str.substring(0, n/2);
			String v = str.substring(n/2);
			findRepetitions(u, L, L+u.length()-1); findRepetitions(v, L+u.length(), R);

			int[] z1 = zValues(reverse(u));
			int[] z2 = zValues(v + "#" + u);
			int[] z3 = zValues(reverse(u) + "#" + reverse(v));
			int[] z4 = zValues(v);

			int uLen = u.length(), vLen = v.length();
			for(int cntr = 0; cntr < n; cntr++) {
				int totLen, k1, k2;
				if(cntr < uLen) {
					totLen = uLen-cntr;
					k1 = getIdx(z1, uLen-cntr);
					k2 = getIdx(z2, vLen+1+cntr);

					if(k1+k2 >= totLen) {
						int min = find(k1, k2, totLen, true, 0);
						int max = find(k1, k2, totLen, false, 0);
						int start = Math.max(L, L+cntr-max);
						int end = Math.min(L+cntr-1, L+cntr-min);

						if(start <= end) {
							list.add(new Event(0, start, totLen));
							list.add(new Event(1, end+1, totLen));
						}
					}

				}
				else {
					totLen = cntr-uLen+1;
					k1 = getIdx(z3, uLen + 1 + vLen - 1 - (cntr - uLen));
					k2 = getIdx(z4, (cntr - uLen) + 1);

					if(k1+k2 >= totLen) {
						int max = find(k1, k2, totLen, false, 1);
						int min = find(k1, k2, totLen, true, 1);
						int start = Math.max(L, L+n/2-1 - max + 1);
						int end = Math.min(L+n/2-1, L+n/2-1-min+1);

						if(start <= end) {
							list.add(new Event(0, start, totLen));
							list.add(new Event(1, end+1, totLen));
						}
					}

				}
			}

		}

		int find(int k1, int k2, int len, boolean small, int lim) {
			int lo = lim, hi = k1, res = 0;
			for(int bs = 0; bs < 50 && lo <= hi; bs++) {
				int mid = (lo+hi)/2;
				int v = len-mid;
				if(v < 0) { //too much
					hi = mid-1;
				}
				else if(v > k2) { //too little
					lo = mid+1;
				}
				else { //great
					res = mid;
					if(small) hi = mid-1;
					else lo = mid+1;
				}
			}
			return res;
		}

		class Event implements Comparable<Event> {
			int type, pos, val;
			Event(int t, int p, int v) {
				type = t; val = v;
				pos = p;
			}
			public int compareTo(Event e) {
				int comp = Integer.compare(pos, e.pos);
				if(comp == 0) comp = Integer.compare(e.type, type);
				return comp;
			}
			public String toString() {
				return String.format("Pos = %d Type = %d V = %d", pos, type, val);
			}
		}

		int getIdx(int[] a, int i) {
			if(i >= 0 && i < a.length) return a[i];
			return 0;
		}

		int[] zValues(String string) {
			int n = string.length();  char[] s = string.toCharArray();
			int[] z = new int[n];  z[0] = n;
			int L = 0, R = 0;
			int[] left = new int[n], right = new int[n];
			for(int i = 1; i < n; ++i) {
				if(i > R) {
					L = R = i;
					while(R < n && s[R-L] == s[R]) R++;
					z[i] = R - L;  R--;
				} else {
					int k = i-L;
					if(z[k] < R-i+1) z[i] = z[k];
					else {
						L = i;
						while(R < n && s[R-L] == s[R]) R++;
						z[i] = R - L;  R--;
					}
				}
				left[i] = L;  right[i] = R;
			}
			return z;
		}

		void add(TreeMap<Integer, Integer> map, int x) {
			map.put(x, map.getOrDefault(x, 0)+1);
		}
		void rem(TreeMap<Integer, Integer> map, int x) {
			int fr = map.get(x)-1;
			if(fr == 0) map.remove(x);
			else map.put(x, fr);
		}
	}

	void doPrimes() {
		primes = new boolean[200200];
		Arrays.fill(primes, true);
		primes[0] = primes[1] = false;
		for(int i = 2; i < primes.length; i++) {
			if(!primes[i]) continue;
			for(int j = i+i; j < primes.length; j += i) primes[j] = false;
		}
	}

	String reverse(String s) {
		return new StringBuilder(s).reverse().toString();
	}
	int[] reverse(int[] a) {
		int n = a.length;
		int[] res = new int[n];
		for(int i = 0, j = n-1; i < n; i++, j--) {
			res[i] = a[j];
		}
		return res;
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;
		public FastScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
			st = new StringTokenizer("");
		}
		String next() {
			if(st.hasMoreTokens()) return st.nextToken();
			try { st = new StringTokenizer(br.readLine()); } catch (Exception e) {}
			return next();
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
	}

}


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

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

class TaskD_EgorAndCaves {
    public static final int MOD = (int)1e9 + 7;

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

        if (m < 2) {
            out.println(0);
            return;
        }
        long[][] dp = new long[n+1][m+1];
        long[][] lastRow = new long[n+1][m+1];

        for (int width = 2; width <= m; ++width) {
            dp[0][width] = 1;
        }
        for (int row = 1; row < n; ++row) {
            for (int width = 2; width <= m; ++width) {
                dp[row][width] = 1;
                lastRow[row][width] = 0;
                for (int prevWidth = 2; prevWidth <= width; ++prevWidth) {
                    dp[row][width] += (dp[row-1][prevWidth] * (width - prevWidth + 1)) % MOD;
                    if (prevWidth < width) {
                        lastRow[row][width] += (dp[row - 1][prevWidth] * (width - prevWidth + 1)) % MOD;
                    }
                    if (lastRow[row][width] >= MOD) {
                        lastRow[row][width] -= MOD;
                    }
                    if (dp[row][width] >= MOD) {
                        dp[row][width] -= MOD;
                    }
                }
            }
        }

        long res = 0;
        for (int t = 0; t < n; ++t) {
            for (int width = 2; width <= m; ++width) {
                res += ((dp[t][width]) % MOD) * (m - width + 1) % MOD;
                if (res >= MOD) {
                    res -= MOD;
                }
                res += ((dp[t][width] * lastRow[n - t - 1][width]) % MOD) * (m - width + 1) % MOD;
                if (res >= MOD) {
                    res -= MOD;
                }
            }
        }
        out.println(res);
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer stt;

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

    public String nextLine() {
        try {
            return reader.readLine();
        } catch (IOException e) {
            return null;
        }
    }

    public String nextString() {
        while (stt == null || !stt.hasMoreTokens()) {
            stt = new StringTokenizer(nextLine());
        }
        return stt.nextToken();
    }

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

}


import java.util.Map;
import java.io.IOException;
import java.util.HashMap;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.util.NoSuchElementException;
import java.io.InputStream;

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

class TaskC {
    long[] fib;
    Map<State, Long> map;

    public void solve(int testNumber, MyScanner in, PrintWriter out) {
        int t = in.nextInt();
        int n = in.nextInt();
        long[] u = new long[t];
        long[] v = new long[t];
        for (int i = 0; i < t; i++){
            u[i] = in.nextInt();
            v[i] = in.nextInt();
        }
        long[] res= solve(u,v,n);
        for(long r:res)out.println(r);
    }
    private long[] solve(long[] u, long[] v, int n){
        n = Math.min(n, 85);
        fib = new long[n + 1];
        for (int i = 0; i <= n; i++) {
            fib[i] = i <= 1 ? i + 1 : fib[i - 1] + fib[i - 2];
        }
//        map = new TreeMap<State, Long>();
        map = new HashMap<State, Long>();
        long[]res =new long[u.length];
        for (int i = 0; i < u.length; i++) {
            map.clear();
            if(i%1000==0) System.err.println(i);
            res[i] = solve(u[i],v[i],n);
        }
        return res;
    }

    class State implements Comparable<State> {
        State(long i, long j, int n) {
            this.i = i;
            this.j = j;
            this.n = n;
        }

        long i, j;
        int n;

        public int compareTo(State o) {
            if (i != o.i) return Long.compare(i, o.i);
            if (j != o.j) return Long.compare(j, o.j);
            return Integer.compare(n, o.n);
        }

        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            State state = (State) o;

            if (i != state.i) return false;
            if (j != state.j) return false;
            if (n != state.n) return false;

            return true;
        }

        public int hashCode() {
            int result = (int) (i ^ (i >>> 32));
            result = 31 * result + (int) (j ^ (j >>> 32));
            result = 31 * result + n;
            return result;
        }
    }

    private long solve(long i, long j, int n) {
        if (i > j) return solve(j, i, n);
        if (j > fib[n]) throw new AssertionError();
        if (n == 0) return 0;
        if (n == 1) return i != j ? 1 : 0;
        State cur = new State(i, j, n);
        Long res = map.get(cur);
        if (res != null) return res;
        if (j <= fib[n - 1]) res = Math.min(
                solve(i, j, n - 1),
                Math.min(
                        solve(i, 1, n - 1) + solve(j, fib[n - 1], n - 1) + 2,
                        solve(i, fib[n - 1], n - 1) + solve(j, 1, n - 1) + 2
                )
        );
        else if (i <= fib[n - 1]) res = Math.min(
                solve(i, 1, n - 1) + solve(1, j - fib[n - 1], n - 2) + 1,
                solve(i, fib[n - 1], n - 1) + solve(1, j - fib[n - 1], n - 2) + 1
        );
        else res = solve(i - fib[n - 1], j - fib[n - 1], n - 2);
        map.put(cur, res);
        return res;
    }

    }

class MyScanner {
    private final InputStream in;
    public MyScanner(InputStream in){
        this.in = in;
    }

    public int nextInt(){
		try{
			int c=in.read();
			if(c==-1) return c;
			while(c!='-'&&(c<'0'||'9'<c)){
				c=in.read();
				if(c==-1) return c;
			}
			if(c=='-') return -nextInt();
			int res=0;
			do{
				res*=10;
				res+=c-'0';
				c=in.read();
			}while('0'<=c&&c<='9');
			return res;
		}catch(Exception e){
			return -1;
		}
	}

    }


import java.io.*;

public class Codeforces832E {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] sp = br.readLine().split(" ");
		int n = Integer.parseInt(sp[0]);
		int m = Integer.parseInt(sp[1]);
		int[][] matrix = new int[n][m];
		for (int i = 0; i < n; i++) {
			sp = br.readLine().split(" ");
			String s = sp[0];
			for (int j = 0; j < m; j++) {
				matrix[i][j] = (int) s.charAt(j) - 97;
			}
		}

		int counter = 0;
		int i = 0;
		while ((i < n) && (counter < m)) {
			if (matrix[i][counter] == 0) {
				int counter2 = -1;
				for (int j = i+1; j < n; j++) {
					if (matrix[j][counter] != 0) {
						counter2 = j;
					}
				}
				if (counter2 == -1)
					counter++;
				else {
					for (int k = counter; k < m; k++) {
						int temp = matrix[i][k];
						matrix[i][k] = matrix[counter2][k];
						matrix[counter2][k] = temp;
					}
				}
			}
			if ((counter < m) && (matrix[i][counter] != 0)) {
				for (int j = i+1; j < n; j++) {
					int z = matrix[j][counter];
					for (int k = counter; k < m; k++) {
						matrix[j][k] -= z*matrix[i][k]*matrix[i][counter]*matrix[i][counter]*matrix[i][counter];
						matrix[j][k] = (matrix[j][k]+2000)%5;
					}
				}
				i++;
				counter++;
			}
		}
		int asdf = i;

		int[] firstnonzero = new int[n];
		int counter2 = 0;
		for (i = 0; i < asdf; i++) {
			while (matrix[i][counter2] == 0)
				counter2++;
			firstnonzero[i] = counter2;
		}

		int val = 1;
		if (n > asdf)
			val = fivepower(n-asdf, 1000000007);
		sp = br.readLine().split(" ");
		int q = Integer.parseInt(sp[0]);
		for (i = 0; i < q; i++)	{
			sp = br.readLine().split(" ");
			String t = sp[0];
			int[] result = new int[m];
			for (int j = 0; j < m; j++) {
				result[j] = (int) t.charAt(j) - 97;
			}
			for (int k = 0; k < asdf; k++) {
				int u = result[firstnonzero[k]];
				for (int l = firstnonzero[k]; l < m; l++) {
					result[l] -= u*matrix[k][l]*matrix[k][firstnonzero[k]]*matrix[k][firstnonzero[k]]*matrix[k][firstnonzero[k]];
					result[l] = (result[l]+2000)%5;
				}
			}
			boolean bool = true;
			for (int j = 0; j < m; j++) {
				if (result[j] != 0)
					bool = false;
			}
			if (bool)
				System.out.println(val);
			else
				System.out.println(0);
		}

	}

	public static int fivepower(int n, int mod) {
		long a = 5;
		while (n > 0) {
			if (n%2 == 1) {
				n /= 2;
				a = (5*a*a)%mod;
			}
			else {
				n /= 2;
				a = (a*a)%mod;
			}
		}
		return (int) a;
	}
}


import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;

import static java.lang.Math.max;
import static java.lang.Math.min;

public class C implements Runnable{

    // SOLUTION!!!
    // HACK ME PLEASE IF YOU CAN!!!
    // PLEASE!!!
    // PLEASE!!!
    // PLEASE!!!

    private final static Random rnd = new Random();
    private final static String fileName = "";

    private void solve() {
        int n = readInt();
        int[] a = readIntArray(n);

        Point minMax = getMinMax(a);

        int answer = a[minMax.y] ^ a[n - 1];
        out.println(answer);
    }

    /////////////////////////////////////////////////////////////////////

    private final static boolean FIRST_INPUT_STRING = false;
    private final static boolean MULTIPLE_TESTS = true;
    private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private final static int MAX_STACK_SIZE = 128;

    private final static boolean OPTIMIZE_READ_NUMBERS = false;

    /////////////////////////////////////////////////////////////////////

    public void run(){
        try{
            timeInit();
            Locale.setDefault(Locale.US);

            init();

            if (ONLINE_JUDGE) {
                solve();
            } else {
                do {
                    try {
                        timeInit();
                        solve();
                        time();

                        out.println();
                    } catch (NumberFormatException e) {
                        break;
                    } catch (NullPointerException e) {
                        if (FIRST_INPUT_STRING) break;
                        else throw e;
                    }
                } while (MULTIPLE_TESTS);
            }

            out.close();
            time();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private BufferedReader in;
    private OutputWriter out;
    private StringTokenizer tok = new StringTokenizer("");

    public static void main(String[] args){
        new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start();
    }

    /////////////////////////////////////////////////////////////////////

    private void init() throws FileNotFoundException{
        Locale.setDefault(Locale.US);

        if (ONLINE_JUDGE){
            if (fileName.isEmpty()) {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new OutputWriter(System.out);
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new OutputWriter(fileName + ".out");
            }
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new OutputWriter("output.txt");
        }
    }

    ////////////////////////////////////////////////////////////////

    private long timeBegin;

    private void timeInit() {
        this.timeBegin = System.currentTimeMillis();
    }

    private void time(){
        long timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    private void debug(Object... objects){
        if (ONLINE_JUDGE){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    /////////////////////////////////////////////////////////////////////

    private String delim = " ";

    private String readLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private String readString() {
        try {
            while(!tok.hasMoreTokens()){
                tok = new StringTokenizer(readLine());
            }

            return tok.nextToken(delim);
        } catch (NullPointerException e) {
            return null;
        }
    }

    /////////////////////////////////////////////////////////////////

    private final char NOT_A_SYMBOL = '\0';

    private char readChar() {
        try {
            int intValue = in.read();

            if (intValue == -1){
                return NOT_A_SYMBOL;
            }

            return (char) intValue;
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private char[] readCharArray() {
        return readLine().toCharArray();
    }

    private char[][] readCharField(int rowsCount) {
        char[][] field = new char[rowsCount][];
        for (int row = 0; row < rowsCount; ++row) {
            field[row] = readCharArray();
        }

        return field;
    }

    /////////////////////////////////////////////////////////////////

    private long optimizedReadLong() {
        int sign = 1;
        long result = 0;
        boolean started = false;
        while (true) {
            try {
                int j = in.read();
                if (-1 == j) {
                    if (started) return sign * result;
                    throw new NumberFormatException();
                }

                if (j == '-') {
                    if (started) throw new NumberFormatException();
                    sign = -sign;
                }

                if ('0' <= j && j <= '9') {
                    result = result * 10 + j - '0';
                    started = true;
                } else if (started) {
                    return sign * result;
                }
            } catch (IOException e) {
                throw new RuntimeIOException(e);
            }
        }
    }

    private int readInt() {

        if (!OPTIMIZE_READ_NUMBERS) {
            return Integer.parseInt(readString());
        } else {
            return (int) optimizedReadLong();
        }
    }

    private int[] readIntArray(int size) {
        int[] array = new int[size];

        for (int index = 0; index < size; ++index){
            array[index] = readInt();
        }

        return array;
    }

    private int[] readSortedIntArray(int size) {
        Integer[] array = new Integer[size];

        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    private int[] readIntArrayWithDecrease(int size) {
        int[] array = readIntArray(size);

        for (int i = 0; i < size; ++i) {
            array[i]--;
        }

        return array;
    }

    ///////////////////////////////////////////////////////////////////

    private int[][] readIntMatrix(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArray(columnsCount);
        }

        return matrix;
    }

    private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
        }

        return matrix;
    }

    ///////////////////////////////////////////////////////////////////

    private long readLong() {
        if (!OPTIMIZE_READ_NUMBERS) {
            return Long.parseLong(readString());
        } else {
            return optimizedReadLong();
        }
    }

    private long[] readLongArray(int size) {
        long[] array = new long[size];

        for (int index = 0; index < size; ++index){
            array[index] = readLong();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    private double readDouble() {
        return Double.parseDouble(readString());
    }

    private double[] readDoubleArray(int size) {
        double[] array = new double[size];

        for (int index = 0; index < size; ++index){
            array[index] = readDouble();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    private BigInteger readBigInteger() {
        return new BigInteger(readString());
    }

    private BigDecimal readBigDecimal() {
        return new BigDecimal(readString());
    }

    /////////////////////////////////////////////////////////////////////

    private Point readPoint() {
        int x = readInt();
        int y = readInt();
        return new Point(x, y);
    }

    private Point[] readPointArray(int size) {
        Point[] array = new Point[size];

        for (int index = 0; index < size; ++index){
            array[index] = readPoint();
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    @Deprecated
    private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
        @SuppressWarnings("unchecked")
        List<Integer>[] graph = new List[vertexNumber];

        for (int index = 0; index < vertexNumber; ++index){
            graph[index] = new ArrayList<>();
        }

        while (edgeNumber-- > 0){
            int from = readInt() - 1;
            int to = readInt() - 1;

            graph[from].add(to);
            graph[to].add(from);
        }

        return graph;
    }

    private static class GraphBuilder {

        final int size;
        final List<Integer>[] edges;

        static GraphBuilder createInstance(int size) {
            List<Integer>[] edges = new List[size];
            for (int v = 0; v < size; ++v) {
                edges[v] = new ArrayList<>();
            }

            return new GraphBuilder(edges);
        }

        private GraphBuilder(List<Integer>[] edges) {
            this.size = edges.length;
            this.edges = edges;
        }

        public void addEdge(int from, int to) {
            addDirectedEdge(from, to);
            addDirectedEdge(to, from);
        }

        public void addDirectedEdge(int from, int to) {
            edges[from].add(to);
        }

        public int[][] build() {
            int[][] graph = new int[size][];
            for (int v = 0; v < size; ++v) {
                List<Integer> vEdges = edges[v];
                graph[v] = castInt(vEdges);
            }

            return graph;
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class IntIndexPair {

        static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() {

            @Override
            public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
                int value1 = indexPair1.value;
                int value2 = indexPair2.value;

                if (value1 != value2) return value1 - value2;

                int index1 = indexPair1.index;
                int index2 = indexPair2.index;

                return index1 - index2;
            }
        };

        static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() {

            @Override
            public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
                int value1 = indexPair1.value;
                int value2 = indexPair2.value;

                if (value1 != value2) return -(value1 - value2);

                int index1 = indexPair1.index;
                int index2 = indexPair2.index;

                return index1 - index2;
            }
        };

        static IntIndexPair[] from(int[] array) {
            IntIndexPair[] iip = new IntIndexPair[array.length];
            for (int i = 0; i < array.length; ++i) {
                iip[i] = new IntIndexPair(array[i], i);
            }

            return iip;
        }

        int value, index;

        IntIndexPair(int value, int index) {
            super();
            this.value = value;
            this.index = index;
        }

        int getRealIndex() {
            return index + 1;
        }
    }

    private IntIndexPair[] readIntIndexArray(int size) {
        IntIndexPair[] array = new IntIndexPair[size];

        for (int index = 0; index < size; ++index) {
            array[index] = new IntIndexPair(readInt(), index);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    private static class OutputWriter extends PrintWriter {

        final int DEFAULT_PRECISION = 12;

        private int precision;
        private String format, formatWithSpace;

        {
            precision = DEFAULT_PRECISION;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        OutputWriter(OutputStream out) {
            super(out);
        }

        OutputWriter(String fileName) throws FileNotFoundException {
            super(fileName);
        }

        int getPrecision() {
            return precision;
        }

        void setPrecision(int precision) {
            precision = max(0, precision);
            this.precision = precision;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        String createFormat(int precision){
            return "%." + precision + "f";
        }

        @Override
        public void print(double d){
            printf(format, d);
        }

        void printWithSpace(double d){
            printf(formatWithSpace, d);
        }

        void printAll(double...d){
            for (int i = 0; i < d.length - 1; ++i){
                printWithSpace(d[i]);
            }

            print(d[d.length - 1]);
        }

        @Override
        public void println(double d){
            printlnAll(d);
        }

        void printlnAll(double... d){
            printAll(d);
            println();
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class RuntimeIOException extends RuntimeException {

        /**
         *
         */
        private static final long serialVersionUID = -6463830523020118289L;

        RuntimeIOException(Throwable cause) {
            super(cause);
        }
    }

    /////////////////////////////////////////////////////////////////////
    //////////////// Some useful constants and functions ////////////////
    /////////////////////////////////////////////////////////////////////

    private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private static final int[][] steps8 = {
            {-1, 0}, {1, 0}, {0, -1}, {0, 1},
            {-1, -1}, {1, 1}, {1, -1}, {-1, 1}
    };

    private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
        return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
    }

    private static boolean checkIndex(int index, int lim){
        return (0 <= index && index < lim);
    }

    /////////////////////////////////////////////////////////////////////

    private static boolean checkBit(int mask, int bit){
        return (mask & (1 << bit)) != 0;
    }
    private static boolean checkBit(long mask, int bit){
        return (mask & (1L << bit)) != 0;
    }

    /////////////////////////////////////////////////////////////////////

    private static long getSum(int[] array) {
        long sum = 0;
        for (int value: array) {
            sum += value;
        }

        return sum;
    }

    private static Point getMinMax(int[] array) {
        int min = array[0];
        int max = array[0];

        for (int index = 0, size = array.length; index < size; ++index, ++index) {
            int value = array[index];

            if (index == size - 1) {
                min = min(min, value);
                max = max(max, value);
            } else {
                int otherValue = array[index + 1];

                if (value <= otherValue) {
                    min = min(min, value);
                    max = max(max, otherValue);
                } else {
                    min = min(min, otherValue);
                    max = max(max, value);
                }
            }
        }

        return new Point(min, max);
    }

    /////////////////////////////////////////////////////////////////////

    private static int[] getPrimes(int n) {
        boolean[] used = new boolean[n];
        used[0] = used[1] = true;

        int size = 0;
        for (int i = 2; i < n; ++i) {
            if (!used[i]) {
                ++size;
                for (int j = 2 * i; j < n; j += i) {
                    used[j] = true;
                }
            }
        }

        int[] primes = new int[size];
        for (int i = 0, cur = 0; i < n; ++i) {
            if (!used[i]) {
                primes[cur++] = i;
            }
        }

        return primes;
    }

    /////////////////////////////////////////////////////////////////////

    private static long lcm(long a, long b) {
        return a / gcd(a, b) * b;
    }

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

    /////////////////////////////////////////////////////////////////////

    private static class MultiSet<ValueType> {

        public static <ValueType> MultiSet<ValueType> createMultiSet() {
            Map<ValueType, Integer> multiset = new HashMap<>();
            return new MultiSet<>(multiset);
        }

        private final Map<ValueType, Integer> multiset;
        private int size;

        public MultiSet(Map<ValueType, Integer> multiset) {
            this.multiset = multiset;
            this.size = 0;
        }

        public int size() {
            return size;
        }

        public void inc(ValueType value) {
            int count = get(value);
            multiset.put(value, count + 1);

            ++size;
        }

        public void dec(ValueType value) {
            int count = get(value);
            if (count == 0) return;

            if (count == 1) multiset.remove(value);
            else multiset.put(value, count - 1);

            --size;
        }

        public int get(ValueType value) {
            Integer count = multiset.get(value);
            return (count == null ? 0 : count);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {

        /**
         *
         */
        private static final long serialVersionUID = -3793737771950984481L;

        public IdMap() {
            super();
        }

        int getId(KeyType key) {
            Integer id = super.get(key);
            if (id == null) {
                super.put(key, id = size());
            }

            return id;
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static int[] castInt(List<Integer> list) {
        int[] array = new int[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    private static long[] castLong(List<Long> list) {
        long[] array = new long[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    /**
     * Generates list with values 0..<n
     * @param n - exclusive limit of sequence
     */
    private static List<Integer> order(int n) {
        List<Integer> sequence = new ArrayList<>();
        for (int i = 0; i < n; ++i) {
            sequence.add(i);
        }

        return sequence;
    }
}


//package round588;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

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

	int Q;

	void solve()
	{
		int n = ni();
		int[][] ps = new int[n][];
		for(int i = 0;i < n;i++){
			ps[i] = na(n);
		}

		if(n % 2 == 1){
			n++;
			int[][] nps = new int[n][n];
			nps[n-1][n-1] = 100;
			for(int i = 0;i < n-1;i++){
				for(int j = 0;j < n-1;j++){
					nps[i][j] = ps[i][j];
				}
			}
			ps = nps;
		}

		if(n == 6)Q = 20;
		if(n == 4)Q = 6;
		if(n == 2)Q = 2;

		long ih = invl(100, mod);
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				ps[i][j] = (int)(ps[i][j] * ih % mod);
			}
		}

		int h = n/2;
		long[] l = go(Arrays.copyOfRange(ps, 0, h));
		long[] r = go(Arrays.copyOfRange(ps, h, n));
		long[] nl = new long[l.length];
		for(int i = 0;i < l.length;i++){
			int ii = i;
			for(int j = 0, k = Q-1;j < k;j++,k--){
				if((i>>>j&1) != (i>>>k&1)){
					ii ^= 1<<j|1<<k;
				}
			}
			nl[ii] = l[i];
		}
		l = nl;

		long[] zl = zetaTransform(l);
		long[] zr = zetaTransform(r);
		for(int i = 0;i < zl.length;i++){
			zl[i] = zl[i] * zr[i] % mod;
		}
		long[] me = inverseZetaTransform(zl);
		long ans = 0;
		for(int i = 1;i < me.length;i++){
			ans += me[i];
		}
		out.println(ans%mod);
	}

	public static long invl(long a, long mod) {
		long b = mod;
		long p = 1, q = 0;
		while (b > 0) {
			long c = a / b;
			long d;
			d = a;
			a = b;
			b = d % b;
			d = p;
			p = q;
			q = d - c * q;
		}
		return p < 0 ? p + mod : p;
	}

	public long[] zetaTransform(long[] f)
	{
		int H = Integer.numberOfTrailingZeros(f.length);
		for(int i = 0;i < H;i++){
			for(int j = 0;j < 1<<H;j++){
				if(j<<~i>=0){
					f[j] += f[j|1<<i];
					if(f[j] >= mod)f[j] -= mod;
				}
			}
		}
		return f;
	}

	public long[] inverseZetaTransform(long[] f)
	{
		int H = Integer.numberOfTrailingZeros(f.length);
		for(int i = 0;i < H;i++){
			for(int j = 0;j < 1<<H;j++){
				if(j<<~i>=0){
					f[j] -= f[j|1<<i];
					if(f[j] < 0)f[j] += mod;
				}
			}
		}
		return f;
	}

	int mod = 1000000007;

	long[] go(int[][] ps)
	{
		int h = ps.length;
		int n = ps[0].length;
		long[] l = new long[1<<Q];
		for(int i = 0;i < 1<<h*n;i++){
			long P = 1;
			for(int j = 0;j < h;j++){
				for(int k = 0;k < n;k++){
					if(i<<~(j*n+k)<0){
						P = P * ps[j][k] % mod;
					}else{
						P = P * (mod+1-ps[j][k]) % mod;
					}
				}
			}
			int ptn = 0;
			int p = 0;
			for(int j = 0;j < 1<<n;j++){
				if(Integer.bitCount(j) == h){
					int[] ds = toArray(j);
					int[] ord = ds;
					inner:
					do{
						for(int k = 0;k < h;k++){
							if(i<<~(k*n+ds[k])>=0)continue inner;
						}
						ptn |= 1<<p;
						break;
					}while(nextPermutation(ord));
					p++;
				}
			}
			l[ptn] += P;
			if(l[ptn] >= mod)l[ptn] -= mod;
		}
		return l;
	}

	public static int[] toArray(long x)
	{
		int[] ret = new int[5];
		int p = 0;
		for(;x != 0;x &= x-1){
			ret[p++] = Long.numberOfTrailingZeros(x);
		}
		return Arrays.copyOf(ret, p);
	}

	public static boolean nextPermutation(int[] a) {
		int n = a.length;
		int i;
		for (i = n - 2; i >= 0 && a[i] >= a[i + 1]; i--)
			;
		if (i == -1)
			return false;
		int j;
		for (j = i + 1; j < n && a[i] < a[j]; j++)
			;
		int d = a[i];
		a[i] = a[j - 1];
		a[j - 1] = d;
		for (int p = i + 1, q = n - 1; p < q; p++, q--) {
			d = a[p];
			a[p] = a[q];
			a[q] = d;
		}
		return true;
	}

	void run() throws Exception
	{
//		int n = 6, m = 99999;
//		Random gen = new Random();
//		StringBuilder sb = new StringBuilder();
//		sb.append(n + " ");
//		for (int i = 0; i < n*n; i++) {
//			sb.append(i + " ");
//		}
//		INPUT = sb.toString();

		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.text.DecimalFormat;
import java.util.*;

public class Main {

    private static int []  A,pref;
    private static int [] [] W;
    private static int n;
    private static Integer [] [] [] [] dp;

    private static int getLeft(int lev,int scale) {
        return scale;
    }
    private static int getRight(int lev,int scale) {
        return scale + lev;
    }
    private static int solve(int lev,int scale,int l,int r) {
        l = Math.max(l,getLeft(lev,scale));
        r = Math.min(r,getRight(lev,scale));
        if (l > r) return 0;
        if (lev == 0) return (A[scale] >= W[lev][scale]) ? A[scale] : 0;
        if (dp[lev][scale][l][r] != null) return dp[lev][scale][l][r];
        int ret = 0;
        for (int k = l-1;k <= r;k++)
            ret = Math.max(ret ,solve(lev-1,scale,l,k) + solve(lev-1,scale+1,k+1,r));
        if (ret < W[lev][scale]) ret = 0;
        return dp[lev][scale][l][r] = ret;
    }
    public static void main(String[] args) throws Exception{
        IO io = new IO(null,null);
        n = io.getNextInt();
        A = new int[n];
        pref = new int[n+1];
        W = new int[n][n];
        dp = new Integer[n][n][n][n];
        for (int i = 0;i < n;i++) {
            A[i] = io.getNextInt();
            pref[i + 1] = pref[i] + A[i];
        }
        for (int i = 0;i < n;i++)
            for (int j = 0;j < n-i;j++)
                W[i][j] = io.getNextInt();

        if (solve(n-1,0,0,n-1) != 0) io.println("Cerealguy");
        else io.println("Fat Rat");
        io.close();
    }
}

class IO{
    private BufferedReader br;
    private StringTokenizer st;
    private PrintWriter writer;
    private String inputFile,outputFile;

    public boolean hasMore() throws IOException{
        if(st != null && st.hasMoreTokens()) return true;
        if(br != null && br.ready()) return true;
        return false;
    }
    public String getNext() throws FileNotFoundException, IOException{
        while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    public String getNextLine() throws FileNotFoundException, IOException{
        return br.readLine().trim();
    }

    public int getNextInt() throws FileNotFoundException, IOException{
        return Integer.parseInt(getNext());
    }
    public long getNextLong() throws FileNotFoundException, IOException{
        return Long.parseLong(getNext());
    }

    public void print(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f" ,x);
    }
    public void println(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f\n" ,x);
    }
    public void print(Object o) throws  IOException{
        writer.print(o.toString());
    }

    public void println(Object o) throws  IOException{
        writer.println(o.toString());
    }
    public IO(String x,String y) throws FileNotFoundException, IOException{
        inputFile = x;
        outputFile = y;
        if(x != null) br = new BufferedReader(new FileReader(inputFile));
        else br = new BufferedReader(new InputStreamReader(System.in));
        if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
        else writer = new PrintWriter(new OutputStreamWriter(System.out));
    }

    protected void close() throws IOException{
        br.close();
        writer.close();
    }
    public void outputArr(Object [] A) throws IOException{
        int L = A.length;
        for (int i = 0;i < L;i++) {
            if(i > 0) writer.print(" ");
            writer.print(A[i]);
        }
        writer.print("\n");
    }
}


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

public class CF1202F extends PrintWriter {
	CF1202F() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1202F o = new CF1202F(); o.main(); o.flush();
	}

	void main() {
		int a = sc.nextInt();
		int b = sc.nextInt();
		if (a > b) {
			int tmp = a; a = b; b = tmp;
		}
		int ab = a + b;
		double x = (double) a / ab;
		int upper = 10000000;
		if (upper > ab)
			upper = ab;
		int ans = ab - upper;
		for (int cd = 2; cd <= upper; cd++) {
			int c = (int) (cd * x + 0.5);
			if (c == 0)
				c = 1;
			int d = cd - c;
			if (d > b)
				continue;
			int k = a / c, l = b / d;
			if (k == l || k == l + 1 && a % c == 0 || k == l - 1 && b % d == 0)
				ans++;
		}
		println(ans);
	}
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class Solution implements Runnable {

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

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st;

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

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

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

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

	BigInteger nextBigInteger() throws IOException {
		return new BigInteger(nextToken());
	}

	class Point {
		int x, y;
		Point(int a, int b) {
			x = a; y = b;
		}
	}

	Point[] a;

	double dist(int q, int w) {
		return Math.sqrt((double)(a[q].x - a[w].x) * (a[q].x - a[w].x) + (double)(a[q].y - a[w].y) * (a[q].y - a[w].y));
	}

	void solve() throws Exception {
		int n = nextInt();
		int k = nextInt() - 1;
		a = new Point[n + 1];
		for (int i = 0; i < n; i++) a[i] = new Point(nextInt(), 0);
		a[n] = new Point(nextInt(), nextInt());
		int kk = 0;
		for (int i = 0; i < n; i++) {
			if (a[i].x < a[k].x) kk++;
		}
		if (k < n) k = kk;
		Arrays.sort(a, 0, n, new Comparator<Point>() {
			public int compare(Point o1, Point o2) {
				return o1.x - o2.x;
			}
		});
		double ans;
		if (k == n) {
			ans = Math.min(dist(0, n), dist(n - 1, n)) + dist(0, n - 1);
		} else {
			double qq;
			if (n > 1) {
				qq = dist(0, n) + dist(1, n) - dist(0, 1);
				for (int i = 1; i < n - 1; i++) {
					if (dist(i, n) + dist(i + 1, n) - dist(i, i + 1) < qq) qq = dist(i, n) + dist(i + 1, n) - dist(i, i + 1);
				}
			} else qq = dist(0, 1);
			qq += dist(0, n - 1);
			ans = Math.min(dist(0, k), dist(n - 1, k)) + qq;
			if (k < n - 1) {
				double tmp = dist(0, k) + dist(0, n) + Math.min(dist(n, k + 1), dist(n - 1, n)) + dist(k + 1, n - 1);
				ans = Math.min(ans, tmp);
			}
			if (k > 0) {
				double tmp = dist(n - 1, k) + dist(n - 1, n) + Math.min(dist(n, k - 1), dist(0, n)) + dist(k - 1, 0);
				ans = Math.min(ans, tmp);
			}
			ans = Math.min(ans, dist(0, n - 1) + Math.min(dist(k, 0) + dist(n - 1, n), dist(k, n - 1) + dist(0, n)));
		}
		out.printf("%.7f", ans);
	}

	public void run() {
		try {
			Locale.setDefault(Locale.US);
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
//			in = new BufferedReader(new FileReader(new File("input.txt")));
//			out = new PrintWriter("output.txt");
			solve();
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.flush();
	}

}


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

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

    static class AmusementPark {
        int[] prefMask = new int[20];
        int MOD = 988244353;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int M = in.nextInt();
            boolean[][] connect = new boolean[N][N];
            int[] linked = new int[N];
            for (int i = 0; i < prefMask.length; i++) {
                prefMask[i] = (1 << i) - 1;
            }
            int[] base = new int[N];
            for (int i = 0; i < N; i++) {
                base[i] = i;
            }
            for (int i = 0; i < M; i++) {
                int a = in.nextInt() - 1;
                int b = in.nextInt() - 1;
                linked[a] |= (1 << b);
                linked[b] |= (1 << a);
                connect[a][b] = true;
            }
            CountMap[] maps = new CountMap[(1 << N)];
            for (int i = 0; i < (1 << N); i++) {
                maps[i] = new CountMap();
            }
            maps[0].add((1 << N) - 1, 1);
            long ans = 0;
            for (int i = 0; i < (1 << N); i++) {
                for (Map.Entry<Integer, Integer> mask : maps[i].count.entrySet()) {
                    int nmask = 0;
                    for (int j = 0; j < N; j++) {
                        if (isSet(mask.getKey(), j)) {
                            maps[i | (1 << j)].add(nmask | ((~i) & (linked[j])), mask.getValue());
                            nmask |= (1 << j);
                        }
                    }
                    ans = Math.max(ans, mask.getValue());
                }
            }
            out.println(((ans * MathUtils.inverse(2, MOD) % MOD) * M) % MOD);
        }

        boolean isSet(int mask, int bit) {
            return ((mask & (1 << bit)) > 0);
        }

        class CountMap {
            HashMap<Integer, Integer> count = new HashMap<>();

            void add(int val, int c) {
                Integer x = count.putIfAbsent(val, c);
                if (x != null) {
                    x += c;
                    while (x >= MOD) {
                        x -= MOD;
                    }
                    count.replace(val, x);
                }
            }

        }

    }

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

    }

    static class MathUtils {
        public static long inverse(long a, long mod) {
            long[] inv = extended_gcd(a, mod);
            if (inv[0] != 1) {
                return 0;
            } else {
                return (inv[1] + 2 * mod) % mod;
            }
        }

        public static long[] extended_gcd(long a, long b) {
            //three numbers, first is gcd, second is x, third is y
            if (a == 0) {
                return new long[]{b, 0, 1};
            }
            long[] next = extended_gcd(b % a, a);
            long tempX = next[1];
            next[1] = next[2] - (b / a) * next[1];
            next[2] = tempX;
            return next;
        }

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class E {

    static class cup {
        int x, i, i0;

        cup(int i, int i0) {
            this.i=i; this.i0=i0;
        }
    }

    static cup find_cup(TreeSet<cup> t, int y, int lo, int hi) {
        cup aux=new cup(0, 0);
        while(lo<=hi) {
            int mid=(lo+hi)>>1;
            aux.i=mid;
            SortedSet<cup> sub=t.headSet(aux);
            if(sub.size()==y) {
                return sub.last();
            } else if(sub.size()<y) {
                lo=mid+1;
            } else {
                hi=mid-1;
            }
        }
        throw new IllegalStateException();
    }

    static void run_stream(InputStream ins) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String[] nm=br.readLine().split(" ");
        int n=Integer.parseInt(nm[0]);
        int m=Integer.parseInt(nm[1]);

        TreeSet<cup> t=new TreeSet<cup>(new Comparator<cup>() {
            public int compare(cup o1, cup o2) {
                return o1.i-o2.i;
            }
        });

        for (int i=0; i<n; i++) {
            t.add(new cup(m+i, i));
        }

        for (int i=1; i<=m; i++) {
            String[] xy=br.readLine().split(" ");
            int x=Integer.parseInt(xy[0]);
            int y=Integer.parseInt(xy[1]);

            cup c=find_cup(t, y, m-i, n+m);
            if(c.x>0&&c.x!=x) {
                System.out.println("-1");
                return;
            } else {
                c.x=x;
            }
            t.remove(c);
            c.i=m-i;
            t.add(c);
        }

        int[] out=new int[n];
        boolean[] b=new boolean[n+1]; int j=1;
        for (cup c: t) {
            if(c.x==0) {
                while(b[j]) {
                    j++;
                }
                c.x=j;
            }
            if(b[c.x]) {
                System.out.println("-1");
                return;
            }
            b[c.x]=true;
            out[c.i0]=c.x;
        }

        StringBuilder sb=new StringBuilder();
        for (int i=0; i<n; i++) {
            sb.append(out[i]+" ");
        }
        System.out.println(sb.toString());
    }

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

}