/**
 * Created by IntelliJ IDEA.
 * User: Taras_Brzezinsky
 * Date: 8/24/11
 * Time: 8:54 PM
 * To change this template use File | Settings | File Templates.
 */

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

public class TaskD extends Thread {

    public TaskD() {
        this.input = new BufferedReader(new InputStreamReader(System.in));
        this.output = new PrintWriter(System.out);
        this.setPriority(Thread.MAX_PRIORITY);
    }

    private int getIndex(int[][] data, int[] values) {
        for (int i = 0; i < data.length; ++i) {
            if (Arrays.equals(data[i], values)) {
                return i;
            }
        }
        throw new IllegalArgumentException();
    }

    private void generate(int index) {
        if (index == helper.length) {
            states[SIZE++] = helper.clone();
        } else {
            for (int value = 0; value < v[index]; ++value) {
                helper[index] = value;
                generate(index + 1);
            }
        }
    }

    private int[][] pow(int[][] src, long power) {
        int[][] result = new int[src.length][src.length];
        for (int i = 0; i < result.length; ++i) {
            result[i][i] = 1;
        }
        for (; power != 0; power >>= 1) {
            if ((power & 1) == 1) {
                result = multiply(result, src);
            }
            src = multiply(src, src);
        }
        return result;
    }

    private int[][] multiply(int[][] left, int[][] right) {
        int[][] result = new int[left.length][left.length];
        for (int i = 0; i < left.length; ++i) {
            for (int j = 0; j < left.length; ++j) {
                for (int k = 0; k < left.length; ++k) {
                    result[i][j] += (left[i][k] * right[k][j]) % MODULO;
                }
                result[i][j] %= MODULO;
            }
        }
        return result;
    }

    private void solve() throws Throwable {
        long n = nextLong();
        int c = nextInt();
        l = new int[c];
        v = new int[c];
        int total = 1;
        for (int i = 0; i < c; ++i) {
            l[i] = nextToken().charAt(0) - 'A';
            used[l[i]] = true;
            total *= (v[i] = nextInt());
        }
        states = new int[total][];
        helper = new int[c];
        generate(0);
        int[][] grid = new int[total][total];
        for (int current = 0; current < total; ++current) {
            for (int i = 0; i < AlPHABET_SIZE; ++i) {
                helper = states[current].clone();
                if (used[i]) {
                    for (int ind = 0; ind < c; ++ind) {
                        if (l[ind] == i) {
                            helper[ind] = (helper[ind] + 1) % v[ind];
                        }
                    }
                    grid[current][getIndex(states, helper)]++;
                }
            }
        }
        int[][] result = pow(grid, n);
        int answer = 0;
        for (int currentState = 0; currentState < total; ++currentState) {
            Arrays.fill(good, false);
            for (int i = 0; i < c; ++i) {
                good[l[i]] |= states[currentState][i] == 0;
            }
            boolean can = true;
            for (int i = 0; i < AlPHABET_SIZE; ++i) {
                if (used[i] && !good[i]) {
                    can = false;
                    break;
                }
            }
            if (can) {
                answer = (answer + result[0][currentState]) % MODULO;
            }
        }
        output.println(answer);
    }

    public void run() {
        try {
            solve();
        } catch (Throwable e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(666);
        } finally {
            output.flush();
            output.close();
        }
    }

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

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

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

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

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

    private static int[][] states;
    static private int[] helper, l, v;
    private static int SIZE = 0;
    private static final int MODULO = 12345, AlPHABET_SIZE = 26;
    static boolean[] used = new boolean[AlPHABET_SIZE], good = new boolean[AlPHABET_SIZE];
    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer tokens = null;
}


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

public class cfRound83_D {

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

	final int MOD = 12345;

	int[][] mul(int[][] a, int[][] b) {
		int[][] res = new int[sz][sz];
		for (int i = 0; i < sz; i++)
			for (int j = 0; j < sz; j++)
				for (int k = 0; k < sz; k++) {
					res[i][j] += a[i][k] * b[k][j];
					res[i][j] %= MOD;
				}

		return res;
	}

	int[][] power(int[][] a, long b) {
		if (b == 0) {
			int[][] res = new int[sz][sz];
			for (int i = 0; i < sz; i++)
				res[i][i] = 1;
			return res;
		}

		if ((b & 1) == 1)
			return mul(a, power(a, b - 1));

		int[][] tmp = power(a, b >> 1);
			return mul(tmp, tmp);

	}

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

	int lcm(int a, int b) {
		if (a == 0)
			return b;
		if (b == 0)
			return a;

		return a / gcd(a, b) * b;
	}

	int sz;

	void solve() throws IOException {
		long n = nextLong();

		ArrayList<Integer>[] list = new ArrayList[26];
		for (int i = 0; i < 26; i++)
			list[i] = new ArrayList<Integer>();

		int c = nextInt();

		for (int i = 0; i < c; i++) {
			String s = nextToken();
			int x = nextInt();
			list[s.charAt(0) - 'A'].add(x);
		}

		ArrayList<Integer> can = new ArrayList<Integer>();
		ArrayList<Integer> mult = new ArrayList<Integer>();
		ArrayList<Integer> lcm = new ArrayList<Integer>();

		sz = 1;

		for (int i = 0; i < 26; i++)
			if (!list[i].isEmpty()) {
				int curLcm = 0;
				for (int x : list[i])
					curLcm = lcm(curLcm, x);
				can.add(i);
				mult.add(sz);
				sz *= curLcm;
				lcm.add(curLcm);
			}

		mult.add(sz);

//		System.err.println(can);
//		System.err.println(mult);
//		System.err.println(lcm);

		int[][] matr = new int[sz][sz];

		for (int i = 0; i < sz; i++) {
			for (int j = 0; j < can.size(); j++) {
				int oldRem = i % mult.get(j + 1) / mult.get(j);
				int newRem = (oldRem + 1) % lcm.get(j);
				matr[i - oldRem * mult.get(j) + newRem * mult.get(j)][i]++;
			}
		}

		matr = power(matr, n);

		int ans = 0;

		for (int i = 0; i < sz; i++) {
			boolean goodTotalRem = true;
			for (int j = 0; j < can.size(); j++) {
				int curRem = i % mult.get(j + 1) / mult.get(j);
				boolean goodRem = false;
				for (int good : list[can.get(j)])
					if (curRem % good == 0) {
						goodRem = true;
						break;
					}
				if (!goodRem) {
					goodTotalRem = false;
					break;
				}
			}
			if (goodTotalRem) {
				ans += matr[0][i];
				if (ans >= MOD)
					ans -= MOD;
			}
		}

		out.println(ans);
	}

	void inp() 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 cfRound83_D().inp();
	}

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

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

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

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

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


import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import java.util.*;

public class D{

