/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

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

public class Codeforces429D
{

	InputStream in;
	PrintWriter out;

	long MAX=Long.MAX_VALUE;
	void solve()
	{
		long f=nl();
		long T=nl();
		long t0=nl();
		long a1,t1,p1,a2,t2,p2;
		a1=nl();t1=nl();p1=nl();
		a2=nl();t2=nl();p2=nl();

		long max1=f/a1;
		long max2=f/a2;
		long cost=MAX;

		if (t1<t2)
		{
			for (int k1=0;k1<=max1;k1++)
			{
				long sz=f-k1*a1;

				long l=0,r=sz/a2,result=-1,t=a1*k1*t1;
				long td;
				while (l<=r)
				{
					long mid=((l+r)>>1);
					td=a2*mid;
					if (t+td*t2+(sz-td)*t0 <= T)
					{
						result=mid;
						r=mid-1;
					}
					else
					{
						l=mid+1;
					}
				}

				if (t+sz*t2<=T)
					cost=Math.min(cost, k1*p1+((sz+a2-1)/a2)*p2);

				if (result!=-1)
				{
					cost=Math.min(cost, k1*p1+result*p2);
				}

			}

			if (f*t1<=T)
				cost=Math.min(cost, ((f+a1-1)/a1)*p1);
		}
		else
		{
			for (int k2=0;k2<=max2;k2++)
			{
				long sz=f-k2*a2;

				long l=0,r=sz/a1,result=-1,t=a2*k2*t2;
				long td;
				while (l<=r)
				{
					long mid=((l+r)>>1);
					td=a1*mid;
					if (t+td*t1+(sz-td)*t0<=T)
					{
						result=mid;
						r=mid-1;
					}
					else
					{
						l=mid+1;
					}
				}

				if (t+sz*t1<=T)
					cost=Math.min(cost, k2*p2+((sz+a1-1)/a1)*p1);

				if (result!=-1)
				{
					cost=Math.min(cost, k2*p2+result*p1);
				}

			}

			if (f*t2<=T)
				cost=Math.min(cost, ((f+a2-1)/a2)*p2);
		}

		if (cost==MAX)
			out.println(-1);
		else
			out.println(cost);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		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 Codeforces429D().run();
	}

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

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

	private boolean inSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

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

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

	private char nc()
	{
		return (char) skip();
	}

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

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

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

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

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

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

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

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

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

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

}


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

public class Codeforces913F {
	public static void main(String[] args) throws IOException {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int a = input.nextInt();
		int b = input.nextInt();
		input.close();
		final int mod = 998244353;

		int frac = multiply(a, inverse(b, mod), mod);
		int reverse = (mod+1-frac)%mod;

		int[] fracpower = new int[n+1];
		int[] reversepower = new int[n+1];
		fracpower[0] = 1;
		reversepower[0] = 1;
		for (int i = 1; i <= n; i++) {
			fracpower[i] = multiply(fracpower[i-1], frac, mod);
			reversepower[i] = multiply(reversepower[i-1], reverse, mod);
		}

		int[][] dp1 = new int[n+1][n+1];
		dp1[2][1] = 1;
		for (int i = 3; i <= n; i++) {
			for (int j = 1; j < i; j++) {
				if (j == 1) {
					dp1[i][j] = fracpower[i-1];
				}
				else {
					dp1[i][j] = multiply(dp1[i-1][j-1], fracpower[i-j], mod);
				}
				if (j == i-1) {
					dp1[i][j] += reversepower[i-1];
					dp1[i][j] %= mod;
				}
				else {
					dp1[i][j] += multiply(dp1[i-1][j], reversepower[j], mod);
					dp1[i][j] %= mod;
				}
			}
		}

		int[][] dp2 = new int[n+1][n+1];
		dp2[1][1] = 1;
		dp2[2][1] = 1;
		dp2[2][2] = 0;
		for (int i = 3; i <= n; i++) {
			int val = 0;
			for (int j = 1; j < i; j++) {
				dp2[i][j] = multiply(dp2[j][j], dp1[i][j], mod);
				val += dp2[i][j];
				val %= mod;
			}
			dp2[i][i] = (mod+1-val)%mod;
		}

		/*for (int i = 2; i <= n; i++) {
			for (int j = 1; j <= i; j++) {
				System.out.print(dp2[i][j] + " ");
			}
			System.out.println();
		}*/

		int[] EV = new int[n+1];
		EV[1] = 0;
		EV[2] = 1;
		for (int i = 3; i <= n; i++) {
			int val = 0;
			for (int j = 1; j < i; j++) {
				int r = j*(i-j) + (j*(j-1))/2 + EV[i-j] + EV[j];
				r %= mod;
				val += multiply(dp2[i][j], r, mod);
				val %= mod;
			}
			val += multiply((i*(i-1))/2, dp2[i][i], mod);
			val %= mod;

			int s = (mod+1-dp2[i][i])%mod;
			EV[i] = multiply(val, inverse(s, mod), mod);
		}

		System.out.println(EV[n]);
	}

	public static int multiply(int a, int b, int mod) {
		long x = (long)a*(long)b;
		return (int) (x%mod);
	}

	public static int inverse (int a, int n) {
		int m = n;
		int r1 = 1;
		int r2 = 0;
		int r3 = 0;
		int r4 = 1;
		while ((a > 0) && (n > 0)) {
			if (n >= a) {
				r3 -= r1*(n/a);
				r4 -= r2*(n/a);
				n = n%a;
			}
			else {
				int tmp = a;
				a = n;
				n = tmp;
				tmp = r1;
				r1 = r3;
				r3 = tmp;
				tmp = r2;
				r2 = r4;
				r4 = tmp;
			}
		}
		if (a == 0) {
			if (r3 >= 0)
				return (r3%m);
			else
				return (m+(r3%m));
		}
		else {
			if (r1 >= 0)
				return (r1%m);
			else
				return (m+(r1%m));
		}

	}
}


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

public class MainE {

    private FastScanner in;
    private PrintWriter out;

    long MOD = 998244353L;

    long[] gcd_ex(long a, long b) {
        if (a == 0) {
            return new long[]{0, 1};
        }
        long[] res = gcd_ex(b % a, a);
        long t = res[0];
        res[0] = res[1] - (b / a) * res[0];
        res[1] = t;
        return res;
    }

    long reverse(long a) {
        return (gcd_ex(a, MOD)[0] + 100 * MOD) % MOD;
    }

    long powMod(long a, long b) {
        long res = 1;
        long mul = a;
        while (b > 0) {
            if ((b & 1) > 0) {
                res = (res * mul) % MOD;
            }
            mul = (mul * mul) % MOD;
            b /= 2;
        }
        return res;
    }

    public void solve() {
        long N = in.nextInt();
        long[] combs = new long[(int)(N + 1)];
        combs[0] = 1;
        for (int i = 1; i <= N; i++) {
            long t = combs[i - 1];
            t = (t * (N - i + 1)) % MOD;
            t = (t * reverse(i)) % MOD;
            combs[i] = t;
        }
        long res = 0;
        long p1 = 1;
        long p2 = 1;
        long R = powMod(reverse(3), N);
        for (int i = 1; i <= N; i++) {
            p1 = (p1 * R) % MOD;
            p2 = (p2 * 3) % MOD;
            long t = combs[i] * p1 % MOD;
            t = (t * p2) % MOD;
            if ((i & 1) > 0) {
                res += 2 * t;
            } else {
                res = (res + 2 * MOD - 2 * t) % MOD;
            }
            res %= MOD;
        }
        res = res * powMod(3, N * N) % MOD;
        long i3 = 1;
        for (int i = 0; i < N; i++){
            long mi3 = (MOD - i3) % MOD;
            i3 = (i3 * 3) % MOD;
            long t = combs[i] * ((MOD + powMod(1 + mi3, N) - powMod(mi3, N)) % MOD);
            if ((i & 1) > 0) {
                res += 3 * t;
            } else {
                res = (res + 3 * MOD - 3 * t) % MOD;
            }
            res %= MOD;
        }
        System.out.println(res);
    }

    public void run() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    class FastScanner {

        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

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

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

    public static void main(String[] arg) {
        new MainE().run();
    }
}


import java.util.Scanner;

public class F {
  static Scanner sc = new Scanner(System.in);
  static final double logE = Math.log(Math.E);

  public static void main(String[] args) {
    int V = sc.nextInt();
    double[] factLog = new double[5001];
    for (int i = 1; i < factLog.length; i++) {
      factLog[i] = Math.log(i) + factLog[i - 1];
    }
    for (int i = 0; i < V; i++) {
      int[] K = new int[250];
      int min = 0;
      int max = 0;
      long sum = 0;
      long sum2 = 0;
      for (int j = 0; j < K.length; j++) {
        K[j] = sc.nextInt();
        min = Math.min(min, K[j]);
        max = Math.max(max, K[j]);
        sum += K[j];
        sum2 += K[j] * K[j];
      }
      double ave = 1.0 * sum / K.length;
      double ave2 = 1.0 * sum2 / K.length;
      double var = ave2 - ave * ave;
      System.err.println("var:" + var);
      double uniform = -Math.log(2 * Math.max(0, Math.max(max, -min) + 1)) * K.length;
      double poisson = -Double.MAX_VALUE;
      for (int j = Math.max(1, Math.max(-min, (int) var - 100)); j <= (int) var + 300; j++) {
        double likelyhood = 0;
        for (int k = 0; k < K.length; k++) {
          likelyhood += (K[k] + j) * Math.log(j) - j * logE - factLog[K[k] + j];
        }
        if (likelyhood > poisson) {
          poisson = likelyhood;
        }
      }
      System.err.println(uniform + " " + poisson);
      System.out.println(uniform < poisson ? "poisson" : "uniform");
    }
  }

}


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

public class Div2_421C {

