import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;

import java.math.BigInteger;

import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;

public class Main{

    void run(){
        Locale.setDefault(Locale.US);
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
//        boolean oj = true;
        try{
            if( oj ){
                sc  = new FastScanner( new InputStreamReader(System.in  ) );
                out = new PrintWriter(   new OutputStreamWriter(System.out) );
            } else{
                sc  = new FastScanner(new FileReader("in.txt") );
//                sc  = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") );
                out = new PrintWriter(   new FileWriter("out.txt") );
            }
        } catch (Exception e) {
            System.exit(-1);
        }
        long tB = System.currentTimeMillis();
        solve();
        if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 );
        out.flush();
    }

    class FastScanner{
        BufferedReader br;
        StringTokenizer st = new StringTokenizer("");
        FastScanner( InputStreamReader a ){
            br = new BufferedReader(a);
        }
        FastScanner( FileReader a ){
            br = new BufferedReader(a);
        }
        String next(){
            while( !st.hasMoreTokens() )
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    return null;
                }
            return st.nextToken();
        }
        String readLine(){
            try {
                return br.readLine();
            } catch (Exception e) {
                return null;
            }
        }
        int nextInt(){ return Integer.parseInt(next()); }
        long nextLong(){ return Long.parseLong(next()); }
    }

    FastScanner sc;
    PrintWriter out;

    public static void main(String[] args){
        new Main().run();
//        new Thread( null, new Runnable() {
//            @Override
//            public void run() {
//                new Main().run();
//            }
//            }, "LOL", 256L * 1024 * 1024 / 2 ).run();
//        }, "LOL", 2000 * 1024 * 1024 ).run();
    }

    void TLE(){ for(;;); }

    void MLE(){
        int[][] adj = new int[1024*1024][];
        for( int i = 0; i < adj.length; ++i )
            adj[i] = new int[1024*1024];
    }

    void exit( int val ){
        out.flush();
        System.exit(val);
    }
    //////////////////////////////////////////////////////////////////////////////////////////

    class Item{
        int i, j, msk;
        Item( int _i, int _j, int _msk ){
            i = _i;
            j = _j;
            msk = _msk;
        }
    }

    final int inf = Integer.MAX_VALUE / 10;
    int n, m, Si, Sj;
    char[][] gr;

    int timer, mskOfBomb;
    int[] idObj;

    int[] cost = new int[8];
    int[][] dp;
    int[][] howI = new int[1000][1000];
    int[][] howJ = new int[1000][1000];
    int[][] howM = new int[1000][1000];
    {
        for( int i = 0; i < 1000; ++i ){
            fill( howI[i], -1 );
            fill( howJ[i], -1 );
            fill( howM[i], -1 );
        }
    }

    void f( int i, int j, int msk ){
        if( i==Si && j==Sj && msk==0 ){
        }
        else{
            f(
                howI[i*m+j][msk],
                howJ[i*m+j][msk],
                howM[i*m+j][msk]);
        }
        out.printf("%d %d %4s\n", i, j, Integer.toBinaryString(msk));
    }

    void solve(){
        n = sc.nextInt();
        m = sc.nextInt();
        gr = new char[n][];
        idObj = new int[n*m]; fill( idObj, -1 );
        for( int i = 0; i < n; ++i )
            gr[i] = sc.next().toCharArray();

        for( int i = 0; i < n; ++i ){
            for( int j = 0; j < m; ++j ){
                char c = gr[i][j];
                if( Character.isDigit(c) ){
                    idObj[i*m+j] = timer++;
                    cost[timer-1] = sc.nextInt();
                }
                if( c=='B' ){
                    idObj[i*m+j] = timer++;
                    mskOfBomb |= 1 << (timer-1);
                }
                if( c == 'S' ){
                    Si = i;
                    Sj = j;
                }
            }
        }

        dp = new int[n*m][1<<8];
        for( int[] dpi : dp ) fill( dpi, inf );
        dp[Si*m + Sj][0] = 0;
        ArrayDeque<Item> Q = new ArrayDeque<Item>();
        Q.add(new Item(Si,Sj,0));
        while( !Q.isEmpty() ){
            Item v = Q.pollFirst();
            for( int di = -1; di <= 1; ++di ){
            for( int dj = -1; dj <= 1; ++dj ){
                if( abs(di) + abs(dj) != 1 ) continue;
                Item to = new Item(v.i+di, v.j+dj, v.msk);
                if(!( 0<=to.i && to.i<n &&
                      0<=to.j && to.j<m &&
                      (gr[to.i][to.j] == '.' || gr[to.i][to.j]=='S') ))
                    continue;
                if( abs(di)==1 ){
                    int curI = min(v.i, to.i);
                    for( int k = 0; k < v.j; ++k ){
                        int id = idObj[curI*m + k];
                        if( id != -1 ) to.msk ^= 1 << id;
                    }
                }
                if( dp[to.i*m + to.j][to.msk] > dp[v.i*m + v.j][v.msk] + 1 ){
                    dp[to.i*m + to.j][to.msk] = dp[v.i*m + v.j][v.msk] + 1;
                    Q.addLast(to);
                    howI[to.i*m + to.j][to.msk] = v.i;
                    howJ[to.i*m + to.j][to.msk] = v.j;
                    howM[to.i*m + to.j][to.msk] = v.msk;
                }
            }
            }
        }

        int ans = 0;
        for( int msk = 0; msk < 1<<8; ++msk ){
            if( (msk & mskOfBomb) == 0 &&
                    dp[Si*m + Sj][msk] != inf ){
                int cost = 0;
                for( int i = 0; i < 8; ++i )
                    if( (msk & (1<<i)) != 0 )
                        cost += this.cost[i];
                ans = max( ans, cost - dp[Si*m + Sj][msk] );
                if( ans == 96 ){
                    out.printf("%4s\n", Integer.toBinaryString(msk));
                }
            }
        }
//        f( Si, Sj, 1<<3 );
        out.println(ans);
    }

}


import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;

import java.math.BigInteger;

import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;

public class Main{

    void run(){
        Locale.setDefault(Locale.US);
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
//        boolean oj = true;
        try{
            if( oj ){
                sc  = new FastScanner( new InputStreamReader(System.in  ) );
                out = new PrintWriter(   new OutputStreamWriter(System.out) );
            } else{
                sc  = new FastScanner(new FileReader("in.txt") );
//                sc  = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") );
                out = new PrintWriter(   new FileWriter("out.txt") );
            }
        } catch (Exception e) {
            System.exit(-1);
        }
        long tB = System.currentTimeMillis();
        solve();
        if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 );
        out.flush();
    }

    class FastScanner{
        BufferedReader br;
        StringTokenizer st = new StringTokenizer("");
        FastScanner( InputStreamReader a ){
            br = new BufferedReader(a);
        }
        FastScanner( FileReader a ){
            br = new BufferedReader(a);
        }
        String next(){
            while( !st.hasMoreTokens() )
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    return null;
                }
            return st.nextToken();
        }
        String readLine(){
            try {
                return br.readLine();
            } catch (Exception e) {
                return null;
            }
        }
        int nextInt(){ return Integer.parseInt(next()); }
        long nextLong(){ return Long.parseLong(next()); }
    }

    FastScanner sc;
    PrintWriter out;

    public static void main(String[] args){
        new Main().run();
//        new Thread( null, new Runnable() {
//            @Override
//            public void run() {
//                new Main().run();
//            }
//            }, "LOL", 256L * 1024 * 1024 / 2 ).run();
//        }, "LOL", 2000 * 1024 * 1024 ).run();
    }

    void TLE(){ for(;;); }

    void MLE(){
        int[][] adj = new int[1024*1024][];
        for( int i = 0; i < adj.length; ++i )
            adj[i] = new int[1024*1024];
    }

    void exit( int val ){
        out.flush();
        System.exit(val);
    }
    //////////////////////////////////////////////////////////////////////////////////////////

    class Item{
        int i, j, msk;
        Item( int _i, int _j, int _msk ){
            i = _i;
            j = _j;
            msk = _msk;
        }
    }

    final int inf = Integer.MAX_VALUE / 10;
    int n, m, Si, Sj;
    char[][] gr;

    int timer, mskOfBomb;
    int[] idObj;

    int[] cost = new int[9];
    int[][] dp;
    int[][] howI = new int[1000][1000];
    int[][] howJ = new int[1000][1000];
    int[][] howM = new int[1000][1000];
    {
        for( int i = 0; i < 1000; ++i ){
            fill( howI[i], -1 );
            fill( howJ[i], -1 );
            fill( howM[i], -1 );
        }
    }

    void f( int i, int j, int msk ){
        if( i==Si && j==Sj && msk==0 ){
        }
        else{
            f(
                howI[i*m+j][msk],
                howJ[i*m+j][msk],
                howM[i*m+j][msk]);
        }
        out.printf("%d %d %4s\n", i, j, Integer.toBinaryString(msk));
    }

    void solve(){
        n = sc.nextInt();
        m = sc.nextInt();
        gr = new char[n][];
        idObj = new int[n*m]; fill( idObj, -1 );
        for( int i = 0; i < n; ++i )
            gr[i] = sc.next().toCharArray();

        int[] tmp = new int[9];
        for( int i = 1; ; ++i )
            try {
                tmp[i] = sc.nextInt();
            } catch (Exception e) {
                break;
            }

        for( int i = 0; i < n; ++i ){
            for( int j = 0; j < m; ++j ){
                char c = gr[i][j];
                if( Character.isDigit(c) ){
                    idObj[i*m+j] = timer++;
                    cost[timer-1] = tmp[c - '0'];
                }
                if( c=='B' ){
                    idObj[i*m+j] = timer++;
                    mskOfBomb |= 1 << (timer-1);
                }
                if( c == 'S' ){
                    Si = i;
                    Sj = j;
                }
            }
        }

        dp = new int[n*m][1<<8];
        for( int[] dpi : dp ) fill( dpi, inf );
        dp[Si*m + Sj][0] = 0;
        ArrayDeque<Item> Q = new ArrayDeque<Item>();
        Q.add(new Item(Si,Sj,0));
        while( !Q.isEmpty() ){
            Item v = Q.pollFirst();
            for( int di = -1; di <= 1; ++di ){
            for( int dj = -1; dj <= 1; ++dj ){
                if( abs(di) + abs(dj) != 1 ) continue;
                Item to = new Item(v.i+di, v.j+dj, v.msk);
                if(!( 0<=to.i && to.i<n &&
                      0<=to.j && to.j<m &&
                      (gr[to.i][to.j] == '.' || gr[to.i][to.j]=='S') ))
                    continue;
                if( abs(di)==1 ){
                    int curI = min(v.i, to.i);
                    for( int k = 0; k < v.j; ++k ){
                        int id = idObj[curI*m + k];
                        if( id != -1 ) to.msk ^= 1 << id;
                    }
                }
                if( dp[to.i*m + to.j][to.msk] > dp[v.i*m + v.j][v.msk] + 1 ){
                    dp[to.i*m + to.j][to.msk] = dp[v.i*m + v.j][v.msk] + 1;
                    Q.addLast(to);
                    howI[to.i*m + to.j][to.msk] = v.i;
                    howJ[to.i*m + to.j][to.msk] = v.j;
                    howM[to.i*m + to.j][to.msk] = v.msk;
                }
            }
            }
        }

        int ans = 0;
        for( int msk = 0; msk < 1<<8; ++msk ){
            if( (msk & mskOfBomb) == 0 &&
                    dp[Si*m + Sj][msk] != inf ){
                int cost = 0;
                for( int i = 0; i < 8; ++i )
                    if( (msk & (1<<i)) != 0 )
                        cost += this.cost[i];
                ans = max( ans, cost - dp[Si*m + Sj][msk] );
                if( ans == 23 ){
                    out.printf("%4s\n", Integer.toBinaryString(msk));
                }
            }
        }

        out.println(ans);
    }

}