    int mod=12345;
    void solve()throws Exception
    {
        int ones=0;
        HashMap<Integer,ArrayList<Integer>>map=new HashMap<Integer,ArrayList<Integer>>();
        long n=nextLong();
        int c=nextInt();
        int p=1;
        for(int i=0;i<c;i++)
        {
            int t=nextString().charAt(0)-'A';
            int m=nextInt();
            if(!map.containsKey(t))
                map.put(t,new ArrayList<Integer>());
            map.get(t).add(m);
        }
        int[][]ar=new int[map.size()][];
        int[]l=new int[ar.length];

        int ind=0;
        for(Integer x: map.keySet())
            {
                ArrayList<Integer>t=map.get(x);
                ar[ind]=new int[t.size()];
                int ind2=0;
                l[ind]=1;
                for(int i=0;i<t.size();i++)
                {
                    ar[ind][ind2]=t.get(i);
                    l[ind]=getLcm(l[ind],ar[ind][ind2]);
                    ind2++;
                }
                p*=l[ind];
                ind++;
            }
        long[][]mat=new long[p][p];
        for(int i=0;i<p;i++)
        {
            int[]state=new int[ar.length];
            int cur=i;
            for(int j=0;j<state.length;j++)
            {
                state[j]=cur%l[j];
                cur/=l[j];
            }
            for(int j=0;j<state.length;j++)
            {
                int[]ns=state.clone();
                ns[j]=(ns[j]+1)%l[j];
                cur=0;
                for(int k=state.length-1;k>=0;k--)
                {
                    cur=cur*l[k]+ns[k];
                }
                mat[i][cur]++;
            }

        }
        long[][]res=pow(mat,n);
        long sum=0;
        for(int i=0;i<p;i++)
        {
            int[]state=new int[ar.length];
            int cur=i;
            boolean ok=true;
            for(int j=0;j<state.length;j++)
            {
                state[j]=cur%l[j];
                cur/=l[j];
                boolean  any=false;
                for(int x: ar[j])
                    if(state[j]%x==0)
                        any=true;
                if(!any)
                    ok=false;

            }
            if(ok)
                sum=(sum+res[0][i])%mod;

        }
        System.out.println(sum);

    }

    private int getLcm(int a, int b) {
        return a/BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue()*b;
    }

    private long[][] pow(long[][] mat, long p) {
        if(p==0)
        {
            long[][]res=new long[mat.length][mat.length];
            for(int i=0;i<res.length;i++)
                res[i][i]=1;
            return res;
        }
        long[][]res=pow(mat,p/2);
        res=mul(res,res);
        if(p%2==1)
            res=mul(res,mat);
        return res;
    }

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