	public static void main(String[] args) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer inputData = new StringTokenizer(reader.readLine());
		int a = Integer.parseInt(inputData.nextToken());
		int b = Integer.parseInt(inputData.nextToken());
		int l = Integer.parseInt(inputData.nextToken());
		int r = Integer.parseInt(inputData.nextToken());

		StringBuilder cString = new StringBuilder();
		for (int i = 0; i < a; i++) {
			cString.append((char) ('a' + i));
		}
		char last = cString.charAt(cString.length() - 1);
		for (int i = 0; i < b; i++) {
			cString.append(last);
		}
		TreeSet<Integer> used = new TreeSet<Integer>();
		for (char c : cString.substring(cString.length() - a, cString.length()).toCharArray()) {
			used.add(c - 'a');
		}

		int nxt = 0;
		for (int i = 0; i < a; i++) {
			while (used.contains(nxt)) {
				nxt++;
			}
			cString.append((char) ('a' + nxt));
			nxt++;
		}

		last = cString.charAt(cString.length() - 1);
		for (int i = 0; i < b; i++) {
			cString.append(last);
		}

		int len = cString.length();

		used.clear();
		if (r - l + 1 >= len) {
			for (char c : cString.toString().toCharArray()) {
				used.add(c - 'a');
			}
		} else {
			for (int i = l; i != (r + 1) % len; i = (i + 1) % len) {
				used.add(cString.charAt(i) - 'a');
			}
		}
		System.out.println(used.size());
	}

}


import java.util.Scanner;

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

	long x=scan.nextLong();

		if(x%2==1){
			System.out.print(x/2);
		}

		else{
			long y=1;
			while (y<=x){
				y=y*2;
			}
			y=y/2;
			System.out.print((x-y)/2);

		}
}
}


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

public class MethodTest {

	static final int P = 1_000_000_007;

	static void submit() {
		int n = nextInt();
		int m = nextInt();
		long exp = nextLong();
		int[] a = new int[n];
		int[] b = new int[m];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		int maxCoef = 0;
		for (int i = 0; i < m; i++) {
			b[i] = nextInt();
			maxCoef = Math.max(maxCoef, b[i]);
		}

		int[] bPoly = new int[maxCoef + 1];
		bPoly[maxCoef] = 1;
		for (int pow : b) {
			bPoly[maxCoef - pow]--;
			if (bPoly[maxCoef - pow] < 0) {
				bPoly[maxCoef - pow] += P;
			}
		}

		int[] aPoly = {};
		for (int pow : a) {
			aPoly = sum(aPoly, quotPow(new int[] { 0, 1 }, bPoly, pow));
		}
		int[] ans = quotPow(aPoly, bPoly, exp);

		ans = prod(ans, quotPow(new int[] { 0, 1 }, bPoly, maxCoef));
		ans = quot(ans, bPoly);

		out.println((long)ans[0] * inv(P - bPoly[0]) % P);
	}

	static int inv(int x) {
		return x == 1 ? 1 : P - (int)((long)(P / x) * inv(P % x) % P);
	}

	static int[] quotPow(int[] a, int[] b, long n) {
		a = quot(a, b);
		int[] ret = { 1 };
		for (; n > 0; n >>= 1) {
			if ((n & 1) == 1) {
				ret = quot(prod(ret, a), b);
			}
			a = quot(prod(a, a), b);
		}
		return ret;
	}

	static int[] sum(int[] a, int[] b) {
		int[] c = Arrays.copyOf(a, Math.max(a.length, b.length));
		for (int i = 0; i < b.length; i++) {
			c[i] += b[i];
			if (c[i] >= P) {
				c[i] -= P;
			}
		}
		return c;
	}

	static int[] prod(int[] a, int[] b) {
		int[] c = new int[a.length + b.length - 1];
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < b.length; j++) {
				c[i + j] += (int) ((long) a[i] * b[j] % P);
				if (c[i + j] >= P) {
					c[i + j] -= P;
				}
			}
		}
		return c;
	}

	static int[] quot(int[] a, int[] b) {
		a = a.clone();
		// leading coef of b is 1
		if (a.length < b.length) {
			return a;
		}
		int degB = b.length - 1;
		for (int ptr = a.length - 1; ptr >= degB; ptr--) {
			long coef = a[ptr];
			for (int i = 0, j = ptr - degB; i < degB; i++, j++) {
				a[j] -= (int) (coef * b[i] % P);
				if (a[j] < 0) {
					a[j] += P;
				}
			}
		}
		return Arrays.copyOf(a, degB);
	}

	static void preCalc() {

	}

	static void stress() {

	}

	static void test() {

	}

	public static void run() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		preCalc();
		submit();
		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 {
		run();
	}

	static BufferedReader br;
	static PrintWriter out;
	static StringTokenizer st;

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

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

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

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

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


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

public class MainD {
	static final StdIn in = new StdIn();
	static final PrintWriter out = new PrintWriter(System.out);
	static final long M=(long)1e9+7;
	static int n=in.nextInt(), m=in.nextInt();
	static Map<Integer, Node> graph = new HashMap<Integer, Node>();

	public static void main(String[] args) {
		addNode(1);
		for(int i=0; i<m; ++i) {
			int u=in.nextInt(), v=in.nextInt();
			addNode(u).adj.add(v);
			addNode(v).adj.add(u);
		}
		for(Map.Entry<Integer, Node> nodeEntry : graph.entrySet()) {
			Node u=nodeEntry.getValue();
			for(int i=u.adj.size()-1; i>=0; --i) {
				if(!graph.containsKey(u.adj.get(i))) {
					u.s+=sts(u.adj.get(i));
					u.adj.remove(i);
				}
			}
		}
		long ans=0;
		for(Map.Entry<Integer, Node> nodeEntry : graph.entrySet())
			ans=(dfs(nodeEntry.getKey(), 0)+ans)%M;
		out.println(ans);
		out.close();
	}

	static Node addNode(int u) {
		if(u<=0)
			return null;
		Node node = graph.get(u);
		if(node!=null)
			return node;
		node = new Node();
		if(u>1)
			node.adj.add(u/2);
		if(u*2<=n)
			node.adj.add(u*2);
		if(u*2+1<=n)
			node.adj.add(u*2+1);
		graph.put(u, node);
		addNode(u/2);
		return node;
	}

	static long sts(int u) {
		long res=0;
		int l=u, r=u;
		while(r<=n) {
			res+=r-l+1;
			l=2*l;
			r=2*r+1;
		}
		return (res+Math.min(r, n)-Math.min(l, n+1)+1)%M;
	}

	static long dfs(int u, long ps) {
		Node node=graph.get(u);
		if(ps==0)
			ps=node.s;
		node.active=true;
		long res=ps*node.s;
		for(int v : node.adj)
			if(!graph.get(v).active)
				res+=dfs(v, ps);
		node.active=false;
		return res;
	}

	static class Node {
		List<Integer> adj = new ArrayList<Integer>();
		long s=1;
		boolean active;
	}

	interface Input {
		public String next();
		public String nextLine();
		public int nextInt();
		public long nextLong();
		public double nextDouble();
	}
	static class StdIn implements Input {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;
		public StdIn() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public StdIn(InputStream in) {
			try{
				din = new DataInputStream(in);
			} catch(Exception e) {
				throw new RuntimeException();
			}
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public String next() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == ' ' || c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c=read();
			}
			return s.toString();
		}
		public String nextLine() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c = read();
			}
			return s.toString();
		}
		public int nextInt() {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}
		public int[] readIntArray(int n) {
			int[] ar = new int[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextInt();
			return ar;
		}
		public long nextLong() {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
		public long[] readLongArray(int n) {
			long[] ar = new long[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextLong();
			return ar;
		}
		public double nextDouble() {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (c == '.')
				while ((c = read()) >= '0' && c <= '9')
					ret += (c - '0') / (div *= 10);
			if (neg)
				return -ret;
			return ret;
		}
		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}
		private byte read() {
			try{
				if (bufferPointer == bytesRead)
					fillBuffer();
				return buffer[bufferPointer++];
			} catch(IOException e) {
				throw new RuntimeException();
			}
		}
		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
}


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

public class ab6 {

    public static void debug(Object... obs)
    {
        System.out.println(Arrays.deepToString(obs));
    }

    static int[][]h;
    static int[][]w;

    public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());
        int k=Integer.parseInt(st.nextToken());
        int t=Integer.parseInt(st.nextToken());

        h=new int[k][k];
        w=new int[k][k];

        for(int i=0;i<k;i++)
        {
            st=new StringTokenizer(br.readLine());
            int hi=Integer.parseInt(st.nextToken())-1;
            int wi=Integer.parseInt(st.nextToken())-1;
            int ri=Integer.parseInt(st.nextToken());
            h[hi][wi]=ri;
            w[wi][hi]=ri;
        }

        boolean[]dp=new boolean[30];
        boolean[]ah=new boolean[n];
        boolean[]aw=new boolean[n];

        bld_h(0,dp,ah,aw,0,n,h,w);

        dp[0]=true;

        //debug(dp);

        for(int i=0;i<dp.length;i++)
        {
            if(dp[i])
            {
                if(t==1)
                {
                    System.out.println(i);
                    return;
                }
                else
                {
                    t--;
                }
            }
        }

    }

    private static void bld_h(int pos, boolean[] dp,boolean[]ah,boolean[]aw, int su,int n,int[][]hi,int[][]wi)
    {
        if(pos==n) return;

        for(int i=0;i<n;i++)
        {
            if(ah[i]) continue;

            ah[i]=true;
            for(int j=0;j<n;j++)
            {
                if(!aw[j] && hi[i][j]>0)
                {
                    su+=hi[i][j];
                    dp[su]=true;
                    aw[j]=true;
                    bld_h(pos+1,dp,aw,ah,su,n,wi,hi);

                    aw[j]=false;
                    su-=hi[i][j];
                }
            }
            ah[i]=false;
        }
    }
}


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

