/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.Scanner;

/**
 *
 * @author esteban
 */
public class Codeforces_131A {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        String c= sc.next();
        String [] parts= c.split("");
        int f=-1;
        int d=1;
        for (int i = 0; i < parts.length; i++) {

         if(parts[0].equals(parts[0].toUpperCase()) && i==0){ // si la primera letra es mayuscula
             f=1;
         }else if (parts[0].equals(parts[0].toLowerCase()) && i==0){ // si la segunda letra es minuscula
            f=2;
         }

        if(parts[i].equals(parts[i].toLowerCase()) && i!=0){
            d=-1;

        }
        }

        if(f==1 && d==1){

            System.out.println(c.toLowerCase());
        }

        else if(f==2 && d==1){
              for (int i = 0; i < parts.length; i++) {
                if(i==0)System.out.print(parts[0].toUpperCase());
                else System.out.print(parts[i].toLowerCase());
            }
               System.out.println(" ");
        }else if(c.length()!=1 && d!=1){

                System.out.println(c);
        }else if(c.length()==1){
            System.out.println(c.toUpperCase());

        }

    }

}


import java.util.*;

public class Solution {
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
                System.out.println(2 * n * (n - 1) + 1 );
        }

    }


import java.util.Scanner;

public class D {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int m = sc.nextInt();
        int vx = sc.nextInt();
        int vy = sc.nextInt();
        int vz = sc.nextInt();
        double time = (double)m/(-vy);
        double dz = time*vz, dx = Math.abs(time*vx);
        double x0 = 0, z0 = 0;
        if (vx==0)
            x0 = a/2.0;
        else {
            if (vx > 0) {
                for (int i = 0; ; i += 2) {
                    if (dx >= (2*i-1)*a/2.0 && dx <= (2*i+1)*a/2.0) {
                        x0 = dx-(2*i-1)*a/2.0;
                        break;
                    }
                    if (dx >= (2*i+1)*a/2.0 && dx <= (2*i+3)*a/2.0) {
                        x0 = a-(dx-(2*i+1)*a/2.0);
                        break;
                    }
                }
            }
            else {
                for (int i = 0; ; i += 2) {
                    if (dx >= (2*i-1)*a/2.0 && dx <= (2*i+1)*a/2.0) {
                        x0 = a-(dx-(2*i-1)*a/2.0);
                        break;
                    }
                    if (dx >= (2*i+1)*a/2.0 && dx <= (2*i+3)*a/2.0) {
                        x0 = dx-(2*i+1)*a/2.0;
                        break;
                    }
                }
            }
        }
        for (int i = 0; ; i += 2) {
            if (dz >= i*b && dz <= (i+1)*b) {
                z0 = dz-i*b;
                break;
            }
            if (dz >= (i+1)*b && dz <= (i+2)*b) {
                z0 = b-(dz-(i+1)*b);
                break;
            }
        }
        System.out.println(x0+" "+z0);
    }

}


import java.util.Scanner;

public class Main{
    public static void main(String args[])
    {
    	int n,c;
    	int p[]=new int[10000];
    	int t[]=new int[10000];
    	Scanner cin=new Scanner(System.in);
    	n=cin.nextInt();
    	c=cin.nextInt();
    	int ans1=0,ans2=0;
    	int tsum1=0,tsum2=0;
    	for(int i=0;i<n;i++)
    	{
    		p[i]=cin.nextInt();
    	}
    	for(int i=0;i<n;i++)
    	{
    		t[i]=cin.nextInt();
    	}
    	for(int i=0;i<n;i++)
    	{
    		tsum1+=t[i];
    		int M=Max(0,p[i]-c*tsum1);
    		ans1+=M;
    	}
    	for(int i=n-1;i>=0;i--)
    	{
    		tsum2+=t[i];
    		int M=Max(0,p[i]-c*tsum2);
    		ans2+=M;
    	}
    	if(ans1>ans2)
    		System.out.println("Limak");
    	else if(ans2>ans1)
    		System.out.println("Radewoosh");
    	else
    		System.out.println("Tie");

    }
    public static int Max(int a,int b)
    {
    	if(a>b)
    		return a;
    	else
    		return b;
    }
}


import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Vector;

public class B {
    static Vector<Integer> primes;

    public static void main(String[] args) throws IOException {
        Scanner myScanner = new Scanner(System.in);
        int n = myScanner.nextInt(), nn = n;
        int[] dig = new int[10];
        while (nn > 0) {
            dig[nn % 10] = 1;
            nn /= 10;
        }
        int cnt = 0;
        for (long i = 1; i * i <= n; i++) {
            if (n % i == 0) {
                nn = (int) i;
                while (nn > 0) {
                    if (dig[nn % 10] == 1) {
                        cnt++;
                        break;
                    }
                    nn /= 10;
                }
                nn = (int) (n / i);
                if (nn != i)
                    while (nn > 0) {
                        if (dig[nn % 10] == 1) {
                            cnt++;
                            break;
                        }
                        nn /= 10;
                    }
            }
        }
        System.out.println(cnt);

    }
}


import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.io.IOException;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;

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

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

		byte nextByte() { return Byte.parseByte(next()); }

		short nextShort() { return Short.parseShort(next()); }

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

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

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

	public static void main(String[] args)
	{
		FastReader fr=new FastReader();

		int n=fr.nextInt();
		// int n=100;
		int mod=998244353;
		short fac[]=new short[1000001];
		fac[1]=-1;
		// int steps=0;

		for(int i=2;i<1001;i++)
		{
			for(int j=i*i;j<1000001;j+=i)
			{
				fac[j]+=2;
				// if(fac[j]>125)
				// 	System.out.println(j+" "+i);
				// steps++;
			}

			fac[i*i]--;
		}

		// System.out.println(steps);
		int ans=0,sum=0;
		for(int i=-1;++i<n;)
		{
			int f=fac[i+1]+2;
			ans=sum+f;
			ans%=mod;
			sum+=ans;
			sum%=mod;
		}
		System.out.println(ans);
	}
}


import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;

public class E {

    public static ArrayList<Long> getDividers(long n) {
        ArrayList<Long> result = new ArrayList<Long>();
        for (int i = 2; i <= Math.ceil(Math.sqrt(n)) + 1; ++i) {
            while (n % i == 0) {
                n = n / i;
                result.add((long)i);
            }
        }
        if (n > 1)
            result.add(n);

        return result;
    }

    public static long f(long a, long b, ArrayList<Long> primes) {
        if (b <= 1)
            return b;

        ArrayList<Long> wasPrimes = new ArrayList<Long>();

        boolean divides = false;
        long gcd = 1;
        long lastB = b;

        for (Long prime : primes) {
            if (b % prime == 0) {
                divides = true;
                b = b / prime;
                wasPrimes.add(prime);
                gcd *= prime;
            }
        }
        if (divides) {
            for (Long prime : wasPrimes)
                primes.remove(prime);

            long inResult = f(a / gcd, lastB / gcd - 1, primes) + 1;
            //System.out.println("divides" + gcd + " " + a + " " + lastB + " " + inResult);
            return inResult;
        }

        long next = 0;
        for (long prime : primes) {
            long nextDiv = b - b % prime;
            next = Math.max(next, nextDiv);
        }

        long result = f(a, next, primes) + b - next;
        //System.out.println(a + " " + b + " " + result);

        return result;
    }

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

        long a = scan.nextLong();
        long b = scan.nextLong();

        ArrayList<Long> primes = getDividers(a);

        long result = f(a, b, primes);

        System.out.println(result);
    }

}


import java.util.*;

public class A_Beautiful_Matrix {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[][] a = new int[5][5];
        int x = 0, y = 0,ans=0;
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                a[i][j] = in.nextInt();
                if (a[i][j] == 1) {
                    x = i;
                    y = j;
                }
            }
        }
       // System.out.println("x="+x +" y="+y);
        ans = Math.abs(x-2)+Math.abs(y-2);
        System.out.println(ans);
    }

}


 import java.util.*;

  public class B
  {
     public static void main(String[] args)
     {
        new B(new Scanner(System.in));
     }

     public B(Scanner in)
     {
        int ma = in.nextInt();
        int mb = in.nextInt();
        int mod = in.nextInt();

        TreeSet<Integer> ts = new TreeSet<Integer>();
        for (int x=1; x<=ma; x++)
        {
           int rr = (int)((1000000000L*x)%mod);
           if (rr == 0)
              break;

           if (rr < (mod-mb))
           {
              System.out.printf("1 %09d%n", x);
              return;
           }
        }

        System.out.println("2");
     }
  }


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

public class C {

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

	static long[] ONES = new long[17];
	static {
		ONES[1] = 1;
		for (int i = 2; i < 17; i++) {
			ONES[i] = 10 * ONES[i - 1] + 1;
		}
	}

	long go(long x, int len) {
		x = Math.abs(x);
//		System.err.println(x + " " + len);
		if (x % ONES[len] == 0) {
			return x / ONES[len] * len;
		}
		long low = x / ONES[len];
		long high = low + 1;

		long ret1 = low * len + go(x - low * ONES[len], len - 1);
		long ret2 = high * len + go(high * ONES[len] - x, len - 1);
		return Math.min(ret1, ret2);
	}

