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

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

public class E {

	private void solve() throws IOException {
		int[] abc = new int[3];
		for (int i = 0; i < 3; i++) {
			abc[i] = nextInt();
			moveDistance[i] = nextInt();
			throwDistance[i] = nextInt();
		}
		Position init = new Position(abc[0], abc[1], abc[2], 511, 0);
		queue.add(init);
		visited.add(init);
		best = Integer.MIN_VALUE;
		// long time = System.currentTimeMillis();
		bfs();
		// System.err.println(visited.size());
		// System.err.println(System.currentTimeMillis() - time);
		out.println(best);
	}

	static Queue<Position> queue = new ArrayDeque<E.Position>();
	static HashSet<Position> visited = new HashSet<E.Position>();
	static Position temp = new Position(0, 0, 0, 0, 0);
	static int[] moveDistance = new int[3];
	static int[] throwDistance = new int[3];
	static int best;

	static int[] array = new int[3];

	static boolean containedInArray(int i) {
		return array[0] == i || array[1] == i || array[2] == i;
	}

	static void bfs() {
		while (!queue.isEmpty()) {
			Position p = queue.poll();
			p.copyTo(temp);
			for (int i = 0; i < 3; i++) {
				array[i] = p.getPos(i);
				best = max(best, array[i]);
			}

			for (int manMoving = 0; manMoving < 3; manMoving++) {
				int pos = temp.getPos(manMoving);
				int holding = ((temp.holding123 >> 2 * manMoving) & 3) - 1;
				if (beingHeld(temp.holding123, manMoving)) {
					continue;
				}

				if (holding == -1 && !bit(temp.movesMask, 3 * manMoving + 1)) {
					if (bit(temp.movesMask, (3 * manMoving))) {
						best = max(best, pos + moveDistance[manMoving]);
						continue;
					}
				}

				if (holding == -1 && bit(temp.movesMask, (3 * manMoving))) {
					temp.movesMask ^= 1 << 3 * manMoving;
					for (int i = max(pos - moveDistance[manMoving], 1); i <= pos
							+ moveDistance[manMoving]; i++) {
						if (containedInArray(i)) {
							continue;
						}
						temp.setPosition(manMoving, i);
						if (!visited.contains(temp)) {
							Position t = temp.copy();
							visited.add(t);
							queue.add(t);
						}
					}
					temp.setPosition(manMoving, pos);
					temp.movesMask ^= 1 << 3 * manMoving;
				}

				if (holding != -1 && bit(temp.movesMask, 3 * manMoving + 1)) {
					temp.movesMask ^= 1 << 3 * manMoving + 1;
					temp.holding123 ^= (holding + 1) << 2 * manMoving;
					int otherManHolds = ((temp.holding123 >> 2 * holding) & 3) - 1;
					for (int i = max(pos - throwDistance[manMoving], 1); i <= pos
							+ throwDistance[manMoving]; i++) {
						if (containedInArray(i)) {
							continue;
						}
						temp.setPosition(holding, i);
						if (otherManHolds != -1) {
							temp.setPosition(otherManHolds, i);
						}
						if (!visited.contains(temp)) {
							Position t = temp.copy();
							visited.add(t);
							queue.add(t);
						}
					}
					if (otherManHolds != -1) {
						temp.setPosition(otherManHolds, pos);
					}
					temp.holding123 ^= (holding + 1) << 2 * manMoving;
					temp.setPosition(holding, pos);
					temp.movesMask ^= 1 << 3 * manMoving + 1;
				}

				if (bit(temp.movesMask, 3 * manMoving + 2)) {
					temp.movesMask ^= 1 << 3 * manMoving + 2;
					for (int i = 0; i < 3; i++) {
						if (i == manMoving) {
							continue;
						}
						int oldpos = temp.getPos(i);
						if (abs(oldpos - pos) != 1) {
							continue;
						}
						if (beingHeld(temp.holding123, i)) {
							continue;
						}
						temp.holding123 ^= (i + 1) << (2 * manMoving);
						temp.setPosition(i, pos);
						if (!visited.contains(temp)) {
							Position t = temp.copy();
							visited.add(t);
							queue.add(t);
						}
						temp.holding123 ^= (i + 1) << (2 * manMoving);
						temp.setPosition(i, oldpos);
					}
					temp.movesMask ^= 1 << 3 * manMoving + 2;
				}
			}
		}
	}

	static boolean beingHeld(int holding, int man) {
		++man;
		if (man == (holding & 3))
			return true;
		if (man == ((holding >> 2) & 3))
			return true;
		if (man == ((holding >> 4) & 3))
			return true;
		return false;
	}

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

	static class Position {
		int a, b, c;
		int movesMask;
		int holding123;

		void setPosition(int man, int pos) {
			if (man == 0) {
				a = pos;
			} else {
				if (man == 1) {
					b = pos;
				} else {
					c = pos;
				}
			}
		}

		int getPos(int manMoving) {
			return manMoving == 0 ? a : manMoving == 1 ? b : c;
		}

		Position() {
		}

		Position copy() {
			Position res = new Position();
			copyTo(res);
			return res;
		}

		public Position(int a, int b, int c, int movesMask, int holding123) {
			this.a = a;
			this.b = b;
			this.c = c;
			this.movesMask = movesMask;
			this.holding123 = holding123;
		}

		void copyTo(Position to) {
			to.a = a;
			to.b = b;
			to.c = c;
			to.movesMask = movesMask;
			to.holding123 = holding123;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + a;
			result = prime * result + b;
			result = prime * result + c;
			result = prime * result + holding123;
			result = prime * result + movesMask;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Position other = (Position) obj;
			if (a != other.a)
				return false;
			if (b != other.b)
				return false;
			if (c != other.c)
				return false;
			if (holding123 != other.holding123)
				return false;
			if (movesMask != other.movesMask)
				return false;
			return true;
		}
	}

	public static void main(String[] args) {
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			new E().solve();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			System.exit(239);
		}
	}

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

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

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

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

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


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

public class Solution {

 public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s=scan.next();
        int i=0;
        int level1=0;
        while(i<s.length()){

                if(s.charAt(i)=='A'){
                    if(i<s.length()-2 && s.charAt(i+1)=='B'){
                        if(s.charAt(i+2)=='C')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }

                    }
                    else if(i<s.length()-2 && s.charAt(i+1)=='C'){
                        if(s.charAt(i+2)=='B')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }

                    }
                    i++;
                }

               else if(s.charAt(i)=='B'){
                    if(i<s.length()-2 && s.charAt(i+1)=='A'){
                        if(s.charAt(i+2)=='C')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }

                    }
                    else if(i<s.length()-2 && s.charAt(i+1)=='C'){
                        if(s.charAt(i+2)=='A')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }
                    }
                   i++;
                }
            else if(s.charAt(i)=='C'){
                    if(i<s.length()-2 && s.charAt(i+1)=='B'){
                        if(s.charAt(i+2)=='A')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }

                    }
                    else if(i<s.length()-2 && s.charAt(i+1)=='A'){
                        if(s.charAt(i+2)=='B')
                        {
                            System.out.println("YES");
                            level1=1;
                            break;
                        }
                    }
                    i++;
                }
            else{
                i++;
            }

        }
     if(level1==0)
        System.out.println("NO");
   }
}