    ////////////
    BufferedReader reader;
    PrintWriter writer;
    StringTokenizer stk;
    void run()throws Exception
    {
        reader=new BufferedReader(new InputStreamReader(System.in));
        stk=null;
        writer=new PrintWriter(System.out);
        solve();
        reader.close();
        writer.close();
    }
    int nextInt()throws Exception
    {
        return Integer.parseInt(nextToken());
    }

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

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

    }

    String nextString()throws Exception
    {
        return nextToken();
    }
    String nextLine()throws Exception
    {
        return reader.readLine();
    }
    String nextToken()throws Exception
    {
        if(stk==null || !stk.hasMoreTokens())
        {
            stk=new StringTokenizer(nextLine());
            return nextToken();

        }
        return stk.nextToken();
    }

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

}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: piyushd
 * Date: 3/29/11
 * Time: 7:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class TaskD {

    int[] product;
    int[][] I;
    final int MOD = 12345;

    int[] decode(int code) {
        int[] a = new int[26];
        for(int i = 0; i < 26; i++) {
            a[i] = code % product[i];
            code /= product[i];
        }
        return a;
    }

    int encode(int[] a) {
        int code = 0;
        for(int i = 25; i >= 0; i--) {
            code = code * product[i] + a[i];
        }
        return code;
    }

    int[][] matrixMult(int[][] a, int[][] b) {
        int[][] c = new int[a.length][a.length];
        for(int k = 0; k < a.length; k++) {
            for(int i = 0; i < a.length; i++) {
                for(int j = 0; j < a.length; j++) {
                    c[i][j] += a[i][k] * b[k][j];
                    c[i][j] %= MOD;
                }
            }
        }
        return c;
    }

    int[][] matrixExponentiation(int[][] a, long N) {
        if(N == 0) return this.I;

        if(N % 2 == 0) {
            int[][] x = matrixExponentiation(a, N / 2);
            return matrixMult(x, x);
        }

        return matrixMult(a, matrixExponentiation(a, N - 1));
    }

    void run() {
        long N = nextLong();
        int c = nextInt();

        ArrayList<Integer>[] multiplicities = new ArrayList[26];
        for(int i = 0; i < multiplicities.length; i++) multiplicities[i] = new ArrayList<Integer>();

        for(int i = 0; i < c; i++) {
            String character = next();
            int multiple = nextInt();
            multiplicities[character.charAt(0) - 'A'].add(multiple);
        }

        int M = 1;
        this.product = new int[26];
        for (int i = 0; i < 26; i++) {
            product[i] = 1;
            for (int x : multiplicities[i])
                product[i] *= x;
            M *= product[i];
        }

        int[][] a = new int[M][M];
        for(int i = 0; i < M; i++) {
            for(int j = 0; j < 26; j++) if(multiplicities[j].size() > 0) {
                int[] d = decode(i);
                d[j]++;
                d[j] %= product[j];
                int code = encode(d);
                a[i][code]++;
            }
        }

        this.I = new int[M][M];
        for(int i = 0; i < M; i++) I[i][i] = 1;

        int[][] na = matrixExponentiation(a, N);

        int ans = 0;
        for(int code = 0; code < M; code++) {
            int[] d = decode(code);

            boolean ok = true;
            for(int j = 0; j < 26 && ok; j++) if(multiplicities[j].size() > 0) {
                boolean got = false;
                for(int x : multiplicities[j])
                    if(d[j] % x == 0) got = true;
                ok = got;
            }

            if(ok) {
                ans = (ans + na[0][code]) % MOD;
            }
        }

        System.out.println(ans);
    }

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

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

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

    String next(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(Character.isWhitespace(c))
                c = System.in.read();
            do{
                res.append((char)c);
            }while(!Character.isWhitespace(c=System.in.read()));
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

    String nextLine(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(c == '\r' || c == '\n')
                c = System.in.read();
            do{
                res.append((char)c);
                c = System.in.read();
            }while(c != '\r' && c != '\n');
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

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


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

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

	void solve()
	{
		long n = nl();
		int m = ni();
		int[] alp = new int[m];
		int[] val = new int[m];
		int r = 1;
		for(int i = 0;i < m;i++){
			alp[i] = nc()-'A';
			val[i] = ni();
			r *= val[i];
		}
		int[][] g = packD(26, alp, val);
		int[] mul = new int[26];
		for(int i = 0;i < 26;i++){
			mul[i] = 1;
			for(int j : g[i]){
				mul[i] *= j;
			}
		}

		int[][] M = new int[r][r];
		for(int i = 0;i < r;i++){
			int[] a = dec(i, mul);
			for(int j = 0;j < 26;j++){
				if(g[j].length > 0){
					a[j] = (a[j]+1)%mul[j];
					M[enc(a, mul)][i]++;
					a[j] = (a[j]+mul[j]-1)%mul[j];
				}
			}
		}

		int[] v = new int[r];
		v[0] = 1;
		int[] rv = pow(M, v, n);
		int ret = 0;
		outer:
		for(int i = 0;i < r;i++){
			int[] a = dec(i, mul);
			for(int j = 0;j < 26;j++){
				if(g[j].length > 0){
					boolean ok = false;
					for(int k : g[j]){
						if(a[j] % k == 0){
							ok = true;
							break;
						}
					}
					if(!ok)continue outer;
				}
			}
			ret += rv[i];
		}
		out.println(ret % MOD);
	}

	int[] dec(int a, int[] mul)
	{
		int n = mul.length;
		int[] ret = new int[n];
		for(int i = 0;i < n;i++){
			ret[i] = a % mul[i];
			a /= mul[i];
		}
		return ret;
	}

	int enc(int[] a, int[] mul)
	{
		int n = a.length;
		int ret = 0;
		for(int i = n-1;i >= 0;i--){
			ret = ret * mul[i]+a[i];
		}
		return ret;
	}

	public static int MOD = 12345;

	// int行列*ベクトル
	public static int[] mul(int[][] A, int[] v)
	{
		int m = A.length;
		int n = v.length;
		int[] w = new int[m];
		for(int i = 0;i < m;i++){
			long sum = 0;
			for(int k = 0;k < n;k++){
				sum += (long)A[i][k] * v[k];
				sum %= MOD;
			}
			w[i] = (int)sum;
		}
		return w;
	}

	// int行列の2乗
	public static int[][] p2(int[][] A)
	{
		int n = A.length;
		int[][] C = new int[n][n];
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				long sum = 0;
				for(int k = 0;k < n;k++){
					sum += (long)A[i][k] * A[k][j];
					sum %= MOD;
				}
				C[i][j] = (int)sum;
			}
		}
		return C;
	}

	// A^e*v
	public static int[] pow(int[][] A, int[] v, long e)
	{
		int[][] MUL = A;
		for(;e > 0;e>>>=1) {
			if((e&1)==1)v = mul(MUL, v);
			MUL = p2(MUL);
		}
		return v;
	}

	public static int[][] packD(int n, int[] from, int[] to)
	{
		int[][] g = new int[n][];
		int[] p = new int[n];
		for(int f : from)p[f]++;
		for(int i = 0;i < n;i++)g[i] = new int[p[i]];
		for(int i = 0;i < from.length;i++){
			g[from[i]][--p[from[i]]] = to[i];
		}
		return g;
	}

	void run() throws Exception
	{
//		long n = 1000000000000000000L;
//		int c = 1000;
//		Random gen = new Random();
//		StringBuilder sb = new StringBuilder();
//		sb.append(n + " ");
//		sb.append(c + " ");
//		for (int i = 0; i < c-2; i++) {
//			sb.append((char)(gen.nextInt(26)+'A') + " " + 1 + " ");
//		}
//		sb.append((char)(gen.nextInt(26)+'A') + " " + 3 + " ");
//		sb.append((char)(gen.nextInt(26)+'A') + " " + 41 + " ");
//		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 D3().run();
	}

	char nc() {
		try {
			int b;
			while ((b = is.read()) != -1
					&& (b == ' ' || b == '\r' || b == '\n'))
				;
			if (b == -1)
				return 0;
			return (char) b;
		} catch (IOException e) {
		}
		return 0;
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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

public class B {

	static int n, t[], g[], MOD = (int) 1e9 + 7;
	static int[][][] memo1, memo2[], memo3[];

	static int dp1(int idx, int remCnt, int remSum) {
		if (idx == n)
			return remSum == 0 && remCnt == 0 ? 1 : 0;
		if (remCnt < 0 || remSum < 0)
			return 0;
		if (memo1[idx][remCnt][remSum] != -1)
			return memo1[idx][remCnt][remSum];
		int ans = dp1(idx + 1, remCnt, remSum);
		if (g[idx] == 0) {
			ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]);
			if (ans >= MOD)
				ans -= MOD;
		}
		return memo1[idx][remCnt][remSum] = ans;
	}

	static int dp2(int idx, int remCnt1, int remCnt2, int remSum) {

		if (idx == n)
			return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0;
		if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0)
			return 0;
		if (memo2[idx][remCnt1][remCnt2][remSum] != -1)
			return memo2[idx][remCnt1][remCnt2][remSum];
		int ans = dp2(idx + 1, remCnt1, remCnt2, remSum);

		if (g[idx] == 1)
			ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]);
		else if (g[idx] == 2)
			ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]);

		return memo2[idx][remCnt1][remCnt2][remSum] = ans;
	}

	private static int dp3(int cnt0, int cnt1, int cnt2, int last) {
		if (cnt0 + cnt1 + cnt2 == 0)
			return 1;
		if (memo3[last][cnt0][cnt1][cnt2] != -1)
			return memo3[last][cnt0][cnt1][cnt2];
		long ans = 0;
		if (cnt0 > 0 && last != 0)
			ans += dp3(cnt0 - 1, cnt1, cnt2, 0);
		if (cnt1 > 0 && last != 1)
			ans += dp3(cnt0, cnt1 - 1, cnt2, 1);
		if (cnt2 > 0 && last != 2)
			ans += dp3(cnt0, cnt1, cnt2 - 1, 2);
		return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD);

	}

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		n = sc.nextInt();
		int[] fac = new int[n + 1];
		t = new int[n];
		g = new int[n];
		int[] cnt = new int[3];
		fac[0] = 1;
		for (int i = 1; i <= n; i++)
			fac[i] = (int) (i * 1L * fac[i - 1] % MOD);
		int T = sc.nextInt();
		for (int i = 0; i < n; i++) {
			t[i] = sc.nextInt();
			g[i] = sc.nextInt() - 1;
			cnt[g[i]]++;

		}
		memo1 = new int[n][cnt[0] + 1][T + 1];
		memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1];
		memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j <= cnt[0]; j++)
				Arrays.fill(memo1[i][j], -1);
			for (int j = 0; j <= cnt[1]; j++)
				for (int k = 0; k <= cnt[2]; k++)
					Arrays.fill(memo2[i][j][k], -1);

		}
		for (int i = 0; i < 4; i++)
			for (int j = 0; j <= cnt[0]; j++)
				for (int k = 0; k <= cnt[1]; k++)
					Arrays.fill(memo3[i][j][k], -1);
		int ans = 0;
		for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++)
			for (int sum0 = 0; sum0 <= T; sum0++)
				for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++)
					for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) {
						long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD;
						ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD;
						ways *= fac[cnt0];
						ways %= MOD;
						ways *= fac[cnt1];
						ways %= MOD;
						ways *= fac[cnt2];
						ways %= MOD;
						ans += ways;
						if (ans >= MOD)
							ans -= MOD;
					}
		out.println(ans);
		out.close();

	}

	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

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

		Scanner(String fileName) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(fileName));
		}

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

		String nextLine() throws IOException {
			return br.readLine();
		}

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

		long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}

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

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

	}

}


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

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