/*
 * 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.
 */
package com.mycompany.codeforces;

import java.util.Scanner;

/**
 *
 * @author dmalahov
 */
public class Main {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            String[] s1 = scanner.nextLine().split("\\s+");
            Boolean x1 = Integer.valueOf(s1[0]) == 1;
            Boolean y1 = Integer.valueOf(s1[1]) == 1;
            Boolean z1 = Integer.valueOf(s1[2]) == 1;
            String[] s2 = scanner.nextLine().split("\\s+");
            Boolean x2 = Integer.valueOf(s2[0]) == 1;
            Boolean y2 = Integer.valueOf(s2[1]) == 1;
            Boolean z2 = Integer.valueOf(s2[2]) == 1;
            System.out.println((x1 ^ x2 && y1 ^ y2 && z1 ^ z2) ? "YES" : "NO");
        }
    }

}


/*
 * Hello! You are trying to hack my solution, are you? =)
 * Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number.
 * And I'm just to lazy to create a new .java for every task.
 * And if you were successful to hack my solution, please, send me this test as a message or to Abrackadabraa@gmail.com.
 * It can help me improve my skills and i'd be very grateful for that.
 * Sorry for time you spent reading this message. =)
 * Good luck, unknown rival. =)
 * */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.Writer;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;

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

	static class myLib {
		long fact(long x) {
			long a = 1;
			for (long i = 2; i <= x; i++) {
				a *= i;
			}
			return a;
		}

		long digitSum(String x) {
			long a = 0;
			for (int i = 0; i < x.length(); i++) {
				a += x.charAt(i) - '0';
			}
			return a;
		}

		long digitSum(long x) {
			long a = 0;
			while (x > 0) {
				a += x % 10;
				x /= 10;
			}
			return a;
		}

		long digitMul(long x) {
			long a = 1;
			while (x > 0) {
				a *= x % 10;
				x /= 10;
			}
			return a;
		}

		int digitCubesSum(int x) {
			int a = 0;
			while (x > 0) {
				a += (x % 10) * (x % 10) * (x % 10);
				x /= 10;
			}
			return a;
		}

		double pif(double ax, double ay, double bx, double by) {
			return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
		}

		long gcd(long a, long b) {
			if (a == 0 || b == 0) return 1;
			if (a < b) {
				long c = b;
				b = a;
				a = c;
			}
			while (a % b != 0) {
				a = a % b;
				if (a < b) {
					long c = b;
					b = a;
					a = c;
				}
			}
			return b;
		}

		int gcd(int a, int b) {
			if (a == 0 || b == 0) return 1;
			if (a < b) {
				int c = b;
				b = a;
				a = c;
			}
			while (a % b != 0) {
				a = a % b;
				if (a < b) {
					int c = b;
					b = a;
					a = c;
				}
			}
			return b;
		}

		long lcm(long a, long b) throws IOException {
			return a * b / gcd(a, b);
		}

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

		int countOccurences(String x, String y) {
			int a = 0, i = 0;
			while (true) {
				i = y.indexOf(x);
				if (i == -1) break;
				a++;
				y = y.substring(i + 1);
			}
			return a;
		}

		int[] findPrimes(int x) {
			boolean[] forErato = new boolean[x - 1];
			List<Integer> t = new Vector<Integer>();
			int l = 0, j = 0;
			for (int i = 2; i < x; i++) {
				if (forErato[i - 2]) continue;
				t.add(i);
				l++;
				j = i * 2;
				while (j < x) {
					forErato[j - 2] = true;
					j += i;
				}
			}
			int[] primes = new int[l];
			Iterator<Integer> iterator = t.iterator();
			for (int i = 0; iterator.hasNext(); i++) {
				primes[i] = iterator.next().intValue();
			}
			return primes;
		}

		int rev(int x) {
			int a = 0;
			while (x > 0) {
				a = a * 10 + x % 10;
				x /= 10;
			}
			return a;
		}

		class myDate {
			int d, m, y;

			int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

			public myDate(int da, int ma, int ya) {
				d = da;
				m = ma;
				y = ya;
				if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) {
					d = 1;
					m = 1;
					y = 9999999;
				}
			}

			void incYear(int x) {
				for (int i = 0; i < x; i++) {
					y++;
					if (m == 2 && d == 29) {
						m = 3;
						d = 1;
						return;
					}
					if (m == 3 && d == 1) {
						if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
							m = 2;
							d = 29;
						}
						return;
					}
				}
			}

			boolean less(myDate x) {
				if (y < x.y) return true;
				if (y > x.y) return false;
				if (m < x.m) return true;
				if (m > x.m) return false;
				if (d < x.d) return true;
				if (d > x.d) return false;
				return true;
			}

			void inc() {
				if ((d == 31) && (m == 12)) {
					y++;
					d = 1;
					m = 1;
				} else {
					if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
						ml[1] = 29;
					}
					if (d == ml[m - 1]) {
						m++;
						d = 1;
					} else
						d++;
				}
			}
		}

		int partition(int n, int l, int m) {// n - sum, l - length, m - every
											// part
			// <= m
			if (n < l) return 0;
			if (n < l + 2) return 1;
			if (l == 1) return 1;
			int c = 0;
			for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) {
				c += partition(n - i, l - 1, i);
			}
			return c;
		}

		int rifmQuality(String a, String b) {
			if (a.length() > b.length()) {
				String c = a;
				a = b;
				b = c;
			}
			int c = 0, d = b.length() - a.length();
			for (int i = a.length() - 1; i >= 0; i--) {
				if (a.charAt(i) == b.charAt(i + d)) c++;
				else
					break;
			}
			return c;
		}

		String numSym = "0123456789ABCDEF";

		String ZFromXToYNotation(int x, int y, String z) {
			if (z.equals("0")) return "0";
			String a = "";
			long q = 0, t = 1;
			for (int i = z.length() - 1; i >= 0; i--) {
				q += (z.charAt(i) - 48) * t;
				t *= x;
			}
			while (q > 0) {
				a = numSym.charAt((int) (q % y)) + a;
				q /= y;
			}
			return a;
		}

		double angleFromXY(int x, int y) {
			if ((x == 0) && (y > 0)) return Math.PI / 2;
			if ((x == 0) && (y < 0)) return -Math.PI / 2;
			if ((y == 0) && (x > 0)) return 0;
			if ((y == 0) && (x < 0)) return Math.PI;
			if (x > 0) return Math.atan((double) y / x);
			else {
				if (y > 0) return Math.atan((double) y / x) + Math.PI;
				else
					return Math.atan((double) y / x) - Math.PI;
			}
		}

		static boolean isNumber(String x) {
			try {
				Integer.parseInt(x);
			} catch (NumberFormatException ex) {
				return false;
			}
			return true;
		}

		static boolean stringContainsOf(String x, String c) {
			for (int i = 0; i < x.length(); i++) {
				if (c.indexOf(x.charAt(i)) == -1) return false;
			}
			return true;
		}

		long pow(long a, long n) { // b > 0
			if (n == 0) return 1;
			long k = n, b = 1, c = a;
			while (k != 0) {
				if (k % 2 == 0) {
					k /= 2;
					c *= c;
				} else {
					k--;
					b *= c;
				}
			}
			return b;
		}

		int pow(int a, int n) { // b > 0
			if (n == 0) return 1;
			int k = n, b = 1, c = a;
			while (k != 0) {
				if (k % 2 == 0) {
					k /= 2;
					c *= c;
				} else {
					k--;
					b *= c;
				}
			}
			return b;
		}

		double pow(double a, int n) { // b > 0
			if (n == 0) return 1;
			double k = n, b = 1, c = a;
			while (k != 0) {
				if (k % 2 == 0) {
					k /= 2;
					c *= c;
				} else {
					k--;
					b *= c;
				}
			}
			return b;
		}

		double log2(double x) {
			return Math.log(x) / Math.log(2);
		}

		int lpd(int[] primes, int x) {// least prime divisor
			int i;
			for (i = 0; primes[i] <= x / 2; i++) {
				if (x % primes[i] == 0) {
					return primes[i];
				}
			}
			;
			return x;
		}

		int np(int[] primes, int x) {// number of prime number
			for (int i = 0; true; i++) {
				if (primes[i] == x) return i;
			}
		}

		int[] dijkstra(int[][] map, int n, int s) {
			int[] p = new int[n];
			boolean[] b = new boolean[n];
			Arrays.fill(p, Integer.MAX_VALUE);
			p[s] = 0;
			b[s] = true;
			for (int i = 0; i < n; i++) {
				if (i != s) p[i] = map[s][i];
			}
			while (true) {
				int m = Integer.MAX_VALUE, mi = -1;
				for (int i = 0; i < n; i++) {
					if (!b[i] && (p[i] < m)) {
						mi = i;
						m = p[i];
					}
				}
				if (mi == -1) break;
				b[mi] = true;
				for (int i = 0; i < n; i++)
					if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i];
			}
			return p;
		}

		boolean isLatinChar(char x) {
			if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true;
			else
				return false;
		}

		boolean isBigLatinChar(char x) {
			if (x >= 'A' && x <= 'Z') return true;
			else
				return false;
		}

		boolean isSmallLatinChar(char x) {
			if (x >= 'a' && x <= 'z') return true;
			else
				return false;
		}

		boolean isDigitChar(char x) {
			if (x >= '0' && x <= '9') return true;
			else
				return false;
		}

		class NotANumberException extends Exception {
			private static final long serialVersionUID = 1L;
			String mistake;

			NotANumberException() {
				mistake = "Unknown.";
			}

			NotANumberException(String message) {
				mistake = message;
			}
		}

		class Real {
			String num = "0";
			long exp = 0;
			boolean pos = true;

			long length() {
				return num.length();
			}

			void check(String x) throws NotANumberException {
				if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character.");
				long j = 0;
				for (long i = 0; i < x.length(); i++) {
					if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) {
						if (j == 0) j = 1;
						else
							if (j == 5) j = 6;
							else
								throw new NotANumberException("Unexpected sign.");
					} else
						if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
							if (j == 0) j = 2;
							else
								if (j == 1) j = 2;
								else
									if (j == 2)
									;
									else
										if (j == 3) j = 4;
										else
											if (j == 4)
											;
											else
												if (j == 5) j = 6;
												else
													if (j == 6)
													;
													else
														throw new NotANumberException("Unexpected digit.");
						} else
							if (x.charAt((int) i) == '.') {
								if (j == 0) j = 3;
								else
									if (j == 1) j = 3;
									else
										if (j == 2) j = 3;
										else
											throw new NotANumberException("Unexpected dot.");
							} else
								if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
									if (j == 2) j = 5;
									else
										if (j == 4) j = 5;
										else
											throw new NotANumberException("Unexpected exponent.");
								} else
									throw new NotANumberException("O_o.");
				}
				if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end.");
			}

			public Real(String x) throws NotANumberException {
				check(x);
				if (x.charAt(0) == '-') pos = false;
				long j = 0;
				String e = "";
				boolean epos = true;
				for (long i = 0; i < x.length(); i++) {
					if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
						if (j == 0) num += x.charAt((int) i);
						if (j == 1) {
							num += x.charAt((int) i);
							exp--;
						}
						if (j == 2) e += x.charAt((int) i);
					}
					if (x.charAt((int) i) == '.') {
						if (j == 0) j = 1;
					}
					if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
						j = 2;
						if (x.charAt((int) (i + 1)) == '-') epos = false;
					}
				}
				while ((num.length() > 1) && (num.charAt(0) == '0'))
					num = num.substring(1);
				while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) {
					num = num.substring(0, num.length() - 1);
					exp++;
				}
				if (num.equals("0")) {
					exp = 0;
					pos = true;
					return;
				}
				while ((e.length() > 1) && (e.charAt(0) == '0'))
					e = e.substring(1);
				try {
					if (e != "") if (epos) exp += Long.parseLong(e);
					else
						exp -= Long.parseLong(e);
				} catch (NumberFormatException exc) {
					if (!epos) {
						num = "0";
						exp = 0;
						pos = true;
					} else {
						throw new NotANumberException("Too long exponent");
					}
				}
			}

			public Real() {
			}

			String toString(long mantissa) {
				String a = "", b = "";
				if (exp >= 0) {
					a = num;
					if (!pos) a = '-' + a;
					for (long i = 0; i < exp; i++)
						a += '0';
					for (long i = 0; i < mantissa; i++)
						b += '0';
					if (mantissa == 0) return a;
					else
						return a + "." + b;
				} else {
					if (exp + length() <= 0) {
						a = "0";
						if (mantissa == 0) {
							return a;
						}
						if (mantissa < -(exp + length() - 1)) {
							for (long i = 0; i < mantissa; i++)
								b += '0';
							return a + "." + b;
						} else {
							if (!pos) a = '-' + a;
							for (long i = 0; i < mantissa; i++)
								if (i < -(exp + length())) b += '0';
								else
									if (i + exp >= 0) b += '0';
									else
										b += num.charAt((int) (i + exp + length()));
							return a + "." + b;
						}
					} else {
						if (!pos) a = "-";
						for (long i = 0; i < exp + length(); i++)
							a += num.charAt((int) i);
						if (mantissa == 0) return a;
						for (long i = exp + length(); i < exp + length() + mantissa; i++)
							if (i < length()) b += num.charAt((int) i);
							else
								b += '0';
						return a + "." + b;
					}
				}
			}
		}

		boolean containsRepeats(int... num) {
			Set<Integer> s = new TreeSet<Integer>();
			for (int d : num)
				if (!s.contains(d)) s.add(d);
				else
					return true;
			return false;
		}

		int[] rotateDice(int[] a, int n) {
			int[] c = new int[6];
			if (n == 0) {
				c[0] = a[1];
				c[1] = a[5];
				c[2] = a[2];
				c[3] = a[0];
				c[4] = a[4];
				c[5] = a[3];
			}
			if (n == 1) {
				c[0] = a[2];
				c[1] = a[1];
				c[2] = a[5];
				c[3] = a[3];
				c[4] = a[0];
				c[5] = a[4];
			}
			if (n == 2) {
				c[0] = a[3];
				c[1] = a[0];
				c[2] = a[2];
				c[3] = a[5];
				c[4] = a[4];
				c[5] = a[1];
			}
			if (n == 3) {
				c[0] = a[4];
				c[1] = a[1];
				c[2] = a[0];
				c[3] = a[3];
				c[4] = a[5];
				c[5] = a[2];
			}
			if (n == 4) {
				c[0] = a[0];
				c[1] = a[2];
				c[2] = a[3];
				c[3] = a[4];
				c[4] = a[1];
				c[5] = a[5];
			}
			if (n == 5) {
				c[0] = a[0];
				c[1] = a[4];
				c[2] = a[1];
				c[3] = a[2];
				c[4] = a[3];
				c[5] = a[5];
			}
			return c;
		}

		int min(int... a) {
			int c = Integer.MAX_VALUE;
			for (int d : a)
				if (d < c) c = d;
			return c;
		}

		int max(int... a) {
			int c = Integer.MIN_VALUE;
			for (int d : a)
				if (d > c) c = d;
			return c;
		}

		int[] normalizeDice(int[] a) {
			int[] c = a.clone();
			if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0);
			else
				if (c[2] == 0) c = rotateDice(c, 1);
				else
					if (c[3] == 0) c = rotateDice(c, 2);
					else
						if (c[4] == 0) c = rotateDice(c, 3);
						else
							if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0);
			while (c[1] != min(c[1], c[2], c[3], c[4]))
				c = rotateDice(c, 4);
			return c;
		}

		boolean sameDice(int[] a, int[] b) {
			for (int i = 0; i < 6; i++)
				if (a[i] != b[i]) return false;
			return true;
		}

		final double goldenRatio = (1 + Math.sqrt(5)) / 2;
		final double aGoldenRatio = (1 - Math.sqrt(5)) / 2;

		long Fib(int n) {
			if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
			else
				return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
			return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5));
		}

		class japaneeseComparator implements Comparator<String> {
			@Override
			public int compare(String a, String b) {
				int ai = 0, bi = 0;
				boolean m = false, ns = false;
				if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
					if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true;
					else
						return -1;
				}
				if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
					if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true;
					else
						return 1;
				}
				a += "!";
				b += "!";
				int na = 0, nb = 0;
				while (true) {
					if (a.charAt(ai) == '!') {
						if (b.charAt(bi) == '!') break;
						return -1;
					}
					if (b.charAt(bi) == '!') {
						return 1;
					}
					if (m) {
						int ab = -1, bb = -1;
						while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
							if (ab == -1) ab = ai;
							ai++;
						}
						while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
							if (bb == -1) bb = bi;
							bi++;
						}
						m = !m;
						if (ab == -1) {
							if (bb == -1) continue;
							else
								return 1;
						}
						if (bb == -1) return -1;
						while (a.charAt(ab) == '0' && ab + 1 != ai) {
							ab++;
							if (!ns) na++;
						}
						while (b.charAt(bb) == '0' && bb + 1 != bi) {
							bb++;
							if (!ns) nb++;
						}
						if (na != nb) ns = true;
						if (ai - ab < bi - bb) return -1;
						if (ai - ab > bi - bb) return 1;
						for (int i = 0; i < ai - ab; i++) {
							if (a.charAt(ab + i) < b.charAt(bb + i)) return -1;
							if (a.charAt(ab + i) > b.charAt(bb + i)) return 1;
						}
					} else {
						m = !m;
						while (true) {
							if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') {
								if (a.charAt(ai) < b.charAt(bi)) return -1;
								if (a.charAt(ai) > b.charAt(bi)) return 1;
								ai++;
								bi++;
							} else
								if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1;
								else
									if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1;
									else
										break;
						}
					}
				}
				if (na < nb) return 1;
				if (na > nb) return -1;
				return 0;
			}
		}

		Random random = new Random();
	}

	StreamTokenizer in;
	PrintWriter out;
	boolean oj;
	BufferedReader br;

	void init() throws IOException {
		oj = System.getProperty("ONLINE_JUDGE") != null;
		oj = !true;
		Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
		Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
		br = new BufferedReader(reader);
		in = new StreamTokenizer(br);
		out = new PrintWriter(writer);
	}

	long selectionTime = 0;

	void startSelection() {
		selectionTime -= System.currentTimeMillis();
	}

	void stopSelection() {
		selectionTime += System.currentTimeMillis();
	}

	void run() throws IOException {
		long beginTime = System.currentTimeMillis();
		init();
		solve();
		long endTime = System.currentTimeMillis();
		if (!oj) {
			System.out.println("Memory used = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
			System.out.println("Running time = " + (endTime - beginTime));
			System.out.println("Time of the selection = " + selectionTime);
		}
		out.flush();
	}

	int nextInt() throws IOException {
		in.nextToken();
		return (int) in.nval;
	}

	long nextLong() throws IOException {
		in.nextToken();
		return (long) in.nval;
	}

	String nextString() throws IOException {
		in.nextToken();
		return in.sval;
	}

	double nextDouble() throws IOException {
		in.nextToken();
		return in.nval;
	}

	myLib lib = new myLib();

	void solve() throws IOException {
		int x1 = nextInt(), y1 = nextInt(), z1 = nextInt();
		int x2 = nextInt(), y2 = nextInt(), z2 = nextInt();
		int c = 0;
		if (x1 == x2) c++;
		if (y1 == y2) c++;
		if (z1 == z2) c++;
		if (c >= 1) out.println("YES"); else out.println("NO");
	}
}