/* package whatever; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner in = new Scanner(System.in);

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

 		int sasha = 0;
 		int lena = 0;

		if (n / k % 2 == 0) System.out.println("NO");
		else System.out.println("YES");
	}
}


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

public class Main {
	public static final int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59 };
	public static int[][] dp, last;
	public static int[] masking;
	public static int[] a;
	public static int N;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		dp = new int[105][1 << 17];
		for (int i = 0; i < 105; i++) {
			Arrays.fill(dp[i], 1 << 29);
		}
		last = new int[105][1 << 17];
		dp[0][0] = 0;
		N = sc.nextInt();
		a = new int[N + 1];
		for (int i = 1; i <= N; i++) {
			a[i] = sc.nextInt();
		}
		init();
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j < 60; j++) {
				int x = (~masking[j]) & ((1 << 17) - 1);
				for (int s = x;; s = (s - 1) & x) {
					if (Math.abs(j - a[i]) + dp[i - 1][s] < dp[i][s | masking[j]]) {
						dp[i][s | masking[j]] = Math.abs(j - a[i]) + dp[i - 1][s];
						last[i][s | masking[j]] = j;
					}
					if (s == 0)
						break;
				}
			}
		}
		int res = 1 << 29;
		int curr = -1;
		int cmask = -1;
		for (int mask = 0; mask < (1 << 17); mask++) {
			if (dp[N][mask] < res) {
				res = dp[N][mask];
				curr = last[N][mask];
				cmask = mask;
			}
		}
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = N; i > 0; i--) {
			list.add(curr);
			cmask = cmask & (~masking[curr]);
			curr = last[i - 1][cmask];
		}
		Collections.reverse(list);
		for (int i : list) {
			System.out.print(i + " ");
		}
	}

	public static void init() {
		masking = new int[60];
		for (int i = 1; i < 60; i++) {
			for (int k = 0; k < 17; k++) {
				if (i % primes[k] == 0) {
					masking[i] |= (1 << k);
				}
			}
		}
	}
}


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

public class A {

	static IR in  = new IR(System.in);
	static double L,v1,v2;
	static double d;

	public static boolean can(double s)
	{
		double d0 = v1*s;
		double d1 = v2*s;

		if(Math.abs(d1-d0) > d) return true;
		else return false;
	}
	public static void main(String[]args)throws Throwable
	{
		d = in.d(); L = in.d(); v1 = in.d(); v2 = in.d();

	   double res = (double)(L-d)/(double)(Math.abs(v2+v1));
	   System.out.printf("%.9f",res);
	}

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

		public IR(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 long ll()
		{
			return Long.parseLong(next());
		}

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

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

	}
}


import java.util.Scanner;

public class Sleuth {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		String str = scan.nextLine();
		int flag = 0;
		String str2 = str.replaceAll(" ", "");
		String str3 = str2.toLowerCase();
		char arr[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
		char lasChar = str3.charAt(str3.length() - 2);
		for (int i = 0; i < arr.length; i++) {
			if (lasChar == arr[i]) {
				flag = 1;
				break;
			}
		}

		if (flag == 1) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}

	}

}


import java.util.Scanner;
public class Main {
	private static int[] ans=new int[1000001];
	public static void main(String[] args){
		Scanner cin=new Scanner(System.in);
		long x=cin.nextLong();
		long max=0;
		if(check(x)||x==1) {
			System.out.println(1+" "+x);
			return;
		}
		for(long i=1;i*i<=x;i++) {
			if(lcm(i,x/i)==x&&gcd(i,x/i)==1) {
				max=Math.max(max, i);
			}
		}
		System.out.println(max+" "+x/max);
	}
	public static long gcd(long m,long n) {
		return m%n==0?n:gcd(n,m%n);
	}
	public static long lcm(long m,long n) {
		return m*n/gcd(m,n);
	}
	public static boolean check(long n) {
		if(n<2) return false;
		for(int i=2;i<=Math.sqrt(n);i++) {
			if(n%i==0) return false;
		}
		return true;
	}
}


import java.util.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt();
        int g = sc.nextInt();
        int b = sc.nextInt();
        int time=29;
        if(r==0&&g==0&&b==0)System.out.print(0);
        else{
        while(r>0||g>0||b>0){
            r-=2;
            time++;
            if(r<1&&g<1&&b<1)break;
            g-=2;
            time++;
            if(r<1&&g<1&&b<1)break;
            b-=2;
            time++;
        }
        System.out.print(time);}
        System.exit(0);
    }

}


import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        StringBuilder s1 = new StringBuilder(scan.nextLine());
        String s2 = scan.nextLine();
        StringBuilder s3 = new StringBuilder(scan.nextLine());

        s1.append(s2.charAt(0));
        s3.insert(0, s2.charAt(2));

        boolean res = true;
        for(int i = 0; i<4; i++) {
            if(s1.charAt(i) != s3.charAt(3-i)) {
                res = false;
                break;
            }
        }
        System.out.println(res ? "YES" : "NO");
    }
}


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

public class Sol {
    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        long n = in.nextLong();
        System.out.println(solve(n));
    }

    private static long solve(long n) {
        if(n == 1) return 1;
        List<Long> divisor = primeFactors(n);
        if(divisor.size() == 1) return divisor.get(0);
        return 1;
    }

    static List<Long> primeFactors(long n) {
        Set<Long> res = new HashSet<>();
        if(n%2==0) res.add(2l);
        for(long i = 2; i < (long)Math.sqrt(n)+1; i++) {
            while(n%i == 0) {
                res.add(i);
                n = n/i;
            }
        }
        if(n > 2) res.add(n);
        return new ArrayList<>(res);
    }
}


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

public class Main
{
    public static void main(String args[])
    {
        // String s=fs.next();
        //char c[]=s.toCharArray();
        //int len=s.length();
         InputStream in=System.in;
         FastScanner fs=new FastScanner(in);
         PrintWriter out=new PrintWriter(System.out);
         int t=fs.nextInt();

         int x=fs.nextInt();
         int y=fs.nextInt();
         int tr=0;

            for(int i=0;i<=x;i++)
              {
                  long n=(long)t-((long)y*(long)i);
                  if(n<0)
                     break;
                   if(n%x==0)
                    {
                        tr=1;
                        x=(int)n/x;
                        y=i;
                        break;
                    }
              }

         if(tr==1)
         {  out.println("YES");
         out.println(x+" "+y);
     }
     else
        out.println("NO");
         out.close();

    }
   static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream f) {
            try {
                br = new BufferedReader(new InputStreamReader(f));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        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());
        }
        char [] charArray()
          {
            return  next().toCharArray();
          }

    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

    static class EBeautifulMatrix {
        long[] fac;
        int mod = 998244353;
        long[][] dp;

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

            int[][] a = new int[n][n];

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    a[i][j] = in.nextInt() - 1;
                }
            }

            fac = new long[2001];

            fac[0] = 1;

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

            long[] rank = new long[n];

            rank[0] = calRank(a[0], n);

            long tot = calTot(n);
            for (int i = 1; i < n; i++) {
                rank[i] = calDel(a[i - 1], a[i], n);
            }

            long ans = rank[0];

            for (int i = 1; i < n; i++) {
                ans *= tot;
                ans %= mod;

                ans += rank[i];
                ans %= mod;
            }

            out.println(ans);
        }

        long calRank(int[] a, int n) {
            long rank = 0;

            BinaryIndexedTree bit = new BinaryIndexedTree(n);
            for (int i = 0; i < n; i++) {
                int num = a[i];

                int prev = 0;
                if (num > 0) {
                    prev = num - bit.sum(num - 1);
                }

                if (prev > 0) {
                    rank += prev * fac[n - 1 - i];
                    rank %= mod;
                }

                bit.update(num, 1);
            }

            return rank;
        }

        long calTot(int n) {

            dp = new long[n + 1][n + 1];

            dp[0][0] = 1;
            dp[1][0] = 1;

            for (int i = 2; i <= n; i++) {
                for (int j = 0; j <= i; j++) {
                    if (i > j) {
                        if (j > 0) {
                            dp[i][j] += j * dp[i - 1][j - 1];
                            dp[i][j] %= mod;
                        }
                        dp[i][j] += (i - j) * dp[i - 1][j];
                        dp[i][j] %= mod;
                    } else {
                        dp[i][j] += (i - 1) * dp[i - 1][j - 2];
                        dp[i][j] %= mod;
                    }
                }
            }

            return dp[n][n];
        }

        long calDel(int[] pa, int[] a, int n) {

            long rank = 0;

            BinaryIndexedTree sbit = new BinaryIndexedTree(n);
            BinaryIndexedTree nsbit = new BinaryIndexedTree(n);

            for (int i = 0; i < n; i++) {
                sbit.update(i, 1);
            }

            int totsame = n;

            for (int i = 0; i < n; i++) {
                int same = sbit.sum(a[i] - 1);
                int usame = nsbit.sum(a[i] - 1);

                if (pa[i] < a[i]) {
                    int val = sbit.value(pa[i]);

                    same -= val;
                }

                if (sbit.value(pa[i]) == 1) {
                    if (totsame > 1)
                        rank += same * dp[n - 1 - i][totsame - 2];
                    rank %= mod;
                    if (totsame > 0)
                        rank += usame * dp[n - 1 - i][totsame - 1];

                    sbit.update(pa[i], -1);
                    nsbit.update(pa[i], 1);

                    totsame--;
                } else {
                    if (totsame > 0)
                        rank += same * dp[n - 1 - i][totsame - 1];
                    rank %= mod;
                    rank += usame * dp[n - 1 - i][totsame];
                }

                if (sbit.value(a[i]) == 1) {
                    sbit.update(a[i], -1);
                    totsame--;
                } else {
                    nsbit.update(a[i], -1);
                }

                rank %= mod;
            }

            return rank;
        }

        class BinaryIndexedTree {
            int n;
            int[] tree;

            public BinaryIndexedTree(int n) {
                super();
                this.n = n;
                this.tree = new int[n + 1];
            }

            public int sum(int idx) {
                idx++;

                int sum = 0;

                while (idx > 0) {
                    sum += tree[idx];
                    idx -= (idx & -idx);
                }

                return sum;
            }

            public void update(int idx, int v) {
                idx++;

                while (idx <= n) {
                    tree[idx] += v;
                    idx += (idx & -idx);
                }
            }

            public int value(int i) {
                int val = sum(i);

                if (i > 0) {
                    val -= sum(i - 1);
                }

                return val;
            }

        }

    }

    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 static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

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

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

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

        }

    }

    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 close() {
            writer.close();
        }

        public void println(long i) {
            writer.println(i);
        }

    }
}


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

public class A {

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

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

        int r1 = a / m;
        int c1 = a - r1 * m;

        int r2 = b / m;
        int c2 = b - r2 * m;

        if (a == 0 && b == n - 1) {
            out.print(1);
            return;
        }

        if (r1 == r2) {
            out.print(1);
            return;
        }

        if (c1 == 0 && c2 == m - 1) {
            out.print(1);
            return;
        }

        if (c1 == 0 && b == n - 1) {
            out.print(1);
            return;
        }

        if (c1 == 0 || c2 == m - 1) {
            out.print(2);
            return;
        }

        if (c1 == c2 + 1) {
            out.print(2);
            return;
        }

        if (r2 == r1 + 1) {
            out.print(2);
            return;
        }

        if (b == n - 1) {
            out.print(2);
            return;
        }

        out.print(3);

    }

    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 A().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.util.Arrays;
import java.util.Scanner;
public class A {

	public static void main(String[] args) {
 	Scanner scan=new Scanner(System.in);
 	int [] studenti=new int[6];
 	String otvet="";
 	for (int i = 0; i < 6; i++) {
        studenti[i] = scan.nextInt();
    }
 for (int i=3;i<6;i++)
 {
	 if (studenti [0]+studenti[1]+studenti[2]==studenti [3]+studenti[4]+studenti[5])
	    {
	    	otvet="YES";
	    	break;
    }
	 int per=studenti[0];
	 studenti[0]=studenti[i];
	 studenti[i]=per;
	 for (int j=3;j<6;j++)
	 {
		 if (studenti [0]+studenti[1]+studenti[2]==studenti [3]+studenti[4]+studenti[5])
		    {
		    	otvet="YES";
		    	break;
	 }
		 int per1=studenti[1];
		 studenti[1]=studenti[j];
		 studenti[j]=per1;
		 for (int k=3;k<6;k++)
		 {
			 if (studenti [0]+studenti[1]+studenti[2]==studenti [3]+studenti[4]+studenti[5])
			    {
			    	otvet="YES";
			    	break;
			    }
			 int per2=studenti[2];
			 studenti[2]=studenti[k];
			 studenti[k]=per2;
		 }
	 }
 }

 if (otvet=="YES")
 {
	 System.out.println(otvet);
 }

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

	}
}


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

public class B {

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

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

		k = Math.min(k, n / 2);

		long res = (long)k * (k - 1); // first and last
		res += (long)k * k; // first to last
		res += (long)(n - 2 * k) * 2 * k; // mid to rest

		out.println(res);
	}

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

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

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

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

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

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


import java.util.Scanner;

public class ProblemB {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		Long n = scan.nextLong();
		Long k = scan.nextLong();
		scan.close();
		long m;
		if(k % 2 == 0) {
			m = k / 2 - 1;
		}else {
			m = k / 2;
		}
		if(n >= k) {
			System.out.println(m);
		}else {
			if(2 * n - 1 < k) {
				System.out.println(0);
			}else {
				long ans = (2 * n - k + 1) / 2;
				System.out.println(ans);
			}
		}

	}
}


import java.util.Scanner;

public class SolutionA {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        if (!(a==0&&b==0)&&(a == b || a + 1 == b || b + 1 == a)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }
}


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.io.InputStream;
import java.util.Arrays;

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

class TaskA {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int [] lengths = {
            in.next().substring(2).length(),
            in.next().substring(2).length(),
            in.next().substring(2).length(),
            in.next().substring(2).length()
        };

        int [] buf, buf2;

        int numberOfGreater = 0, numberOfLess = 0;

        int max_ind = getMax(lengths);
        int min_ind = getMin(lengths);

        buf = Arrays.copyOf(lengths, 4);
        for(int item:buf)
            if(item/lengths[min_ind] >= 2)
                numberOfGreater++;

        buf2 = Arrays.copyOf(lengths, 4);
        for(int item:buf2)
            if(item*2 <= lengths[max_ind])
                numberOfLess++;

        int indx = 0;
        if(numberOfGreater == 3 && numberOfLess == 3)
            indx = 2;
        else if(numberOfGreater == 3)
            indx = min_ind;
        else if(numberOfLess == 3)
            indx = max_ind;
        else
            indx = 2;

        out.println("ABCD".charAt(indx));
    }

    public int getMin(int [] items){
        int min = 101;
        int index = 0;
        for(int i = 0; i<items.length; i++)
            if(items[i] < min){
                min = items[i];
                index = i;
            }
        return index;
    }

    public int getMax(int [] items){
        int max = 0;
        int index = 0;
        for(int i = 0; i<items.length; i++)
            if(items[i] > max){
                max = items[i];
                index = i;
            }
        return index;
    }
}

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

}


/*
javac f.java && java f
*/

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