class TaskE {
    final int mod = (int) 1e9 + 7;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int k = in.readInt();
        int[][] c = Combinatorics.GetCombinations(n, n, mod);
        int[][][][] dp = new int[n + 2][n + 2][2][2];
        dp[0][0][0][1] = 1;
        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j <= i; ++j) {
                for (int first = 0; first < 2; ++first) {
                    for (int second = 0; second < 2; ++second) {
                        if (first == 1) {
                            if (j > 0) {
                                dp[i][j][second][1] += dp[i - 1][j - 1][first][second];
                                dp[i][j][second][1] %= mod;
                            }
                        }
                        if (i < n && j > 0) {
                            dp[i][j][second][0] += dp[i - 1][j - 1][first][second];
                            dp[i][j][second][0] %= mod;
                        }
                        dp[i][j][second][1] += dp[i - 1][j][first][second];
                        dp[i][j][second][1] %= mod;
                    }
                }
            }
        }
        long[] fact = new long[n + 5];
        fact[0] = 1;
        for (int i = 1; i <= n; ++i) {
            fact[i] = fact[i - 1] * i;
            fact[i] %= mod;
        }
        long[] f = new long[n + 1];
        for (int i = 0; i <= n; ++i) {
            f[i] = 0;
            for (int first = 0; first < 2; ++first) {
                for (int second = 0; second < 2; ++second) {
                    f[i] += dp[n][i][first][second];
                    f[i] %= mod;
                }
            }
            f[i] *= fact[n - i];
            f[i] %= mod;
        }

        for (int i = n; i >= 0; --i) {
            for (int j = i + 1; j <= n; ++j) {
                f[i] -= (f[j] * c[j][i]) % mod;
                f[i] += mod;
                f[i] %= mod;
            }
        }
        out.println(f[k]);
    }
}

class InputReader {

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

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

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

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

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

    }

class Combinatorics {
    public static int[][] GetCombinations(int n, int m, int MOD) {
        int[][] c = new int[n + 1][m + 1];
        c[0][0] = 1;
        for (int i = 1; i <= n; ++i) {
            c[i][0] = 1;
            for (int j = 1; j < i && j <= m; ++j) {
                c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
                if (c[i][j] >= MOD) {
                    c[i][j] -= MOD;
                }
            }
            c[i][i] = 1;
        }
        return c;
    }

    }


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;

public class myFile
{
	public static void main(String args[])
	{
	   Scanner sc = new Scanner(System.in);
	   int i,n,k;
	   while(sc.hasNextInt())
	   {
		   n = sc.nextInt();
		   k = sc.nextInt();
		   sc.nextLine();
		   String str = sc.nextLine();
		   if(n==1 && k==1)
		   {
			   System.out.println("0");
			   continue;
		   }
		   StringBuilder sb = new StringBuilder(str);
		   if(str.charAt(0)!='1' && k>0)
		   {
			   sb.setCharAt(0, '1');
			   k--;
		   }
		   for(i=1;k>0 && i<str.length();i++)
		   {
			   if(str.charAt(i)!='0') {
				   k--;
				   sb.setCharAt(i, '0');
			   }
		   }
		   System.out.println(sb);
	   }

	}

}


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

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

	final static int PERIOD = 60;
	final static int POWER = 13;

	long fib(long n, long mod) {
		long[][] mat = new long[2][2];
		mat[0][1] = mat[1][0] = mat[1][1] = 1;
		Matrix v = new Matrix(mat);
		v = v.power(n, mod);
		return v.mat[0][1];
	}

	void run() {
		InputReader in = new InputReader(System.in);
		PrintWriter out = new PrintWriter(System.out);

		long num = in.nextLong(), mod = 10, per = PERIOD;
		ArrayList<Long> valid = new ArrayList<Long>();
		for (int i = 0; i < PERIOD; ++i)
			if (fib(i, mod) == num % mod)
				valid.add((long)i);

		for (int i = 1; i < POWER; ++i) {
			mod *= 10;
			long rem = num % mod;
			ArrayList<Long> nv = new ArrayList<Long>();
			for (int j = 0; j < 10; ++j)
				for (int k = 0; k < valid.size(); ++k) {
					if (fib(j * per + valid.get(k), mod) == rem)
						nv.add(j * per + valid.get(k));
				}
			valid = nv;
			per *= 10;
		}

		if (valid.size() == 0)
			out.println(-1);
		else
			out.println(valid.get(0));
		out.close();
	}
}

class Matrix {
	long[][] mat;
	final static Matrix ONE = new Matrix(new long[][] {{1, 0}, {0, 1}});
	Matrix(long[][] mat) {
		this.mat = mat;
	}
	long add(long a, long b, long mod) {
		if (a + b >= mod)
			return a + b - mod;
		return a + b;
	}
	long multiply(long a, long b, long mod) {
		long ret = 0;
		while (a > 0) {
			if ((a & 1) == 1)
				ret = add(ret, b, mod);
			b = add(b, b, mod);
			a >>= 1;
		}
		return ret;
	}
	Matrix multiply(Matrix o, long mod) {
		long[][] ret = new long[2][2];
		for (int i = 0; i < 2; ++i)
			for (int j = 0; j < 2; ++j)
				for (int k = 0; k < 2; ++k)
					ret[i][j] = add(ret[i][j], multiply(mat[i][k], o.mat[k][j], mod), mod);
		return new Matrix(ret);
	}
	Matrix power(long p, long mod) {
		if (p == 0) {
			return Matrix.ONE;
		}
		Matrix ret = power(p / 2, mod);
		ret = ret.multiply(ret, mod);
		if ((p & 1) == 1)
			ret = ret.multiply(this, mod);
		return ret;
	}
}

class InputReader {
	BufferedReader buff;
	StringTokenizer tokenizer;

	InputReader(InputStream stream) {
		buff = new BufferedReader(new InputStreamReader(stream));
		tokenizer = null;
	}
	boolean hasNext() {
		while (tokenizer == null || !tokenizer.hasMoreTokens())
			try {
				tokenizer = new StringTokenizer(buff.readLine());
			}
			catch (Exception e) {
				return false;
			}
		return true;
	}
	String next() {
		if (!hasNext())
			throw new RuntimeException();
		return tokenizer.nextToken();
	}
	int nextInt() { return Integer.parseInt(next()); }
	long nextLong() { return Long.parseLong(next()); }
}


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

public class Solution {
    final static long MOD = 10000000000000L;

    long multiply(long a, long b) {
        return BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)).remainder(BigInteger.valueOf(MOD)).longValue();
    }

    long[][] multiply(long[][] a, long[][] b) {
        long[][] c = new long[2][2];
        for (int i = 0; i < 2; ++ i) {
            for (int j = 0; j < 2; ++ j) {
                c[i][j] = (multiply(a[i][0], b[0][j]) + multiply(a[i][1], b[1][j])) % MOD;
            }
        }
        return c;
    }

    long[][] pow(long[][] a, long n) {
        long[][] ret = new long[][] {{1, 0}, {0, 1}};
        while (n > 0) {
            if (n % 2 == 1) {
                ret = multiply(ret, a);
            }
            a = multiply(a, a);
            n >>= 1;
        }
        return ret;
    }

    long fibonacci(long n) {
        return multiply(new long[][] {{0, 1}, {0, 0}}, pow(new long[][]{{0, 1}, {1, 1}}, n))[0][0];
    }

    public void run() {
        try {
            long m = reader.nextLong();
            ArrayList <Long> indices = new ArrayList <Long>();
            indices.add(0L);
            long period = 1;
            for (long mod = 10; mod <= MOD; mod *= 10) {
                ArrayList <Long> newIndices = new ArrayList <Long>();
                int times = mod == 10 ? 60 : mod <= 1000 ? 5 : 10;
                for (long iter : indices) {
                    long now = iter;
                    for (int i = 0; i < times; ++ i) {
                        if (fibonacci(now) % mod == m % mod) {
                            newIndices.add(now);
                        }
                        now += period;
                    }
                }
                period *= times;
                indices = newIndices;
            }
            Collections.sort(indices);
            writer.println(indices.isEmpty() ? -1 : indices.get(0));
        } catch (IOException ex) {
        }
        writer.close();
    }

    InputReader reader;
    PrintWriter writer;

    Solution() {
        reader = new InputReader();
        writer = new PrintWriter(System.out);
    }

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

}