package solution;

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

public class Main {

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

        int[] a = new int[3];
        int[] b = new int[3];

        for (int i = 0; i < 3; i++) {
            a[i] = in.nextInt();
        }
        for (int i = 0; i < 3; i++) {
            b[i] = in.nextInt();
        }

        if (a[0]!=b[0] && a[1]!=b[1] && a[2]!=b[2])
        {
            out.print("NO");
        } else {
            out.print("YES");
        }

      out.flush();
    }
}


package solution;

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

public class Solution {

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

        int[] a = new int[3];
        int[] b = new int[3];

        for (int i = 0; i < 3; i++) {
            a[i] = in.nextInt();
        }
        for (int i = 0; i < 3; i++) {
            b[i] = in.nextInt();
        }

        if (a[0]!=b[0] && a[1]!=b[1] && a[2]!=b[2])
        {
            out.print("NO");
        } else {
            out.print("YES");
        }

      out.flush();
    }
}


import java.util.Scanner;

public class OBA
{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        long num = scan.nextLong();
        System.out.println(""+prog(num));
    }

    public static long genUnos(long n){
        long res=0;
        /*for(long i=1;i <= n;i++){
            res=Math.pow(10,i-1);
        }*/
        res=(long)(Math.pow(10,n)-1)/9;
        return res;
    }

    public static long prog(long n){
        long total=0;
        long temp=n;
        long sec=0;
        long signo=0;
        long valuno=0;
        while(n-sec!=0){
            long tam=(long)((Math.log10(Math.abs(temp)))+1);
           // System.out.println("tamaño"+tam);
            int a=genUnos(1+tam);
            int b=a/10;
            if(a-temp> temp-b valuno=a;
            else valuno=b;
           // signo=(valuno*temp)/(long)Math.abs(valuno*temp);//% 10;
            if(temp>0){
                sec=sec+valuno;
                temp=temp-valuno;
            }else{
                sec=sec-valuno;
                temp=temp+valuno;
            }

            total=total+(long)((Math.log10(valuno)+1));
        }
        return total;
    }
}