public class cfCEOI2019Day1B {

	static class HLD {
		int n, root;

		private int[][] g;
		private int[] sz;
		private int timePtr = 0;

		// parent of node, time -> time
		public int[] par;

		// tree traversal, time -> node
		int[] time2Node;

		// time when you get in/out of the node
		// Subtree of v has times [ v; rgh(v) )
		int[] node2Time; // node -> time
		int[] rgh; // time -> time

		// lft and order are inverse permutations

		// depth, time -> int
		int[] depth;

		// if chainInfo[v] < 0 then v is the head of chain with id =
		// (~chainInfo[v]), time->chainId
		// if chainInfo[v] >=0 then chainInfo[v] is the head of chain that v
		// belongs to, time->time
		private int[] chainInfo;

		// top-most node of the corresponding chain, chainId -> time
		int[] chainHead;

		int chainCnt = 0;
		private int[] buf;

		public HLD(int[] vs, int[] us, int root) {
			n = vs.length + 1;
			this.root = root;
			if (vs.length != us.length) {
				throw new AssertionError("vs.length != us.length");
			}
			if (!(0 <= root && root < n)) {
				throw new AssertionError("bad root");
			}

			// Building the graph.
			int[] deg = new int[n];
			for (int i = 0; i < n - 1; i++) {
				if (!(0 <= vs[i] && vs[i] < n && 0 <= us[i] && us[i] < n && vs[i] != us[i])) {
					throw new AssertionError("bad node in edge");
				}
				deg[vs[i]]++;
				deg[us[i]]++;
			}
			g = new int[n][];
			for (int i = 0; i < n; i++) {
				g[i] = new int[deg[i]];
			}
			for (int i = 0; i < n - 1; i++) {
				int v = vs[i];
				int u = us[i];
				g[v][--deg[v]] = u;
				g[u][--deg[u]] = v;
			}

			// Find sizes/parents and reorder children.
			sz = new int[n];
			dfsSz(root, -1);

			// Find the chains/subtree ranges.
			par = new int[n];
			par[0] = -1;

			depth = new int[n];
			time2Node = new int[n];
			node2Time = new int[n];
			rgh = new int[n];

			chainHead = new int[n];
			chainHead[chainCnt] = 0;

			chainInfo = new int[n];
			chainInfo[0] = ~(chainCnt++);

			dfsChains(root, -1);

			chainHead = Arrays.copyOf(chainHead, chainCnt);
			buf = new int[3 * chainCnt];
		}

		/**
		 * @return list of triplets [chainId; pos1; pos2] in order corresponding
		 *         to the path from v to u

		 *         pos1 <= pos2 = going down

		 *         pos1 > pos2 = going up
		 */
		public int[] getPath(int v, int u) {
			int headPtr = 0, tailPtr = buf.length;
			int chV = chainId(v), upV = chainHead[chV], chU = chainId(u), upU = chainHead[chU];
			while (chV != chU) {
				if (depth[upV] > depth[upU]) {
					buf[headPtr] = chV;
					buf[headPtr + 1] = v - upV;
					buf[headPtr + 2] = 0;
					headPtr += 3;
					v = par[upV];
					chV = chainId(v);
					upV = chainHead[chV];
				} else {
					buf[tailPtr - 3] = chU;
					buf[tailPtr - 2] = 0;
					buf[tailPtr - 1] = u - upU;
					tailPtr -= 3;
					u = par[upU];
					chU = chainId(u);
					upU = chainHead[chU];
				}
			}
			int base = chainHead[chV];
			buf[headPtr] = chV;
			buf[headPtr + 1] = v - base;
			buf[headPtr + 2] = u - base;
			headPtr += 3;

			System.arraycopy(buf, tailPtr, buf, headPtr, buf.length - tailPtr);
			return Arrays.copyOf(buf, headPtr + buf.length - tailPtr);
		}

		// the length of chain #id
		// chainId -> int
		public int chainSz(int id) {
			return (id == chainHead.length - 1 ? n : chainHead[id + 1]) - chainHead[id];
		}

		// the id of chain that node belongs to
		// time -> chainId
		public int chainId(int node) {
			// if node is not a chain's head, set node to the head
			if (chainInfo[node] >= 0) {
				node = chainInfo[node];
			}
			return ~chainInfo[node];
		}

		// the position of a node within its chain
		// time -> int
		public int chainPos(int t) {
			int x = chainInfo[t];
			return x >= 0 ? t - x : 0;
		}

		// returns the NODE in the given chain at the given position
		// this is called getTime because you should only care
		// about "times" and not original node numbers
		public int getTime(int chainId, int chainPos) {
			return chainHead[chainId] + chainPos;
		}

		// time -> boolean
		public boolean isLeaf(int t) {
			return g[time2Node[t]].length == (t == 0 ? 0 : 1);
		}

		private void dfsSz(int v, int p) {
			sz[v] = 1;
			int[] adj = g[v];
			for (int i = 0; i < adj.length; i++) {
				int u = adj[i];
				if (u == p) {
					continue;
				}
				dfsSz(u, v);
				sz[v] += sz[u];
				if (adj[0] == p || sz[u] > sz[adj[0]]) {
					adj[i] = adj[0];
					adj[0] = u;
				}
			}
		}

		private void dfsChains(int v, int p) {
			int tv = timePtr++;
			time2Node[tv] = v;
			node2Time[v] = tv;

			int[] adj = g[v];
			for (int i = 0; i < adj.length; i++) {
				int u = adj[i];
				if (u == p) {
					continue;
				}
				par[timePtr] = tv;
				depth[timePtr] = depth[tv] + 1;
				if (i == 0) {
					chainInfo[timePtr] = chainInfo[tv] >= 0 ? chainInfo[tv] : tv;
				} else {
					chainHead[chainCnt] = timePtr;
					chainInfo[timePtr] = ~(chainCnt++);
				}
				dfsChains(u, v);
			}

			rgh[tv] = timePtr;
		}
	}