class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;

    InputReader() {
        reader = new BufferedReader(new InputStreamReader(System.in));
        tokenizer = new StringTokenizer("");
    }

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

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

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


//package round122;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

	void solve()
	{
		int M2 = 1<<13;
		int M5 = 5*5*5*5*5*5*5*5*5*5*5*5*5;

		long f = nl();
		int x2 = (int)(f % M2);
		int[] fa2 = new int[M2];
		int[] a2 = new int[1<<14];
		a2[0] = 0;
		a2[1] = 1;
		Arrays.fill(fa2, -1);
		fa2[0] = 0;
		fa2[1] = 1;
		for(int i = 2;i < 13000;i++){
			a2[i] = (a2[i-1] + a2[i-2]) % M2;
			if(fa2[a2[i]] == -1)fa2[a2[i]] = i;
		}
		if(fa2[x2] == -1){
			out.println(-1);
			return;
		}

		int f5 = (int)(f%5);
		List<Long> l = new ArrayList<Long>();
		{
			int[] a = new int[20];
			a[0] = 0;
			a[1] = 1;
			for(int i = 2;i < 4*5;i++){
				a[i] = (a[i-1] + a[i-2]) % 5;
			}
			for(int i = 0;i < 4*5;i++){
				if(a[i] == f5){
					l.add((long)i);
				}
			}
		}

		int[][] F = {
				{1, 1}, {1, 0}
		};
		for(long m = 25;m <= M5;m*=5){
			int fm = (int)(f % m);
			List<Long> nl = new ArrayList<Long>();
			for(long ll : l){
				for(int k = 0;k < 5;k++){
					long ne = ll+k*4*(m/5);
					long nf = 0;
					if(ne == 0){
						nf = 0;
					}else{
						nf = pow(F, new int[]{1, 0}, ne-1, (int)m)[0];
					}
					if(nf == fm){
						nl.add(ne);
					}
				}
			}
			l = nl;
		}

		long min = Long.MAX_VALUE;
		for(long ll : l){
			for(int i = 0;i < a2.length;i++){
				if(a2[i] == f % M2){
					long num = crtx(new long[]{M2*3/2, 4L*M5}, new long[]{i, ll}).longValue();
					if(num >= 0){
						min = Math.min(min, num);
					}
				}
			}
//			long num = crt(M2*3/2, fa2[x2], 4L*M5, ll);
		}
		if(min == Long.MAX_VALUE){
			out.println(-1);
		}else{
			out.println(min);
		}
	}

	public static long crt(long p, long m, long q, long n)
	{
		long[] apr = exGCD(p, q);
		if((n - m) % apr[0] != 0)return -1;
		long mod = p * q / apr[0];
		long a = (apr[1] * (n - m) / apr[0] * p + m) % mod;
		if(a < 0)a += mod;
		return a;
	}

	// int行列*ベクトル
	public static int[] mul(int[][] A, int[] v, int mod)
	{
		int m = A.length;
		int n = v.length;
		int[] w = new int[m];
		for(int i = 0;i < m;i++){
			long sum = 0;
			for(int k = 0;k < n;k++){
				sum += (long)A[i][k] * v[k];
				sum %= mod;
			}
			w[i] = (int)sum;
		}
		return w;
	}

	// int行列の2乗
	public static int[][] p2(int[][] A, int mod)
	{
		int n = A.length;
		int[][] C = new int[n][n];
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				long sum = 0;
				for(int k = 0;k < n;k++){
					sum += (long)A[i][k] * A[k][j];
					sum %= mod;
				}
				C[i][j] = (int)sum;
			}
		}
		return C;
	}

	public static BigInteger[] exGCD(BigInteger a, BigInteger b)
	{
		BigInteger p = BigInteger.ONE, q = BigInteger.ZERO, r = BigInteger.ZERO, s = BigInteger.ONE;
		while(b.signum() > 0){
			BigInteger c = a.divide(b);
			BigInteger d;
			d = a; a = b; b = d.mod(b);
			d = p; p = q; q = d.subtract(c.multiply(q));
			d = r; r = s; s = d.subtract(c.multiply(s));
		}
		return new BigInteger[]{a, p, r};
	}

	public static BigInteger bi(long x){ return BigInteger.valueOf(x); }

	public static BigInteger crtx(long[] divs, long[] mods)
	{
		BigInteger div = bi(divs[0]), mod = bi(mods[0]);
		for(int i = 1;i < divs.length;i++){
			BigInteger[] apr = exGCD(div, bi(divs[i]));
			BigInteger mm = bi(mods[i]).subtract(mod);
			if(mm.mod(apr[0]).signum() != 0)return bi(-1);
			BigInteger da = div.divide(apr[0]);
			BigInteger ndiv = bi(divs[i]).multiply(da);
			BigInteger nmod = apr[1].multiply(mm).multiply(da).add(mod).mod(ndiv);
			if(nmod.signum() < 0)nmod = nmod.add(ndiv);
			div = ndiv;
			mod = nmod;
		}
		return mod;
	}

	// A^e*v
	public static int[] pow(int[][] A, int[] v, long e, int mod)
	{
		int[][] MUL = A;
		for(;e > 0;e>>>=1) {
			if((e&1)==1)v = mul(MUL, v, mod);
			MUL = p2(MUL, mod);
		}
		return v;
	}

	public static long[] exGCD(long a, long b)
	{
		long p = 1, q = 0, r = 0, s = 1;
		while(b > 0){
			long c = a / b;
			long d;
			d = a; a = b; b = d % b;
			d = p; p = q; q = d - c * q;
			d = r; r = s; s = d - c * s;
		}
		return new long[]{a, p, r};
	}

	void run() throws Exception
	{
		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 E2().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
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
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
    static final long MODULO = (long) 1e13;

    private long[][] mul(long[][] a, long[][] b, long modulo) {
        long[][] c = new long[2][2];
        for (int i = 0; i < 2; ++i)
            for (int j = 0; j < 2; ++j) {
                BigInteger sum = BigInteger.ZERO;
                for (int k = 0; k < 2; ++k)
                    sum = sum.add(BigInteger.valueOf(a[i][k]).multiply(BigInteger.valueOf(b[k][j])));
                c[i][j] = sum.mod(BigInteger.valueOf(modulo)).longValue();
            }
        return c;
    }

    static class Candidate {
        long offset;
        long[][] trans;

        Candidate(long offset, long[][] trans) {
            this.offset = offset;
            this.trans = trans;
        }
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        long f = in.nextLong();
        long mod = 1;
        long period = 1;
        long[][] mPeriod = new long[][]{new long[]{0, 1}, new long[]{1, 1}};
        List<Candidate> offsets = new ArrayList<Candidate>();
        offsets.add(new Candidate(0, new long[][]{new long[]{1, 0}, new long[]{0, 1}}));
        for (int i = 0; i < 26; ++i) {
            if (i < 13)
                mod *= 2;
            else
                mod *= 5;
            long nperiod = period;
            long[][] nmPeriod = mPeriod;
            while (nmPeriod[0][1] % mod != 0 || nmPeriod[1][1] % mod != 1) {
                nmPeriod = mul(nmPeriod, mPeriod, MODULO);
                nperiod += period;
            }
            List<Candidate> newOffsets = new ArrayList<Candidate>();
            for (Candidate old : offsets) {
                long[][] trans = old.trans;
                for (long noffset = old.offset; noffset < nperiod; noffset += period) {
                    if ((trans[0][1] % mod == f % mod)) {
                        newOffsets.add(new Candidate(noffset, trans));
                    }
                    trans = mul(trans, mPeriod, MODULO);
                }
            }
            offsets = newOffsets;
            period = nperiod;
            mPeriod = nmPeriod;
        }
        long min = Long.MAX_VALUE;
        for (Candidate c : offsets)
            min = Math.min(min, c.offset);
        if (min == Long.MAX_VALUE) out.println(-1); else out.println(min);
	}
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

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

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

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

    }


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