public class f {
	public static void main(String[] args) { new f(); }
	FS in = new FS();
	PrintWriter out = new PrintWriter(System.out);

	int n;
	long[] a;

	int MAX = 5001;
	int pcnt, pr[];
	int[][] vp, cs;
	boolean[] isnt;

	f() {
		pcnt = 0;
		isnt = new boolean[MAX];
		isnt[0] = true; isnt[1] = true;
		for (int i = 2; i < MAX; i++)
			if (!isnt[i]) {
				pcnt++;
				for (int j = (i << 1); j < MAX; j += i)
					isnt[j] = true;
			}
		pr = new int[pcnt]; pcnt = 0;
		for (int i = 0; i < MAX; i++)
			if (!isnt[i])
				pr[pcnt++] = i;

		/*
		long ops = 0, gap3 = 0;
		for (int i = 0; i < pcnt; i++) {
			long del = i == 0 ? 1 : pr[i] - pr[i - 1];
			out.printf("del = %d | p = %d%n", del, pr[i]);
			ops += (del * del * del);
			gap3 = max(gap3, del * del * del);
		}
		out.println("--> " + ops + " OW3 " + gap3);
		*/

		vp = new int[MAX][pcnt];
		for (int i = 2; i < MAX; i++)
			for (int j = 0; j < pcnt; j++) {
				int k = i;
				while (k > 0) {
					vp[i][j] += (k / pr[j]);
					k /= pr[j];
				}
			}
		cs = new int[MAX][pcnt + 1];
		for (int i = 2; i < MAX; i++)
			for (int j = 1; j <= pcnt; j++)
				cs[i][j] = vp[i][j - 1] + cs[i][j - 1];

		n = in.nextInt();
		a = new long[MAX];
		for (int i = 0; i < n; i++) {
			int x = in.nextInt();
			if (x == 0) x++;
			a[x]++;
		}
		long[] f = new long[MAX + 1];
		for (int i = 1; i <= MAX; i++)
			f[i] = f[i - 1] + a[i - 1];

		long[] dist = new long[MAX + 1];
		for (int i = 1; i <= MAX; i++)
			dist[i] = dist[i - 1] + a[i - 1] * cs[i - 1][pcnt];

		// F I X  T H I S
		long ans = dist[MAX];
		int l = 2, r;
		for (int i = 0; i < pcnt; i++) {
			r = i == pcnt - 1 ? MAX - 1 : pr[i + 1] - 1;
			// everybody outside this range of highest prime must travel to 1 first
			// then travel up to the lca we're trying at each step
			long blw = dist[MAX] - (dist[r + 1] - dist[l]);
			// so when trying lca(j, k) we need to know how many primes are on in it
			// and how far every person in the range [l, r] will need to travel
			for (int x = r; x >= l; x--)
				for (int y = x; y >= l; y--) {
					// lca will be gotten as (pIDX, cnt)
					int[] lca = {-1, 0};
					for (int z = i; z >= 0; z--)
						if (vp[x][z] != vp[y][z]) {
							lca[0] = z;
							lca[1] = min(vp[x][z], vp[y][z]);
							break;
						}

					long up = lca[1] + cs[x][pcnt] - cs[x][lca[0] + 1];
					up *= (f[MAX] - f[r + 1] + f[l]);

					long abv = 0;
					for (int z = r; z >= l; z--) {
						if (x == z && y == z) continue;
						// given lca(x, y) = {w, cnt}
						// if we get to w add in prefix of other primes in a[z] * cs[w - 1]
						// add a[z] * [abs(cnt - cnt[z]) to abv
						// if we dont get to w before they differ
						// add a[z] * (diff to here + here up)
						for (int w = i; w >= lca[0]; w--) {
							if (w == lca[0]) {
								abv += a[z] * cs[z][w];
								abv += a[z] * abs(vp[z][w] - lca[1]);
								break;
							}
							if (vp[z][w] != vp[x][w]) {
								abv += a[z] * cs[z][w];
								abv += a[z] * abs(vp[z][w] - vp[x][w]);
								abv += a[z] * (cs[x][w] - cs[x][lca[0] + 1]);
								abv += a[z] * lca[1];
								break;
							}
						}
					}
					ans = min(ans, abv + blw + up);
				}
			l = r + 1;
		}

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

	int abs(int x) { if (x < 0) return -x; return x; }
	long abs(long x) { if (x < 0) return -x; return x; }
	int max(int x, int y) { if (x < y) return y; return x; }
	int min(int x, int y) { if (x > y) return y; return x; }
	long max(long x, long y) { if (x < y) return y; return x; }
	long min(long x, long y) { if (x > y) return y; return x; }
	int gcd(int x, int y) { while (y != 0) { x = y^(x^(y = x)); y %= x; } return x; }
	long gcd(long x, long y) { while (y != 0) { x = y^(x^(y = x)); y %= x; } return x; }
	long lcm(int x, int y) { long xy = x; xy *= y; return xy / gcd(x, y); }
	long lcm(long x, long y) { return (x * y) / gcd(x, y); }

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

		void intArr(int sz, int[] x) { for (int i = 0; i < sz; i++) x[i] = nextInt(); }
		void longArr(int sz, long[] x) { for (int i = 0; i < sz; i++) x[i] = nextLong(); }
		void doubleArr(int sz, double[] x) { for (int i = 0; i < sz; i++) x[i] = nextDouble(); }
	}
}


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