	void submit() {
		int n = nextInt();
		int q = nextInt();
		long w = nextLong();
		int[] vs = new int[n - 1];
		int[] us = new int[n - 1];
		long[] ws = new long[n - 1];
		for (int i = 0; i < n - 1; i++) {
			vs[i] = nextInt() - 1;
			us[i] = nextInt() - 1;
			ws[i] = nextLong();
		}

		HLD hld = new HLD(vs, us, 0);

		for (int i = 0; i < n - 1; i++) {
			vs[i] = hld.node2Time[vs[i]];
			us[i] = hld.node2Time[us[i]];
		}

		int[] lft = hld.node2Time;
		int[] rgh = hld.rgh;
		for (int i = 0; i < n - 1; i++) {
			if (vs[i] > us[i]) {
				int tmp = vs[i];
				vs[i] = us[i];
				us[i] = tmp;
			}
		}

		SegTree depths = new SegTree(n);
		for (int i = 0; i < n - 1; i++) {
			depths.addSegment(us[i], rgh[us[i]], ws[i]);
		}

		SegTree[] aux = new SegTree[hld.chainCnt];
		for (int i = 0; i < aux.length; i++) {
			aux[i] = new SegTree(hld.chainSz(i));
		}

		int[] chainHead = hld.chainHead;
		for (int v = 0; v < n; v++) {
			if (hld.isLeaf(v)) {
				continue;
			}
			int ch = hld.chainId(v);
			int pos = hld.chainPos(v);
			int head = chainHead[ch];

			long maxExceptChain = depths.getSegment(rgh[v + 1], rgh[v]);
			if (maxExceptChain < 0) {
				aux[ch].addPoint(pos, -INF);
				continue;
			}
			aux[ch].addPoint(pos, maxExceptChain + depths.getPoint(head) - 2 * depths.getPoint(v));
		}

		long last = 0;
		while (q-- > 0) {
			int edgeIdx = nextInt();
			long newW = nextLong();
			edgeIdx = (int) ((edgeIdx + last) % (n - 1));
			newW = (newW + last) % w;

//			System.err.println(edgeIdx + " " + newW);
//			System.err.println("old: " + Arrays.toString(ws));

			long oldW = ws[edgeIdx];
			long deltaW = newW - oldW;

			ws[edgeIdx] = newW;

//			System.err.println("new: " + Arrays.toString(ws));

			// update edge weight
			{
				int v = us[edgeIdx];
				depths.addSegment(v, rgh[v], deltaW);

				// update relative depth and maxRelExceptChain for nodes below v
				// on its chain
				int ch = hld.chainId(v);
				int pos = hld.chainPos(v);
				if (pos != 0) {
					aux[ch].addSegment(pos, hld.chainSz(ch), -deltaW);
				}

				// update maxRelExceptChain for last nodes on the chains
				int[] path = hld.getPath(0, v);
				for (int i = 0; i < path.length - 3; i += 3) {
					int chainId = path[i];
					int headV = chainHead[chainId];
					int vPos = path[i + 2];
					v = hld.getTime(chainId, vPos);
					long newVal = depths.getSegment(rgh[v + 1], rgh[v]) + depths.getPoint(headV) - 2
							* depths.getPoint(v);

					aux[chainId].setPoint(vPos, newVal);
				}
			}

			long ans;

			// find diameter
			{
				int deepV = depths.maxPos();
				if (!hld.isLeaf(deepV)) {
					throw new AssertionError("deepest node must be a leaf!");
				}
				ans = depths.getPoint(deepV);
				long vDepth = ans;

				int[] path = hld.getPath(0, deepV);
				for (int i = 0; i < path.length; i += 3) {
					int chainId = path[i];
					int headV = chainHead[chainId];
					// not last node on a chain, use aux seg tree
					ans = Math.max(
							ans,
							aux[chainId].getSegment(0, path[i + 2])
									+ (vDepth - depths.getPoint(headV)));

					if (i == path.length - 3) {
						continue;
					}

					// last node on a chain
					int lastNode = hld.getTime(chainId, path[i + 2]);
					int nxtNode = chainHead[path[i + 3]];
					long deepOther = Math.max(depths.getSegment(lastNode, nxtNode),
							depths.getSegment(rgh[nxtNode], rgh[lastNode]));
					ans = Math.max(ans, deepOther + vDepth - 2 * depths.getPoint(lastNode));
				}
			}
			out.println(ans);
			last = ans;
		}
	}

	static final long INF = Long.MAX_VALUE / 3;

	// TODO: check with local parameters/without SegTree class at all?
	static class SegTree {
		static int ql, qr;
		static long delta;
		Node root;

		public SegTree(int n) {
			root = new Node(0, n);
		}

		public void addSegment(int ql, int qr, long delta) {
			if (ql == qr) {
				return;
			}
			if (ql > qr) {
				throw new AssertionError("ql > qr");
			}
			SegTree.ql = ql;
			SegTree.qr = qr;
			SegTree.delta = delta;
			root.add();
		}

		// TODO: can improve!
		public void addPoint(int idx, long delta) {
			addSegment(idx, idx + 1, delta);
		}

		public long getSegment(int ql, int qr) {
			if (ql == qr) {
				return -INF;
			}
			if (ql > qr) {
				throw new AssertionError("ql > qr");
			}
			SegTree.ql = ql;
			SegTree.qr = qr;
			return root.get();
		}

		public void setPoint(int idx, long val) {
			ql = idx;
			delta = val;
			root.setPoint();
		}

		// TODO: can improve!
		public long getPoint(int idx) {
			return getSegment(idx, idx + 1);
		}

		public int maxPos() {
			return root.maxPos();
		}

		static class Node {
			int l, r;
			Node left, right;
			long add, max;

			long getMax() {
				return max + add;
			}

			public Node(int l, int r) {
				this.l = l;
				this.r = r;
				if (r - l > 1) {
					int m = (l + r) >> 1;
					left = new Node(l, m);
					right = new Node(m, r);
				}
			}

			void add() {
				if (l >= qr || ql >= r) {
					return;
				}
				if (ql <= l && r <= qr) {
					add += delta;
					return;
				}
				left.add();
				right.add();
				max = Math.max(left.getMax(), right.getMax());
			}

			long get() {
				if (l >= qr || ql >= r) {
					return -INF;
				}
				if (ql <= l && r <= qr) {
					return getMax();
				}
				return Math.max(left.get(), right.get()) + add;
			}

			int maxPos() {
				if (r - l == 1) {
					return l;
				}
				return left.getMax() > right.getMax() ? left.maxPos() : right.maxPos();
			}

			void setPoint() {
				if (r - l == 1) {
					add = 0;
					max = delta;
					return;
				}
				left.add += add;
				right.add += add;
				add = 0;
				(ql < left.r ? left : right).setPoint();
				max = Math.max(left.getMax(), right.getMax());
			}
		}
	}

	void test() {

	}

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

	cfCEOI2019Day1B() throws IOException {
		if (System.getProperty("ONLINE_JUDGE") == null) {
			is = new FileInputStream("in.txt");
		} else {
			is = System.in;
		}
		out = new PrintWriter(System.out);
		submit();
		// stress();
		// test();
		out.close();
	}

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

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

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

	private InputStream is;
	PrintWriter out;

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

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

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

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

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

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

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

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

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

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


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

public class code{
  public static class Pair{
    int a;
    int b;
    Pair(int i,int j){
      a=i;
      b=j;
    }
  }

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

  public static void shuffle(int a[], int n)
  {
      for (int i = 0; i < n; i++) {

          // getting the random index
          int t = (int)Math.random() * a.length;

          // and swapping values a random index
          // with the current index
          int x = a[t];
          a[t] = a[i];
          a[i] = x;
      }
  }

  public static PrintWriter out = new PrintWriter(System.out);
  //@SuppressWarnings("unchecked")
  public static void main(String[] arg) throws IOException{
      //Reader in=new Reader();

      //PrintWriter out = new PrintWriter(System.out);
      //Scanner in = new Scanner(System.in);
      FastScanner in=new FastScanner();
      int t=1;

      while(t-- > 0){
        String s=in.next();
        if(s.equals("0") || s.equals("X") || s.equals("_")){
          out.println(1);
          continue;
        }
        char[] arr=s.toCharArray();

        int low=(int)Math.pow(10,s.length()-1);
        int high=(int)Math.pow(10,s.length())-25;
        while(low%25!=0) low++;
        int res=0;

        for(;low<=high;low+=25){
          String s1=Integer.toString(low);
          char[] c=s1.toCharArray();
          int count=1;
          char x='#';
          for(int i=0;i<arr.length;i++){
            if(arr[i]=='_') continue;
            if(arr[i]=='X'){
              if(x=='#') x=c[i];
              if(x!=c[i]){
                count=0;
                break;
              }
            }
            else if(arr[i]!=c[i]){
              count=0;
              break;
            }
          }
          res+=count;
        }

        out.println(res);
      }

      out.flush();
  }

}

class Fenwick{
  int[] bit;
  public Fenwick(int n){
    bit=new int[n];
    //int sum=0;
  }

  public void update(int index,int val){
    index++;
    for(;index<bit.length;index += index&(-index)) bit[index]+=val;
  }

  public int presum(int index){
    int sum=0;
    for(;index>0;index-=index&(-index)) sum+=bit[index];
    return sum;
  }

  public int sum(int l,int r){
    return presum(r+1)-presum(l);
  }
}

class FastScanner {

  private int BS = 1 << 16;
  private char NC = (char) 0;
  private byte[] buf = new byte[BS];
  private int bId = 0, size = 0;
  private char c = NC;
  private double cnt = 1;
  private BufferedInputStream in;

  public FastScanner() {
      in = new BufferedInputStream(System.in, BS);
  }

  public FastScanner(String s) {
      try {
          in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
      } catch (Exception e) {
          in = new BufferedInputStream(System.in, BS);
      }
  }

  private char getChar() {
      while (bId == size) {
          try {
              size = in.read(buf);
          } catch (Exception e) {
              return NC;
          }
          if (size == -1) return NC;
          bId = 0;
      }
      return (char) buf[bId++];
  }

  public int nextInt() {
      return (int) nextLong();
  }

  public int[] nextInts(int N) {
      int[] res = new int[N];
      for (int i = 0; i < N; i++) {
          res[i] = (int) nextLong();
      }
      return res;
  }

  public long[] nextLongs(int N) {
      long[] res = new long[N];
      for (int i = 0; i < N; i++) {
          res[i] = nextLong();
      }
      return res;
  }

  public long nextLong() {
      cnt = 1;
      boolean neg = false;
      if (c == NC) c = getChar();
      for (; (c < '0' || c > '9'); c = getChar()) {
          if (c == '-') neg = true;
      }
      long res = 0;
      for (; c >= '0' && c <= '9'; c = getChar()) {
          res = (res << 3) + (res << 1) + c - '0';
          cnt *= 10;
      }
      return neg ? -res : res;
  }

  public double nextDouble() {
      double cur = nextLong();
      return c != '.' ? cur : cur + nextLong() / cnt;
  }