public class D {

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

    final int ROOT = 46300;

    ArrayList<Integer> primes;

    int ind;

    int go(int x, int div, int sign, int lastInd) {
        //System.err.println(x + " " + div + " " + sign + " " + lastInd);
        if (x < div)
            return 0;
        int res = sign * (x / div);
        for (int i = lastInd + 1; i < ind; i++) {
            if (primes.get(i) > x / div)
                break;
            res += go(x, div * primes.get(i), -sign, i);
        }
        return res;
    }

    int go(int x) {
        return go(x, 1, 1, -1);
    }

    void solve() throws IOException {
        int l = nextInt();
        int r = nextInt();
        int k = nextInt();

        boolean[] isPrime = new boolean[ROOT];
        Arrays.fill(isPrime, true);

        primes = new ArrayList<Integer>();

        for (int i = 2; i < ROOT; i++) {
            if (isPrime[i]) {
                primes.add(i);
                for (int j = i * i; j < ROOT; j += i)
                    isPrime[j] = false;
            }
        }

        for (int p : primes) if (k != p && k % p == 0) {
            out.print(0);
            return;
        }

        if (k > ROOT) {
            if (l <= k && k <= r)
                out.print(1);
            else
                out.print(0);
            return;
        }

        ind = Collections.binarySearch(primes, k);

        if (l % k == 0)
            l /= k;
        else
            l = l / k + 1;

        r /= k;

        //System.err.println(go(7));

        out.print(go(r) - go(l - 1));

    }

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

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

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

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

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

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

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

}


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

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

class E {
    public double[][][][] dp;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int x = in.nextInt();
        int k = in.nextInt();
        int p = in.nextInt();
        dp = new double[2][256][251][2];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 256; j++) {
                for (int u = 0; u < 251; u++) {
                    dp[i][j][u][0] = 0;
                    dp[i][j][u][1] = 0;
                }
            }
        }
        int y=x/256;
        if(y==0) {
            dp[0][x&255][0][0]=1;
        } else {
            if((y&1)==0) {
                int z=0;
                for(; (y&1)==0; z++) {
                    y>>=1;
                }
                dp[0][x&255][z][0]=1;
            } else {
                int z=0;
                for(; (y&1)>0; z++) {
                    y>>=1;
                }
                dp[0][x&255][z][1]=1;
            }
        }
        for(int i=0; i<k; i++) {

            for(int j=0; j<256; j++) {
                for (int u = 0; u < 250; u++) {
                    dp[(i+1)&1][j][u][0]=0;
                    dp[(i+1)&1][j][u][1]=0;
                }
            }
            for(int j=0; j<256; j++) {
                for(int u=0; u<250; u++) {
                    if((j&128)>0) {
                        dp[(i+1)&1][(j<<1)&255][1][1]+=dp[i&1][j][u][0]*p*0.01;
                        dp[(i+1)&1][(j<<1)&255][u+1][1]+=dp[i&1][j][u][1]*p*0.01;
                    } else {
                        dp[(i+1)&1][(j<<1)&255][u+1][0]+=dp[i&1][j][u][0]*p*0.01;
                        dp[(i+1)&1][(j<<1)&255][1][0]+=dp[i&1][j][u][1]*p*0.01;
                    }
                    if(j==255) {
                        dp[(i+1)&1][0][1][1]+=dp[i&1][j][u][0]*(1-p*0.01);
                        dp[(i+1)&1][0][u][0]+=dp[i&1][j][u][1]*(1-p*0.01);
                    } else {
                        dp[(i+1)&1][j+1][u][0]+=dp[i&1][j][u][0]*(1-p*0.01);
                        dp[(i+1)&1][j+1][u][1]+=dp[i&1][j][u][1]*(1-p*0.01);
                    }
                }
            }
        }
        double ans=0;
        for(int j=0; j<256; j++) {
            int cnt=0;
            if(j>0) {
                for (int t = j; (t & 1) == 0; cnt++) {
                    t >>= 1;
                }
            }
            for(int u=0; u<250; u++) {
                if(j==0) {
                    ans+=dp[k&1][0][u][0]*(8+u);
                    ans+=dp[k&1][0][u][1]*8;
                } else {
                    ans+=dp[k&1][j][u][0]*cnt;
                    ans+=dp[k&1][j][u][1]*cnt;
                }
            }
        }
        out.printf("%.13f\n",ans);
    }
}