import java.util.Scanner;

public class OBA
{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        long num = scan.nextLong();
        System.out.println(""+prog(num));
    }

    public static long genUnos(long n){
        long res=0;
        /*for(long i=1;i <= n;i++){
            res=Math.pow(10,i-1);
        }*/
        res=(long)(Math.pow(10,n)-1)/9;
        return res;
    }

    public static long prog(long n){
        long total=0;
        long temp=n;
        long sec=0;
        long signo=0;
        long valuno=0;
        while(n-sec!=0){
            long tam=(long)(Math.log10(Math.abs(temp)))+1);
           // System.out.println("tamaño"+tam);
            if(temp%(int)Math.pow(10,tam)>=5) valuno=genUnos(1+tam);
            else valuno=genUnos(tam);
           // signo=(valuno*temp)/(long)Math.abs(valuno*temp);//% 10;
            if(temp>0){
                sec=sec+valuno;
                temp=temp-valuno;
            }else{
                sec=sec-valuno;
                temp=temp+valuno;
            }

            total=total+(long)(Math.log10(valuno)+1));
        }
        return total;
    }
}


import java.util.Scanner;
import java.lang.Math.*;
public class Main_C {
	static long n;
	private static Scanner enter;

	static long[] a;
	public static void main(String[] args) {
		enter=new Scanner(System.in);
		n=enter.nextLong();
		a=new long[20];
		a[1] = 1;
	    for(int i = 2;i <= 16 ;i ++ ) {
	        a[i] = a[i-1] *10 + 1;
	    }
	    System.out.println(sol(n));
	}
	static int sol (long l) {
		int i = 16;
		int r = 0;
		if(l <= 11) {
			return (int) Math.min(l,2+11-l);
		}
		while(a[i-1] > l)i--;
	    r = (int) (l/a[i-1]) *(i-1) + sol(l%(a[i-1]));
	    if(2*l<a[i])
	    	return r;
	    return Math.min(r, i + sol(a[i] - l));

	}


import java.util.Scanner;

public class OBA
{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        long num = scan.nextLong();
        System.out.println(""+prog(num));
    }

    public static long genUnos(long n){
        long res=0;
        /*for(long i=1;i <= n;i++){
            res=Math.pow(10,i-1);
        }*/
        res=(long)(Math.pow(10,n)-1)/9;
        return res;
    }

    public static long prog(long n){
        long total=0;
        long temp=n;
        long sec=0;
        long signo=0;
        long valuno=0;
        while(n-sec!=0){
            long tam=(long)((Math.log10(Math.abs(temp)))+1);
           // System.out.println("tamaño"+tam);
            if(genUnos(1+tam)-temp> temp-getUnos(tam)) valuno=genUnos(1+tam);
            else valuno=genUnos(tam);
           // signo=(valuno*temp)/(long)Math.abs(valuno*temp);//% 10;
            if(temp>0){
                sec=sec+valuno;
                temp=temp-valuno;
            }else{
                sec=sec-valuno;
                temp=temp+valuno;
            }

            total=total+(long)((Math.log10(valuno)+1));
        }
        return total;
    }
}


import java.util.Scanner;

public class TaskB {
	public static Scanner in = new Scanner(System.in);

	public static void main(String[] args){
		int n = in.nextInt();
		int m = in.nextInt();
		int k = in.nextInt();
		int a = in.nextInt();
		int b = in.nextInt();
		int time = 0;
		int n1 , n2;
		int m1, m2;
		n1 = a/(m*k) + 1;
		n2 = b/(m*k)+1  ;
		if(a %(m*k) == 0 ) n1--;
		if(b%(m*k) == 0) n2--;
		m1 = (a - (n1-1)* m* k)/k + 1 ;
		m2 = (b - (n2-1)*m*k)/k + 1;
		if((a - (n1-1)* m* k)%k == 0 ) m1--;
		if((b - (n2-1)*m*k)%k == 0) m2--;
		if(n1 > n2){
			if(Math.abs((n1 - n2)) < n-n1 + n2 ) time +=Math.abs((n1 - n2))*15;
			else
				time +=(n-n1 + n2)*15;
		}else
			if(Math.abs((n1 - n2)) < n+n1 - n2 ) time +=Math.abs((n1 - n2))*15;
			else
				time +=(n+n1 - n2)*15;
		if(n1 != n2){
			if(m1 > 3) time+= (10 + m1-1);
			else time += (5 * (m1-1));
			if(m2 > 3) time+= (10 + m2-1);
			else time += (5 * (m2-1));
		}else {

			if(Math.abs(m1- m2) > 2) time+= (10 + Math.abs(m1- m2));
			else time += (5 * Math.abs(m1- m2));
		}
		System.out.println(time);

	}

}


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

public class CFB {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int k = in.nextInt();
		int a = in.nextInt()-1;
		int b = in.nextInt()-1;
		int homeA = a/(m*k);
		int homeB = b/(m*k);
		int floorA = (a%(m*k))/k;
		int floorB = (b%(m*k))/k;
		if (homeA==homeB&&floorA==floorB){
			System.out.println(0);
		} else if (homeA==homeB){
			int d = Math.abs(floorA-floorB);
			System.out.println(Math.min(10+d, 5*d));
		} else {
			int down = Math.min(10+floorA, 5*floorA);
			int betw = -1;
			if (homeA>homeB){
				betw = Math.min(homeA-homeB, homeB+n-homeA);
			} else {
				betw = Math.min(homeB-homeA, homeA+n-homeB);
			}
			int up = Math.min(10+floorB, 5*floorB);
			System.out.println(down+betw*15+up);
		}
	}

}


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

/**
 * Created by boris on 26.03.2016.
 */
public class TaskB {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] tmp = reader.readLine().split("\\s");

        int pods = Integer.parseInt(tmp[0]);
        int florsc = Integer.parseInt(tmp[1]);
        int doorsc = Integer.parseInt(tmp[2]);

        String[] tmp1 = reader.readLine().split("\\s");

        int fr = Integer.parseInt(tmp1[0]);
        int to = Integer.parseInt(tmp1[1]);

        int frPod = (int) Math.ceil(fr*1.0/doorsc/florsc);
        int frFlor = (int) Math.ceil((fr*1.0-(frPod-1)*(florsc*doorsc))/doorsc);

        int toPod = (int) Math.ceil(to*1.0/doorsc/florsc);
        int toFlor = (int) Math.ceil((to*1.0-(toPod-1)*(florsc*doorsc))/doorsc);

        int time = 0;
        if (frPod == toPod) {
            int florsToGo = Math.abs(toFlor-frFlor);

            if (florsToGo < 3) {
                time += florsToGo*5;
            } else {
                time += 10;
                time += florsToGo;
            }
        } else {
            int florsToGo1 = toFlor-1;
            int florsToGo2 = frFlor-1;

            int podsToGo = Math.min(Math.abs(toPod-frPod), pods-Math.max(toPod, frPod)+Math.min(toPod, frPod));

            if (florsToGo1 < 3) {
                time += florsToGo1*5;
            } else {
                time += 10;
                time += florsToGo1;
            }

            if (florsToGo2 < 3) {
                time += florsToGo2*5;
            } else {
                time += 10;
                time += florsToGo2;
            }

            time += podsToGo*15;
        }

        System.out.println(time);
    }
}


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

public class b1 {
	BufferedReader br;
	StringTokenizer in;
	PrintWriter out;

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

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

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

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

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

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

		int a = nextInt();
		int b = nextInt();

		int n1 = (a + m * k - 1) / (m * k);
		int n2 = (b + m * k - 1) / (m * k);

		int fl1 = (a - (n1 - 1) * m * k + k - 1) / k;
		int fl2 = (b - (n2 - 1) * m * k + k - 1) / k;

		if (n1 == n2) {
			out.println(Math.min(Math.abs(fl1 - fl2) * 5, 10 + Math.abs(fl1 - fl2)));
		} else {
			long cur_ans = Math.min((fl1 - 1) * 5, 10 + fl1 - 1);

			cur_ans += Math.min(Math.abs(n1 - n2) * 15, (n - Math.abs(n1 - n2)) * 15);

			out.println(cur_ans + Math.min((fl2 - 1) * 5, (fl2 - 1) + 10));

		}
	}

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

			solve();

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


import java.util.Scanner;

/**
 * Created by zhengyanglzy on 2017/6/24.
 */
public class Main {
    private static final int MAXIMUM_IND = 65;
    private static final long[] POWER;
    private static final long[] POWER_SUM;

    static {
        POWER = new long[MAXIMUM_IND];
        POWER_SUM = new long[MAXIMUM_IND];
        POWER[0] = POWER_SUM[0] = 0;
        POWER[1] = POWER_SUM[1] = 1;
        for (int i = 2; i < MAXIMUM_IND; ++i) {
            POWER[i] = POWER[i - 1] * 2;
            POWER_SUM[i] = POWER_SUM[i - 1] + POWER[i];
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long houseNum = sc.nextLong();
            long k = sc.nextLong();
            if (k == 1) {
                System.out.println(1);
                continue;
            } else if (k == 2) {
                System.out.println(houseNum);
                continue;
            }
            System.out.println(1 + findLabel(houseNum - 2, k - 2));
        }
    }

    static long findLabel(long houseNum, long k) {
        long medium = (houseNum + 1) / 2;
        if (k == 1) {
            return medium;
        }
        k -= 1;
        int ind;
        for (ind = 1; k > 2 * POWER_SUM[ind]; ++ind) {
            k -= 2 * POWER_SUM[ind];
        }
        if (k <= POWER[ind] && POWER_SUM[ind - 1] + k <= medium - 1) {
            // left
            return findLabel(medium - 1, POWER_SUM[ind - 1] + k);
        }
        // right
        if (POWER_SUM[ind - 1] + k > medium - 1) {
            return medium + findLabel(houseNum - medium, POWER_SUM[ind - 1]+ k - (medium - 1 - POWER_SUM[ind - 1]));
        }
        return medium + findLabel(houseNum - medium, POWER_SUM[ind - 1] + k - POWER[ind]);
    }
}


import java.util.*;

/**
 * Created by zhengyanglzy on 2017/6/24.
 */
public class Main {
    private static final int MAXIMUM_IND = 65;
    private static final long[] POWER;
    private static final long[] POWER_SUM;
    private static final Map<Long, Long> SPACE;
    static Random random = new Random(System.currentTimeMillis());

    static {
        POWER = new long[MAXIMUM_IND];
        POWER_SUM = new long[MAXIMUM_IND];
        POWER[0] = POWER_SUM[0] = 0;
        POWER[1] = POWER_SUM[1] = 1;
        for (int i = 2; i < MAXIMUM_IND; ++i) {
            POWER[i] = POWER[i - 1] * 2;
            POWER_SUM[i] = POWER_SUM[i - 1] + POWER[i];
        }
        SPACE = new HashMap<Long, Long>();
        SPACE.put(0L, 0L);
        SPACE.put(1L, 0L);
        SPACE.put(2L, 0L);
    }