  public double[] nextDoubles(int N) {
      double[] res = new double[N];
      for (int i = 0; i < N; i++) {
          res[i] = nextDouble();
      }
      return res;
  }

  public String next() {
      StringBuilder res = new StringBuilder();
      while (c <= 32) c = getChar();
      while (c > 32) {
          res.append(c);
          c = getChar();
      }
      return res.toString();
  }

  public String nextLine() {
      StringBuilder res = new StringBuilder();
      while (c <= 32) c = getChar();
      while (c != '\n') {
          res.append(c);
          c = getChar();
      }
      return res.toString();
  }

  public boolean hasNext() {
      if (c > 32) return true;
      while (true) {
          c = getChar();
          if (c == NC) return false;
          else if (c > 32) return true;
      }
  }
}


import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;

// Please name your class Main
public class Main {
    static FastScanner fs=new FastScanner();
    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        public String next() {
            while (!st.hasMoreElements())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }
        int Int() {
            return Integer.parseInt(next());
        }

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

        String Str(){
            return next();
        }
    }

    public static void main (String[] args) throws java.lang.Exception {
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        //reading /writing file
        //Scanner in=new Scanner(System.in);
        //Scanner in=new Scanner(new File("input.txt"));
        //PrintWriter pr=new PrintWriter("output.txt");

        int T=1;
        for(int t=0;t<T;t++){
            Solution sol1=new Solution(out,fs);
            sol1.solution(T,t);
        }
        out.flush();

    }

    public static int[] Arr(int n){
        int A[]=new int[n];
        for(int i=0;i<n;i++)A[i]=Int();
        return A;
    }
    public static int Int(){
        return fs.Int();
    }
    public static long Long(){
        return fs.Long();
    }
    public static String Str(){
        return fs.Str();
    }

}

class Solution {
    PrintWriter out;
    int INF = Integer.MAX_VALUE;
    int NINF = Integer.MIN_VALUE;
    int MOD = 998244353;
    int mod = 1000000007;
    Main.FastScanner fs;

    public Solution(PrintWriter out, Main.FastScanner fs) {
        this.out = out;
        this.fs = fs;

    }

    public void solution(int all, int testcase) {
        int n = fs.Int();
        mod = fs.Int();

        long dp[][] = new long[n][n * n + 5];
        dp[0][0] = 1;
        for(int i = 1; i < n; i++) {
            for(int j = 0; j < dp[0].length; j++) {
                for(int cnt = 0; cnt <= i; cnt++){
                    if(j - cnt >= 0) {
                        dp[i][j] += dp[i - 1][j - cnt];
                        dp[i][j] %= mod;
                        if(dp[i][j] == 0){
                            dp[i][j] += mod;
                        }
                    }
                }
            }
        }

        long sums[][] = new long[dp.length][dp[0].length];
        for(int i = 0; i < dp.length;i++){
            int sum = 0;
            for(int j = 0; j < dp[0].length; j++){
                sum += dp[i][j];
                sum %= mod;
                if(sum == 0) sum += mod;
                sums[i][j] = sum;
            }
        }

        long fact[] = new long[3000];
        fact[0] = fact[1] = 1;
        for(int i = 2; i < fact.length;i++){
            fact[i] = fact[i - 1] * i;
            fact[i] %= mod;
        }

        long ncr[][] = new long[55][55];
        ncr[0][0]=1;
        for (int i=1;i<ncr.length;i++) {
            ncr[i][0]=1;
            for (int j=1;j<ncr[0].length;j++) {
                ncr[i][j]=(ncr[i-1][j] + ncr[i-1][j-1])%mod;
                if(ncr[i][j] == 0)ncr[i][j] += mod;
            }
        }

        long res = 0;
        for(int i = n - 2; i >= 0; i--) {
            int cnt = n - i;
            int pre = n - cnt;
            long com = (ncr[n][pre] * fact[pre]) % mod;
            long sum = 0;

            for(int dif = 1; dif < cnt; dif++){
                for(int inv = dif; inv < dp[0].length; inv++){
                    if(dp[cnt - 1][inv] == 0){
                        break;
                    }
                    if(inv - dif - 1 < 0)continue;
                    long x = dp[cnt - 2][inv];
                    long y = sums[cnt - 2][inv - dif - 1];
                    x *= y;
                    x %= mod;
                    if(x == 0) x += mod;
                    sum += x * (cnt - dif);
                    sum %= mod;
                }
            }
            res += sum * com;
            res%=mod;
        }

        out.println(res % mod);
    }

}


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.print(' ');}
			  out.flush();
		  }
	}
}
}


import java.io.*;
import java.util.*;
public class CF939_D2_F {
	public static void main(String[] args)throws Throwable {
		MyScanner sc=new MyScanner();
		PrintWriter pw=new PrintWriter(System.out);

		int n=sc.nextInt()*2;
		int k=sc.nextInt();
		int [] l=new int [k+1];
		int [] r=new int [k+1];
		SparseTable [][] seg=new SparseTable [2][2];
		for(int i=0;i<k;i++){
			l[i]=sc.nextInt();
			r[i]=sc.nextInt();
		}
		l[k]=n;
		for(int j=0;j<2;j++){
			int [] a=new int [n+2];
			Arrays.fill(a, inf);
			a[n/2]=0;
			seg[1][j]=new SparseTable(a);
		}
		int p=0;
		for(int i=k-1;i>=0;i--){
			for(int j=0;j<2;j++){
				int [] a=new int [n+2];
				Arrays.fill(a, inf);
				for(int c=0;c<=l[i];c++){
					int best=seg[1-p][j].query(c+l[i+1]-l[i], c+l[i+1]-l[i]);
					best=Math.min(best, 1+seg[1-p][1-j].query(l[i+1]-(c+r[i]-l[i]), l[i+1]-(c)));
					if(r[i]>l[i])
						best=Math.min(best, 2+seg[1-p][j].query(c+1, c+r[i]-l[i]));
					a[c]=best;
				}
				seg[p][j]=new SparseTable(a);
			}
			p^=1;
		}
		p^=1;
		int ans=Math.min(seg[p][0].query(l[0], l[0]), seg[p][1].query(l[0], l[0]));
		if(ans>2*k)
			pw.println("Hungry");
		else{
			pw.println("Full");
			pw.println(ans);
		}
		pw.flush();
		pw.close();
	}

	static int inf=(int)1e7;

	static class SparseTable {
		int [] a;
		int [][] st;
		//st[i][j] --> minimum of sub array starting at index i and of length 2^j
		SparseTable(int [] a){
			int n=a.length;
			this.a=a;
			int k=(int)Math.floor(Math.log(n)/Math.log(2))+1;
			st=new int [n][k];
			for(int i=0;i<n;i++)
				st[i][0]=i;
			//(1<<j)===(2^j)
			for(int j=1;(1<<j)<=n;j++)
				for(int i=0;i+(1<<j)-1<n;i++)
					if(a[st[i][j-1]] < a[st[i+(1<<(j-1))][j-1]])
						st[i][j]=st[i][j-1]; //
					else
						st[i][j]=st[i+(1<<(j-1))][j-1];
		}
		int query(int i,int j){
			int k=(int)Math.floor(Math.log(j-i+1)/Math.log(2));
			return Math.min(a[st[i][k]], a[st[j-(1<<k)+1][k]]);
		}
	}

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


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

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

    static class TaskG {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            String s = in.next();
            int[] primes = new int[100];
            int nprimes = 0;
            int rem = n;
            for (int p = 2; p <= rem; ++p)
                if (rem % p == 0) {
                    while (rem % p == 0) rem /= p;
                    primes[nprimes++] = p;
                }
            primes = Arrays.copyOf(primes, nprimes);
            int prod = 1;
            for (int x : primes) prod *= x;
            int indep = n / prod;
            long[] a = new long[prod];
            for (int i = 0; i < indep; ++i) {
                for (int j = 0; j < prod; ++j) {
                    a[j] = s.charAt(i + j * indep) - '0';
                }
                if (!can(primes, a)) {
                    out.println("NO");
                    return;
                }
            }
            out.println("YES");
        }

        private boolean can(int[] primes, long[] a) {
            long[] b = new long[a.length];
            for (int p : primes) {
                for (int i = 0; i < a.length; ++i) {
                    b[i] = a[i] - a[(i + a.length / p) % a.length];
                }
                long[] t = a;
                a = b;
                b = t;
                boolean allzeo = true;
                for (long x : a) if (x != 0) allzeo = false;
                if(allzeo) return true;
            }
            return false;
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

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

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

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

    }
}


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