public class Main {

    public static void main(String[] args) {
        FastReader in = new FastReader();
        String s = in.next();
        boolean flag = true;
        char c[] = new char[s.length()];
        if (s.charAt(0) == 'a') {
            c[0] = 'a';
            for (int i = 1; i < s.length(); i++) {
                for (int j = 0; j < s.length(); j++) {
                    if (s.charAt(i) == c[j] || s.charAt(i) - c[j] == 1) {
                        c[i] = s.charAt(i);
                        break;
                    }
                }
            }
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) != c[i]) {
                    flag = false;
                }
            }
            if (flag == true) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }

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

    }
}

class FastReader {

    BufferedReader br;
    StringTokenizer st;

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

    }

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

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

    }

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

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


import java.util.*;
public class Main {
public static void main(String [] args){
	Scanner in=new Scanner(System.in);
	int xp=in.nextInt();
	int yp=in.nextInt();
	int xv=in.nextInt();
	int yv=in.nextInt();
	if(xp <= xv && yp <=yv || xp + yp <= Math.max(xv,yv)){
		System.out.print("Polycarp");
		return;
	}
     System.out.print("Vasiliy");
}
}


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

/**
 * Generated by Contest helper plug-in
 * Actual solution is at the bottom
 */
public class Main {
    public static void main(String[] args) {
        InputReader in = new StreamInputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        run(in, out);
    }

    public static void run(InputReader in, PrintWriter out) {
        Solver solver = new Move();
        solver.solve(1, in, out);
        Exit.exit(in, out);
    }
}

class StreamInputReader extends InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar, numChars;

    public StreamInputReader(InputStream stream) {
        this.stream = stream;
        curChar = 0;
    }

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

    @Override
    public void close() {
        try {
            stream.close();
        } catch (IOException ignored) {
        }
    }
}

abstract class InputReader {
    private boolean finished = false;

    public abstract int read();

    public String nextToken() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }
    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public void setFinished(boolean finished) {
        this.finished = finished;
    }

    public abstract void close();
}

interface Solver {
    public void solve(int testNumber, InputReader in, PrintWriter out);
}

class Exit {
    private Exit() {
    }

    public static void exit(InputReader in, PrintWriter out) {
        in.setFinished(true);
        in.close();
        out.close();
    }
}

class Move implements Solver {

    Vector<String> ans ;