    public static void main(String[] args) {
        // testSO(5000);
        // compare(51, 400);
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long houseNum = sc.nextLong();
            long k = sc.nextLong();
            System.out.println(cal(houseNum, k));
        }
    }

    public static void compare(int start, int end) {
        for (int i = start; i <= end; ++i) {
            List<Integer> res = generate(i);
            assert res.size() == i;
            boolean isMatch = true;
            for (int j = 0; j < res.size(); ++j) {
                long got = cal(i + 2, j + 3);
                long expected = res.get(j) + 1;
                if (expected != got) {
                    isMatch = false;
                    System.err.printf("(%d, %d) expected %d, got %d\n", i + 2, j + 3, expected, got);
                }
            }
            if (!isMatch) {
                break;
            }
            System.out.printf("complete %d\n", i);
        }
        System.out.println("over");
    }

    public static void testSO(int casenum) {
        while (casenum -- > 0) {
            long n = random.nextLong();
            long k = random.nextLong();
            if (k > n) {
                long tmp = n;
                n = k;
                k = tmp;
            }
            try {
                findLabel(n, k);
            } catch (StackOverflowError e) {
                System.err.printf("%d %d", n, k);
                break;
            }
        }
        System.out.println("over");
    }

    public static List<Integer> generate(int houseNum) {
        TreeSet<Seg> segs = new TreeSet<Seg>();
        segs.add(new Seg(1, houseNum));
        List<Integer> ret = new ArrayList<Integer>();
        while (!segs.isEmpty()) {
            Seg seg = segs.first();
            segs.remove(seg);
            int pos = (seg.length + 1) / 2 + seg.start - 1;
            ret.add(pos);
            if (pos - seg.start > 0) {
                segs.add(new Seg(seg.start, pos - seg.start));
            }
            if (seg.length + seg.start - pos - 1> 0) {
                segs.add(new Seg(pos + 1, seg.length + seg.start - pos - 1));
            }
        }
        return ret;
    }

    static long cal(long houseNum, long k) {
        if (k == 1) {
            return 1;

        } else if (k == 2) {
            return 2;
        }
        return 1 + findLabel(houseNum - 2, k - 2);
    }

    static long findSpace(long num) {
        if (SPACE.containsKey(num)) {
            return SPACE.get(num);
        }
        long medium = (num + 1) / 2;
        long res = 1 + findSpace(medium - 1) + findSpace(num - medium);
        SPACE.put(num, res);
        return res;
    }

    static long findLabel(long houseNum, long k) {
        // System.out.printf("%d %d\n", houseNum, k);
        long medium = (houseNum + 1) / 2;
        if (k == 1) {
            return medium;
        }
        /*
        long totalSpace = findSpace(houseNum);
        if (totalSpace < k) {
            // 慢慢填
            if (totalSpace == 0) {
                return k;
            }
            k -= totalSpace;
            long left = medium - 1 - findSpace(medium - 1);
            if (k <= left) {
                return findLabel(medium - 1, k + findSpace(medium - 1));
            }
            return medium + findLabel(houseNum - medium, k - left + findSpace(houseNum - medium));
        }*/
        k -= 1;
        Part leftPart = new Part(medium - 1);
        Part rightPart = new Part(houseNum - medium);
        long leftTotal = 0;
        long rightTotal = 0;
        while (true) {
            long left = leftPart.peek();
            long right = rightPart.peek();
            if (left == 0 && right == 0) {
                break;
            }
            if (k > left + right) {
                k -= left + right;
                leftTotal += left;
                rightTotal += right;
                leftPart.split();
                rightPart.split();
                continue;
            }
            leftPart.collapse();
            rightPart.collapse();
            TreeSet<Long> set = new TreeSet<Long>();
            set.addAll(leftPart.segs.keySet());
            set.addAll(rightPart.segs.keySet());
            for (long len : set.descendingSet()) {
                if (leftPart.segs.containsKey(len)) {
                    if (leftPart.segs.get(len) >= k) {
                        return findLabel(medium - 1, leftTotal + k);
                    } else {
                        k -= leftPart.segs.get(len);
                        leftTotal += leftPart.segs.get(len);
                    }
                }
                if (rightPart.segs.containsKey(len)) {
                    if (rightPart.segs.get(len) >= k) {
                        return medium + findLabel(houseNum - medium, rightTotal + k);
                    } else {
                        k -= rightPart.segs.get(len);
                        rightTotal += rightPart.segs.get(len);
                    }
                }
            }
        }
        // 只剩1和2
        if (medium - 1 - leftTotal >= k) {
            return findLabel(medium - 1, leftTotal + k);
        }
        return medium + findLabel(houseNum - medium, rightTotal + k - (medium - 1 - leftTotal));
    }

    static class Part {
        Map<Long, Long> segs;

        Part(long num) {
            segs = new HashMap<Long, Long>();
            segs.put(num, 1L);
        }

        void split() {
            Map<Long, Long> newMap = new HashMap<Long, Long>();
            for (Map.Entry<Long, Long> entry : segs.entrySet()) {
                if (entry.getKey() <= 2) {
                    update(newMap, entry.getKey(), entry.getValue());
                    continue;
                }
                long medium = (entry.getKey() + 1) / 2;
                update(newMap, medium - 1, entry.getValue());
                update(newMap, entry.getKey() - medium, entry.getValue());
            }
            segs = newMap;
        }

        long peek() {
            long ret = 0;
            for (Map.Entry<Long, Long> entry : segs.entrySet()) {
                if (entry.getKey() > 2) {
                    ret += entry.getValue();
                }
            }
            return ret;
        }

        void collapse() {
            Map<Long, Long> newMap = new HashMap<Long, Long>();
            for (Map.Entry<Long, Long> entry : segs.entrySet()) {
                update(newMap, (entry.getKey() + 1) / 2, entry.getValue());
            }
            segs = newMap;
        }

        static void update(Map<Long, Long> map, long key, long inc) {
            if (!map.containsKey(key)) {
                map.put(key, 0L);
            }
            map.put(key, map.get(key) + inc);
        }
    }

    static class Seg implements Comparable<Seg> {
        int start;
        int length;

        public Seg(int start, int length) {
            this.start = start;
            this.length = length;
        }

        public int compareTo(Seg o) {
            int diff = (length - 1) / 2 - (o.length -1) / 2;
            if (diff != 0) {
                return -diff;
            }
            return start - o.start;
        }
    }
}


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

/**
 * Created by zhengyanglzy on 2017/6/24.
 */
public class Main {
    private static final int MAXIMUM_IND = 65;
    private static final long[] POWER;
    private static final long[] POWER_SUM;
    static Random random = new Random(System.currentTimeMillis());

    static {
        POWER = new long[MAXIMUM_IND];
        POWER_SUM = new long[MAXIMUM_IND];
        POWER[0] = POWER_SUM[0] = 0;
        POWER[1] = POWER_SUM[1] = 1;
        for (int i = 2; i < MAXIMUM_IND; ++i) {
            POWER[i] = POWER[i - 1] * 2;
            POWER_SUM[i] = POWER_SUM[i - 1] + POWER[i];
        }
    }

    public static void main(String[] args) {
        // test(5000);
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long houseNum = sc.nextLong();
            long k = sc.nextLong();
            if (k == 1) {
                System.out.println(1);
                continue;
            } else if (k == 2) {
                System.out.println(houseNum);
                continue;
            }
            System.out.println(1 + findLabel(houseNum - 2, k - 2));
        }
    }

    public static void test(int casenum) {
        while (casenum -- > 0) {
            long n = random.nextLong();
            long k = random.nextLong();
            if (k > n) {
                long tmp = n;
                n = k;
                k = tmp;
            }
            try {
                findLabel(n, k);
            } catch (StackOverflowError e) {
                System.err.printf("%d %d", n, k);
                break;
            }
        }
        System.out.println("over");
    }

    static long findLabel(long houseNum, long k) {
        //System.out.printf("%d %d\n", houseNum, k);
        long medium = (houseNum + 1) / 2;
        if (k == 1) {
            return medium;
        }
        k -= 1;
        Part left = new Part(0, medium - 1);
        Part right = new Part(medium, houseNum - medium);
        boolean strict = left.houseNum % 2 == 0 && right.houseNum - left.houseNum == 1;
        if (left.houseNum <= 2) {
            if (strict && k == 1) {
                return right.start + findLabel(right.houseNum, k);
            }
            if (k - (strict ? 1 : 0) <= left.houseNum) {
                return k - (strict ? 1 : 0);
            }
            return right.start + findLabel(right.houseNum, k - left.houseNum);
        }
        if (strict) {
            Part tmp = left;
            left = right;
            right = tmp;
        }
        int ind;
        for (ind = 1; k > 2 * POWER_SUM[ind]; ++ind);
        k -= 2 * POWER_SUM[ind - 1];
        if (left.houseNum - POWER_SUM[ind - 1] <= 2 && k <= left.houseNum - POWER_SUM[ind - 1]) {
            // 此时不满足规律
            return left.start + findLabel(left.houseNum, POWER_SUM[ind - 1] + k);
        }
        // if (k <= 2 && k == left.houseNum - POWER_SUM[ind - 1])
        if (k <= POWER[ind] && POWER_SUM[ind - 1] + k <= left.houseNum) {
            // left
            return left.start + findLabel(left.houseNum, POWER_SUM[ind - 1] + k);
        }
        // right
        long newK = POWER_SUM[ind - 1] + k - POWER[ind];
        if (POWER_SUM[ind - 1] + k > left.houseNum) {
            // 左边剩余的房子不一定够POWER[ind]
            newK = POWER_SUM[ind - 1]+ k - (left.houseNum - POWER_SUM[ind - 1]);
        }
        return right.start + findLabel(right.houseNum, newK);
    }

    static class Part {
        long start;
        long houseNum;

        Part(long start, long houseNum) {
            this.start = start;
            this.houseNum = houseNum;
        }
    }
}


import java.util.Scanner;

/**
 * Created by zhengyanglzy on 2017/6/24.
 */
public class Main {
    private static final int MAXIMUM_IND = 65;
    private static final long[] POWER;
    private static final long[] POWER_SUM;

    static {
        POWER = new long[MAXIMUM_IND];
        POWER_SUM = new long[MAXIMUM_IND];
        POWER[0] = POWER_SUM[0] = 0;
        POWER[1] = POWER_SUM[1] = 1;
        for (int i = 2; i < MAXIMUM_IND; ++i) {
            POWER[i] = POWER[i - 1] * 2;
            POWER_SUM[i] = POWER_SUM[i - 1] + POWER[i];
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long houseNum = sc.nextLong();
            long k = sc.nextLong();
            if (k == 1) {
                System.out.println(1);
                continue;
            } else if (k == 2) {
                System.out.println(houseNum);
                continue;
            }
            System.out.println(1 + findLabel(houseNum - 2, k - 2));
        }
    }