public final class yet_another
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	static long mod=(long)(1e9+7);
	static long[][] c;
	static int maxn=(int)51;

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

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

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

		return x;
	}

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

		for(int i=1;i<maxn;i++)
		{
			c[i][0]=1;

			for(int j=1;j<=i;j++)
			{
				c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
			}
		}
	}

	static long[][] matrix_mul(long[][] a,long[][] b,int r1,int c1,int r2,int c2) throws Exception
	{
		if(c1!=r2)
		{
			throw new Exception("Matrices not fit for multiplication!");
		}

		long[][] c=new long[r1][c2];

		for(int i=0;i<r1;i++)
		{
			for(int j=0;j<c2;j++)
			{
				for(int k=0;k<c1;k++)
				{
					long mul=(a[i][k]*b[k][j])%mod;

					c[i][j]=(c[i][j]+mul)%mod;
				}
			}
		}

		return c;
	}

	static long[][] id(int n) throws Exception
	{
		long[][] ret=new long[n][n];

		for(int i=0;i<n;i++)
		{
			ret[i][i]=1;
		}

		return ret;
	}

	static long[][] matrix_pow(long[][] a,long b,int n) throws Exception
	{
		long[][] x=id(n),y=a;

		while(b>0)
		{
			if(b%2==1)
			{
				x=matrix_mul(x,y,n,n,n,n);
			}

			y=matrix_mul(y,y,n,n,n,n);b=b/2;
		}

		return x;
	}

    public static void main(String args[]) throws Exception
    {
		build();long n=sc.nextLong();int k=sc.nextInt(),size=((k+1)*2)+1;

		long[][] a=new long[size][size];

		for(int j=0;j<=k;j++)
		{
			for(int i=0,ctr=0;ctr<=j;i++,ctr++)
			{
				a[i][j]=c[j][ctr];
			}

			for(int i=k+1,ctr=0;ctr<=j;i++,ctr++)
			{
				a[i][j]=(c[j][ctr]*pow(2,j-ctr))%mod;
			}
		}

		for(int j=k+1;j<=2*k+1;j++)
		{
			a[j-(k+1)][j]=1;
		}

		a[k][size-1]=1;a[size-1][size-1]=1;

		if(n==1 || n==2)
		{
			long[] f=new long[]{0,1,2};long res=0;

			for(int i=1;i<=n;i++)
			{
				long mul=(f[i]*pow(i,k))%mod;

				res=(res+mul)%mod;
			}

			out.println(res);
		}

		else
		{
			long[][] now=matrix_pow(a,n-2,size),val=new long[1][size];

			for(int i=0;i<=k;i++)
			{
				val[0][i]=(2*pow(2,i))%mod;
			}

			for(int i=k+1;i<=2*k+1;i++)
			{
				val[0][i]=1;
			}

			val[0][size-1]=1;

			now=matrix_mul(val,now,1,size,size,size);

		//	out.println(Arrays.deepToString(val)+" "+Arrays.deepToString(now));

			long res=(now[0][k]+now[0][size-1])%mod;

			out.println(res);
		}

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

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

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

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

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

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

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


import java.io.* ;
import java.util.* ;
import java.util.stream.* ;
import java.text.* ;
import java.math.* ;
public class Codeshefcode{
	public static void main(String[] args) throws IOException{
		Solver Machine = new Solver() ;
		Machine.Solve() ;
		Machine.Finish();
	}
}
class Mod{
	static long mod=1000000007 ;
	static long d(long a,long b){ return (a*MI(b))%mod ; }
	static long m(long a , long b){ return (a*b)%mod ; }
	static private long MI(long a ){ return pow(a,mod-2) ; }
	static long pow(long a,long b){
		if(b<0) return pow(MI(a),-b) ;
		long val=a ; long ans=1 ;
		while(b!=0){
			if((b&1)==1) ans = (ans*val)%mod ;
			val = (val*val)%mod ;
			b>>=1 ;
		}
		return ans ;
	}
}
class pair implements Comparable<pair>{
	long x ; long y ;
	pair(long x,long y){ this.x=x ; this.y=y ;}
	public int compareTo(pair p){
		return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ;
	}
}
class Solver{
	FasterScanner ip = new FasterScanner(System.in) ;
	PrintWriter op = new PrintWriter(System.out) ;
	void Solve() throws IOException{
		int N = ip.i() ;
		int R = ip.i() ;
		int F[] = new int[N+1], S[] = new int[N+1] ;
		double P[] = new double[N+1] ;
		for(int i=1 ; i<=N ; i++){
			F[i] = ip.i() ;
			S[i] = ip.i() ;
			P[i] = ip.i()/100.0 ;
		}
		double low = 0 ;
		double high = 1000000000l ;
		int itr=150 ;
		while(itr--!=0){
			double k = (high+low)/2 ;
			double dp[][] = new double[N+1][R+1] ;
			for(int i=(N-1) ; i>=0 ; i--)
				for(int j=0 ; j<=R ; j++){
					if(j<F[i+1])
						dp[i][j] = k ;
					else if(j<S[i+1])
						dp[i][j] = Math.min((dp[i+1][j-F[i+1]]+F[i+1])*P[i+1]+(k+S[i+1])*(1-P[i+1]),k) ;
					else
						dp[i][j] = Math.min(((dp[i+1][j-F[i+1]]+F[i+1])*P[i+1]+(dp[i+1][j-S[i+1]]+S[i+1])*(1-P[i+1])),k) ;
				}
			if(dp[0][R]<k)
				high=k ;
			else
				low=k ;
		}
		pln(high) ;
	}
	void p(Object o){
		op.print(o) ;
	}
	void pln(Object o){
		op.println(o) ;
	}
	void pArr(String name,Object arr,char type){
		p(name+": [") ;
		if(type=='i'){
			int arr1[] = (int[]) arr ;
			for(int i=0 ; i<arr1.length ; i++) p(arr1[i]+(i+1==arr1.length ? "" : ",")) ;
		}else if(type=='l'){
			long arr1[] = (long[]) arr ;
			for(int i=0 ; i<arr1.length ; i++) p(arr1[i]+(i+1==arr1.length ? "" : ",")) ;
		}else if(type=='b'){
			boolean arr1[] = (boolean[]) arr ;
			for(int i=0 ; i<arr1.length ; i++) p((arr1[i] ? 1 : 0)+(i+1==arr1.length ? "" : ",")) ;
		}
		pln("]") ;
	}
	void Finish(){
		op.flush();
		op.close();
	}
}
@SuppressWarnings("serial")
class mylist extends ArrayList<Integer>{
}
@SuppressWarnings("serial")
class myset extends TreeSet<Long>{

}
@SuppressWarnings("serial")
class mystack extends Stack<Integer>{
}
@SuppressWarnings("serial")
class mymap extends TreeMap<Long,Integer>{
}
class FasterScanner {
	private InputStream mIs;
	private byte[] buf = new byte[1024];
	private int curChar,numChars;
	public FasterScanner() { this(System.in); }
	public FasterScanner(InputStream is) { mIs = is;}
	public int read() {
		if (numChars == -1) throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}
			if (numChars <= 0) return -1;
		}
		return buf[curChar++];
	}
	public String nextLine(){
		int c = read();
		while (isSpaceChar(c)) c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}
	public String S(){
		int c = read();
		while (isSpaceChar(c)) c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		}while (!isSpaceChar(c));
		return res.toString();
	}
	public long l(){
		int c = read();
		while (isSpaceChar(c)) c = read();
		int sgn = 1;
		if (c == '-') { sgn = -1 ; c = read() ; }
		long res = 0;
		do{
			if (c < '0' || c > '9') throw new InputMismatchException();
			res *= 10 ; res += c - '0' ; c = read();
		}while(!isSpaceChar(c));
		return res * sgn;
	}
	public int i(){
		int c = read() ;
		while (isSpaceChar(c)) c = read();
		int sgn = 1;
		if (c == '-') { sgn = -1 ; c = read() ; }
		int res = 0;
		do{
			if (c < '0' || c > '9') throw new InputMismatchException();
		res *= 10 ; res += c - '0' ; c = read() ;
		}while(!isSpaceChar(c));
		return res * sgn;
	}
	public int[] ia(int n){
		int a[] = new int[n] ;
		for(int i=0 ; i<n ; i++) a[i] = i() ;
		return a ;
	}
	public long[] la(int n){
		long a[] = new long[n] ;
		for(int i=0 ; i<n ; i++) a[i] = l() ;
		return a ;
	}
	public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
	public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}


import java.io.*;
import java.util.InputMismatchException;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class ABCm {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        ExpectedEarnings solver = new ExpectedEarnings();
        solver.solve(1, in, out);
        out.close();
    }
    static class ExpectedEarnings {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt(), X = in.nextInt();
            double c = X / 1_000_000.0;
            double[] cprob = new double[n + 1];
            for (int i = 0; i <= n; i++) {
                cprob[i] = in.nextInt();
            }
            double[] dp = new double[n + 1];
            for (int nballs = n - 1; nballs >= 0; nballs--) {
                double[] next = new double[nballs + 1];
                double[] nprob = new double[nballs + 1];
                for (int red = 0; red <= nballs; red++) {
                    if (cprob[red] < 1e-10 && cprob[red + 1] < 1e-10) continue;
                    int black = nballs - red;
                    double probred = cprob[red + 1] * (red + 1) / (cprob[red + 1] * (red + 1) + cprob[red] * (black + 1));
                    nprob[red] = ((red + 1) * cprob[red + 1] + (black + 1) * cprob[red]) / (double) (nballs + 1);
                    next[red] = Math.max(0, -c + probred * (1 + dp[red + 1]) + (1 - probred) * dp[red]);
                }
                dp = next;
                cprob = nprob;
            }
            out.printf("%.10f\n", dp[0]);
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        public InputReader(InputStream stream) {
            this.stream = stream;
        }
        public int read() {
            if (this.numChars == -1) {
                throw new InputMismatchException();
            } else {
                if (this.curChar >= this.numChars) {
                    this.curChar = 0;
                    try {
                        this.numChars = this.stream.read(this.buf);
                    } catch (IOException var2) {
                        throw new InputMismatchException();
                    }
                    if (this.numChars <= 0) {
                        return -1;
                    }
                }
                return this.buf[this.curChar++];
            }
        }
        public int nextInt() {
            int c;
            for (c = this.read(); isSpaceChar(c); c = this.read()) {
                ;
            }
            byte sgn = 1;
            if (c == 45) {
                sgn = -1;
                c = this.read();
            }
            int res = 0;
            while (c >= 48 && c <= 57) {
                res *= 10;
                res += c - 48;
                c = this.read();
                if (isSpaceChar(c)) {
                    return res * sgn;
                }
            }
            throw new InputMismatchException();
        }
        public static boolean isSpaceChar(int c) {
            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;
        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }
        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }
        public void printf(String format, Object... objects) {
            writer.printf(format, objects);
        }
        public void close() {
            writer.close();
        }
    }
}


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