    void print(int i0, int j0, int i1, int j1) {
        if (i0 == i1) {
            int mn = Math.min(j0, j1);
            String p[] = H.split(" ");
            for (int j = 0; j < p.length; ++j) {
                if (p[j].equals("D")) {
                    ans.add("D"+(mn+1));
                } else {
                    ans.add(p[j]+(i0+1));
                }
            }
        } else {
            int mx = Math.max(i0, i1);
            String p[] = V.split(" ");
            for (int j = 0; j < p.length; ++j) {
                if (p[j].equals("R")) {
                    ans.add("R"+(mx+1));
                } else {
                    ans.add(p[j]+(j0+1));
                }
            }
        }
    }
    static final String H = "D L D R D L D R D L D R D";
    static final String V = "R D R U R D R U R D R U R";
    public void solve(int testNumber, InputReader in, PrintWriter out) {

        String H = "D L D R D L D R D L D R D";//swap, (i, j) -> (i, j + 1)/

        //
        //                                       // Uj Li Ri
        String V = "R D R U R D R U R D R U R"; // swap (i, j) (i + 1, j)
                                                // R(i+1), Down up -> j

        ans = new Vector<String> () ;
        //build();
        char s[] = new char[36];
        for (int i = 0; i <= 9; ++i) {
            s[i] = (char)(i + '0');
        }
        for (int i = 0; i < 26; ++i) {
            s[i + 10] = (char)(i + 'A');
        }
        char tmp[][] = new char[6][6];
        int p = 0;
        for (int i = 0; i < s.length; ++i) {
            tmp[p / 6][p % 6] = s[i];
            p ++ ;
        }
        State start = new State(tmp);

        char r[][] = new char[6][];
        for (int i =0 ; i < 6; ++i)
            r[i] = in.nextToken().toCharArray();
        State cur = new State(r);

        HashMap<Character, P> pointer = new HashMap<Character, P> ();
        for (int i = 0; i < 6; ++i)
            for (int j = 0; j < 6; ++j)
                pointer.put(cur.s[i][j], new P(j, i));

        while (!start.equals(cur)) {
            for (int i = 0; i < 6; ++i)
                for (int j = 0; j < 6; ++j) {
                    if (start.s[i][j] != cur.s[i][j])  {
                        while (start.s[i][j] != cur.s[i][j]) {
                            P tt = pointer.get(start.s[i][j]);
                            int pi = tt.y;
                            int pj = tt.x;
                            int dj = (j - pj == 0 ? 0 : (j - pj) / Math.abs(j - pj));
                            int di = (i - pi == 0 ? 0 : (i - pi) / Math.abs(i - pi));
                            int npi = -1, npj = -1;
                            if (di != 0) {
                                npi = pi + di;
                                npj = pj ;
                            } else if (dj != 0) {
                                npi = pi;
                                npj = pj + dj;
                            } else throw new RuntimeException();
                            print(npi, npj, pi, pj);
                            char ch = cur.s[npi][npj];
                            cur.s[npi][npj] = cur.s[pi][pj];
                            cur.s[pi][pj] = ch;
                            pointer.put(cur.s[npi][npj], new P(npj, npi));
                            pointer.put(cur.s[pi][pj], new P(pj, pi));
                        }
                    }
                }
        }

        cur = new State(r);
        out.print(ans.size() + "\n");
        for (String str : ans) {
            out.println(str);
        /*    char ch = str.charAt(0);
            int dig = str.charAt(1) - '1';
            if (ch == 'D') cur = cur.rotateDown(dig);
            else if (ch == 'U') cur = cur.rotateUp(dig);
            else if (ch == 'R') cur = cur.rotateRight(dig);
            else if (ch == 'L') cur = cur.rotateLeft(dig);*/
        }
      //  out.print("res : \n");
      //  out.print(cur);

    }
    class P {
        int x, y;

        P(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof P)) return false;

            P p = (P) o;

            if (x != p.x) return false;
            if (y != p.y) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }

    class State {
        char s[][] ;

        State(char[][] s) {
            this.s = new char[s.length][];
            for (int i = 0; i < s.length; ++i)
                this.s[i] = s[i].clone();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;

            State tmp = (State) o;
            for (int i =0 ; i < 6; ++i)
                for (int j =0 ; j < 6; ++j)
                    if (this.s[i][j] != tmp.s[i][j]) return false;
            return true;
        }

        @Override
        public int hashCode() {
            int r = 1;
            for (int i = 0; i < 6; ++i)
                for (int j = 0; j < 6; ++j)
                    r = 31 * r + (s[i][j] - '0' + 1);
            return r;
        }

        @Override
        public String toString() {
            String tmp = "";
            for (int i =0 ; i < 6; ++i) {
                tmp += Arrays.toString(this.s[i]) + "\n";
            }
            return tmp;
        }
    }
}


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Arrays;
public class Cards {
	public static void main(String[]args)throws IOException,NumberFormatException{
		BufferedReader bf =new BufferedReader(new InputStreamReader(System.in));
		int n=Integer.parseInt(bf.readLine());
		String s=bf.readLine();
		String[]sa=s.split(" ");
		int[]a=new int[n];
		for(int i=0;i<n;i++){
			a[i]=Integer.parseInt(sa[i]);
		}
		boolean[]v=new boolean[n];
		for(int i=0;i<n/2;i++){
			int min=Integer.MAX_VALUE;
			int max=0;
			int minp=0;
			int maxp=0;
			for(int j=0;j<n;j++){
				if(!v[j]){
					if(a[j]>=max){
						max=a[j];
						maxp=j;
					}
					if(a[j]<min){
						min=a[j];
						minp=j;
					}
				}
			}
			v[maxp]=true;
			v[minp]=true;
			System.out.println((minp+1)+" "+(maxp+1));
		}
	}
}


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[] 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 {
		Node root;
		int n;

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

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

		public void addPoint(int idx, long delta) {
			Node.ql = idx;
			Node.delta = delta;
			root.addPoint(0, n);
		}

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

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

		public long getPoint(int idx) {
			Node.ql = idx;
			return root.getPoint(0, n);
		}

		public int maxPos() {
			return root.maxPos(0, n);
		}

		static class Node {
			static int ql, qr;
			static long delta;

			Node left, right;
			long add, max;

			long getMax() {
				return max + add;
			}

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

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

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

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

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

			void addPoint(int l, int r) {
				if (r - l == 1) {
					add += delta;
					return;
				}
				int m = (l + r) >> 1;
				if (ql < m) {
					left.addPoint(l, m);
				} else {
					right.addPoint(m, r);
				}
				max = Math.max(left.getMax(), right.getMax());
			}

			long getPoint(int l, int r) {
				if (r - l == 1) {
					return getMax();
				}
				int m = (l + r) >> 1;
				return (ql < m ? left.getPoint(l, m) : right.getPoint(m, r)) + add;
			}
		}
	}

	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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

public class E {

    static boolean DEBUG=false;
    static int N=4;

    static class bits {
        int d,cnt;
        bits(int d, int cnt) {
            this.d=d; this.cnt=cnt;
        }
        long h(bits b) {
            if(d==b.d) {
                return Math.abs(cnt-b.cnt);
            } else {
                return (long)Math.min(cnt, b.cnt)+(long)Math.min(N-cnt, N-b.cnt);
            }
        }
        public String toString() {
            return d+":"+cnt;
        }
    }

    static long h(bits a, bits b, bits c) {
        return a.h(b)+b.h(c)+c.h(a);
    }

    static long maxh(bits[] in, int l, int r) {
        bits lb=in[l], rb=in[r];
        long max=-1;

        for (int i=0; i<in.length; i++) {
            if(i!=l&&i!=r) {
                long h=h(lb,rb,in[i]);
                if(h>max) {
                    max=h;
                }
            }
        }

        return max;
    }

    static long cnt_between(bits[] in, int ll, int rr, long max) {
        int lr=ll, rl=rr;
        while (lr+1<=rr&&in[lr+1].cnt==in[ll].cnt) {
            lr++;
        }
        //at this point lr points to rightmost position s.t. in[lr].cnt==in[ll].cnt

        while (rl-1>=ll&&in[rl-1].cnt==in[rr].cnt) {
            rl--;
        }
        //at this point rl points to leftmost position s.t. in[rl].cnt==in[rr].cnt

        if(lr>=rl) {
            //all numbers [ll,rr] are the same, (rr-ll+1) take 3...
            long k=(rr-ll+1);
            return max==0? k*(k-1)*(k-2)/6: 0;
        }

        long ret=0;
        //here we count triples (i,j,k) where ll<=i<=lr && lr<j<rl && rl<=k<=rr
        for (int i=lr+1; i<rl; i++) {
            long v=(long)(lr-ll+1)*(long)(rr-rl+1);
            if(h(in[ll],in[rr],in[i])==max) {
                ret+=v;
                if(DEBUG) {
                    System.out.println("added "+v+" for "+i+" in["+ll+","+rr+"]");
                }
            }
        }

        //here we count triples (i,j,k) where ll<=i,j<=lr && rl<=k<=rr || ll<=i<=lr && rl<=j,k<=rr
        if(max==2*in[ll].h(in[rr])) {
            long l=lr-ll+1, r=rr-rl+1;
            ret+=(l*(l-1)*r + r*(r-1)*l)/2;
        }
        return ret;
    }