	long solve(long x) {
		return go(x, 16);
	}

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

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

	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.*;
import java.io.*;

public class codeforces{
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] s = br.readLine().split(" ");
		int a = Integer.parseInt(s[0]);
		int b = Integer.parseInt(s[1]);

		int count = a, c2 = 0;
		int r = 0;
		while(a >= b){
			count += a/b;
			r = a % b;
			a = r + a/b;
		}

		System.out.println(count);

	}
}


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

public class E implements Runnable {

	void solve() {
		int n = nextInt();
		int t = nextInt();
		char[][] c = new char[n][];
		for (int i = 0; i < n; i++) {
			c[i] = nextToken().toCharArray();
		}
		int[][] infectTime = new int[n][n];
		for (int i = 0; i < n; i++) {
			Arrays.fill(infectTime[i], Integer.MAX_VALUE);
		}
		Queue<State> q = new ArrayDeque<State>();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (c[i][j] == 'Z') {
					q.add(new State(i, j));
					infectTime[i][j] = 0;
				}
			}
		}
		while (!q.isEmpty()) {
			State state = q.poll();
			for (int dir = 0; dir < 4; dir++) {
				int x = state.x + DX[dir];
				int y = state.y + DY[dir];
				if (x < 0 || y < 0 || x >= n || y >= n || c[x][y] == 'Y'
						|| infectTime[x][y] != Integer.MAX_VALUE) {
					continue;
				}
				infectTime[x][y] = infectTime[state.x][state.y] + 1;
				q.add(new State(x, y));
			}
		}
		int[][][][] dist = new int[n][n][][];
		for (int i = 0; i < n; i++) {
			// System.err.println(Arrays.toString(infectTime[i]));
			for (int j = 0; j < n; j++) {
				dist[i][j] = findDists(n, c, i, j, infectTime);
			}
		}
		Graph g = new Graph(1 + n * n + n * n + 1);
		int sink = 1 + 2 * n * n;
		int shiftCapsule = 1 + n * n;
		int shiftMen = 1;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (c[i][j] != '0' && c[i][j] != 'Y' && c[i][j] != 'Z') {
					g.addEdge(0, i * n + j + shiftMen, 0, c[i][j] - '0');
				}
			}
		}
		char[][] capsule = new char[n][];
		for (int i = 0; i < n; i++) {
			capsule[i] = nextToken().toCharArray();
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (capsule[i][j] != '0' && capsule[i][j] != 'Y'
						&& capsule[i][j] != 'Z') {
					g.addEdge(i * n + j + shiftCapsule, sink, 0,
							capsule[i][j] - '0');
				}
			}
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int k = 0; k < n; k++) {
					for (int k2 = 0; k2 < n; k2++) {
						if (dist[i][j][k][k2] <= t) {
							g.addEdge(i * n + j + shiftMen, k * n + k2
									+ shiftCapsule, 0, 1 << 20);
						}
					}
					// System.err.println(Arrays.toString(dist[i][j][k]));
				}
				// System.err.println();
			}
		}
		out.println(g.getMaxFlow(0, sink));
	}

	static int[][] findDists(int n, char[][] c, int startX, int startY,
			int[][] infectTime) {
		if (c[startX][startY] == 'Y' || c[startX][startY] == 'Z') {
			return new int[n][n];
		}
		Queue<State> q = new ArrayDeque<State>();
		int[][] d = new int[n][n];
		for (int i = 0; i < n; i++) {
			Arrays.fill(d[i], Integer.MAX_VALUE);
		}
		q.add(new State(startX, startY));
		d[startX][startY] = 0;
		while (!q.isEmpty()) {
			State state = q.poll();
			for (int dir = 0; dir < 4; dir++) {
				int x = state.x + DX[dir];
				int y = state.y + DY[dir];
				int newD = d[state.x][state.y] + 1;
				if (x < 0 || y < 0 || x >= n || y >= n || c[x][y] == 'Y'
						|| c[x][y] == 'Z' || d[x][y] != Integer.MAX_VALUE
						|| newD >= infectTime[x][y]) {
					continue;
				}
				d[x][y] = newD;
				q.add(new State(x, y));
			}
		}
		int[][] e = new int[n][];
		for (int i = 0; i < n; i++) {
			e[i] = d[i].clone();
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (d[i][j] == Integer.MAX_VALUE) {
					continue;
				}
				for (int dir = 0; dir < 4; dir++) {
					int x = i + DX[dir];
					int y = j + DY[dir];
					if (x < 0 || y < 0 || x >= n || y >= n || c[x][y] == 'Y'
							|| c[x][y] == 'Z') {
						continue;
					}
					if (d[i][j] + 1 == infectTime[x][y]
							&& d[i][j] + 1 < e[x][y]) {
						e[x][y] = d[i][j] + 1;
					}
				}
			}
		}
		return e;
	}

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

	static class State {
		int x;
		int y;

		public State(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

	}

	static class Edge {
		int from;
		int to;
		int flow;
		int cap;
		Edge rev;

		public Edge(int from, int to, int flow, int cap) {
			super();
			this.from = from;
			this.to = to;
			this.flow = flow;
			this.cap = cap;
		}

	}

	static class Graph {
		ArrayList<Edge>[] edges;
		int[] cur;
		int[] q;
		int[] d;
		int n;

		public Graph(int n) {
			edges = new ArrayList[n];
			this.n = n;
			for (int i = 0; i < edges.length; i++) {
				edges[i] = new ArrayList<Edge>();
			}
		}

		void addEdge(int from, int to, int flow, int cap) {
			Edge e1 = new Edge(from, to, flow, cap);
			Edge e2 = new Edge(to, from, -flow, 0);
			e1.rev = e2;
			e2.rev = e1;
			edges[from].add(e1);
			edges[to].add(e2);
		}

		boolean bfs(int source, int target) {
			int head = 0;
			int tail = 1;
			Arrays.fill(d, Integer.MAX_VALUE);
			d[source] = 0;
			q[0] = source;
			while (head < tail) {
				int x = q[head++];
				for (Edge e : edges[x]) {
					if (e.cap - e.flow > 0 && d[e.to] == Integer.MAX_VALUE) {
						d[e.to] = d[x] + 1;
						q[tail++] = e.to;
						if (e.to == target) {
							return true;
						}
					}
				}
			}
			return false;
		}

		int dfs(int x, int target, int cMin) {
			if (x == target) {
				return cMin;
			}
			for (int i = cur[x]; i < edges[x].size(); cur[x] = ++i) {
				Edge e = edges[x].get(i);
				if (d[e.to] != d[x] + 1 || e.cap - e.flow == 0) {
					continue;
				}
				int add = dfs(e.to, target, Math.min(cMin, e.cap - e.flow));
				if (add == 0) {
					continue;
				}
				e.flow += add;
				e.rev.flow -= add;
				return add;
			}
			return 0;
		}

		long getMaxFlow(int source, int target) {
			cur = new int[n];
			q = new int[n];
			d = new int[n];
			long flow = 0;
			while (bfs(source, target)) {
				Arrays.fill(cur, 0);
				while (true) {
					int add = dfs(source, target, Integer.MAX_VALUE);
					if (add == 0) {
						break;
					}
					flow += add;
				}
			}
			return flow;
		}
	}

	FastScanner sc;
	PrintWriter out;

	public void run() {
		Locale.setDefault(Locale.US);
		try {
			sc = new FastScanner(System.in);
			out = new PrintWriter(System.out);
			solve();
			sc.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() {
		return sc.nextInt();
	}

	String nextToken() {
		return sc.nextToken();
	}

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

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

	BigInteger nextBigInteger() {
		return sc.nextBigInteger();
	}

	class FastScanner extends BufferedReader {
		StringTokenizer st;
		boolean eof;
		String buf;
		String curLine;
		boolean createST;

		public FastScanner(String fileName) throws FileNotFoundException {
			this(fileName, true);
		}

		public FastScanner(String fileName, boolean createST)
				throws FileNotFoundException {
			super(new FileReader(fileName));
			this.createST = createST;
			nextToken();
		}

		public FastScanner(InputStream stream) {
			this(stream, true);
		}

		public FastScanner(InputStream stream, boolean createST) {
			super(new InputStreamReader(stream));
			this.createST = createST;
			nextToken();
		}

		String nextLine() {
			String ret = curLine;
			if (createST) {
				st = null;
			}
			nextToken();
			return ret;
		}

		String nextToken() {
			if (!createST) {
				try {
					curLine = readLine();
				} catch (Exception e) {
					eof = true;
				}
				return null;
			}
			while (st == null || !st.hasMoreTokens()) {
				try {
					curLine = readLine();
					st = new StringTokenizer(curLine);
				} catch (Exception e) {
					eof = true;
					break;
				}
			}
			String ret = buf;
			buf = eof ? "-1" : st.nextToken();
			return ret;
		}

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

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

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

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

		public void close() {
			try {
				buf = null;
				st = null;
				curLine = null;
				super.close();
			} catch (Exception e) {

			}
		}

		boolean isEOF() {
			return eof;
		}
	}

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


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

public class Main {
    static int [][] M;
    static Scanner sc = new Scanner(System.in);
    static int [][] dp = new int[1001][11];
    static int N;

    public static int solve(int n, int i, int d, int a, String s) {
        if(i == N) {
            return d + M[i][3] * (n / M[i][2]);
        }
        if(dp[n][i] != -1) {
            return dp[n][i];
        }
        int r = 0;
        if(M[i][2] <= n && a >= M[i][1]) {
            //System.out.println(i + " " + (n - M[i][2]));
            r = solve(n - M[i][2], i, d + M[i][3], a - M[i][1], s + " " + i);
        }
        int b = solve(n, i + 1, d, M[i + 1][0], s);
        r = Math.max(r, b);
        //System.out.println(s);
        dp[n][i] = r;
        return r;
    }

    public static int r() {
        return sc.nextInt();
    }

    public static void main(String [] args) {
        int n = r(), m = r(), c0 = r(), d0 = r();
        M = new int[m + 1][4];
        for(int i = 1; i <= m; i++) {
            M[i][0] = r(); M[i][1] = r(); M[i][2] = r(); M[i][3] = r();
        }
        dp = new int[n + 1][m + 1];
        for(int i = 0; i <= n; i++) {
            Arrays.fill(dp[i], 0);
        }
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m; j++) {
                int K = M[j][0] / M[j][1];
                K = Math.min(K, i / M[j][2]);
                for(int k = 0; k <= K; k++) {
                    //System.out.println(M[j][3]);
                    dp[i][j] = Math.max(dp[i][j], M[j][3] * k + dp[i - M[j][2] * k][j-1]);
                }
            }
        }
        int max = 0;
        for(int i = 0; i <= n; i++) {
            max = Math.max(max, dp[i][m] +  ((n-i)/c0)*d0);
        }
        System.out.println(max);
        //System.out.println(solve(n, 0, 0, M[0][0], ""));
    }
}


// -*- coding: utf-8 -*-
//import java.awt.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    InputStream inputStream;
    if (args.length > 0 && args[0].equals("devTesting")) {
      try {
        inputStream = new FileInputStream(args[1]);
      } catch(FileNotFoundException e) {
        throw new RuntimeException(e);
      }
    } else {
      inputStream = System.in;
    }
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    TaskE solver = new TaskE();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskE {
    int n;
    int[] color, r, b, cr, cb;
    int[][][] state;

    void solve(int testNumber, InputReader in, PrintWriter out) {
      n = in.nextInt();
      color = new int[n];
      r = new int[n];
      b = new int[n];
      int base = 0; // count of obligatory token-collecting turns
      int needred = 0; // count of obligatory red tokens to collect
      int needblue = 0; // count of obligatory blue tokens to collect
      for (int i = 0; i < n; ++i) {
        color[i] = in.next().charAt(0) == 'R' ? 0 : 1;
        r[i] = in.nextInt();
        b[i] = in.nextInt();
        needred += Math.max(0, r[i] - n);
        needblue += Math.max(0, b[i] - n);
        r[i] = Math.min(n, r[i]);
        b[i] = Math.min(n, b[i]);
      }
      base = Math.max(needred, needblue);
      cr = new int[1 << n]; // count of red cards after completing a given set S of cards
      cb = new int[1 << n]; // count of blue cards after completing a given set S of cards;
      for (int i = 1; i < 1 << n; ++i) {
        cr[i] = cr[i ^ (i & -i)];
        cb[i] = cb[i ^ (i & -i)];
        cr[i] += color[Integer.numberOfTrailingZeros(i & -i)] ^ 1;
        cb[i] += color[Integer.numberOfTrailingZeros(i & -i)];
      }
      state = new int[2][n * n + 1][1 << n];
      for (int[][] i : state) {
        for (int[] j : i) {
          Arrays.fill(j, -1);
        }
      }
      int ans = base + (needred < needblue ? go(0, 0, Math.min(n * n, needblue - needred)) : go(0, 1, Math.min(n * n, needred - needblue))) + n;
      out.println(ans);
    }

    int go(int mask, int redempty, int other) {
      if (mask == (1 << n) - 1) {
        return 0;
      }
      if (state[redempty][other][mask] != -1) {
        return state[redempty][other][mask];
      }
      int ret = Integer.MAX_VALUE / 2;
      for (int i = 0; i < n; ++i) {
        if ((mask & 1 << i) != 0) {
          continue;
        }
        int nextmask = mask | 1 << i;
        int remtokenred = (redempty ^ 1) * other;
        int remtokenblue = redempty * other;
        int cardred = cr[mask];
        int cardblue = cb[mask];
        int nred = Math.max(0, r[i] - (cardred + remtokenred)); // attempt to buy new red tokens saving as much new turns as possible
        int nblue = Math.max(0, b[i] - (cardblue + remtokenblue)); // attempt to buy new blue tokens saving as much new turns as possible
        int needmoves = Math.max(nred, nblue); // turns to do after saves
        int nextred = Math.min(n * n, remtokenred + needmoves - Math.max(0, r[i] - cardred)); // red tokens remaining, with clamping
        int nextblue = Math.min(n * n, remtokenblue + needmoves - Math.max(0, b[i] - cardblue)); // red tokens remaining, with clamping
        if (nextred == 0) {
          ret = Math.min(ret, go(nextmask, 1, nextblue) + needmoves);
        }
        if (nextblue == 0) {
          ret = Math.min(ret, go(nextmask, 0, nextred) + needmoves);
        }
      }
      state[redempty][other][mask] = ret;
      return ret;
    }

    int i(long x) {
      return (int) x;
    }

    <T> void heapsort(T[] a, int s, int e) {
      Queue<T> queue = new PriorityQueue<>();
      for (int i = s; i <= e; ++i)
        queue.add(a[i]);
      for (int i = s; i <= e; ++i)
        a[i] = queue.poll();
    }

  }

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

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

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

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

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

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

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

    public boolean hasInput() {
      try {
        if (tokenizer != null && tokenizer.hasMoreTokens()) {
          return true;
        }
        reader.mark(1);
        int ch = reader.read();
        if (ch != -1) {
          reader.reset();
          return true;
        }
        return false;
      } catch(IOException e) {
        throw new RuntimeException(e);
      }
    }

  }
}


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