public class S_39I {
    BufferedReader in;
    StringTokenizer st;
    PrintWriter out;

    List<List<Integer>> edges = new ArrayList<List<Integer>>();

    int[] depth;

    int dfs_GCD(int index, int d) {
        if (depth[index] == 0) {
            depth[index] = d;
            int rv = 0;
            for (int next : edges.get(index)) {
                rv = gcd(rv, dfs_GCD(next, d + 1));
            }
            return rv;
        } else {
            return d - depth[index];
        }
    }

    private static int gcd(int a, int b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            int t = a % b;
            a = b;
            b = t;
        }
        return a;
    }

    void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        for (int i = 0; i < n; ++i) {
            edges.add(new ArrayList<Integer>());
        }
        for (int i = 0; i < m; ++i) {
            int s = nextInt() - 1;
            int e = nextInt() - 1;
            edges.get(s).add(e);
        }
        depth = new int[n];
        int gcd = dfs_GCD(0, 1);
        List<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < n; ++i) {
            if (depth[i] % gcd == depth[0] % gcd && depth[i] != 0) {
                ans.add(i + 1);
            }
        }
        out.println(gcd);
        out.println(ans.size());
        for (int i : ans) {
            out.print(i);
            out.print(" ");
        }
    }

    public void run() throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        eat("");
        solve();
        out.close();
        in.close();
    }

    void eat(String s) {
        st = new StringTokenizer(s);
    }

    String next() throws IOException {
        while (!st.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) {
                return null;
            }
            eat(line);
        }
        return st.nextToken();
    }

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

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

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

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