    static long cnt_pairs(int ll, int lr, int rl, int rr) {
        if(lr<rl) {
            long l=lr-ll+1, r=rr-rl+1;
            return l*r;
        } else {
            long rl_lr=lr-rl+1, ll_rl=rl-ll, lr_rr=rr-lr;

            return
                    ll_rl*lr_rr+
                    rl_lr*lr_rr+
                    ll_rl*rl_lr+
                    rl_lr*(rl_lr-1)/2;
        }
    }

    static long solve(bits[] in) {
        int n=in.length;
        Arrays.sort(in, new Comparator<bits>() {
            @Override
            public int compare(bits o1, bits o2) {
                int ret=o1.d-o2.d;
                if(ret==0) {
                    ret=o1.d==1? o1.cnt-o2.cnt: o2.cnt-o1.cnt;
                }
                return ret;
            }});

        int max0=-1;
        for (int i=0; i<n; i++) {
            if(in[i].d==0) {
                max0=i;
            }
        }

        if(max0<0||max0==n-1) {
            long maxh=maxh(in,0,n-1);
            return cnt_between(in, 0, n-1, maxh);
        } else {
            long maxh=Math.max(maxh(in,0,max0), maxh(in,max0+1,n-1));
            if(DEBUG) {
                System.out.println("maxh: "+maxh);
            }
            long ret=cnt_between(in, 0, max0, maxh);
            ret+=cnt_between(in, max0+1, n-1, maxh);

            int lo=n-2, hi=n-1;
            for (int i=0; i<=max0; i++) {
                if(h(in[max0+1],in[n-1],in[i])==maxh) {
                    while(h(in[lo],in[n-1],in[i])<h(in[max0+1],in[n-1],in[i])) {
                        lo--;
                    }

                    while(hi-1>max0+1&&h(in[max0+1],in[hi-1],in[i])==h(in[max0+1],in[n-1],in[i])) {
                        hi--;
                    }

                    long v=cnt_pairs(max0+1, lo, hi, n-1);
                    ret+=v;
                    if(DEBUG) {
                        System.out.println("added "+v+" for "+i+" out["+(max0+1)+","+(n-1)+"]");
                    }
                }
            }

            lo=0; hi=1;
            for (int i=n-1; i>=max0+1; i--) {
                if(h(in[0],in[max0],in[i])==maxh) {
                    while(lo+1<max0&&h(in[lo+1],in[max0],in[i])==h(in[0],in[max0],in[i])) {
                        lo++;
                    }

                    while(h(in[0],in[hi],in[i])<h(in[0],in[max0],in[i])) {
                        hi++;
                    }

                    long v=cnt_pairs(0, lo, hi, max0);
                    ret+=v;
                    if(DEBUG) {
                        System.out.println("added "+v+" for "+i+" out[0,"+max0+"]");
                    }
                }
            }
            return ret;
        }
    }

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

        bits[] in=new bits[Integer.parseInt(nm[1])];
        for (int i=0; i<in.length; i++) {
            String l=br.readLine();

            in[i]=new bits(
                    Integer.parseInt(l.substring(0, 1)),
                    Integer.parseInt(l.substring(2)));
        }

        System.out.println(solve(in));
        //System.out.println(baseline(in));
    }

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

        //run_random();
        //run();
    }

    static void run_random() {
        Random r=new Random();

        int n=100;
        bits[] in=new bits[n];

        for (int j=0; j<100; j++) {
            for (int i=0; i<n; i++) {
                int d=r.nextBoolean()? 1: 0;
                in[i]=new bits(d, d==0? N: r.nextInt(N)+1);
            }

            run(in);
        }
    }

    static void run() {
        DEBUG=true;
        bits[] in=new bits[] {new bits(0,4),new bits(0,4),new bits(0,4),new bits(0,4), new bits(0,4),new bits(1,1),new bits(1,1),new bits(1,1),new bits(1,1),new bits(1,2)};
        run(in);
    }

    static void run(bits[] in) {
        long ret1=solve(in);
        long ret2=baseline(in);

        if(ret1!=ret2) {
            System.out.println("expected: "+ret2+" got "+ret1);
            System.out.println(Arrays.deepToString(in));
        } else {
            System.out.println("all good");
        }
    }

    static long baseline(bits[] in) {
        int n=in.length;
        long max=-1, ret=0;
        for (int i=0; i<n; i++) {
            for (int j=i+1; j<n; j++) {
                for (int k=j+1; k<n; k++) {
                    if(h(in[i],in[j],in[k])>max) {
                        max=h(in[i],in[j],in[k]);
                        ret=1;
                        if(DEBUG&&max==4) {
                            System.out.println(i+","+j+","+k);
                        }
                    } else if(h(in[i],in[j],in[k])==max) {
                        ret++;
                        if(DEBUG&&max==4) {
                            System.out.println(i+","+j+","+k);
                        }
                    }
                }
            }
        }

        if(DEBUG) {
            System.out.println("maxh: "+max);
        }
        return ret;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main
{
	public static void main(String[] args) {
		new Thread(null, new Runnable() {
			public void run() {
                solve();
            }
        }, "1", 1 << 26).start();
	}
	static void solve () {
		FastReader fr =new FastReader();	PrintWriter op =new PrintWriter(System.out);

 		int t =fr.nextInt() ,n ,k ,l ,m ,tx[][] ,i ,j ;
 		boolean psbl[][] ,dm ;

 		while (t-- > 0) {
 			n =fr.nextInt() ;	k =fr.nextInt() ;	l =fr.nextInt() ;

 			tx =new int[2*k][n+1] ;	psbl =new boolean[2*k][n+1] ;

 			for (i =1 ; i<=n ; ++i)	tx[0][i] =fr.nextInt() ;

 			for (i =1 ; i<=k ; ++i)	{
 				for (j =1 ; j<=n ; ++j)	tx[i][j] =tx[0][j] + i ;
 			}
 			for (; i<2*k ; ++i) {
 				for (j =1 ; j<=n ; ++j)	tx[i][j] =tx[k][j] - (i-k) ;
 			}

 			for (i =0 ; i<2*k ; ++i) {
 				if (tx[i][n] <= l)	psbl[i][n] =true ;
 			}

 			for (i =n-1 ; i>0 ; --i) {
 				for (j =0 ; j<2*k ; ++j) {
 					dm =false ;
 					for (m =0 ; m<2*k ; ++m) {
 						if (tx[(j+m)%(2*k)][i] > l)	break;

 						dm |= psbl[(j+m+1)%(2*k)][i+1] ;
 					}
 					psbl[j][i] =dm ;
 				}
 			}

 			dm =false ;
 			for (i =0 ; i<2*k ; ++i)	dm |= psbl[i][1] ;
 			if (dm)	op.println("Yes") ;
 			else 	op.println("No") ;
 		}
		op.flush();	op.close();
	}
	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		String nextLine() {
			String str ="";

			try
			{
				str =br.readLine();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}

			return str;
		}

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

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


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

public class E_new {

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

	static final int P = 1_000_000_007;
	static final long P2 = (long) P * P;

	int[] oneCol(int[] dp, int h, int prevH) {

		for (int j = 0; j < h; j++) {
			int[] next = new int[1 << h];
			boolean canDown = j != 0;
			boolean canLeft = j < prevH;
			for (int was = 0; was < (1 << h); was++) {
				if (dp[was] == 0) {
					continue;
				}
				boolean needLeft = (was & 1) == 1;
				if (needLeft && !canLeft) {
					throw new AssertionError();
				}
				// down and left
				if (canDown && canLeft) {
					int tmp = clear(was, h - 1) >> 1;
					next[tmp] += dp[was];
					if (next[tmp] >= P) {
						next[tmp] -= P;
					}
				}
				// down
				if (canDown && !needLeft) {
					int tmp = clear(was, h - 1) >> 1;
					next[tmp] += dp[was];
					if (next[tmp] >= P) {
						next[tmp] -= P;
					}
				}
				// left
				if (canLeft) {
					int tmp = was >> 1;
					next[tmp] += dp[was];
					if (next[tmp] >= P) {
						next[tmp] -= P;
					}
				}
				// nothing
				if (!needLeft) {
					int tmp = set(was >> 1, h - 1);
					next[tmp] += dp[was];
					if (next[tmp] >= P) {
						next[tmp] -= P;
					}
				}

			}
			dp = next;
		}
		return dp;
	}

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

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

		for (int h = 1; h <= 7; h++) {
			int w = ws[h - 1];
			if (w == 0) {
				continue;
			}
			dp = Arrays.copyOf(dp, 1 << h);
			dp = oneCol(dp, h, prevH);
			prevH = h;
			int[][] m = new int[1 << h][];
			int[] tmp = new int[1 << h];
			for (int i = 0; i < 1 << h; i++) {
				tmp[i] = 1;
				if (i > 0) {
					tmp[i - 1] = 0;
				}
				m[i] = oneCol(tmp, h, h);
			}
//			System.err.println(Arrays.toString(dp));
//			System.err.println(Arrays.deepToString(m));
			m = pow(m, w - 1);

			int[] next = new int[1 << h];
			for (int i = 0; i < (1 << h); i++) {
				for (int j = 0; j < (1 << h); j++) {
					next[j] += (int) ((long) dp[i] * m[i][j] % P);
					next[j] %= P;
				}
			}
			dp = next;

		}

		out.println(dp[0]);
	}

	static int[][] mul(int[][] a, int[][] b) {
		int n = a.length;
		int[][] c = new int[n][n];
		for (int i = 0; i < n; i++) {
			int[] A = a[i];
			for (int j = 0; j < n; j++) {
				long tmp = 0;
				for (int k = 0; k < n; k++) {
					tmp += (long) A[k] * b[k][j];
					if (tmp >= P2) {
						tmp -= P2;
					}
				}
				c[i][j] = (int) (tmp % P);
			}
		}
		return c;
	}

	static int[][] pow(int[][] a, int b) {
		int[][] ret = new int[a.length][a.length];
		for (int i = 0; i < a.length; i++) {
			ret[i][i] = 1;
		}
		for (; b > 0; b >>= 1) {
			if ((b & 1) == 1) {
				ret = mul(ret, a);
			}
			a = mul(a, a);
		}
		return ret;
	}

	int clear(int mask, int i) {
		return mask & ~(1 << i);
	}

	int set(int mask, int i) {
		return mask | (1 << i);
	}

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

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

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

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

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

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

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


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
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);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            ArrayList<Integer> al = new ArrayList<>();
            for (int i = n; i > n - 85 && i > 0; i--) {
                if (i + digitsum(i) == n) {
                    al.add(i);
                }
            }
            out.println(al.size());
            Collections.sort(al);
            for (Integer ii : al) {
                out.println(ii);
            }
        }

        public int digitsum(int n) {
            String[] p = Integer.toString(n).split("");
            int sum = 0;
            for (String ll : p) {
                sum += Integer.parseInt(ll);
            }
            return sum;
        }

    }

    static class InputReader {
        public byte[] buf = new byte[8000];
        public int index;
        public int total;
        public InputStream in;

        public InputReader(InputStream stream) {
            in = stream;
        }

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

        public int nextInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n))
                n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                } else
                    throw new InputMismatchException();
            }
            return neg * integer;
        }

        public boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
                return true;
            return false;
        }

    }
}