    static long findLabel(long houseNum, long k) {
        long medium = (houseNum + 1) / 2;
        if (k == 1) {
            return medium;
        }
        k -= 1;
        Part left = new Part(0, medium - 1);
        Part right = new Part(medium, houseNum - medium);
        boolean strict = left.houseNum % 2 == 0 && right.houseNum - left.houseNum == 1;
        if (left.houseNum <= 2) {
            if (strict && k == 1) {
                return right.start + findLabel(right.houseNum, k);
            }
            if (k - (strict ? 1 : 0) <= left.houseNum) {
                return k - (strict ? 1 : 0);
            }
            return right.start + findLabel(right.houseNum, k - left.houseNum);
        }
        if (strict) {
            Part tmp = left;
            left = right;
            right = tmp;
        }
        int ind;
        for (ind = 1; k > 2 * POWER_SUM[ind]; ++ind) {
        }
        k -= 2 * POWER_SUM[ind - 1];
        if (left.houseNum - POWER_SUM[ind - 1] <= 2 && k <= 2) {
            // 此时不满足规律
            return left.start + findLabel(left.houseNum, POWER_SUM[ind - 1] + k);
        }
        // if (k <= 2 && k == left.houseNum - POWER_SUM[ind - 1])
        if (k <= POWER[ind] && POWER_SUM[ind - 1] + k <= left.houseNum) {
            // left
            return left.start + findLabel(left.houseNum, POWER_SUM[ind - 1] + k);
        }
        // right
        long newK = POWER_SUM[ind - 1] + k - POWER[ind];
        if (POWER_SUM[ind - 1] + k > left.houseNum) {
            // 左边剩余的房子不一定够POWER[ind]
            newK = POWER_SUM[ind - 1]+ k - (left.houseNum - POWER_SUM[ind - 1]);
        }
        return right.start + findLabel(right.houseNum, newK);
    }

    static class Part {
        long start;
        long houseNum;

        Part(long start, long houseNum) {
            this.start = start;
            this.houseNum = houseNum;
        }
    }
}


/*
 * 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.
 */