class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

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

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

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

}


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

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

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

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

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

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

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

    public static void main(String[] args) {

        new Test().start();

    }
}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Test {
  static PrintWriter writer =
      new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
  int R, C;
  long[][] ch = new long[61][61];
  int[] cntA = new int[61], cntB = new int[61];
  long best = Long.MAX_VALUE;
  String str;
  Map<Long, Long> cache = new HashMap<>();
  Set<Long> tried = new HashSet<>();

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

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

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

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

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

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

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

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


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

public class F {

	long[][] ways;

	static class Half implements Comparable<Half> {
		long match;
		long value;

		public Half(long match, long value) {
			this.match = match;
			this.value = value;
		}

		@Override
		public int compareTo(Half o) {
			return Long.compare(value, o.value);
		}
	}

	boolean nextCombination(int[] a, int n) {
		int k = a.length;
		int ptr = k - 1;
		while (ptr >= 0 && a[ptr] == ptr - k + n) {
			ptr--;
		}
		if (ptr < 0) {
			return false;
		}
		a[ptr]++;
		for (int i = ptr + 1; i < k; i++) {
			a[i] = a[ptr] + i - ptr;
		}
		return true;
	}

	long getWins(char[] s, int r, int c) {
		int curA = 0;
		int curB = 0;
		long ret = 0;
		for (char cc : s) {
			if (cc == 'A') {
				curA++;
			} else {
				ret += choose(curB, r - 1) * choose(curA, r);
				curB++;
			}
		}
		return ret;
	}

	long slow(int r, int c, String s) {
		int[] as = new int[r + c];
		for (int i = 0; i < r + c; i++) {
			as[i] = i;
		}
		long totalWays = ways[r + c][r] * ways[r + c][c];

		char[] buf = new char[2 * (r + c)];

		long bestDiff = Integer.MAX_VALUE;
		long ans = 0;

		List<String> good = new ArrayList<>();

		outer: do {
			Arrays.fill(buf, 'B');
			for (int pos : as) {
				buf[pos] = 'A';
			}
			int match = 1;
			for (int i = 0; i < 2 * (r + c); i++) {
				if (s.charAt(i) != '?' && s.charAt(i) != buf[i]) {
					match = 0;
					break;
				}
			}
			long winsA = getWins(buf, r, c);
			long diff = Math.abs(2 * winsA - totalWays);
			if (diff < bestDiff) {
				bestDiff = diff;
				good.clear();
				if (match == 1)
				good.add(new String(buf));
				ans = match;
			} else if (diff == bestDiff) {
				ans += match;
				if (match == 1)
				good.add(new String(buf));
			}
		} while (nextCombination(as, 2 * (r + c)));
//		System.err.println(good);
		return ans;
	}

	long solve(int r, int c, String s) {

		bestDiff = Long.MAX_VALUE;
		ans = 0;

		long maskA = 0;
		long maskB = 0;
		int[][] cnt = new int[s.length() + 1][2];
		for (int i = 0; i < s.length(); i++) {
			cnt[i + 1] = cnt[i].clone();
			if (s.charAt(i) == 'A') {
				cnt[i + 1][0]++;
				maskA |= 1L << i;
			}
			if (s.charAt(i) == 'B') {
				cnt[i + 1][1]++;
				maskB |= 1L << i;
			}
		}

		long lastA = maskA >> (2 * r + c - 1);
		long lastB = maskB >> (2 * r + c - 1);

		Half[][] fst = new Half[c + 2][];
		Half[][] snd = new Half[c + 2][];
		int[] sz = new int[c + 2];
		for (int i = 0; i < c + 2; i++) {
			sz[i] = (int) ways[c + 1][i];
			fst[i] = new Half[sz[i]];
			snd[i] = new Half[sz[i]];
		}

		for (int mask = 0; mask < 1 << (c + 1); mask++) {
			// 0 - a, 1 - b
			int btc = Integer.bitCount(mask);
			int compBtc = c + 1 - btc;
			int idx = --sz[btc];
			{
				int samePref = Math.min(Integer
						.numberOfTrailingZeros((mask & 1) == 0 ? mask
								: (mask + 1)), c + 1);

				int totalA = r - 1 - cnt[2 * r - 2 + samePref][0];
				int totalB = r - 1 - cnt[2 * r - 2 + samePref][1];
				if ((mask & 1) == 0) {
					totalA += samePref;
				} else {
					totalB += samePref;
				}

				long winsA = 0;

				int curA = 0;
				int curB = 0;
				for (int i = 0; i < c + 1; i++) {
					if (test(mask, i)) {
						winsA += ways[r - 1 + curB][r - 1]
								* choose(r - 1 + curA, r);
						curB++;
					} else {
						curA++;
					}
				}

				// can be optimized into some bit operations
				int exactMatch = 1;
				for (int i = samePref; i < c + 1; i++) {
					if (!test(mask, i) && s.charAt(2 * r - 2 + i) == 'B') {
						exactMatch = 0;
						break;
					}
					if (test(mask, i) && s.charAt(2 * r - 2 + i) == 'A') {
						exactMatch = 0;
						break;
					}
				}

				fst[btc][idx] = new Half(choose(totalA + totalB, totalA)
						* exactMatch, winsA);
			}

			{
				int match = 1;
				if (((~mask) & lastB) != 0) {
					match = 0;
				}
				if ((mask & lastA) != 0) {
					match = 0;
				}

				long winsA = 0;

				int curA = btc;
				int curB = compBtc;
				for (int i = 0; i < c + 1; i++) {
					if (test(mask, i)) {
						winsA += ways[r - 1 + curB][r - 1]
								* choose(r - 1 + curA, r);
						curB++;
					} else {
						curA++;
					}
				}

				snd[btc][idx] = new Half(match, winsA);
			}
		}

		totalWays = ways[r + c][r] * ways[r + c][r];
		long halfTotal = totalWays / 2;

		for (int i = 0; i <= c + 1; i++) {
			Half[] one = compress(fst[i]);
			Half[] two = compress(snd[c + 1 - i]);

			int ptr = two.length - 1;

			for (Half a : one) {
				while (ptr >= 0 && a.value + two[ptr].value > halfTotal) {
					ptr--;
				}
				if (ptr >= 0) {
					update(a, two[ptr]);
				}
				if (ptr + 1 < two.length) {
					update(a, two[ptr + 1]);
				}
			}
		}
		return ans;
	}

	void submit() {
		int r = nextInt();
		int c = nextInt();
		String s = nextToken();
		out.println(solve(r, c, s));
	}

	long totalWays;

	long bestDiff = Long.MAX_VALUE;
	long ans = 0;

	void update(Half a, Half b) {
		long totalValue = a.value + b.value;
		long diff = Math.abs(2 * totalValue - totalWays);
		long delta = a.match * b.match;
		if (diff < bestDiff) {
			bestDiff = diff;
			ans = delta;
		} else if (diff == bestDiff) {
			ans += delta;
		}
	}

	Half[] compress(Half[] arr) {
		Arrays.sort(arr);
		int sz = 1;
		for (int i = 1; i < arr.length; i++) {
			if (arr[i].value == arr[sz - 1].value) {
				arr[sz - 1].match += arr[i].match;
			} else {
				arr[sz++] = arr[i];
			}
		}
		return Arrays.copyOf(arr, sz);
	}

	long choose(int n, int k) {
		return n >= 0 && k >= 0 && k <= n ? ways[n][k] : 0;
	}

	static boolean test(int mask, int i) {
		return ((mask >> i) & 1) == 1;
	}

	void preCalc() {
		ways = new long[61][];
		for (int i = 0; i < ways.length; i++) {
			ways[i] = new long[i + 1];
			ways[i][0] = ways[i][i] = 1;
			for (int j = 1; j < i; j++) {
				ways[i][j] = ways[i - 1][j - 1] + ways[i - 1][j];
			}
		}
	}

	void stress() {
		for (int tst = 0;; tst++) {
			int r = rand(1, 3);
			int c = rand(1, 3);
			char[] buf = new char[2 * (r + c)];
			Arrays.fill(buf, '?');
			String s = new String(buf);
			long fast = solve(r, c, s);
			long slow = slow(r, c, s);
			if (fast != slow) {
				System.err.println(r + " " + c + " " + s);
				System.err.println(fast);
				System.err.println(slow);
				throw new AssertionError();
			}
			System.err.println(tst + " passed");
		}
	}

	void test() {
		int r = 1;
		int c = 3;
		String s = "ABBAABBA";
		System.err.println(solve(r, c, s));
//		System.err.println(slow(r, c, s));
	}

	F() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		preCalc();
		 submit();
//		stress();
//		 test();
		out.close();
	}

	static final Random rng = new Random();

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

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

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;

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

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

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

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

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


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

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

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

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

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

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

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

    public static void main(String[] args) {

        new Test().start();

    }
}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    public static void main(String[] args) {

        new Test().start();

    }
}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    public static void main(String[] args) {

        new Test().start();

    }
}


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