/*
 * Author: Abhi Sapariya
 */
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;

public class Solution{

	static long mod =(long)Math.pow(10,9)+7;
	static InputReader in;
    static PrintWriter out;

	public static void main(String[] args) {

		in = new InputReader(System.in);
		out = new PrintWriter(System.out);

		//CODE
        long t=in.nextLong();
        int l=in.nextInt();
        int r=in.nextInt();
        long[] ans=new long[r+1];
        Arrays.fill(ans, -1);
        long[] min=new long[r+1];
        Arrays.fill(min, -1);
        int sqr=(int)Math.sqrt(r);
        for(int i=2;i<=sqr;i++){
            if(min[i]==-1){
                min[i]=i;
                for(int j=i*i;j<=r;j+=i){
                    if(min[j]==-1){
                        min[j]=i;
                    }
                }
            }
        }
        ans[1]=0;
        for(int i=2;i<=r;i++){
            if(min[i]==-1)
                min[i]=i;
            long x=((long)i/min[i])*(min[i]*(min[i]-1))/2;
            ans[i]=(x+ans[(int) (i/min[i])])%mod;
        }
        //for(int i=2;i<=r;i++)
            //System.out.println(ans[i]);
        long ans1=0;
        long pow=1;
        for(int i=l;i<=r;i++){
            //System.out.println(ans[i]);
            ans1=(ans1+(pow*ans[i])%mod)%mod;
            pow=(pow*t)%mod;
        }
        out.println(ans1);

	    out.close();
	}

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

    static long power(long base, long exponent, long modulus){
	    long result = 1L;
	    while (exponent > 0) {
	        if (exponent % 2L == 1L)
	            result = (result * base) % modulus;
	        exponent = exponent >> 1;
	        base = (base * base) % modulus;
	    }
	    return result;
	}

    // This class represents a directed graph using adjacency list
	// representation
	class Graph {
		private int V; // No. of vertices

		// Array  of lists for Adjacency List Representation
		private LinkedList<Integer> adj[];

		// Constructor
		Graph(int v) {
			V = v;
			adj = new LinkedList[v];
			for (int i = 0; i < v; ++i)
				adj[i] = new LinkedList<Integer>();
		}

		//Function to add an edge into the graph
		void addEdge(int v, int w) {
			adj[v].add(w); // Add w to v's list.
		}

		// A function used by DFS
		void DFSUtil(int v, boolean visited[]) {
			// Mark the current node as visited and print it
			visited[v] = true;
			System.out.print(v + " ");

			// Recur for all the vertices adjacent to this vertex
			Iterator<Integer> i = adj[v].listIterator();
			while (i.hasNext()) {
				int n = i.next();
				if (!visited[n])
					DFSUtil(n, visited);
			}
		}

		// The function to do DFS traversal. It uses recursive DFSUtil()
		void DFS(int v) {
			// Mark all the vertices as not visited(set as
			// false by default in java)
			boolean visited[] = new boolean[V];

			// Call the recursive helper function to print DFS traversal
			DFSUtil(v, visited);
		}
	}