public class C {
    private FastScanner in;
    private PrintWriter out;

    private void solve() {
        int input = in.nextInt();
        while(input%10 == 0){
        	input/=10;
        }
        String input2 = input+"";
        boolean pal = true;
        for(int i = 0; i<input2.length()/2;i++){
            if(input2.charAt(i)!=input2.charAt(input2.length()-i-1)){
                pal = false;
                break;
            }
        }
        if(pal == true)
            out.println("YES");
        else
            out.println("NO");
    }

    private void run() {
        try {
            in = new FastScanner(new File("A.in"));
            out = new PrintWriter(new File("A.out"));

            solve();

            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void runIO() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);

        solve();

        out.close();
    }

    private class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

        boolean hasMoreTokens() {
            while (st == null || !st.hasMoreTokens()) {
                String s = null;
                try {
                    s = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (s == null)
                    return false;
                st = new StringTokenizer(s);
            }
            return true;
        }

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

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

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

    public static void main(String[] args) {
        new C().runIO();
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.io.*;
import java.math.BigInteger;

import javax.xml.bind.ParseConversionEvent;

public class task {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int vp, vd, t, f, c, ans = 0;
		vp = in.nextInt();
		vd = in.nextInt();
		t = in.nextInt();
		f = in.nextInt();
		c = in.nextInt();
		double x = vp * t;
		double T;
		while((x < c) && (vp < vd))
		{
			T = x / (double)(vd - vp);
			x += (double)vp * T;
			if(x < c)
			{
				ans++;
				x += f * vp;
				x += T * vp;
			}
		}
		System.out.println(ans);
	}
}


import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Stream;

/**
 *
 * @author Pradyumn Agrawal coderbond007
 */
public class B{
    public static InputStream inputStream = System.in;
    public static FastReader in = new FastReader(inputStream);
    public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    public static void main(String[] args)throws java.lang.Exception
    {
        new B().run();
        out.close();
    }
    void run() throws java.lang.Exception
    {
    	char[] s = ns().toCharArray();
    	int n = s.length;
    	int k = ni();
    	int ct = 0;
    	int ans = 0;
    	for(int i = n - 1;i >= 0; i--){
    		if(s[i] == '0'){
    			ct++;
    		} else {
    			ans++;
    		}
    		if(ct == k){
    			break;
    		}
    	}
    	if(ct == k){
    		out.println(ans);
    	} else {
    		out.println(n - 1);
    	}
    }
    private static int ni(){
        return in.nextInt();
    }
    private static long nl(){
        return in.nextLong();
    }
    private static String ns(){
        return in.nextString();
    }
    private static char nc(){
        return in.nextCharacter();
    }
    private static double nd(){
        return in.nextDouble();
    }

    private static char[] ns(int n)
    {
        char[] a = new char[n];
        for(int i=0;i<n;i++) a[i] = nc();
        return a;
    }

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

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

    private static long[] nal(int n)
    {
        long[] a = new long[n];
        for(int i=0;i<n;i++) a[i] = nl();
        return a;
    }
    //private void tr(Object... o) { if(o.length() > 0)System.out.println(Arrays.deepToString(o)); }
}

class FastReader{
    private boolean finished = false;

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

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

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

    public int peek(){
        if (numChars == -1){
            return -1;
        }
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read (buf);
            } catch (IOException e){
                return -1;
            }
            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==','){
                c = read();
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    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 String nextString(){
        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 boolean isSpaceChar(int c){
        if (filter != null){
            return filter.isSpaceChar (c);
        }
        return isWhitespace (c);
    }

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

    private String readLine0(){
        StringBuilder buf = new StringBuilder ();
        int c = read ();
        while (c != '\n' && c != -1){
            if (c != '\r'){
                buf.appendCodePoint (c);
            }
            c = read ();
        }
        return buf.toString ();
    }

    public String nextLine(){
        String s = readLine0 ();
        while (s.trim ().length () == 0)
            s = readLine0 ();
        return s;
    }

    public String nextLine(boolean ignoreEmptyLines){
        if (ignoreEmptyLines){
            return nextLine ();
        }else{
            return readLine0 ();
        }
    }

    public BigInteger nextBigInteger(){
        try{
            return new BigInteger (nextString());
        } catch (NumberFormatException e){
            throw new InputMismatchException ();
        }
    }

    public char nextCharacter(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        return (char) c;
    }

    public double nextDouble(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        double res = 0;
        while (!isSpaceChar (c) && c != '.'){
            if (c == 'e' || c == 'E'){
                return res * Math.pow (10, nextInt ());
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        }
        if (c == '.'){
            c = read ();
            double m = 1;
            while (!isSpaceChar (c)){
                if (c == 'e' || c == 'E'){
                    return res * Math.pow (10, nextInt ());
                }
                if (c < '0' || c > '9'){
                    throw new InputMismatchException ();
                }
                m /= 10;
                res += (c - '0') * m;
                c = read ();
            }
        }
        return res * sgn;
    }

    public boolean isExhausted(){
        int value;
        while (isSpaceChar (value = peek ()) && value != -1)
            read ();
        return value == -1;
    }
    public SpaceCharFilter getFilter(){
        return filter;
    }

    public void setFilter(SpaceCharFilter filter){
        this.filter = filter;
    }

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


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

import static java.lang.Math.*;

public class Main extends PrintWriter {
    final Random rand = new Random(31);
    final int inf = (int) 1e9;
    final long linf = (long) 1e18;

    final static String IO = "_std";

    class Edge {
        int to, f, c, cost;

        public Edge(int to, int c, int cost) {
            this.to = to;
            this.c = c;
            this.cost = cost;
            this.f = 0;
        }
    }

    List<Edge> edges = new ArrayList<>();
    List<Integer>[] g;

    void addEdge(int from, int to, int cap, int cost) {
        g[from].add(edges.size());
        edges.add(new Edge(to, cap, cost));
        g[to].add(edges.size());
        edges.add(new Edge(from, 0, -cost));
    }

    class QItem implements Comparable<QItem> {
        int d, id;

        public QItem(int d, int id) {
            this.d = d;
            this.id = id;
        }

        @Override
        public int compareTo(QItem o) {
            return Integer.compare(d, o.d);
        }
    }

    void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        int[][] a = new int[n][];
        for (int i = 0; i < n; i++) {
            a[i] = nextIntArray(m);
        }

        int s = 0;
        int t = n * m + 1;
        g = createAdjacencyList(n * m + 2);
        int[] dx = new int[] {-1, 1, 0, 0};
        int[] dy = new int[] {0, 0, 1, -1};
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (((i + j) & 1) == 0) {
                    addEdge(0, i * m + j + 1, 1, 0);
                    for (int k = 0; k < 4; k++) {
                        int x = i + dx[k];
                        int y = j + dy[k];
                        if (x < 0 || x >= n || y < 0 || y >= m) {
                            continue;
                        }
                        addEdge(i * m + j + 1, x * m + y + 1, 1, a[i][j] == a[x][y] ? 0 : 1);
                    }
                } else {
                    addEdge(i * m + j + 1, t, 1, 0);
                }
            }
        }

        int flow = 0;
        int cost = 0;
        n = n * m + 2;
        int[] d = new int[n];
        int[] p = new int[n];
        int[] phi = new int[n];
        int[] f = new int[n];
        f[s] = inf;
        Queue<QItem> q = new PriorityQueue<>();
        boolean[] done = new boolean[n];

        while (true) {
            Arrays.fill(d, inf);
            Arrays.fill(p, -1);
            d[s] = 0;
            Arrays.fill(done, false);

            q.add(new QItem(0, s));

            while (!q.isEmpty()) {
                int v = q.poll().id;
                if (done[v]) {
                    continue;
                }
                done[v] = true;
                for (int i : g[v]) {
                    Edge e = edges.get(i);
                    if (e.f == e.c) {
                        continue;
                    }
                    int c = d[v] + e.cost + phi[v] - phi[e.to];
                    if (d[e.to] > c) {
                        d[e.to] = c;
                        q.add(new QItem(d[e.to], e.to));
                        p[e.to] = i;
                        f[e.to] = min(f[v], e.c - e.f);
                    }
                }
            }

            if (p[t] == -1) {
                break;
            }

            int cf = f[t];
            int x = t;
            int cc = 0;
            while (p[x] != -1) {
                Edge e = edges.get(p[x]);
                e.f += cf;
                cc += e.cost;
                e = edges.get(p[x] ^ 1);
                e.f -= cf;
                x = e.to;
            }

            flow += cf;
            cost += cf * cc;

            for (int i = 0; i < n; i++) {
                if (d[i] != inf) {
                    phi[i] += d[i] - d[t];
                }
            }
        }

        println(cost);
    }

    BufferedReader in;
    StringTokenizer stok;

    Main() {
        super(System.out);
        in = new BufferedReader(new InputStreamReader(System.in));
    }

    Main(String fileIn, String fileOut) throws IOException {
        super(fileOut);
        in = new BufferedReader(new FileReader(fileIn));
    }

    public static void main(String[] args) throws IOException {
        Main main;
        if ("_std".equals(IO)) {
            main = new Main();
        } else if ("_iotxt".equals(IO)) {
            main = new Main("input.txt", "output.txt");
        } else {
            main = new Main(IO + ".in", IO + ".out");
        }
        main.solve();
        main.close();
    }

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

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

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

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

    int[] nextIntArray(int len) throws IOException {
        int[] a = new int[len];
        for (int i = 0; i < len; i++) {
            a[i] = nextInt();
        }
        return a;
    }

    int[] nextIntArraySorted(int len) throws IOException {
        int[] a = nextIntArray(len);
        shuffle(a);
        Arrays.sort(a);
        return a;
    }

    void shuffle(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int x = rand.nextInt(i + 1);
            int _ = a[i];
            a[i] = a[x];
            a[x] = _;
        }
    }

    void shuffleAndSort(int[] a) {
        shuffle(a);
        Arrays.sort(a);
    }

    boolean nextPermutation(int[] p) {
        for (int a = p.length - 2; a >= 0; --a) {
            if (p[a] < p[a + 1])
                for (int b = p.length - 1; ; --b)
                    if (p[b] > p[a]) {
                        int t = p[a];
                        p[a] = p[b];
                        p[b] = t;
                        for (++a, b = p.length - 1; a < b; ++a, --b) {
                            t = p[a];
                            p[a] = p[b];
                            p[b] = t;
                        }
                        return true;
                    }
        }
        return false;
    }

    <T> List<T>[] createAdjacencyList(int n) {
        List<T>[] res = new List[n];
        for (int i = 0; i < n; i++) {
            res[i] = new ArrayList<>();
        }
        return res;
    }

    void println(Object... a) {
        for (int i = 0; i < a.length; i++) {
            if (i != 0) {
                print(" ");
            }
            print(a[i]);
        }
        println();
    }
}


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

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