package pkg124d;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Integer.max;
import static java.lang.Math.abs;
/**
 *
 * @author Sergey
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String str = "";

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

        int[] arr = new int[6];
        int t1, t2;

        for(int i = 0; i < arr.length -1; i++){
            int index = str.indexOf(" ");
            arr[i] = Integer.parseInt(str.substring(0, index));
            str = str.substring(index+1);
        }

        arr[5] = Integer.parseInt(str);

        t1 = arr[2]; t2 = arr[3];
        arr[2] = t1 + t2;
        arr[3] = t2 - t1;

        t1 = arr[4]; t2 = arr[5];
        arr[4] = t1 + t2;
        arr[5] = t2 - t1;

        arr[0] *= 2;
        arr[1] *= 2;

        arr[2]= arr[2] / arr[0] + ((arr[2] > 0)? 1 : 0);
        arr[4] = arr[4] / arr[0] + ((arr[4] > 0)? 1 : 0);
        arr[3] = arr[3] / arr[1] + ((arr[3] > 0)? 1 : 0);
        arr[5] = arr[5] / arr[1] + ((arr[5] > 0)? 1 : 0);

        System.out.print(max(abs(arr[5] - arr[3]), abs(arr[4] - arr[2])));
    }

}


package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a= in.nextInt();
        int b= in.nextInt();
        int x1= in.nextInt();
        int x2= in.nextInt();
        int y1= in.nextInt();
        int y2 = in.nextInt();
        int parity1, parity2;

        a *= 2;
        b *= 2;

        parity1 = x1;
        parity2 = y1;
        x1 = parity1 + parity2;
        y1 = parity2 - parity1;

        parity1 = x2;
        parity2 = y2;
        x2 = parity1 + parity2;
        y2 = parity2 - parity1;

        if
                (x1>0) x1 = x1/a+1;
        else
            x1 = x1/a;

        if
                (x2>0) x2 = x2/a+1;
        else
            x2 = x2/a;

        if
                (y1>0)  y1 = y1/b+1;
        else
            y1 = y1/b;

        if
                (y2>0)  y2 = y2/b+1;
        else
            y2 = y2/b;

        System.out.println(Math.max(Math.abs((x2-x1)),Math.abs((y2-y1))));
    }
}


package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a= in.nextInt(), b= in.nextInt(), x1= in.nextInt(), x2= in.nextInt(), y1= in.nextInt(), y2 = in.nextInt();
        int parity1, parity2;

        a *= 2;
        b *= 2;

        parity1 = x1;
        parity2 = y1;
        x1 = parity1 + parity2;
        y1 = parity2 - parity1;

        parity1 = x2;
        parity2 = y2;
        x2 = parity1 + parity2;
        y2 = parity2 - parity1;

        if
                (x1>0) x1 = x1/a+1;
        else
            x1 = x1/a;

        if
                (x2>0) x2 = x2/a+1;
        else
            x2 = x2/a;

        if
                (y1>0)  y1 = y1/b+1;
        else
            y1 = y1/b;

        if
                (y2>0)  y2 = y2/b+1;
        else
            y2 = y2/b;

        System.out.println(Math.max(Math.abs((x2-x1)),Math.abs((y2-y1))));
    }
}


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

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

	void solve()
	{
		int n = ni(), k = ni();
		char[] s = ns(n);
		for(int i = 0;i < n-1 && k > 0;i++){
			if(s[i] == '4' && s[i+1] == '7'){
				if(i % 2 == 0){
					s[i+1] = '4';
					k--;
				}else{
					s[i] = '7';
					k--;
					if(i-1 >= 0 && s[i-1] == '4'){
						k %= 2;
						i = -1;
					}
				}
			}
		}
		out.println(new String(s));
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

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

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

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

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

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

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

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

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


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

public class H {
    static final boolean RUN_TIMING = false;
    static char[] inputBuffer = new char[1 << 20];
    static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    ArrayList<Long> pairs = new ArrayList<>();
    ArrayList<Integer> sets = new ArrayList<>();

    public void go() throws IOException {
        // in = new PushbackReader(new BufferedReader(new FileReader(new File("test.txt"))), 1 << 20);
        // out = new PrintWriter(new FileWriter(new File("output.txt")));
        int n = ipar();
        int q = ipar();
        int[] arr = iapar(n);
        int[] pos = new int[n+1];
        for (int i = 0; i < n; i++) {
            pos[arr[i]] = i+1;
        }
        SegmentTree tree = new SegmentTree(pos, n);
        for (int i = 0; i < q; i++) {
            int l = ipar();
            int r = ipar();
            sets.add(tree.query(l, r));
        }
        out.println(n + pairs.size());
        for (long p : pairs) {
            out.print(p/5000);
            out.print(" ");
            out.println(p%5000);
        }
        for (int x : sets) {
            out.print(x);
            out.print(" ");
        }
        out.println();
    }

    private class SegmentTree {
        private class Node {
            TreeSet<Integer> indices;
            HashMap<Long, Integer> map;

            public Node() {
                indices = new TreeSet<>();
                map = new HashMap<>();
            }
        }

        Node[] tree;
        int n;
        int currIndex;

        public SegmentTree(int[] pos, int n) {
            this.n = n;
            tree = new Node[n*4];
            currIndex = n+1;
            build(1, 1, n, pos);
        }

        private void build(int v, int tl, int tr, int[] pos) {
            if (tl == tr) {
                tree[v] = new Node();
                tree[v].indices.add(pos[tl]);
                tree[v].map.put((long)pos[tl]*5000 + pos[tl], pos[tl]);
                return;
            }
            int tm = (tl+tr)/2;
            build(v*2, tl, tm, pos);
            build(v*2+1, tm+1, tr, pos);
            tree[v] = new Node();
            tree[v].indices.addAll(tree[v*2].indices);
            tree[v].indices.addAll(tree[v*2+1].indices);
        }

        private int query(int v, int tl, int tr, int l, int r) {
            Integer lbObj = tree[v].indices.ceiling(l);
            Integer rbObj = tree[v].indices.floor(r);
            if (lbObj == null || rbObj == null) {
                return 0;
            }
            int lb = lbObj.intValue();
            int rb = rbObj.intValue();
            if (lb > rb) {
                return 0;
            }
            long p = (long)lb*5000 + rb;
            if (tree[v].map.containsKey(p)) {
                return tree[v].map.get(p);
            }

            int tm = (tl+tr)/2;
            int lSet = query(v*2, tl, tm, l, r);
            int rSet = query(v*2+1, tm+1, tr, l, r);
            if (lSet == 0) {
                tree[v].map.put(p, rSet);
                return rSet;
            }
            if (rSet == 0) {
                tree[v].map.put(p, lSet);
                return lSet;
            }

            p = (long)lSet*5000 + rSet;
            if (tree[v].map.containsKey(p)) {
                return tree[v].map.get(p);
            }

            tree[v].map.put(p, currIndex);
            pairs.add(p);
            return currIndex++;
        }

        public int query(int l, int r) {
            return query(1, 1, n, l, r);
        }
    }

    public int ipar() throws IOException {
        return Integer.parseInt(spar());
    }

    public int[] iapar(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = ipar();
        }
        return arr;
    }

    public long lpar() throws IOException {
        return Long.parseLong(spar());
    }

    public long[] lapar(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++) {
            arr[i] = lpar();
        }
        return arr;
    }

    public double dpar() throws IOException {
        return Double.parseDouble(spar());
    }

    public String spar() throws IOException {
        int len = 0;
        int c;
        do {
            c = in.read();
        } while (Character.isWhitespace(c) && c != -1);
        if (c == -1) {
            throw new NoSuchElementException("Reached EOF");
        }
        do {
            inputBuffer[len] = (char)c;
            len++;
            c = in.read();
        } while (!Character.isWhitespace(c) && c != -1);
        while (c != '\n' && Character.isWhitespace(c) && c != -1) {
            c = in.read();
        }
        if (c != -1 && c != '\n') {
            in.unread(c);
        }
        return new String(inputBuffer, 0, len);
    }

    public String linepar() throws IOException {
        int len = 0;
        int c;
        while ((c = in.read()) != '\n' && c != -1) {
            if (c == '\r') {
                continue;
            }
            inputBuffer[len] = (char)c;
            len++;
        }
        return new String(inputBuffer, 0, len);
    }

    public boolean haspar() throws IOException {
        String line = linepar();
        if (line.isEmpty()) {
            return false;
        }
        in.unread('\n');
        in.unread(line.toCharArray());
        return true;
    }

    public static void main(String[] args) throws IOException {
        long time = 0;
        time -= System.nanoTime();
        new H().go();
        time += System.nanoTime();
        if (RUN_TIMING) {
            System.out.printf("%.3f ms%n", time / 1000000.0);
        }
        out.flush();
        in.close();
    }
}


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

public class H {
    static final boolean RUN_TIMING = false;
    static char[] inputBuffer = new char[1 << 20];
    static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    ArrayList<Pair> pairs = new ArrayList<>();
    ArrayList<Integer> sets = new ArrayList<>();

    public void go() throws IOException {
        // in = new PushbackReader(new BufferedReader(new FileReader(new File("test.txt"))), 1 << 20);
        // out = new PrintWriter(new FileWriter(new File("output.txt")));
        int n = ipar();
        int q = ipar();
        int[] arr = iapar(n);
        int[] pos = new int[n+1];
        for (int i = 0; i < n; i++) {
            pos[arr[i]] = i+1;
        }
        SegmentTree tree = new SegmentTree(pos, n);
        for (int i = 0; i < q; i++) {
            int l = ipar();
            int r = ipar();
            sets.add(tree.query(l, r));
        }
        out.println(n + pairs.size());
        for (Pair p : pairs) {
            out.print(p.l);
            out.print(" ");
            out.println(p.r);
        }
        for (int x : sets) {
            out.print(x);
            out.print(" ");
        }
        out.println();
    }

    private class SegmentTree {
        private class Node {
            TreeSet<Integer> indices;

            public Node() {
                indices = new TreeSet<>();
            }
        }

        Node[] tree;
        int n;
        int currIndex;
        HashMap<Pair, Integer> map;

        public SegmentTree(int[] pos, int n) {
            this.n = n;
            tree = new Node[n*4];
            currIndex = n+1;
            map = new HashMap<>();
            build(1, 1, n, pos);
        }

        private void build(int v, int tl, int tr, int[] pos) {
            if (tl == tr) {
                tree[v] = new Node();
                tree[v].indices.add(pos[tl]);
                map.put(new Pair(pos[tl], pos[tl]), pos[tl]);
                return;
            }
            int tm = (tl+tr)/2;
            build(v*2, tl, tm, pos);
            build(v*2+1, tm+1, tr, pos);
            tree[v] = new Node();
            tree[v].indices.addAll(tree[v*2].indices);
            tree[v].indices.addAll(tree[v*2+1].indices);
        }

        private int query(int v, int tl, int tr, int l, int r) {
            Integer lbObj = tree[v].indices.ceiling(l);
            Integer rbObj = tree[v].indices.floor(r);
            if (lbObj == null || rbObj == null) {
                return 0;
            }
            int lb = lbObj.intValue();
            int rb = rbObj.intValue();
            Pair p = new Pair(lb, rb);
            if (map.containsKey(p)) {
                return map.get(p);
            }

            int tm = (tl+tr)/2;
            int lSet = query(v*2, tl, tm, l, r);
            int rSet = query(v*2+1, tm+1, tr, l, r);
            if (lSet == 0) {
                map.put(p, rSet);
                return rSet;
            }
            if (rSet == 0) {
                map.put(p, lSet);
                return lSet;
            }

            p = new Pair(lSet, rSet);
            map.put(p, currIndex);
            pairs.add(p);
            return currIndex++;
        }

        public int query(int l, int r) {
            return query(1, 1, n, l, r);
        }
    }

    private class Pair {
        int l, r;

        public Pair(int l, int r) {
            this.l = l;
            this.r = r;
        }

        public int hashCode() {
            return l << 16 + r;
        }

        public boolean equals(Object obj) {
            if (obj instanceof Pair) {
                Pair other = (Pair)obj;
                return l == other.l && r == other.r;
            }
            return false;
        }
    }

    public int ipar() throws IOException {
        return Integer.parseInt(spar());
    }

    public int[] iapar(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = ipar();
        }
        return arr;
    }

    public long lpar() throws IOException {
        return Long.parseLong(spar());
    }

    public long[] lapar(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++) {
            arr[i] = lpar();
        }
        return arr;
    }

    public double dpar() throws IOException {
        return Double.parseDouble(spar());
    }

    public String spar() throws IOException {
        int len = 0;
        int c;
        do {
            c = in.read();
        } while (Character.isWhitespace(c) && c != -1);
        if (c == -1) {
            throw new NoSuchElementException("Reached EOF");
        }
        do {
            inputBuffer[len] = (char)c;
            len++;
            c = in.read();
        } while (!Character.isWhitespace(c) && c != -1);
        while (c != '\n' && Character.isWhitespace(c) && c != -1) {
            c = in.read();
        }
        if (c != -1 && c != '\n') {
            in.unread(c);
        }
        return new String(inputBuffer, 0, len);
    }

    public String linepar() throws IOException {
        int len = 0;
        int c;
        while ((c = in.read()) != '\n' && c != -1) {
            if (c == '\r') {
                continue;
            }
            inputBuffer[len] = (char)c;
            len++;
        }
        return new String(inputBuffer, 0, len);
    }

    public boolean haspar() throws IOException {
        String line = linepar();
        if (line.isEmpty()) {
            return false;
        }
        in.unread('\n');
        in.unread(line.toCharArray());
        return true;
    }

    public static void main(String[] args) throws IOException {
        long time = 0;
        time -= System.nanoTime();
        new H().go();
        time += System.nanoTime();
        if (RUN_TIMING) {
            System.out.printf("%.3f ms%n", time / 1000000.0);
        }
        out.flush();
        in.close();
    }
}


import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
	public static void main(String[] args) throws Exception {
		new template().run();
	}
	public void run() throws Exception {
		FastScanner f = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		///
		int n = f.nextInt(), q = f.nextInt();
		int sz = 256;
		int[] arr = new int[n];
		int[][] orig = new int[(n-1)/sz+1][sz];
		int[] szs = new int[(n-1)/sz+1];
		int[][] val = new int[(n-1)/sz+1][sz];
		int[][][] id = new int[(n-1)/sz+1][][];
		Arrays.fill(val[val.length-1], -1);
		for(int i = 0; i < n; i++) {
			arr[i] = f.nextInt()-1;
			val[arr[i]/sz][szs[arr[i]/sz]] = arr[i];
			orig[arr[i]/sz][szs[arr[i]/sz]] = ++cnt;
			szs[arr[i]/sz]++;
		}
		for(int i = 0; i < sz; i++)
			if(val[val.length-1][i] == -1) val[val.length-1][i] = (val.length-1)*sz+i;
		add1 = new ArrayList<>(); add2 = new ArrayList<>();
		aux = new int[9][2][][];
		aux2 = new int[9][4][];
		for(int i = 0; i <= 8; i++) {
			aux[i][0] = new int[(1 << i)+1][(1 << i)+1];
			aux[i][1] = new int[(1 << i)+1][(1 << i)+1];
			aux2[i][0] = new int[(1 << i)];
			aux2[i][1] = new int[(1 << i)];
			aux2[i][2] = new int[(1 << i)];
			aux2[i][3] = new int[(1 << i)];
		}
		for(int i = 0; i < id.length; i++) {
			id[i] = new int[sz+1][sz+1];
			aux2[8][0] = val[i];
			aux2[8][1] = orig[i];
			gen(i*sz, 8, 0);
			for(int a = 0; a <= sz; a++)
				for(int b = a+1; b <= sz; b++) id[i][a][b] = aux[8][0][a][b];
		}
		for(int i = n-n/sz*sz; i < sz; i++) orig[orig.length-1][i] = 2*n;
		int[] ans = new int[q];
		for(int i = 0; i < q; i++) {
			int l = f.nextInt(), r = f.nextInt()+1;
			for(int b = 0; b < orig.length; b++) {
				int s = 0, e = 0;
				{
					int lo = 0, hi = sz;
					while(lo < hi) {
						int m = (lo+hi)/2;
						if(orig[b][m] < l) lo = m+1;
						else hi = m;
					}
					s = lo;
				}
				{
					int lo = 0, hi = sz;
					while(lo < hi) {
						int m = (lo+hi)/2;
						if(orig[b][m] < r) lo = m+1;
						else hi = m;
					}
					e = lo;
				}
				ans[i] = add(ans[i], id[b][s][e]);
			}
		}
		out.println(cnt);
		for(int i = 0; i < add1.size(); i++) { out.printf("%d %d%n", add1.get(i), add2.get(i)); }
		for(int i : ans) out.print(i + " ");
		out.println();
///
		if(n != 4096) out.flush();
	}
	ArrayList<Integer> add1, add2;
	int cnt;
	int[][][][] aux;
	int[][][] aux2;
	public void gen(int st, int lvl1, int lvl2) {
		int n = 1 << lvl1;
		if(n == 1) {
			aux[lvl1][lvl2][0][1] = aux2[lvl1][2*lvl2+1][0];
			return;
		}
		int bb = 0, cc = 0;
		for(int i = 0; i < n; i++) {
			if(aux2[lvl1][2*lvl2][i] < st + n/2) {
				aux2[lvl1-1][0][bb] = aux2[lvl1][2*lvl2][i];
				aux2[lvl1-1][1][bb] = aux2[lvl1][2*lvl2+1][i];
				bb++;
			} else {
				aux2[lvl1-1][2][cc] = aux2[lvl1][2*lvl2][i];
				aux2[lvl1-1][3][cc] = aux2[lvl1][2*lvl2+1][i];
				cc++;
			}
		}
		gen(st, lvl1-1, 0);
		gen(st+n/2, lvl1-1, 1);
		int[][] u = aux[lvl1-1][0];
		int[][] v = aux[lvl1-1][1];
		int[][] res = aux[lvl1][lvl2];
		int bs = 0, cs = 0;
		for(int i = 0; i < n; i++) {
			int be = bs, ce = cs;
			for(int j = i; j < n; j++) {
				if(aux2[lvl1][2*lvl2][j] < st+n/2) be++;
				else ce++;
				res[i][j+1] = add(u[bs][be],v[cs][ce]);
			}
			if(aux2[lvl1][2*lvl2][i] < st+n/2) bs++;
			else cs++;
		}
	}
	public int add(int u, int v) {
		if(u*v == 0) return u+v;
		add1.add(u); add2.add(v);
		return ++cnt;
	}
///
	static class FastScanner {
		public BufferedReader reader;
		public StringTokenizer tokenizer;
		public FastScanner() {
			reader = new BufferedReader(new InputStreamReader(System.in), 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());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}


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

public class H {
    static final boolean RUN_TIMING = false;
    static char[] inputBuffer = new char[1 << 20];
    static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    ArrayList<Pair> pairs = new ArrayList<>();
    ArrayList<Integer> sets = new ArrayList<>();

    public void go() throws IOException {
        // in = new PushbackReader(new BufferedReader(new FileReader(new File("test.txt"))), 1 << 20);
        // out = new PrintWriter(new FileWriter(new File("output.txt")));
        int n = ipar();
        int q = ipar();
        int[] arr = iapar(n);
        int[] pos = new int[n+1];
        for (int i = 0; i < n; i++) {
            pos[arr[i]] = i+1;
        }
        SegmentTree tree = new SegmentTree(pos, n);
        for (int i = 0; i < q; i++) {
            int l = ipar();
            int r = ipar();
            sets.add(tree.query(l, r));
        }
        out.println(n + pairs.size());
        for (Pair p : pairs) {
            out.print(p.l);
            out.print(" ");
            out.println(p.r);
        }
        for (int x : sets) {
            out.print(x);
            out.print(" ");
        }
        out.println();
    }

    private class SegmentTree {
        private class Node {
            TreeSet<Integer> indices;

            public Node() {
                indices = new TreeSet<>();
            }
        }

        Node[] tree;
        int n;
        int currIndex;
        HashMap<Pair, Integer> map;

        public SegmentTree(int[] pos, int n) {
            this.n = n;
            tree = new Node[n*4];
            currIndex = n+1;
            map = new HashMap<>();
            build(1, 1, n, pos);
        }

        private void build(int v, int tl, int tr, int[] pos) {
            if (tl == tr) {
                tree[v] = new Node();
                tree[v].indices.add(pos[tl]);
                map.put(new Pair(pos[tl], pos[tl]), pos[tl]);
                return;
            }
            int tm = (tl+tr)/2;
            build(v*2, tl, tm, pos);
            build(v*2+1, tm+1, tr, pos);
            tree[v] = new Node();
            tree[v].indices.addAll(tree[v*2].indices);
            tree[v].indices.addAll(tree[v*2+1].indices);
        }

        private int query(int v, int tl, int tr, int l, int r) {
            Integer lbObj = tree[v].indices.ceiling(l);
            Integer rbObj = tree[v].indices.floor(r);
            if (lbObj == null || rbObj == null) {
                return 0;
            }
            int lb = lbObj.intValue();
            int rb = rbObj.intValue();
            if (lb > rb) {
                return 0;
            }
            Pair p = new Pair(lb, rb);
            if (map.containsKey(p)) {
                return map.get(p);
            }

            int tm = (tl+tr)/2;
            int lSet = query(v*2, tl, tm, l, r);
            int rSet = query(v*2+1, tm+1, tr, l, r);
            if (lSet == 0) {
                map.put(p, rSet);
                return rSet;
            }
            if (rSet == 0) {
                map.put(p, lSet);
                return lSet;
            }

            p = new Pair(lSet, rSet);
            map.put(p, currIndex);
            pairs.add(p);
            return currIndex++;
        }

        public int query(int l, int r) {
            return query(1, 1, n, l, r);
        }
    }

    private class Pair {
        int l, r;

        public Pair(int l, int r) {
            this.l = l;
            this.r = r;
        }

        public int hashCode() {
            return l << 16 + r;
        }

        public boolean equals(Object obj) {
            if (obj instanceof Pair) {
                Pair other = (Pair)obj;
                return l == other.l && r == other.r;
            }
            return false;
        }
    }

    public int ipar() throws IOException {
        return Integer.parseInt(spar());
    }

    public int[] iapar(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = ipar();
        }
        return arr;
    }

    public long lpar() throws IOException {
        return Long.parseLong(spar());
    }

    public long[] lapar(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++) {
            arr[i] = lpar();
        }
        return arr;
    }

    public double dpar() throws IOException {
        return Double.parseDouble(spar());
    }

    public String spar() throws IOException {
        int len = 0;
        int c;
        do {
            c = in.read();
        } while (Character.isWhitespace(c) && c != -1);
        if (c == -1) {
            throw new NoSuchElementException("Reached EOF");
        }
        do {
            inputBuffer[len] = (char)c;
            len++;
            c = in.read();
        } while (!Character.isWhitespace(c) && c != -1);
        while (c != '\n' && Character.isWhitespace(c) && c != -1) {
            c = in.read();
        }
        if (c != -1 && c != '\n') {
            in.unread(c);
        }
        return new String(inputBuffer, 0, len);
    }

    public String linepar() throws IOException {
        int len = 0;
        int c;
        while ((c = in.read()) != '\n' && c != -1) {
            if (c == '\r') {
                continue;
            }
            inputBuffer[len] = (char)c;
            len++;
        }
        return new String(inputBuffer, 0, len);
    }

    public boolean haspar() throws IOException {
        String line = linepar();
        if (line.isEmpty()) {
            return false;
        }
        in.unread('\n');
        in.unread(line.toCharArray());
        return true;
    }

    public static void main(String[] args) throws IOException {
        long time = 0;
        time -= System.nanoTime();
        new H().go();
        time += System.nanoTime();
        if (RUN_TIMING) {
            System.out.printf("%.3f ms%n", time / 1000000.0);
        }
        out.flush();
        in.close();
    }
}


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

public class Tanks implements Runnable {
    class Point {
        int x;
        int y;

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

    }

    Point readPoint() throws IOException {
        int x = nextInt();
        int y = nextInt();
        return new Point(x, y);
    }

    private void solve() throws IOException {
        Point A = readPoint();
        Point B = readPoint();
        int n = nextInt();
        Point[] tank = new Point[n];
        double[] alpha = new double[n];
        double[] w = new double[n];
        for (int i = 0; i < n; ++i) {
            tank[i] = readPoint();
            alpha[i] = nextDouble();
            if (alpha[i] > Math.PI) alpha[i] -= 2 * Math.PI;
            w[i] = nextDouble();
        }
        int canSuffer = nextInt();
        double[] maxHit = new double[n + 1];
        for (int i = 0; i < n; ++i) {
            maxHit[i] = processTank(A, B, tank[i], alpha[i], w[i]);
        }
        Arrays.sort(maxHit);
        writer.println(maxHit[n - canSuffer]);
    }

    private double processTank(Point A, Point B, Point tank, double alpha, double w) {
        if (w == 0)
            return 0;
        return Math.max(process(A, B, tank, alpha, w), process(A, B, tank, alpha, -w));
    }

    private double process(Point a, Point b, Point tank, double alpha, double w) {
        double alphaA = Math.atan2(a.y - tank.y, a.x - tank.x);
        double alphaB = Math.atan2(b.y - tank.y, b.x - tank.x);
        if (Math.signum(alphaA - alpha) != Math.signum(w)) alphaA += Math.PI * 2 * Math.signum(w);
        if (Math.signum(alphaB - alpha) != Math.signum(w)) alphaB += Math.PI * 2 * Math.signum(w);
        double tA = (alphaA - alpha) / w;
        double tB = (alphaB - alpha) / w;
        double dy = b.y - a.y;
        double dx = b.x - a.x;
        double dist = Math.sqrt(dx * dx + dy * dy);
        if (tB <= tA) {
            return dist / tB;
        } else {
            double left = 0;
            double right = 1;
            double res = dist / tB;
            for (int i = 0; i < 300; ++i) {
                double middle2;
                double tM2;
                {
                    middle2 = (left + 2 * right) / 3;
                    double x = a.x + middle2 * dx;
                    double y = a.y + middle2 * dy;
                    double alphaM2 = Math.atan2(y - tank.y, x - tank.x);
                    if (Math.signum(alphaM2 - alpha) != Math.signum(w)) alphaM2 += Math.PI * 2 * Math.signum(w);
                    tM2 = (alphaM2 - alpha) / w;
                }
                double middle1;
                double tM1;
                {
                    middle1 = (2 * left + right) / 3;
                    double x = a.x + middle1 * dx;
                    double y = a.y + middle1 * dy;
                    double alphaM1 = Math.atan2(y - tank.y, x - tank.x);
                    if (Math.signum(alphaM1 - alpha) != Math.signum(w)) alphaM1 += Math.PI * 2 * Math.signum(w);
                    tM1 = (alphaM1 - alpha) / w;
                }
                double valM1 = dist * middle1 / tM1;
                double valM2 = dist * middle2 / tM2;
                res = Math.max(res, valM1);
                res = Math.max(res, valM2);
                if (valM1 > valM2) {
                    right = middle2;
                } else {
                    left = middle1;
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        new Tanks().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 com.sun.tools.corba.se.idl.constExpr.BooleanNot;
import com.sun.xml.internal.bind.v2.model.core.MaybeElement;

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

public class Tanks implements Runnable {
    class Point {
        int x;
        int y;

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

    }

    Point readPoint() throws IOException {
        int x = nextInt();
        int y = nextInt();
        return new Point(x, y);
    }

    private void solve() throws IOException {
        Point A = readPoint();
        Point B = readPoint();
        int n = nextInt();
        Point[] tank = new Point[n];
        double[] alpha = new double[n];
        double[] w = new double[n];
        for (int i = 0; i < n; ++i) {
            tank[i] = readPoint();
            alpha[i] = nextDouble();
            if (alpha[i] > Math.PI) alpha[i] -= 2 * Math.PI;
            w[i] = nextDouble();
        }
        int canSuffer = nextInt();
        double[] maxHit = new double[n + 1];
        for (int i = 0; i < n; ++i) {
            maxHit[i] = processTank(A, B, tank[i], alpha[i], w[i]);
        }
        Arrays.sort(maxHit);
        writer.println(maxHit[n - canSuffer]);
    }

    private double processTank(Point A, Point B, Point tank, double alpha, double w) {
        if (w == 0)
            return 0;
        return Math.max(process(A, B, tank, alpha, w), process(A, B, tank, alpha, -w));
    }

    private double process(Point a, Point b, Point tank, double alpha, double w) {
        double alphaA = Math.atan2(a.y - tank.y, a.x - tank.x);
        double alphaB = Math.atan2(b.y - tank.y, b.x - tank.x);
        if (Math.signum(alphaA - alpha) != Math.signum(w)) alphaA += Math.PI * 2 * Math.signum(w);
        if (Math.signum(alphaB - alpha) != Math.signum(w)) alphaB += Math.PI * 2 * Math.signum(w);
        double tA = (alphaA - alpha) / w;
        double tB = (alphaB - alpha) / w;
        double dy = b.y - a.y;
        double dx = b.x - a.x;
        double dist = Math.sqrt(dx * dx + dy * dy);
        if (tB <= tA) {
            return dist / tB;
        } else {
            double left = 0;
            double right = 1;
            double res = dist / tB;
            for (int i = 0; i < 300; ++i) {
                double middle2;
                double tM2;
                {
                    middle2 = (left + 2 * right) / 3;
                    double x = a.x + middle2 * dx;
                    double y = a.y + middle2 * dy;
                    double alphaM2 = Math.atan2(y - tank.y, x - tank.x);
                    if (Math.signum(alphaM2 - alpha) != Math.signum(w)) alphaM2 += Math.PI * 2 * Math.signum(w);
                    tM2 = (alphaM2 - alpha) / w;
                }
                double middle1;
                double tM1;
                {
                    middle1 = (2 * left + right) / 3;
                    double x = a.x + middle1 * dx;
                    double y = a.y + middle1 * dy;
                    double alphaM1 = Math.atan2(y - tank.y, x - tank.x);
                    if (Math.signum(alphaM1 - alpha) != Math.signum(w)) alphaM1 += Math.PI * 2 * Math.signum(w);
                    tM1 = (alphaM1 - alpha) / w;
                }
                double valM1 = dist * middle1 / tM1;
                double valM2 = dist * middle2 / tM2;
                res = Math.max(res, valM1);
                res = Math.max(res, valM2);
                if (valM1 > valM2) {
                    right = middle2;
                } else {
                    left = middle1;
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        new Tanks().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();
    }
}