    static HashMap<Long,Long> primeFactors(long n){
        HashMap<Long,Long> ans=new HashMap<Long,Long>();
    	// Print the number of 2s that divide n
        while (n%2L==0L)
        {
            if(ans.containsKey(2L)){
            	ans.put(2L,ans.get(2L)+1L);
            }else{
            	ans.put(2L,1L);
            }
            n /= 2L;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (long i = 3; i <= Math.sqrt(n); i+= 2L)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
            	if(ans.containsKey(i)){
                	ans.put(i,ans.get(i)+1L);
                }else{
                	ans.put(i,1L);
                }
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            ans.put(n,1L);
        return ans;
    }

    //for marking all prime numbers greater than 1 and less than equal to N
    static boolean[] sieveOfEratosthenes(int n) {

		boolean prime[] = new boolean[n];
		// Create a boolean array "prime[0..n]" and initialize
		// all entries it as true. A value in prime[i] will
		// finally be false if i is Not a prime, else true.
		for (int i = 0; i < n; i++)
			prime[i] = true;

		for (int p = 2; p * p <= n; p++) {
			// If prime[p] is not changed, then it is a prime
			if (prime[p] == true) {
				// Update all multiples of p
				for (int i = p * 2; i <= n; i += p)
					prime[i] = false;
			}
		}

		return prime;
	}

    // Binary indexed Tree parameters (arr,arr.length)
    static class BITree {

		int[] tree;

		public BITree(int arr[], int n) {
			tree = new int[n + 1];
			for (int i = 0; i < n; i++) {
				update(i, arr[i]);
			}
		}

		public void update(int x, int val) {
			x++;
			while (x < tree.length) {
				tree[x] += val;
				x = next(x);
			}
		}

		public int sum(int x) {
			x++;
			int ans = 0;
			while (x > 0) {
				ans += tree[x];
				x = parent(x);
			}
			return ans;
		}

		public int parent(int x) {
			return x - (x & -x);
		}

		public int next(int x) {
			return x + (x & -x);
		}

	}

    // Range minimum query Segment Tree parameters - (arr,arr.length)
    static class SegmentTree {

		static int[] segT;

		public SegmentTree(int arr[], int n) {
			int nearPow = (int) (Math.ceil(Math.log(n) / Math.log(2)));
			int len = 2 * ((int) Math.pow(2, nearPow)) - 1;
			segT = new int[len];
			constructTree(arr, 0, n - 1, 0);
		}

		public void constructTree(int arr[], int low, int high, int pos) {
			if (low == high) {
				segT[pos] = arr[low];
				return;
			}

			int mid = (low + high) / 2;
			constructTree(arr, low, mid, 2 * pos + 1);
			constructTree(arr, mid + 1, high, 2 * pos + 2);
			segT[pos] = Math.min(segT[2 * pos + 1], segT[2 * pos + 2]);
		}

		public int rmq(int low, int high, int n) {
			return rmq(0, n - 1, low, high, 0);
		}

		public int rmq(int low, int high, int qlow, int qhigh, int pos) {

			if (qlow <= low && qhigh >= high) {
				return segT[pos];
			}
			if (high < qlow || qhigh < low) {
				return Integer.MAX_VALUE;
			}
			int mid = (low + high) / 2;
			return Math.min(rmq(low, mid, qlow, qhigh, 2 * pos + 1),
					rmq(mid + 1, high, qlow, qhigh, 2 * pos + 2));
		}

	}

    // isPrime
	static boolean isPrime(long n) {
		if(n < 2L) return false;
		if(n == 2L || n == 3L) return true;
		if(n%2L == 0 || n%3L == 0) return false;
		long sqrtN = (long)Math.sqrt(n)+1L;
		for(long i = 6L; i <= sqrtN; i += 6L) {
			if(n%(i-1) == 0 || n%(i+1) == 0) return false;
		}
		return true;
	}

	// Nth fibonacci number%mod in log(n)
	static class fibonacci {
		public static long fib(long n, long mod) {
			long F[][] = new long[][] { { 1, 1 }, { 1, 0 } };
			if (n == 0l)
				return 0l;
			power(F, n - 1, mod);

			return F[0][0] % mod;
		}

		public static void multiply(long F[][], long M[][], long mod) {
			long x = (((F[0][0]) * (M[0][0])) % mod + ((F[0][1]) * (M[1][0]))
					% mod)
					% mod;
			long y = (((F[0][0]) * (M[0][1])) % mod + ((F[0][1]) * (M[1][1]))
					% mod)
					% mod;
			long z = (((F[1][0]) * (M[0][0])) % mod + ((F[1][1]) * (M[1][0]))
					% mod)
					% mod;
			long w = (((F[1][0]) * (M[0][1])) % mod + ((F[1][1]) * (M[1][1]))
					% mod)
					% mod;

			F[0][0] = x;
			F[0][1] = y;
			F[1][0] = z;
			F[1][1] = w;
		}

		/* Optimized version of power() in method 4 */
		public static void power(long F[][], long n, long mod) {
			if (n == 0l || n == 1l)
				return;
			long M[][] = new long[][] { { 1l, 1l }, { 1l, 0l } };

			power(F, n / 2l, mod);
			multiply(F, F, mod);
			if (n % 2l != 0l)
				multiply(F, M, mod);
		}
	}

	//minimum prime factor of all the numbers less than n
    static int minPrime[];
	static void minimumPrime(int n){
		minPrime=new int[n+1];
		minPrime[1]=1;
        for (int i = 2; i * i <= n; ++i) {
            if (minPrime[i] == 0) {         //If i is prime
                for (int j = i * i; j <= n; j += i) {
                    if (minPrime[j] == 0) {
                        minPrime[j] = i;
                    }
                }
            }
        }
        for (int i = 2; i <= n; ++i) {
            if (minPrime[i] == 0) {
                minPrime[i] = i;
            }
        }
	}

	static long modInverse(long A, long M)
	{
		long x=extendedEuclid(A,M)[0];
		return (x%M+M)%M;    //x may be negative
	}

	static long[] extendedEuclid(long A, long B) {
		if(B == 0) {
			long d = A;
			long x = 1;
			long y = 0;
			return new long[]{x,y,d};
		}
		else {
			long arr[]=extendedEuclid(B, A%B);
			long temp = arr[0];
			arr[0] = arr[1];
			arr[1] = temp - (A/B)*arr[1];
			return arr;
		}
	}

	public void printArr(int[] arr){
		for(int i = 0; i < arr.length; i++){
			out.print(arr[i] + " ");
		}
		out.println();
	}

	public void print2DArr(int[][] arr){
		for( int i = 0; i < arr.length; i++){
			for ( int j = 0; j < arr[0].length; j++){
				out.print(arr[i][j] + " ");
			}
			out.println();
		}
	}

	static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, numChars;
        private 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 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 readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

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

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

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

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public int[][] nextInt2DArray(int n, int m){
        	int[][] arr = new int[n][m];
        	for (int i = 0; i < n; i++){
        		for(int j = 0; j < m; j++){
        			arr[i][j] = nextInt();
        		}
        	}
        	return arr;
        }

        public long[][] nextLong2DArray(int n, int m){
        	long[][] arr = new long[n][m];
        	for (int i = 0; i < n; i++){
        		for(int j = 0; j < m; j++){
        			arr[i][j] = nextLong();
        		}
        	}
        	return arr;
        }

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

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
	}
}


import java.util.Scanner;

public class AntonDigits {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int val2 = s.nextInt();
		int val3 = s.nextInt();
		int val5 = s.nextInt();
		int val6 = s.nextInt();
		System.out.println(mAntonDigits(val2, val3, val5, val6));
		s.close();

	}

	public static int mAntonDigits(int n2, int n3, int n5, int n6) {
		int maxSum = 0;

		int l = least(n2, n5, n6);
		n2 -= l;
		n5 -= l;
		n6 -= l;

		maxSum += (256 * l);

		l = least(n2, n3);

		maxSum += (32 * l);

		return maxSum;
	}

	public static int least(int n1, int n2, int n3) {
		int least = n1;

		if (least > n2) {
			least = n2;
		}

		if (least > n3) {
			least = n3;
		}

		return least;

	}

	public static int least(int n1, int n2) {
		int least = n1;
		if (least > n2) {
			return n2;
		}
		return least;

	}

}


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

public class CF166E_Tetrahedron {
    private void solve() {
        int n = readInt();
        long total = n % 2 == 0 ? 3 : 6;
        long factor = n % 2 == 0 ? 2 : 6;
        if(n == 0 || n == 1)
            out.print(0);
        else
        {
            n /= 2;
            n--;
            for (int i = 0; i != n; i++)
            {
                factor *= 9;
                factor %= 1000000007;
                total += factor;
                total %= 1000000007;
            }

            out.print(total);
        }

        out.close();
    }

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

    private void run() {
        try {
            init();
            solve();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    private void init() throws IOException {
        String filename = "";
        if (filename.isEmpty()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader(filename + ".in"));
            out = new PrintWriter(new FileWriter(filename + ".out"));
        }
    }

    private String readString() {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine());
            } catch (Exception e) {
                return null;
            }
        }

        return tok.nextToken();
    }

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

    private long readLong() {
        return Long.parseLong(readString());
    }

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