    static class AEatingSoup {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt(), m = in.nextInt();

            out.println(m == 0 ? 1 : Math.min(m, n - m));
        }

    }
}


import java.util.*;

public class Solution {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int sum = 0;
		int maxA = 0;
		for(int i = 0; i < n; i++) {
			int ai = scan.nextInt();
			sum += ai;
			maxA = Math.max(maxA, ai);
		}
		int s = 2*sum;
		int r = (2*sum)/n + 1;
		int result = Math.max(maxA, r);
		System.out.println(result);
	}
}


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

public class E implements Runnable {

	final long[][] E = { { 1, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0, 0}, { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 1 } };

	private void solve() throws IOException {
		long n = nextLong(), sx = nextLong() - 1, sy = nextLong() - 1;
		long dx = ((nextLong() % n) + n) % n, dy = ((nextLong() % n) + n) % n, t = nextLong();
		long[][] start = { { sx, sy, dx, dy, 0, 1 } };
		long[][] next = { { 2, 1, 1, 1, 0, 0 }, { 1, 2, 1, 1, 0, 0 }, { 1, 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 0 }, { 1, 1, 1, 1, 1, 0 }, { 2, 2, 2, 2, 1, 1 } };
		long[][] end = matrixMultiplication(start, binaryMatrixPower(next, t, n), n);
		print(end[0][0] + 1, end[0][1] + 1);
	}