public class Prob03 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] L = new int[N];
        int[] R = new int[N];
        for (int i = 0; i < N; i++) {
            L[i] = in.nextInt();
            R[i] = in.nextInt();
        }
        double[] probabilities = new double[10001];
        for (int i = 0; i < N; i++) {
            for (int j = L[i]; j <= R[i]; j++) {
                double prob = 1./(R[i]-L[i]+1);
                //count probability j to be the second largest
                double probResult = 0;
                outer:
                for (int k = 0; k < N; k++) {
                    if (i == k) continue;

                    double probMax = (1.*R[k] - j)/(R[k]-L[k]+1);
                    if (probMax < 0) continue;
                    if (i < k && L[k]<=j && R[k] >= j)  probMax += 1./(R[k]-L[k]+1);
                    if (probMax > 1) probMax = 1;

                    for (int m = 0; m < N; m++) {
                        if (m==i || m == k) continue;
                        double probMin = (1.*j - L[m])/(R[m]-L[m]+1);
                        if (probMin < 0) continue outer;
                        if (m < i && L[m]<=j && R[m] >= j)  probMin += 1./(R[m]-L[m]+1);
                        if (probMin > 1) probMin = 1;
//                        System.out.println("second: " + j + " max prob: " + probMax + " min prob: " + probMin);
                        probMax *= probMin;
                    }
                    probResult += probMax;
                }
                prob *= probResult;
                probabilities[j] += prob;
//                System.out.println(Arrays.toString(probabilities));
            }
        }

        double sum = 0;
        double prob = 0;
        for (int i = 1; i < 10001; i++) {
            sum += i *probabilities[i];
            prob += probabilities[i];
        }
//        System.out.println(sum);
//        System.out.println(sum / prob);
        System.out.println(String.format("%.9f", sum));
    }

}


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

public class Main {
//	static Scanner in;
	static PrintWriter out;
	static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
//	static BufferedReader in;

	static TreeSet<Long> set = new TreeSet<Long>();
	static int n;
	static int[] x;

	static void count(int[] kol) {
		//System.out.println("!");
	    long a = 0;
		for (int i = 0; i < n; i++) a = a*n + x[i];
		set.add(a);

		int c = 0;
		for (int i = 0; i < n; i++) if (kol[i] > 0) c++;
		if (c < 2) return;

		for (int i = 0; i < n; i++) if (kol[i] > 0) {
			for (int j = i + 1; j < n; j++) if (kol[j] > 0) {
				int[] kol2 = new int[n];
				for (int t = 0; t < n; t++) kol2[t] = kol[t];
				kol2[i]--;
				kol2[j]--;
				int temp = x[i];
				x[i] = x[j];
				x[j] = temp;
				count(kol2);
				temp = x[i];
				x[i] = x[j];
				x[j] = temp;
			}
		}
	}

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

		n = next();

		int[] kol = new int[n];
		for (int i = 0; i < n; i++) kol[i] = next();
		int ones = 0;
		int twos = 0;
		for (int i = 0; i < n; i++)
			if (kol[i] == 1) ones++;
			else twos++;

		int mod = 1000000007;

		long[][] d = new long[n + 1][n + 1];
		int[][] c = new int[n + 1][n + 1];
		for (int i = 0; i <= n; i++) c[i][0] = c[i][i] = 1;
		for (int i = 0; i <= n; i++)
			for (int j = 1; j < i; j++) c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;

		int[] f = new int[n + 1];
		f[0] = 1;
		for (int i = 0; i < n; i++) f[i + 1] = (int)((1L * f[i] * (i + 1)) % mod);

		int[][] a = new int[n + 1][n + 1];
		for (int i = 0; i < n; i++)
			for (int j = 0; j <= i; j++) a[i][j] = (int)(c[i][j] * 1L * f[j] % mod);

		for (int i = 0; i <= ones; i++)
			for (int j = 0; j <= twos; j++) {
				if (i <= 2) d[i][j] = f[i + j];
				else {
					d[i][j] = d[i - 1][j];
					for (int k = 1; k <= j; k++)
						d[i][j] += (a[j][k] * d[i - 1][j - k]) % mod;
					for (int k = 0; k <= j; k++)
						d[i][j] += (i - 1) * a[j][k] * (k + 1) % mod * d[i - 2][j - k] % mod;
					d[i][j] %= mod;
				}
			}

		out.println(d[ones][twos]);

/*		x = new int[n];
		for (int i = 0; i < n; i++) x[i] = i;
		count(kol);

		out.println(set.size());*/

		out.close();
	}
}


import java.io.*;
import java.util.*;
public class z3 {
	public static void main(String[] args) throws IOException {
		StreamTokenizer in;
		PrintWriter out;
		in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
		out = new PrintWriter(new OutputStreamWriter(System.out));

		 in.nextToken();
		 int n=(int) in.nval;
	int[] a = new int[n];
	for (int i=0;i<n;i++) {in.nextToken(); a[i]=(int) in.nval;}
	in.nextToken();
	int t=(int) in.nval;
	int temp;
	for (int i=0;i<t;i++) {in.nextToken(); temp=(int) in.nval;a[temp-1]=-Math.abs(a[temp-1]);}
	if ((n%2)!=0) {out.println("NO");out.flush();}
	else
	  {
		int kol=0;int[] st=new int[n+1];
		  for (int i=n-1;i>=0;i--)
		  {
			  if (kol==0) {kol=1;st[kol]=Math.abs(a[i]);a[i]=-st[kol];} else
			  {
				  if (st[kol]==a[i]) kol-=1; else
				  {kol+=1;st[kol]=Math.abs(a[i]);a[i]=-st[kol];}
			  }
		  }
		  if (kol!=0) {out.println("NO");out.flush();} else
		  {
			  out.println("YES");
			  for (int i=0;i<n;i++) out.print(""+a[i]+" ");
			  out.flush();
		  }
	}
}
}


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

class TaskE {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.nextInt();
        if (n % 2 != 0) {
            out.print("NO");
            return;
        }
        int[] p = new int[n];
        for (int i = 0; i < n; i++) {
            p[i] = in.nextInt();
        }
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int k = in.nextInt();
            p[k - 1] *= -1;
        }

        int[] s = new int[n];
        int h = -1;

        for (int i = n - 1; i >= 0; i--) {
            if (p[i] < 0 || h < 0 || s[h] != p[i]) {
                if (p[i] > 0)
                    p[i] *= -1;
                h++;
                s[h] = -p[i];
            } else {
                h--;
            }
        }

        if (h >= 0) {
            out.print("NO");
            return;
        }

        out.println("YES");
        for (int i = 0; i < n; i++) {
            out.print(p[i]);
            out.print(' ');
        }
    }
}

class InputReader {
    private StreamTokenizer tokenizer;

    public InputReader(InputStream stream) {
        Reader r = new BufferedReader(new InputStreamReader(stream));
        tokenizer = new StreamTokenizer(r);
        tokenizer.eolIsSignificant(false);
    }

    public int nextInt() {
        try {
            int i = tokenizer.nextToken();
            if (i == StreamTokenizer.TT_NUMBER)
                return (int) tokenizer.nval;
            else
                throw new InputMismatchException();
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

    }