import java.util.*;
import java.io.*;
import java.math.*;
public class round51D {
	public static void main(String args[]) throws Exception{
		cf55D tmp=new cf55D();
		tmp.solve();
	}
}
class cf55D {
	final static int N=20;
	final static int mod=2520;
	final static int M=(1<<8);
	long dp[][][]=new long[N][M][mod];
	ArrayList<Integer> dig=new ArrayList<Integer>();
	int t;
	long l,r;
	void init(long num) {
		long xx=num;
		while(xx>0) {
			int y=(int)xx%10;
			dig.add(y);
			xx/=10;
		}
		for(int i=0;i<N;i++) {
			for(int j=0;j<M;j++) {
				Arrays.fill(dp[i][j],-1);
			}
		}
	}
	long calc(int cont,int st,int re,int limit) {
		if(cont==-1) {
			for(int i=0;i<8;i++) {
				if((st&(1<<i))!=0&&re%(i+2)!=0) {
					return 0;
				}
			}
			return 1;
		}
		if(limit==0&&dp[cont][st][re]!=-1) return dp[cont][st][re];
		int bound=(limit==1? dig.get(cont):9);
		long res=0;
		for(int i=0;i<=bound;i++) {
			int stt=st;
			if(i>=2) stt|=(1<<(i-2));
			res+=calc(cont-1,stt,(re*10+i)%mod,(limit==1&&i==bound? 1:0));
		}
		if(limit==0) dp[cont][st][re]=res;
		return res;
	}
	void solve() throws Exception{
		//System.setIn(new BufferedInputStream(new FileInputStream("in.txt")));
		Scanner in=new Scanner(System.in);
		t=in.nextInt();
		for(int i=0;i<t;i++) {
			l=in.nextInt();
			r=in.nextInt();
			dig.clear();
			init(l-1);
			int sz=dig.size();
			long ll=calc(sz-1,0,0,1);

			dig.clear();
			init(r);
			sz=dig.size();
			long rr=calc(sz-1,0,0,1);
			System.out.println(rr-ll);
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.math.BigInteger;

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

    static class ECyclicCipher {
        static final int C = 5000;
        static double[][] pow2D = {{1, 0}};
        static int[][] rev2D = {};

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int[] b = new int[n];
            int[] c = new int[n];

            for (int i = 0; i < n; i++) {
                b[i] = in.readInt();
            }

            int[] initB = b.clone();

            b = makeInvPows(b);

            for (int i = 0; i < n; i++) {
                c[i] = in.readInt();
            }

            int z, p;
            int[] pz;

            int[] fb;

            for (int i = 1; ; i++) {
                p = 2 * n * i + 1;
                if (p < C) {
                    continue;
                }
                if (!BigInteger.valueOf(p).isProbablePrime(30)) {
                    continue;
                }
                z = pow(primitiveRoot(p), (p - 1) / (2 * n), p);
                pz = new int[2 * n];
                pz[0] = 1;
                for (int j = 1; j < pz.length; j++) {
                    pz[j] = (int) ((long) pz[j - 1] * z % p);
                }

                fb = chirp(b, pz, p);
                boolean allGood = true;
                for (int coef : fb) {
                    allGood &= coef != 0;
                }

                if (allGood) {
                    break;
                }
            }

            int[] cc = new int[n];
            int inv2 = (p + 1) / 2;
            for (int i = 0; i < n; i++) {
                cc[i] = (c[(i + n - 1) % n] - c[i]) % p;
                if (cc[i] < 0) {
                    cc[i] += p;
                }
                cc[i] = (int) ((long) cc[i] * inv2 % p);
            }

            int[] fc = chirp(cc, pz, p);

            int[] fa = new int[n];
            for (int i = 0; i < n; i++) {
                fa[i] = (int) ((long) fc[i] * pow(fb[i], p - 2, p) % p);
            }

            int[] aa = chirp(fa, makeInvPows(pz), p);
            int invN = pow(n, p - 2, p);
            for (int i = 0; i < n; i++) {
                aa[i] = (int) ((long) aa[i] * invN % p);
            }

            long[] d = new long[n];
            for (int i = 1; i < n; i++) {
                d[i] = d[i - 1] + makeInt(aa[i], p);
            }

//		System.err.println(Arrays.toString(realAa));

            long B = 0;
            long C = -c[0];
            for (int i = 0; i < n; i++) {
                long diff = initB[i] - d[i];
                B -= diff;
                C += diff * diff;
            }

//		System.err.println(A + " " + B + " " + C);

            List<Long> x0s = new ArrayList<>();

            long D = B * B - (long) n * C;
            if (D >= 0) {
                if (D == 0) {
                    if ((-B % (long) n) == 0) {
                        x0s.add((-B) / (long) n);
                    }
                } else {
                    long rd = (long) Math.sqrt(D);
                    if (rd * rd == D) {
                        if ((-B - rd) % (long) n == 0) {
                            x0s.add((-B - rd) / (long) n);
                        }
                        if ((-B + rd) % (long) n == 0) {
                            x0s.add((-B + rd) / (long) n);
                        }
                    }
                }
            }

            out.printLine(x0s.size());
            for (long x0 : x0s) {
                for (int i = 0; i < n; i++) {
                    out.print(d[i] + x0 + " ");
                }
                out.printLine();
            }
        }

        int pow(int a, int b, int p) {
            int ret = 1;
            for (; b > 0; b >>= 1) {
                if ((b & 1) == 1) {
                    ret = (int) ((long) ret * a % p);
                }
                a = (int) ((long) a * a % p);
            }
            return ret;
        }

        int primitiveRoot(int p) {
            loop:
            for (int i = 2; ; i++) {
                for (int j = 2; j * j <= p - 1; j++) {
                    if ((p - 1) % j != 0) {
                        continue;
                    }
                    if (pow(i, (p - 1) / j, p) == 1) {
                        continue loop;
                    }
                    if (pow(i, j, p) == 1) {
                        continue loop;
                    }
                }
                return i;
            }
        }

        int[] chirp(int[] a, int[] pz, int p) {
            int n = a.length;
            // pz[1] has order 2 * n modulo prime p

            a = a.clone();
            for (int i = 0; i < n; i++) {
                a[i] %= p;
            }

            int[] one = new int[n];
            for (int i = 0; i < n; i++) {
                one[i] = (int) ((long) a[i] * pz[(int) ((long) i * i % (2 * n))] % p);
            }

            int[] two = new int[2 * n - 1];
            for (int i = 0; i <= 2 * n - 2; i++) {
                two[i] = pz[Math.floorMod(-(long) (n - 1 - i) * (n - 1 - i), 2 * n)];
            }

            int[] prod = mult(one, two, p);

            prod = Arrays.copyOfRange(prod, n - 1, 2 * n - 1);
            for (int i = 0; i < n; i++) {
                prod[i] = (int) ((long) prod[i] * pz[(int) ((long) i * i % (2 * n))] % p);
            }

            return prod;
            // returns polynomial a modulo p at points 1, rootZ^2, rootZ^4, ...
        }

        int makeInt(int x, int p) {
            return x < p / 2 ? x : x - p;
        }

        int[] makeInvPows(int[] a) {
            int[] b = new int[a.length];
            b[0] = a[0];
            for (int i = 1, j = a.length - 1; i < a.length; i++, j--) {
                b[i] = a[j];
            }
            return b;
        }

        static int nextPowerOf2(int x) {
            return x == 1 ? 1 : Integer.highestOneBit(x - 1) << 1;
        }

        static double[][] foo(int[] intV, int len, int L) {
            // pack into one complex vector
            double[] f = new double[len << 1];
            for (int i = 0; i < intV.length; i++) {
                f[i << 1] = intV[i] % L;
                f[i << 1 | 1] = intV[i] / L;
            }

            fft(f, false);

            // unpack
            double[] f1 = new double[len << 1];
            double[] f2 = new double[len << 1];

            // LEN MUST BE A POWER OF 2!!!
            int zzz = (len << 1) - 1;
            for (int i = 0; i < len << 1; i += 2) {
                int j = (-i) & zzz;
                f1[i] = .5 * (f[i] + f[j]);
                f1[i + 1] = .5 * (f[i + 1] - f[j + 1]);
                f2[i] = .5 * (f[i + 1] + f[j + 1]);
                f2[i + 1] = .5 * (f[j] - f[i]);
            }

            return new double[][]{f1, f2};
        }

        public static int[] mult(int[] a, int[] b, int pMod) {

            int k = (int) (Math.sqrt(pMod) + 1);
            int k2 = k * k % pMod;

            int len = nextPowerOf2(a.length + b.length - 1);
            int len2 = len << 1;

            double[][] fA = foo(a, len, k);
            double[][] fB = foo(b, len, k);

            double[][] invF = new double[2][len2];

            for (int ia = 0; ia < 2; ia++) {
                for (int ib = 0; ib < 2; ib++) {

                    double[] r = invF[(ia + ib) >> 1];
                    double[] p = fA[ia];
                    double[] q = fB[ib];

                    if (((ia + ib) & 1) == 0) {
                        for (int i = 0; i < len2; i += 2) {
                            r[i] += p[i] * q[i] - p[i + 1] * q[i + 1];
                            r[i + 1] += p[i] * q[i + 1] + p[i + 1] * q[i];
                        }

                    } else {
                        for (int i = 0; i < len2; i += 2) {
                            r[i] -= p[i] * q[i + 1] + p[i + 1] * q[i];
                            r[i + 1] += p[i] * q[i] - p[i + 1] * q[i + 1];
                        }
                    }

                }
            }

            fft(invF[0], true);
            fft(invF[1], true);

            int[] ret = new int[len];

            for (int i = 0; i < len2; i += 2) {
//			long v0 = Math.round(invF[0][i]) % P;
//			long v1 = Math.round(invF[0][i + 1]) % P * L % P;
//			long v2 = Math.round(invF[1][i]) % P * L2 % P;
                long v0 = (long) (invF[0][i] + .5);
                long v1 = ((long) (invF[0][i + 1] + .5)) % pMod * k;
                long v2 = ((long) (invF[1][i] + .5)) % pMod * k2;
                ret[i >> 1] = (int) ((v0 + v1 + v2) % pMod);
            }

            return ret;
        }

        public static void fft(double[] v, boolean invert) {
            int n2 = v.length;
            int n = n2 >> 1;
            int logN = Integer.numberOfTrailingZeros(n);
            prepareArrays(logN);
            int[] rev = rev2D[logN];

            for (int i = 0; i < n2; i += 2) {
                int j = rev[i >> 1] << 1;
                if (i < j) {
                    double t = v[i];
                    v[i] = v[j];
                    v[j] = t;
                    t = v[i + 1];
                    v[i + 1] = v[j + 1];
                    v[j + 1] = t;
                }
            }

            double conj = invert ? -1 : 1;

            for (int len = 2, row = 0; len <= n; len <<= 1, row++) {
                double[] pow = pow2D[row];
                for (int i = 0; i < n; i += len) {
                    for (int j1 = i << 1, j2 = j1 + len, k = 0; k < len; j1 += 2, j2 += 2, k += 2) {
                        double uA = v[j1];
                        double uB = v[j1 + 1];

                        double mRe = pow[k];
                        double mIm = pow[k + 1] * conj;

                        double vA = v[j2] * mRe - v[j2 + 1] * mIm;
                        double vB = v[j2] * mIm + v[j2 + 1] * mRe;

                        v[j1] = uA + vA;
                        v[j1 + 1] = uB + vB;
                        v[j2] = uA - vA;
                        v[j2 + 1] = uB - vB;
                    }
                }
            }
            if (invert) {
                for (int i = 0; i < n2; i++) {
                    v[i] /= n;
                }
            }
        }

        static void prepareArrays(int n) {
            if (rev2D.length < n + 1) {
                rev2D = Arrays.copyOf(rev2D, n + 1);
            }

            if (rev2D[n] == null) {
                int[] tmp = rev2D[n] = new int[1 << n];
                for (int i = 0; i < (1 << n); i++) {
                    tmp[i] = (tmp[i >> 1] >> 1) | ((i & 1) << (n - 1));
                }
            }

            int oldN = pow2D.length;

            if (oldN >= n) {
                return;
            }

            pow2D = Arrays.copyOf(pow2D, n);

            for (int i = oldN; i < n; i++) {
                double angle = Math.PI / (1 << i);

                double mRe = Math.cos(angle);
                double mIm = Math.sin(angle);

                double[] dst = pow2D[i] = new double[2 << i];
                double[] src = pow2D[i - 1];

                for (int j = 0; j < 1 << i; j += 2) {
                    double re = src[j];
                    double im = src[j + 1];

                    dst[j << 1] = re;
                    dst[j << 1 | 1] = im;
                    dst[j << 1 | 2] = re * mRe - im * mIm;
                    dst[j << 1 | 3] = re * mIm + im * mRe;
                }
            }
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine() {
            writer.println();
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }

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

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

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

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

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

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

        public interface SpaceCharFilter {
            boolean isSpaceChar(int ch);

        }

    }
}


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

public class D {

    public static void main(String[] args) {
        FastReader scan = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
        Task solver = new Task();
        int t = 1;
        while (t --> 0) solver.solve(1, scan, out);
        out.close();
    }

    static class Task {
        static char[] a, b;
        static ArrayDeque<State> queue = new ArrayDeque<>();
        static boolean[][][] found;
        static State ans = null;

        public void solve(int testNumber, FastReader scan, PrintWriter out) {
            a = scan.next().toCharArray();
            b = scan.next().toCharArray();
            queue.addLast(new State(0, 0, 0, 'N'));
            found = new boolean[a.length+1][b.length+1][a.length+b.length+1];
            while(!queue.isEmpty()) {
                State p = queue.pollFirst();
                if(p.x == a.length && p.y == b.length && p.z == 0) {
                    ans = p;
                    break;
                }
                State open = next(p, '(');
                if(!found[open.x][open.y][open.z]) {
                    queue.addLast(open);
                    found[open.x][open.y][open.z] = true;
                }
                if(p.z == 0) continue;
                State closed = next(p, ')');
                if(!found[closed.x][closed.y][closed.z]) {
                    queue.addLast(closed);
                    found[closed.x][closed.y][closed.z] = true;
                }
            }
            StringBuilder res = new StringBuilder();
            while(ans.prev != null) {
                res.append(ans.curr);
                ans = ans.prev;
            }
            out.println(res.reverse());
        }

        static State next(State prev, char curr) {
            State ret = new State(prev.x, prev.y, prev.z, curr);
            if(ret.x != a.length && a[ret.x] == curr) ret.x++;
            if(ret.y != b.length && b[ret.y] == curr) ret.y++;
            ret.z += curr == '(' ? 1 : -1;
            ret.prev = prev;
            return ret;
        }

        static class State {
            int x, y, z;
            State prev = null;
            char curr;
            public State(int a, int b, int c, char d) {
                x = a;
                y = b;
                z = c;
                curr = d;
            }
        }

    }

    static void shuffle(int[] a) {
        Random get = new Random();
        for (int i = 0; i < a.length; i++) {
            int r = get.nextInt(a.length);
            int temp = a[i];
            a[i] = a[r];
            a[r] = temp;
        }
    }

    static void shuffle(long[] a) {
        Random get = new Random();
        for (int i = 0; i < a.length; i++) {
            int r = get.nextInt(a.length);
            long temp = a[i];
            a[i] = a[r];
            a[r] = temp;
        }
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

        public FastReader(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(new File(s)));
        }

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

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

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

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

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