	long[][] binaryMatrixPower(long[][] a, long pow, long MOD) {
		if (pow == 0) return E;
		if ((pow & 1) == 0) {
			long[][] res = binaryMatrixPower(a, pow >> 1, MOD);
			return matrixMultiplication(res, res, MOD);
		} else {
			long[][] res = binaryMatrixPower(a, pow - 1, MOD);
			return matrixMultiplication(res, a, MOD);
		}
	}

	long[][] matrixMultiplication(long[][] a, long[][] b, long MOD) {
		int n = a.length, m = a[0].length, q = b.length, p = b[0].length;
		long[][] res = new long[n][p];
		for (int i = 0; i < n; i++)
			for (int j = 0; j < p; j++)
				for (int k = 0; k < m; k++) {
					res[i][j] += a[i][k] * b[k][j];
					res[i][j] %= MOD;
				}
		return res;
	}

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

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

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

	void halt() {
		writer.close();
		System.exit(0);
	}

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

	void println(Object... objects) {
		print(objects);
		writer.println();
	}

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

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

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

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

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


import java.io.*;
import java.util.Scanner;
public class gaurav
{
	public static void main(String[] args)throws IOException
	{
		int[] A=new int[50];
		int[] B=new int[50];
		int[] C=new int[200];
		int n,L,i=0,j=0,x,count=0;
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		L=sc.nextInt();
		for(i=0;i<n;i++)
		{
			x=sc.nextInt();
			C[x]=1;
			C[L+x]=1;
		}
/*for(int k:C)
System.out.print(k+" ");*/
		for(j=0;j<n;j++)
		{
			B[j]=sc.nextInt();
		}
/*for(int k:B)
System.out.print(k+" ");*/
		x=B[0];
		i=0;j=0;
		/*System.out.println("i="+i);*/
		while(i<L)
		{
			//System.out.println("i="+i);
/*System.out.println("j="+j);
System.out.println("x="+x);
System.out.println("n="+n);*/
			if((C[i+x]==1) && (count<=n))
			{
				count++;
				/*System.out.println("count="+count);*/
				if(count==n)
				{
					System.out.println("YES");
					System.exit(0);
				}

				x=B[++j];
				/*System.out.println("x="+x);*/
				continue;
			}
			else
			{
				count=0;j=0;x=B[j];
				i++;
			}
		}
		if(count<n)
		{
			System.out.println("NO");
		}
	}
}


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 Codechef
{
       static boolean isdistinct(String s){
        Set<Character>set=new HashSet<Character>();
        for(int i=0;i<s.length();i++){
            set.add(s.charAt(i));
        }
        if(set.size()==s.length())
         return true;
        return false;
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
		String s=(br.readLine());
		int n=Integer.parseInt(s);
		n++;
		int f=0;
		while(f==0){
		    String s1=n+" ";
		   if(isdistinct(s1)){
		    bw.write(s1+"\n");

		    break;

		   }
		   n++;
		}
		bw.flush();

	}
}


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

public class elements {

	public static HashSet<String> elements;

    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        elements = new HashSet<String>();

        String temp = "H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og";

        String[] ele = temp.split(" ");

        for (String e : ele) {
        	elements.add(e.toUpperCase());
        }

        String s = scan.nextLine();
        //elements.add("H");

        if (possible(0, s)) {
        	System.out.println("YES");
        }
        else {
        	System.out.println("NO");
        }

        //out.close();
    }

    public static boolean possible(int index, String s) {
    	int n = s.length();

    	boolean f = false;

    	if (index >= n)
    		return true;

    	String find = "" + s.charAt(index);

    	if (elements.contains(find)) {
    		f|=possible(index+1, s);
    	}

    	if (index + 1 < n) {
    		find += s.charAt(index+1);
    		if (elements.contains(find)) {
    			f|=possible(index+2, s);
    		}
    		if (index + 2 < n) {
    			find += s.charAt(index+2);
    			if (elements.contains(find)) {
    				f|=possible(index+3, s);
    			}
    		}
    	}

    	return f;
    }

}


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

public class Genetic implements Runnable {
    private void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        Set<String> all = new HashSet<String>();
        Set<String> finish = new HashSet<String>();
        all.add("");
        int maxLength = 1;
        for (int i = 0; i < m; ++i) {
            String s = nextToken();
            maxLength = Math.max(maxLength, s.length());
            finish.add(s);
            for (int j = 0; j < s.length(); ++j)
                all.add(s.substring(0, j + 1));
        }
        Map<String, Integer> index = new HashMap<String, Integer>();
        int last = 0;
        for (String st : all) {
            index.put(st, last++);
        }
        int[] isFinish = new int[last];
        int[][] next = new int[last][4];
        for (String s : all)
            for (String t : finish)
                if (s.endsWith(t))
                    isFinish[index.get(s)] = Math.max(isFinish[index.get(s)], t.length());
        for (String s : all) {
            int start = index.get(s);
            for (int ch = 0; ch < 4; ++ch) {
                String t = s + "ACGT".charAt(ch);
                while (!all.contains(t))
                    t = t.substring(1);
                next[start][ch] = index.get(t);
            }
        }
        int[][] cnt = new int[last][maxLength];
        cnt[index.get("")][0] = 1;
        for (int len = 0; len < n; ++len) {
            cnt = oneStep(cnt, maxLength, last, isFinish, next);
        }
        int res = 0;
        for (int state = 0; state < last; ++state) {
            res += cnt[state][0];
            if (res >= MODULO)
                res -= MODULO;
        }
        writer.println(res);
    }

    static final int MODULO = 1000000009;

    private int[][] oneStep(int[][] cnt, int maxLength, int last, int[] finish, int[][] next) {
        int[][] newCnt = new int[last][maxLength];
        for (int oldState = 0; oldState < last; ++oldState)
            for (int oldNeed = 0; oldNeed < maxLength; ++oldNeed) {
                for (int ch = 0; ch < 4; ++ch) {
                    int newState = next[oldState][ch];
                    int newNeed = oldNeed + 1;
                    if (newNeed <= finish[newState])
                        newNeed = 0;
                    if (newNeed >= maxLength)
                        continue;
                    newCnt[newState][newNeed] += cnt[oldState][oldNeed];
                    if (newCnt[newState][newNeed] >= MODULO) {
                        newCnt[newState][newNeed] -= MODULO;
                    }
                }
            }
        return newCnt;
    }

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

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

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

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

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

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


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

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

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

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

    }

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

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

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

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

    }
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Practice {

	static class length implements Comparator<String>
	{
		public int compare(String a,String b)
		{
			return(a.length()-b.length());
		}
	}

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

		   int nextInt()
		   {
			   return Integer.parseInt(next());
		   }
		   long nextLong()
		   {
			   return Long.parseLong(next());
		   }
		   double nextDouble()
	        {
	            return Double.parseDouble(next());
	        }

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

		public static void main(String []args) throws Exception
		{
			//Scanner sc=new Scanner(System.in);
			FastReader in =new FastReader();
			PrintWriter pw = new PrintWriter(System.out);
			//System.out.println
			int n=in.nextInt();
			int k=in.nextInt();
			String s=in.nextLine();
			char c[]=s.toCharArray();
			Arrays.sort(c);
			int k1=1,m=0,sum=c[0]-'a'+1;
			int j=0;

			//pw.println("");
			if(k!=k1)
			{
			for(int i=1;i<n;i++)
			 {
				if(c[i]-c[j]>1)
				{
					sum=sum+(c[i]-'a')+1;
					j=i;
					k1++;
					if(k1==k)
					{
						m=1;

						break;
					}

					//pw.println(sum+" "+k1+" "+c[i]);

				}

			 }
			}
			if(k1==k)
			{
				pw.print(sum);
			}
			else
			{
				pw.print(-1);
			}

            pw.flush();
			pw.close();

	}

}


import java.util.Scanner;
public class CodeForce {

	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		String palindrome = input.next();

		int count=0;
		int i=0;
		String asal="";
		for(int j=palindrome.length()-1;j>=0;j--)
			asal += palindrome.charAt(j);
		while(i<palindrome.length())
		{
			for(int j=0;j<asal.length();j++)
			{
				if(palindrome.charAt(i)!=asal.charAt(j))
				{
					count++;
				}
				i++;
			}
		}
		if(count==0&&palindrome.length()%2!=0)
			System.out.println("YES");
		else if(count==1||count/2==1)
			System.out.println("YES");
		else
			System.out.println("NO");

	}
}


import java.util.*;
public class Main{
public static void main(String[] args) {

Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int []arr = new int[n];
long sum = 0;
for(int i=0;i<n;i++){
    arr[i] = scn.nextInt();
    if(arr[i]<0){
        sum+= Math.abs(arr[i]);
    }
    else{
        sum+= arr[i];
    }
}
System.out.println(sum);
 }
}


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

public class Main_1184A1 {

	private static Scanner sc;
	private static Printer pr;

	private static void solve() {
		long r = sc.nextLong();

		if (r < 5 || r % 2 == 0) {
			pr.println("NO");
		} else {
			pr.printLongs(1, (r - 3) / 2);
		}
	}

	// ---------------------------------------------------
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		pr = new Printer(System.out);

		solve();

		pr.close();
		sc.close();
	}

	static class Scanner {
		BufferedReader br;

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

		private boolean isPrintable(int ch) {
			return ch >= '!' && ch <= '~';
		}

		private boolean isCRLF(int ch) {
			return ch == '\n' || ch == '\r' || ch == -1;
		}

		private int nextPrintable() {
			try {
				int ch;
				while (!isPrintable(ch = br.read())) {
					if (ch == -1) {
						throw new NoSuchElementException();
					}
				}

				return ch;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		String next() {
			try {
				int ch = nextPrintable();
				StringBuilder sb = new StringBuilder();
				do {
					sb.appendCodePoint(ch);
				} while (isPrintable(ch = br.read()));

				return sb.toString();
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		int nextInt() {
			try {
				// parseInt from Integer.parseInt()
				boolean negative = false;
				int res = 0;
				int limit = -Integer.MAX_VALUE;
				int radix = 10;

				int fc = nextPrintable();
				if (fc < '0') {
					if (fc == '-') {
						negative = true;
						limit = Integer.MIN_VALUE;
					} else if (fc != '+') {
						throw new NumberFormatException();
					}
					fc = br.read();
				}
				int multmin = limit / radix;

				int ch = fc;
				do {
					int digit = ch - '0';
					if (digit < 0 || digit >= radix) {
						throw new NumberFormatException();
					}
					if (res < multmin) {
						throw new NumberFormatException();
					}
					res *= radix;
					if (res < limit + digit) {
						throw new NumberFormatException();
					}
					res -= digit;

				} while (isPrintable(ch = br.read()));

				return negative ? res : -res;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		long nextLong() {
			try {
				// parseLong from Long.parseLong()
				boolean negative = false;
				long res = 0;
				long limit = -Long.MAX_VALUE;
				int radix = 10;

				int fc = nextPrintable();
				if (fc < '0') {
					if (fc == '-') {
						negative = true;
						limit = Long.MIN_VALUE;
					} else if (fc != '+') {
						throw new NumberFormatException();
					}
					fc = br.read();
				}
				long multmin = limit / radix;

				int ch = fc;
				do {
					int digit = ch - '0';
					if (digit < 0 || digit >= radix) {
						throw new NumberFormatException();
					}
					if (res < multmin) {
						throw new NumberFormatException();
					}
					res *= radix;
					if (res < limit + digit) {
						throw new NumberFormatException();
					}
					res -= digit;

				} while (isPrintable(ch = br.read()));

				return negative ? res : -res;
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		float nextFloat() {
			return Float.parseFloat(next());
		}

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

		String nextLine() {
			try {
				int ch;
				while (isCRLF(ch = br.read())) {
					if (ch == -1) {
						throw new NoSuchElementException();
					}
				}
				StringBuilder sb = new StringBuilder();
				do {
					sb.appendCodePoint(ch);
				} while (!isCRLF(ch = br.read()));

				return sb.toString();
			} catch (IOException e) {
				throw new NoSuchElementException();
			}
		}

		int[] nextIntArray(int n) {
			int[] ret = new int[n];
			for (int i = 0; i < n; i++) {
				ret[i] = sc.nextInt();
			}

			return ret;
		}

		long[] nextLongArray(int n) {
			long[] ret = new long[n];
			for (int i = 0; i < n; i++) {
				ret[i] = sc.nextLong();
			}

			return ret;
		}

		int[][] nextIntArrays(int n, int m) {
			int[][] ret = new int[m][n];
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					ret[j][i] = sc.nextInt();
				}
			}

			return ret;
		}

		void close() {
			try {
				br.close();
			} catch (IOException e) {
//				throw new NoSuchElementException();
			}
		}
	}

	static class Printer extends PrintWriter {
		Printer(OutputStream out) {
			super(out);
		}

		void printInts(int... a) {
			StringBuilder sb = new StringBuilder(32);
			for (int i = 0, size = a.length; i < size; i++) {
				if (i > 0) {
					sb.append(' ');
				}
				sb.append(a[i]);
			}

			println(sb);
		}

		void printLongs(long... a) {
			StringBuilder sb = new StringBuilder(64);
			for (int i = 0, size = a.length; i < size; i++) {
				if (i > 0) {
					sb.append(' ');
				}
				sb.append(a[i]);
			}

			println(sb);
		}

		void printStrings(String... a) {
			StringBuilder sb = new StringBuilder(32);
			for (int i = 0, size = a.length; i < size; i++) {
				if (i > 0) {
					sb.append(' ');
				}
				sb.append(a[i]);
			}

			println(sb);
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.StringTokenizer;

public class CodeJ
{
	static class Scanner
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

		public String nextLine()
		{
			try
			{
				return br.readLine();
			}
			catch(Exception e)
			{
				throw(new RuntimeException());
			}
		}

		public String next()
		{
			while(!st.hasMoreTokens())
			{
				String l = nextLine();
				if(l == null)
					return null;
				st = new StringTokenizer(l);
			}
			return st.nextToken();
		}

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

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

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

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

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

		public double[] nextDoubleArray(int n)
		{
			double[] res = new double[n];
			for(int i = 0; i < res.length; i++)
				res[i] = nextDouble();
			return res;
		}
		public void sortIntArray(int[] array)
		{
			Integer[] vals = new Integer[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public void sortLongArray(long[] array)
		{
			Long[] vals = new Long[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public void sortDoubleArray(double[] array)
		{
			Double[] vals = new Double[array.length];
			for(int i = 0; i < array.length; i++)
				vals[i] = array[i];
			Arrays.sort(vals);
			for(int i = 0; i < array.length; i++)
				array[i] = vals[i];
		}

		public String[] nextStringArray(int n)
		{
			String[] vals = new String[n];
			for(int i = 0; i < n; i++)
				vals[i] = next();
			return vals;
		}

		public Integer nextInteger()
		{
			String s = next();
			if(s == null)
				return null;
			return Integer.parseInt(s);
		}

		public int[][] nextIntMatrix(int n, int m)
		{
			int[][] ans = new int[n][];
			for(int i = 0; i < n; i++)
				ans[i] = nextIntArray(m);
			return ans;
		}

		public char[][] nextGrid(int r)
		{
			char[][] grid = new char[r][];
			for(int i = 0; i < r; i++)
				grid[i] = next().toCharArray();
			return grid;
		}

		public static <T> T fill(T arreglo, int val)
		{
			if(arreglo instanceof Object[])
			{
				Object[] a = (Object[]) arreglo;
				for(Object x : a)
					fill(x, val);
			}
			else if(arreglo instanceof int[])
				Arrays.fill((int[]) arreglo, val);
			else if(arreglo instanceof double[])
				Arrays.fill((double[]) arreglo, val);
			else if(arreglo instanceof long[])
				Arrays.fill((long[]) arreglo, val);
			return arreglo;
		}

		<T> T[] nextObjectArray(Class <T> clazz, int size)
		{
			@SuppressWarnings("unchecked")
			T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
			for(int c = 0; c < 3; c++)
			{
				Constructor <T> constructor;
				try
				{
					if(c == 0)
						constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE);
					else if(c == 1)
						constructor = clazz.getDeclaredConstructor(Scanner.class);
					else
						constructor = clazz.getDeclaredConstructor();
				}
				catch(Exception e)
				{
					continue;
				}
				try
				{
					for(int i = 0; i < result.length; i++)
					{
						if(c == 0)
							result[i] = constructor.newInstance(this, i);
						else if(c == 1)
							result[i] = constructor.newInstance(this);
						else
							result[i] = constructor.newInstance();
					}
				}
				catch(Exception e)
				{
					throw new RuntimeException(e);
				}
				return result;
			}
			throw new RuntimeException("Constructor not found");
		}

		public void printLine(int... vals)
		{
			if(vals.length == 0)
				System.out.println();
			else
			{
				System.out.print(vals[0]);
				for(int i = 1; i < vals.length; i++)
					System.out.print(" ".concat(String.valueOf(vals[i])));
				System.out.println();
			}
		}

		public void printLine(long... vals)
		{
			if(vals.length == 0)
				System.out.println();
			else
			{
				System.out.print(vals[0]);
				for(int i = 1; i < vals.length; i++)
					System.out.print(" ".concat(String.valueOf(vals[i])));
				System.out.println();
			}
		}

		public void printLine(double... vals)
		{
			if(vals.length == 0)
				System.out.println();
			else
			{
				System.out.print(vals[0]);
				for(int i = 1; i < vals.length; i++)
					System.out.print(" ".concat(String.valueOf(vals[i])));
				System.out.println();
			}
		}

		public void printLine(int prec, double... vals)
		{
			if(vals.length == 0)
				System.out.println();
			else
			{
				System.out.printf("%." + prec + "f", vals[0]);
				for(int i = 1; i < vals.length; i++)
					System.out.printf(" %." + prec + "f", vals[i]);
				System.out.println();
			}
		}

		public Collection <Integer> wrap(int[] as)
		{
			ArrayList <Integer> ans = new ArrayList <Integer> ();
			for(int i : as)
				ans.add(i);
			return ans;
		}
	}

	static int k;

	static int distance(long b, long a)
	{
		int[] visited = new int[(int) (b - a + 1)];
		Arrays.fill(visited, Integer.MAX_VALUE);
		ArrayDeque <Long> queue = new ArrayDeque <Long> ();
		visited[(int) (b - a)] = 0;
		queue.add(b);
		while(true)
		{
			long head = queue.pollFirst();
			int currentDistance = visited[(int) (head - a)];
			if(head == a) return currentDistance;
			for(int i = 1; i <= k; i++)
			{
				long mod = head % i;
				if(i == 1) mod = 1;
				if(mod != 0)
				{
					long possibleNext = head - mod;
					if(possibleNext >= a && visited[(int) (possibleNext - a)] == Integer.MAX_VALUE)
					{
						visited[(int) (possibleNext - a)] = currentDistance + 1;
						queue.add(possibleNext);
					}
				}
			}
		}
	}

	static int gcd(int a, int b)
	{
		if(b == 0) return a;
		else return gcd(b, a % b);
	}

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

	static int lcm(int a, int b, int currentLcm)
	{
		currentLcm = lcm(currentLcm, a);
		if(a == b) return currentLcm;
		return lcm(a + 1, b, currentLcm);
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner();
		long b = sc.nextLong();
		long a = sc.nextLong();
		k = sc.nextInt();
		long lcm = lcm(2, k, 1);
		long times = (b - a) / lcm;
		if(times == 0)
			System.out.println(distance(b, a));
		else if(times == 1)
			System.out.println(distance(b, b - b % lcm) + distance(b - b % lcm, a));
		else
		{
			long nextA = a / lcm;
			nextA += 1;
			nextA *= lcm;
			long nextB = b - b % lcm;
			times = (nextB - nextA) / lcm;
			System.out.println(distance(b, b - b % lcm) + distance(lcm, 0) * times + distance(nextA, a));
		}
	}
}


/* package codechef; // 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 Codechef
{
	public static void main (String[] args) throws java.lang.Exception
	{   int i,j,x;
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String s[]=br.readLine().split(" ");
		int n=Integer.parseInt(s[0]);
		int k=Integer.parseInt(s[1]);
		long ans=100000000000l;
		for(i=1;i<=Math.sqrt(n)+1;i++)
		{   if(n%i==0)
		    {
		        int a=n/i;
		        int b=i;
		        if(b<k)
		            ans=Math.min(a*k+b,ans);
		        if(a<k)
		            ans=Math.min(b*k+a,ans);
		    }
		}
		System.out.println(ans);
	}
}


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

public class Solution {

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

    static final int Mod = 1000000007;

    void solve() throws IOException {
        int a = nextInt();
        int b = nextInt();
        int c = nextInt();
        int x = nextInt();
        int y = nextInt();
        int z = nextInt();
        int left = 0;
        if (a > x) left += (a - x) / 2;
        if (b > y) left += (b - y) / 2;
        if (c > z) left += (c - z) / 2;
        if (x > a) left -= (x - a);
        if (y > b) left -= (y - b);
        if (z > c) left -= (z - c);
        if (left >= 0) out.println("Yes");
        else out.println("No");
    }

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

    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 static java.lang.System.in;
import static java.lang.System.out;

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

public class C333luckyTickets {
	static final double EPS = 1e-10;
	static final double INF = 1 << 31;
	static final double PI = Math.PI;

	public static Scanner sc = new Scanner(in);
	static StringBuilder sb = new StringBuilder();
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	ArrayList<Set<Integer>> way = new ArrayList<Set<Integer>>();
	int d1,d2,d3,d4;
	public void put(int x){
		if (x<0) x = 10000-x;
		way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
	}

	public void run() throws IOException {
		String input;
		String[] inputArray;
		input = br.readLine();
		inputArray = input.split(" ");

		int k = Integer.valueOf(inputArray[0]);
		int m = Integer.valueOf(inputArray[1]);
		for (int i=0; i<20000; i++)
			way.add(new HashSet<Integer>());
		int x;
		for ( d1 = -9; d1<10; d1++){
			for ( d2 = 0; d2<10; d2++){
				for ( d3 = 0; d3<10; d3++){
					for ( d4 = 0; d4<10; d4++){
						for (int s1 = 0; s1<3; s1++)
							for (int s2 = 0; s2<3; s2++)
								for (int s3 = 0; s3<3; s3++){
									x = op(op(op(d1,s1,d2),s2,d3),s3,d4);
									if (x<0) x = 10000-x;
									way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
									x = op(op(d1,s1,d2),s2,op(d3,s3,d4));
									if (x<0) x = 10000-x;
									way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
									x = op(op(d1,s1,op(d2,s2,d3)),s3,d4);
									if (x<0) x = 10000-x;
									way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
									x = op(d1,s1,op(op(d2,s2,d3),s3,d4));
									if (x<0) x = 10000-x;
									way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
									x = op(d1,s1,op(d2,s2,op(d3,s3,d4)));
									if (x<0) x = 10000-x;
									way.get(x).add(Math.abs(d1)*1000 + d2*100 + d3*10 + d4);
								}
					}
				}
			}
		}
		//ln("EYS");
		for (int c = 0; c<m;){
			if (k<10000){
				for (int j: way.get(0)){
					c++;
					print(j);
					print(k);
					sb.append("\n");
					if (c==m) return;
				}
			}
			for (int i=1; i<k; i++)
				for (int j: way.get(i)){
					c++;
					print(j);
					print(k-i);
					sb.append("\n");
					if (c==m) return;
				}
			for (int i=1; k+i<10000; i++)
				for (int j: way.get(10000+i)){
					c++;
					print(j);
					print(k+i);
					sb.append("\n");
					if (c==m) return;
				}
		}
	}

	private void print(int x) {
		sb.append(x/1000 + "");
		x%=1000;
		sb.append(x/100 + "");
		x%=100;
		sb.append(x/10 + "");
		x%=10;
		sb.append(x+ "");
	}

	private int op(int d1, int s1, int d2) {
		switch (s1) {
			case 0 : return d1+d2;
			case 1 : return d1-d2;
			case 2 : return d1*d2;
			case 3 : {
				int x=1;
				for (;x<d2; x*=10);
				return d1*x+d2;
			}
		}
		return 0;
	}

	public static void main(String[] args) throws IOException {
		new C333luckyTickets().run();
		out.print(sb);
	}
	public static void ln(Object obj) {
		out.println(obj);
	}

}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       Scanner input= new Scanner(System.in);
       int n,a=0,b,c;
       String s;

         s=input.nextLine();
           n=input.nextInt();

            if(null!=s)
                 switch (s) {
            case "February":
                a=2;
                break;
            case "January":
                a = 1;
                break;
            case "March":
                a=3;
                break;
            case "April":
                a=4;
                break;
            case "May":
                a=5;
                break;
            case "June":
                a=6;
                break;
            case "July":
                a=7;
                break;
            case "August":
                a=8;
                break;
            case "September":
                a=9;
                break;
            case "October":
                a=10;
                break;
            case "November":
                a=11;
                break;
            case "December":
                a=12;
                break;
            default:
                break;
        }

c=(a+n)%12;
        switch (c) {
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            case 3:
                System.out.println("March");
                break;
            case 4:
                System.out.println("April");
                break;
            case 5:
                System.out.println("May");
                break;
            case 6:
                System.out.println("June");
                break;
            case 7:
                System.out.println("July");
                break;
            case 8:
                System.out.println("August");
                break;
            case 9:
                System.out.println("September");
                break;
            case 10:
                System.out.println("October");
                break;
            case 11:
                System.out.println("November");
                break;
            case 0:
                System.out.println("December");
                break;
            default:
                break;
        }
}

}


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

public class CollectiveMindsetsMedium implements Closeable {

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

    public void solve() {
        int n = in.ni();
        if (n % 2 == 1) {
            out.println((n - 1) / 2);
        } else {
            int t = 1;
            while (2 * t <= n) {
                t *= 2;
            }
            out.println((n - t) / 2);
        }
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

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

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

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

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

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

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (CollectiveMindsetsMedium instance = new CollectiveMindsetsMedium()) {
            instance.solve();
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class F {

    static int N = 250;
    static int M = 28;
    static int INF = (int) 1e9;
    static int[][][][] dp = new int[2][M * 2 + 1][N][N];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder(br.readLine());
        String s = sb.reverse().append("0").toString();

        for (int carry = 0; carry < M * 2 + 1; carry++) {
            for (int cp = 0; cp < N; cp++) {
                for (int cn = 0; cn < N; cn++) {
                    dp[0][carry][cp][cn] = INF;
                }
            }
        }
        dp[0][M][N - 1][N - 1] = 0;

        for (int i = 0; i < s.length(); i++) {
            for (int carry = 0; carry < M * 2 + 1; carry++) {
                for (int cp = 0; cp < N; cp++) {
                    for (int cn = 0; cn < N; cn++) {
                        dp[1][carry][cp][cn] = INF;
                    }
                }
            }
            for (int carry = 0; carry < M * 2 + 1; carry++) {
                for (int cp = N - 1; cp >= 0; cp--) {
                    for (int cn = N - 1; cn >= 0; cn--) {
                        if (dp[0][carry][cp][cn] != INF) {
                            if (cp > 0) {
                                dp[0][carry][cp - 1][cn] = Math.min(dp[0][carry][cp - 1][cn], dp[0][carry][cp][cn]);
                            }
                            if (cn > 0) {
                                dp[0][carry][cp][cn - 1] = Math.min(dp[0][carry][cp][cn - 1], dp[0][carry][cp][cn]);
                            }
                            int rcarry = carry - M;
                            int val = rcarry + cp - cn;
                            int digit = val % 10;
                            if (digit < 0) {
                                digit += 10;
                            }
                            int ncarry = val / 10;
                            if (val < 0 && digit != 0) {
                                --ncarry;
                            }
                            if (digit == s.charAt(i) - '0') {
                                dp[1][ncarry + M][cp][cn] = Math.min(dp[1][ncarry + M][cp][cn],
                                        dp[0][carry][cp][cn] + cp + cn);
                            }
                        }
                    }
                }
            }
            int[][][] tmp = dp[0];
            dp[0] = dp[1];
            dp[1] = tmp;
        }

        int ans = INF;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                ans = Math.min(ans, dp[0][M][i][j]);
            }
        }
        System.out.println(ans);
    }

}


//package coding2;

import java.util.Scanner;

public class A378 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int len=-1;
		int max = Integer.MIN_VALUE;
		for(int i=0;i<s.length();i++)
		{
			if(s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||s.charAt(i)=='O'||s.charAt(i)=='U'||s.charAt(i)=='Y')
			{
				len=i-len;
				if(max<len)
					max=len;
				len=i;
			}
			else
				if(i==s.length()-1)
				{
					len = i-len+1;
					if(max<len)
						max = len;
				}

		}
		if(max<0)
			max = s.length()+1;
		System.out.println(max);
	}

}


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

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

class TaskE {
	static final long MOD = 1000000007;

	long[][][] result;
	long[][][] resultSmall;
	long[][] c = IntegerUtils.generateBinomialCoefficients(13);

    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int size = in.readInt();
		int count = in.readInt();
		result = new long[size + 1][count + 1][16];
		resultSmall = new long[size + 1][count + 1][16];
		ArrayUtils.fill(result, -1);
		ArrayUtils.fill(resultSmall, -1);
		long answer = calculate(size, count, 0);
		answer *= IntegerUtils.factorial(count, MOD);
		answer %= MOD;
		out.printLine(answer);
    }

	private long calculate(int size, int count, int mask) {
		if (count < 0)
			return 0;
		if (result[size][count][mask] != -1)
			return result[size][count][mask];
		long current = 0;
		if (mask == 0)
			current += 2 * calculate(0, count - 2, 15);
		for (int i = 0; i < 4; i++) {
			int j = (i + 1) & 3;
			if ((mask >> i & 1) != 0 || (mask >> j & 1) != 0)
				continue;
			int remaining = 15 - mask - (1 << i) - (1 << j);
			for (int k = remaining; ; k = (k - 1) & remaining) {
				current += calculateSmall(size, count - 1 - Integer.bitCount(k), mask + (1 << i) + (1 << j) + k);
				if (k == 0)
					break;
			}
		}
		int remaining = 15 - mask;
		for (int k = remaining; ; k = (k - 1) & remaining) {
			current += calculateSmall(size, count - Integer.bitCount(k), mask + k);
			if (k == 0)
				break;
		}
		return result[size][count][mask] = current % MOD;
	}

	private long calculateSmall(int size, int count, int mask) {
		if (count < 0)
			return 0;
		if (resultSmall[size][count][mask] != -1)
			return resultSmall[size][count][mask];
		if (size == 0)
			return resultSmall[size][count][mask] = count == 0 ? 1 : 0;
		int max = 3 * Integer.bitCount(15 - mask);
		int pairCount = 0;
		for (int i = 0; i < 4; i++) {
			int j = (i + 1) & 3;
			if ((mask >> i & 1) == 0 && ((mask >> j & 1) == 0))
				pairCount++;
		}
		long current = 0;
		for (int j = 0; j <= pairCount; j++) {
			for (int i = 0; i <= max - 2 * j; i++)
				current += calculate(size - 1, count - i - j, mask) * c[max - 2 * j][i] * c[pairCount][j];
		}
		return resultSmall[size][count][mask] = current % MOD;
	}
}

class IntegerUtils {

    public static long[][] generateBinomialCoefficients(int n) {
		long[][] result = new long[n + 1][n + 1];
		for (int i = 0; i <= n; i++) {
			result[i][0] = 1;
			for (int j = 1; j <= i; j++)
				result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
		}
		return result;
	}

	public static long factorial(int n, long mod) {
		long result = 1;
		for (int i = 2; i <= n; i++)
			result = result * i % mod;
		return result % mod;
	}

	}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int 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 int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

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

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

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

class OutputWriter {
	private final PrintWriter writer;

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

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

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

    public void printLine(Object...objects) {
		print(objects);
		writer.println();
	}

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

	}

class ArrayUtils {

	public static void fill(long[][] array, long value) {
		for (long[] row : array)
			Arrays.fill(row, value);
	}

	public static void fill(long[][][] array, long value) {
		for (long[][] row : array)
			fill(row, value);
	}

	}


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

public class Codeforces implements Runnable {
	BufferedReader in;
	PrintWriter out;
	StringTokenizer st;
	Random rnd;

	int[] colors;
	ArrayList<Integer>[] gMain, gRev;
	boolean[] usedFirst, reachFirst;
	boolean[] usedSecond, reachSecond;

	void bfsFirst(int n) {
		Queue<Integer> q = new ArrayDeque<Integer>();

		for(int i = 0; i < n; i++) {
			if(colors[i] == 1) {
				q.add(i);
				usedFirst[i] = reachFirst[i] = true;
			}
		}

		while(q.size() > 0) {
			int u = q.poll();

			for(int v : gMain[u]) {
				if(!usedFirst[v]) {
					q.add(v);
					usedFirst[v] = true;
					reachFirst[v] = true;
				}
			}
		}
	}

	void bfsSecond(int n) {
		Queue<Integer> q = new ArrayDeque<Integer>();

		for(int i = 0; i < n; i++) {
			if(colors[i] == 2) {
				q.add(i);
				usedSecond[i] = reachSecond[i] = true;
			}
		}

		while(q.size() > 0) {
			int u = q.poll();

			if(colors[u] == 1) {
				continue;
			}

			for(int v : gRev[u]) {
				if(!usedSecond[v]) {
					q.add(v);
					usedSecond[v] = true;
					reachSecond[v] = true;
				}
			}
		}
	}

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

		gMain = new ArrayList[n];
		gRev = new ArrayList[n];
		colors = new int[n];
		usedFirst = new boolean[n];
		reachFirst = new boolean[n];
		usedSecond = new boolean[n];
		reachSecond = new boolean[n];

		for(int i = 0; i < n; i++) {
			colors[i] = nextInt();
		}

		for(int i = 0; i < n; i++) {
			gMain[i] = new ArrayList<Integer>();
			gRev[i] = new ArrayList<Integer>();
		}

		for(int i = 0; i < m; i++) {
			int u = nextInt() - 1, v = nextInt() - 1;
			gMain[u].add(v);
			gRev[v].add(u);
		}

		bfsFirst(n);
		bfsSecond(n);

		for(int i = 0; i < n; i++) {
			if(reachFirst[i] && reachSecond[i]) {
				out.println(1);
			} else {
				out.println(0);
			}
		}

	}

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

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);

			rnd = new Random();

			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(42);
		}
	}

	String nextToken() throws IOException {
		while (st == null || !st.hasMoreTokens()) {
			String line = in.readLine();

			if (line == null) {
				return null;
			}

			st = new StringTokenizer(line);
		}

		return st.nextToken();
	}

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

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

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