import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by dalt on 2018/3/25.
 */
public class CF933C {
    public static final double PREC = 1e-10;
    static final boolean IS_OJ = System.getProperty("ONLINE_JUDGE") != null;
    public static BlockReader input;

    public static void main(String[] args) throws FileNotFoundException {
        if (!IS_OJ) {
            System.setIn(new FileInputStream("D:\\DataBase\\TESTCASE\\codeforces\\CF933C.in"));
        }
        input = new BlockReader(System.in);

        solve();
    }

    public static void solve() {
        int n = input.nextInteger();
        Circle[] circles = new Circle[n];

        for (int i = 0; i < n; i++) {
            circles[i] = new Circle(input.nextInteger(), input.nextInteger(), input.nextInteger());
        }

        if (n == 3 && !Circle.isIntersect(circles[0], circles[1])) {
            int sum = 4;
            if (Circle.isIntersect2(circles[0], circles[2])) {
                sum++;
            }
            if (Circle.isIntersect2(circles[1], circles[2])) {
                sum++;
            }
            System.out.println(sum);
            return;
        }

        int total = 1;
        TreeSet<Point> set = new TreeSet<>();
        for (int i = 0; i < n; i++) {
            set.clear();
            total++;
            for (int j = 0; j < i; j++) {
                Circle.intersectAt(circles[i], circles[j], set);
            }
            if (set.size() >= 2) {
                total += set.size() - 1;
            }
        }

        System.out.println(total);
    }

    public static double distance(Point a, Point b) {
        return Math.sqrt(distance2(a, b));
    }

    public static double distance2(Point a, Point b) {
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return dx * dx + dy * dy;
    }

    public static class Circle {
        Point center;
        int r;

        public Circle(int x, int y, int r) {
            this.center = new Point(x, y);
            this.r = r;
        }

        public static boolean isIntersect(Circle a, Circle b) {
            double d = distance(a.center, b.center);
            return d <= a.r + b.r + PREC && d + PREC >= Math.abs(a.r - b.r);
        }

        public static boolean isIntersect2(Circle a, Circle b) {
            double d = distance(a.center, b.center);
            return d < a.r + b.r && d > Math.abs(a.r - b.r);
        }

        public static void intersectAt(Circle a, Circle b, Set<Point> set) {
            if (!isIntersect(a, b)) {
                return;
            }

            Line line = new Line(a.center, b.center);
            double d = distance(a.center, b.center);
            double middleDistance = (d * d - b.r * b.r + a.r * a.r) / (2 * d);
            Point middle = a.center.moveAlongLine(line, middleDistance);
            Point alpha = line.asVector().getAlpha();
            double height = Math.sqrt(a.r * a.r - middleDistance * middleDistance);
            Point first = middle.moveAlongVector(alpha, height);
            Point second = middle.moveAlongVector(alpha, -height);

            set.add(first);
            if (!second.equals(first)) {
                set.add(second);
            }
        }
    }

    public static class Point implements Comparable<Point> {
        double x, y;

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

        @Override
        public String toString() {
            return "(" + x + "," + y + ")";
        }

        public Point sub(Point other) {
            return new Point(x - other.x, y - other.y);
        }

        public Point moveAlongLine(Line line, double length) {
            return moveAlongVector(line.asVector(), length);
        }

        public Point moveAlongVector(Point vec, double length) {
            return add(vec.normalize().mul(length));
        }

        public Point add(Point other) {
            return new Point(x + other.x, y + other.y);
        }

        public Point mul(double f) {
            return new Point(x * f, y * f);
        }

        public Point normalize() {
            double len = Math.sqrt(x * x + y * y);
            return div(len);
        }

        public Point div(double f) {
            return new Point(x / f, y / f);
        }

        public Point getAlpha() {
            return new Point(-y, x);
        }

        @Override
        public boolean equals(Object obj) {
            Point other = (Point) obj;
            return Math.abs(x - other.x) < PREC && Math.abs(y - other.y) < PREC;
        }

        @Override
        public int compareTo(Point o) {
            if (equals(o)) {
                return 0;
            }
            if (Math.abs(x - o.x) < PREC) {
                return Double.compare(y, o.y);
            }
            return Double.compare(x, o.x);
        }
    }

    public static class Line {
        Point from;
        Point to;

        public Line(Point from, Point to) {
            this.from = from;
            this.to = to;
        }

        public Point asVector() {
            return to.sub(from);
        }

        public double length() {
            return distance(from, to);
        }
    }

    public static class BlockReader {
        static final int EOF = -1;
        InputStream is;
        byte[] dBuf;
        int dPos, dSize, next;
        StringBuilder builder = new StringBuilder();

        public BlockReader(InputStream is) {
            this(is, 4096);
        }

        public BlockReader(InputStream is, int bufSize) {
            this.is = is;
            dBuf = new byte[bufSize];
            next = nextByte();
        }

        public int nextByte() {
            while (dPos >= dSize) {
                if (dSize == -1) {
                    return EOF;
                }
                dPos = 0;
                try {
                    dSize = is.read(dBuf);
                } catch (Exception e) {
                }
            }
            return dBuf[dPos++];
        }

        public String nextBlock() {
            builder.setLength(0);
            skipBlank();
            while (next != EOF && !Character.isWhitespace(next)) {
                builder.append((char) next);
                next = nextByte();
            }
            return builder.toString();
        }

        public void skipBlank() {
            while (Character.isWhitespace(next)) {
                next = nextByte();
            }
        }

        public int nextInteger() {
            skipBlank();
            int ret = 0;
            boolean rev = false;
            if (next == '+' || next == '-') {
                rev = next == '-';
                next = nextByte();
            }
            while (next >= '0' && next <= '9') {
                ret = (ret << 3) + (ret << 1) + next - '0';
                next = nextByte();
            }
            return rev ? -ret : ret;
        }

        public int nextBlock(char[] data, int offset) {
            skipBlank();
            int index = offset;
            int bound = data.length;
            while (next != EOF && index < bound && !Character.isWhitespace(next)) {
                data[index++] = (char) next;
                next = nextByte();
            }
            return index - offset;
        }

        public boolean hasMore() {
            skipBlank();
            return next != EOF;
        }
    }
}


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

public class C4 {
	InputStream is;
	PrintWriter out;
//	String INPUT = "3 0 0 3 1 0 2 -2 0 1";
//	String INPUT = "3 0 0 1 1 0 1 2 0 1";
//	String INPUT = "3 0 0 5 6 0 5 0 -8 5";
//	String INPUT = "3 0 0 3 1 0 2 2 0 1";
//	String INPUT = "3 0 0 9 0 0 8 0 -10 10";
//	String INPUT = "3 0 10 10 0 -10 10 0 0 1";
	String INPUT = "";

	void solve()
	{
		int n = ni();
		long[][] co = new long[n][];
		for(int i = 0;i < n;i++){
			co[i] = new long[]{ni(), ni(), ni()};
		}

		double[][] nodes = new double[10][];
		int p = 0;
		for(int i = 0;i < n;i++){
			for(int j = i+1;j < n;j++){
				double[] ts = crossSimple(
						co[i][0], co[i][1], co[i][2],
						co[j][0], co[j][1], co[j][2]
								);
				for(int k = 0;k < ts.length;k++){
					nodes[p++] = new double[]{
							co[i][0] + co[i][2] * Math.cos(ts[k]),
							co[i][1] + co[i][2] * Math.sin(ts[k])
					};
				}
			}
		}
		nodes = Arrays.copyOf(nodes, p);
		int q = 0;
		outer:
		for(int i = 0;i < p;i++){
			for(int j = i+1;j < p;j++){
				if(d2(nodes[i][0], nodes[i][1], nodes[j][0], nodes[j][1]) < 1e-12){
					continue outer;
				}
			}
			nodes[q++] = nodes[i];
		}

		int nnodes = q;
		int ne = 0;
		int con = 1;
		for(int j = 0;j < n;j++){
			int e = 0;
			for(int i = 0;i < q;i++){
				if(Math.abs(d2(nodes[i][0], nodes[i][1], co[j][0], co[j][1])-co[j][2]*co[j][2]) < 1e-12){
					e++;
				}
			}
			if(e == 0)con++;
			ne += e;
		}
		if(con > n)con = n;
		out.println(ne-nnodes+con+1);
	}

	public static double d2(double ax, double ay, double bx, double by)
	{
		return (bx - ax) * (bx - ax) + (by - ay) * (by - ay);
	}

	static double EPS = 1E-10;

	// 円(x,y,r)と円(tx,ty,tr)の交わりの偏角を返す。全く同じ円の場合は交わらないとしている
	public static double[] crossSimple(long x, long y, long r, long tx, long ty, long tr)
	{
		long d2 = d2(x, y, tx, ty);
		if(d2 < (r-tr)*(r-tr))return new double[0]; // covered or covering
		if(d2 > (r+tr)*(r+tr))return new double[0]; // not intersects or touched
		double base = Math.atan2(ty-y, tx-x);
		double wing = Math.acos((d2+r*r-tr*tr)/(2*Math.sqrt(d2)*r)); // Law of cosines
//		assert Double.isFinite(base);
//		assert Double.isFinite(wing);
		double inf = base - wing, sup = base + wing;
		return new double[]{inf, sup};
	}

	public static long d2(long ax, long ay, long bx, long by)
	{
		return (bx-ax)*(bx-ax)+(by-ay)*(by-ay);
	}

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

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

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

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

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

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

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

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

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

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

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

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

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

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.List;
import java.util.AbstractCollection;
import java.util.TreeMap;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;

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

    static class TaskC {
        final double eps = 1e-8;

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.nextInt();
            Circle[] circles = new Circle[n];
            for (int i = 0; i < n; i++) {
                int x = in.nextInt();
                int y = in.nextInt();
                int r = in.nextInt();
                circles[i] = new Circle();
                circles[i].o = new Point(x, y);
                circles[i].r = r;
            }

            Set<Point> all = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    List<Point> inter = intersect(circles[i], circles[j]);
                    if (inter == null) {
                        continue;
                    }
                    all.addAll(inter);
                }
            }

            Map<Point, Integer> pointId = new TreeMap<>();
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                List<Double> angles = new ArrayList<>();
                final int K = 3;
                for (int j = 0; j < K; j++) {
                    angles.add(Math.PI * 2 * j / K);
                }
                for (Point p : all) {
                    if (circles[i].contains(p)) {
                        double dx = p.x - circles[i].o.x;
                        double dy = p.y - circles[i].o.y;
                        double alpha = Math.atan2(dy, dx);
                        if (alpha < 0) {
                            alpha += 2 * Math.PI;
                        }
                        angles.add(alpha);
                    }
                }
                Collections.sort(angles);
                Point dir = new Point(1, 0).scale(circles[i].r);
                Double[] as = new TreeSet<>(angles).toArray(new Double[0]);
                for (int j = 0; j < as.length; j++) {
                    Point p = circles[i].o.add(dir.rotate(as[j]));
                    getId(p, pointId, adj);
                }
                for (int j = 0; j < as.length; j++) {
                    Point p = circles[i].o.add(dir.rotate(as[j]));
                    Point q = circles[i].o.add(dir.rotate(as[(j + 1) % as.length]));
                    int u = pointId.get(p);
                    int v = pointId.get(q);
                    if (u == v) {
                        continue;
                    }
                    adj.get(u).add(v);
                    adj.get(v).add(u);
                }
            }

            int v = adj.size();
            int e = 0;
            for (int i = 0; i < v; i++) {
                e += adj.get(i).size();
            }
            e /= 2;

            int comps = 0;
            boolean[] was = new boolean[v];
            for (int i = 0; i < v; i++) {
                if (!was[i]) {
                    ++comps;
                    dfs(i, was, adj);
                }
            }

            out.println(1 + comps + e - v);
        }

        private void dfs(int i, boolean[] was, List<List<Integer>> adj) {
            was[i] = true;
            for (int j : adj.get(i)) {
                if (!was[j]) {
                    dfs(j, was, adj);
                }
            }
        }

        private void getId(Point p, Map<Point, Integer> pointId, List<List<Integer>> adj) {
            if (!pointId.containsKey(p)) {
                int sz = pointId.size();
                pointId.put(p, sz);
                adj.add(new ArrayList<>());
            }
        }

        private List<Point> intersect(Circle c1, Circle c2) {
            double dx = c1.o.x - c2.o.x;
            double dy = c1.o.y - c2.o.y;
            double d = Math.sqrt(dx * dx + dy * dy);
            double cos = (c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d);
            if (cos < -1 - eps) {
                return null;
            }
            if (cos < -1) {
                cos = -1;
            }
            if (cos > 1 + eps) {
                return null;
            }
            if (cos > 1) {
                cos = 1;
            }
            List<Point> res = new ArrayList<>();
            double alpha = Math.acos(cos);
            Point dir = c2.o.sub(c1.o).norm();
            res.add(c1.o.add(dir.scale(c1.r).rotate(+alpha)));
            res.add(c1.o.add(dir.scale(c1.r).rotate(-alpha)));
            return res;
        }

        class Point implements Comparable<Point> {
            double x;
            double y;

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

            Point add(Point o) {
                return new Point(x + o.x, y + o.y);
            }

            Point sub(Point o) {
                return new Point(x - o.x, y - o.y);
            }

            Point rotate(double alpha) {
                double c = Math.cos(alpha);
                double s = Math.sin(alpha);
                double nx = x * c - y * s;
                double ny = x * s + y * c;
                return new Point(nx, ny);
            }

            Point norm() {
                double len = length();
                return scale(1.0 / len);
            }

            Point scale(double f) {
                return new Point(f * x, f * y);
            }

            double length() {
                return Math.sqrt(x * x + y * y);
            }

            public String toString() {
                return String.format("%.6f %.6f", x, y);
            }

            public boolean equals(Object obj) {
                Point o = (Point) obj;
                return Math.abs(x - o.x) < eps && Math.abs(y - o.y) < eps;
            }

            public int compareTo(Point o) {
                if (Math.abs(x - o.x) > eps) {
                    return x < o.x ? -1 : 1;
                }
                if (Math.abs(y - o.y) > eps) {
                    return y < o.y ? -1 : 1;
                }
                return 0;
            }

        }

        class Circle {
            Point o;
            double r;

            boolean contains(Point p) {
                double dist = p.sub(o).length();
                return Math.abs(dist - r) < eps;
            }

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

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

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

    }
}


import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Set;
import java.util.StringTokenizer;

public class D {

    static StringTokenizer st;
    static BufferedReader in;
    static int[]f;
    static ArrayList<Integer>[]g, gt;
    static boolean[] used, used2;
    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int m = nextInt();
        f = new int[n+1];
        for (int i = 1; i <= n; i++) {
            f[i] = nextInt();
        }
        g = new  ArrayList[n+1];
        gt = new ArrayList[n+1];
        for (int i = 1; i <= n; i++) {
            g[i] = new ArrayList<Integer>();
            gt[i] = new ArrayList<Integer>();
        }
        for (int i = 1; i <= m; i++) {
            int v1 = nextInt();
            int v2 = nextInt();
            g[v1].add(v2);
            gt[v2].add(v1);
        }
        used = new boolean[n+1];
        used2 = new boolean[n+1];
        for (int i = 1; i <= n; i++) {
            if (f[i]==1 && !used[i])
                dfs(i);
            if (f[i]==2 && !used2[i])
                dfs2(i);
        }
        for (int i = 1; i <= n; i++) {
            if (used[i] && used2[i])
                pw.println(1);
            else
                pw.println(0);
        }
        pw.close();
    }
    private static void dfs2(int v) {
        used2[v] = true;
        if (f[v]==1)
            return;
        for (int to : gt[v]) {
            if (!used2[to])
                dfs2(to);
        }
    }
    private static void dfs(int v) {
        used[v] = true;
        for (int to : g[v]) {
            if (!used[to])
                dfs(to);
        }
    }
    private static int nextInt() throws IOException{
        return Integer.parseInt(next());
    }

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


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

public class backforth implements Runnable {
	public StringTokenizer strtok;
	public BufferedReader inr;
	public PrintWriter out;

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

	public static final String taskname = "backforth";

	public void run() {
		Locale.setDefault(Locale.US);
		boolean oj = System.getProperty("ONLINE_JUDGE") != null;
		try {
			inr = new BufferedReader(oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader(taskname + ".in"));
			out = new PrintWriter(oj ? new OutputStreamWriter(System.out, "ISO-8859-1") : new FileWriter(taskname + ".out"));
			solve();
		} catch (Exception e) {
			if (!oj)
				e.printStackTrace();
			System.exit(9000);
		} finally {
			out.flush();
			out.close();
		}
	}

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

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

	// Solution

	byte[] action;
	ArrayList<HashSet<Integer>> g;
	ArrayList<HashSet<Integer>> revg;

	boolean[] visited_from_write;
	boolean[] visited_from_read;

	public void dfs_from_write(int start) {
		Stack<Integer> stack = new Stack<Integer>();
		stack.add(start);
		while(!stack.isEmpty()) {
			int node = stack.pop();
			visited_from_write[node] = true;
			HashSet<Integer> neighbours = g.get(node);
			for (int neigh : neighbours) {
				if (visited_from_write[neigh]) {
					continue;
				}
				stack.add(neigh);
			}
		}
	}

	public void dfs_from_read(int start) {
		Stack<Integer> stack = new Stack<Integer>();
		stack.add(start);
		while(!stack.isEmpty()) {
			int node = stack.pop();
			visited_from_read[node] = true;
			if (action[node] == 1) {
				continue;
			}
			HashSet<Integer> neighbours = revg.get(node);
			for (int neigh : neighbours) {
				if (visited_from_read[neigh]) {
					continue;
				}
				stack.add(neigh);
			}
		}
	}

	public void solve() throws NumberFormatException, IOException {
		int n = nextInt(), m = nextInt();
		action = new byte[n];
		g = new ArrayList<HashSet<Integer>>(n);
		for (int i = 0; i < n; i++) {
			g.add(new HashSet<Integer>());
		}
		revg = new ArrayList<HashSet<Integer>>(n);
		for (int i = 0; i < n; i++) {
			revg.add(new HashSet<Integer>());
		}
		visited_from_write = new boolean[n];
		visited_from_read = new boolean[n];
		for (int i = 0; i < n; i++) {
			action[i] = (byte)nextInt();
		}
		for (int i = 0; i < m; i++) {
			int a = nextInt() - 1;
			int b = nextInt() - 1;
			g.get(a).add(b);
			revg.get(b).add(a);
		}
		for (int i = 0; i < n; i++) {
			if (action[i] == 1 && !visited_from_write[i]) {
				dfs_from_write(i);
			}
		}
		for (int i = 0; i < n; i++) {
			if (action[i] == 2 && !visited_from_read[i]) {
				dfs_from_read(i);
			}
		}
		for (int i = 0; i < n; i++) {
			if (visited_from_write[i] && visited_from_read[i]) {
				out.println(1);
			}
			else {
				out.println(0);
			}
		}
	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class D {
    static boolean[] vis1, vis2;
    static boolean[] source, destination;
    static ArrayList<ArrayList<Integer>> graph1, graph2;

    public static void dfs1(int cur) {
        vis1[cur] = true;
        for (Integer i : graph1.get(cur)) {
            if (!vis1[i]&&!source[i])
                dfs1(i);
        }
    }

    public static void dfs2(int cur) {
        vis2[cur] = true;
        if(source[cur]) return;
        for (Integer i : graph2.get(cur)) {
            if (!vis2[i])
                dfs2(i);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        graph1 = new ArrayList<ArrayList<Integer>>();
        graph2 = new ArrayList<ArrayList<Integer>>();
        source = new boolean[n];
        destination = new boolean[n];
        for (int i = 0; i < n; i++) {
            graph1.add(new ArrayList<Integer>());
            graph2.add(new ArrayList<Integer>());
        }
        for (int i = 0; i < n; i++) {
            int val = sc.nextInt();
            if (val == 1) {
                source[i] = true;
            } else if (val == 2) {
                destination[i] = true;
            }
        }
        for (int i = 0; i < m; i++) {
            int f = sc.nextInt() - 1;
            int s = sc.nextInt() - 1;
            graph1.get(f).add(s);
            graph2.get(s).add(f);
        }
        vis1 = new boolean[n];
        vis2 = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (source[i]) {
                dfs1(i);
            }
        }
        for (int i = 0; i < n; i++) {
            if (destination[i]) {
                dfs2(i);
            }
        }
        for (int i = 0; i < n; i++) {
            if (vis1[i] && vis2[i]) {
                System.out.println(1);
            } else {
                System.out.println(0);
            }
        }
    }
}


import java.io.*;
import java.util.*;
public class D {
	private static void solve() throws IOException {
		n = nextInt();
		m = nextInt();
		f = new int[n+1];
		boolean[] visF = new boolean[n+1];
		boolean[] visE = new boolean[n+1];
		Queue<Integer> starts = new LinkedList<Integer>(); //all the locations of starts
		Queue<Integer> ends = new LinkedList<Integer>(); //all the locations of ends
		for(int i = 1; i < n+1; i++) {
			f[i] = nextInt();
			if(f[i] == 1)
				starts.add(i);
			else if(f[i] == 2)
				ends.add(i);
		}
		adj = new ArrayList[n+1];
		back = new ArrayList[n+1];
		for(int i = 0; i < n+1; i++) {
			adj[i] = new ArrayList<Integer>();
			back[i] = new ArrayList<Integer>();
		}
		for(int i = 0; i < m; i++) {
			int f = nextInt();
			int s = nextInt();
			adj[f].add(s);
			back[s].add(f);
		}
		//see if can be found from a 1
		while(!starts.isEmpty()) {
			int cur = starts.poll();
			if(visF[cur])
				continue;
			visF[cur] = true;
			ArrayList<Integer> temp = adj[cur];
			for(int i = 0; i < temp.size(); i++) {
				starts.add(temp.get(i));
			}
		}
		while(!ends.isEmpty()) {
			int cur = ends.poll();
			if(visE[cur])
				continue;
			visE[cur] = true;
			if(f[cur] == 1)
				continue;
			ArrayList<Integer> temp = back[cur];
			for(int i = 0; i < temp.size(); i++) {
				ends.add(temp.get(i));
			}
		}
		for(int i = 1; i < visF.length; i++) {
			if(visF[i] && visE[i])
				out.println(1);
			else
				out.println(0);
		}
	}
	static int b, n, m, k, l;
	static int[] a, f;
	static ArrayList<Integer>[] adj, back;

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

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

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

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

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

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


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;

public class VKRound3A {
    static BufferedReader br = new BufferedReader(new InputStreamReader(
            System.in));
    static StringTokenizer st = new StringTokenizer("");
    static int nextInt() throws Exception {
        return Integer.parseInt(next());
    }
    static String next() throws Exception {
        while (true) {
            if (st.hasMoreTokens()) {
                return st.nextToken();
            }
            String s = br.readLine();
            if (s == null) {
                return null;
            }
            st = new StringTokenizer(s);
        }
    }
    static int n, m;
    static int state [];
    static ArrayList<Integer> graph1 [];
    static ArrayList<Integer> graph2 [];
    static boolean vis1 [], vis2 [];
    public static void dfs_source(int idx){
        vis1[idx] = true;
        for(Integer nxt : graph1[idx]){
            if(!vis1[nxt] && state[nxt] != 1)
                dfs_source(nxt);
        }
    }

    public static void dfs_dest(int idx){
        vis2[idx] = true;
        if(state[idx] == 1)
            return;
        for(Integer nxt : graph2[idx]){
            if(!vis2[nxt])
                dfs_dest(nxt);
        }
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args)throws Exception {
        n = nextInt();
        m = nextInt();
        state = new int [n + 1];
        vis1 = new boolean [n + 1];
        vis2 = new boolean [n + 1];
        graph1 = new ArrayList [n + 1];
        graph2 = new ArrayList [n + 1];
        for(int i = 0 ; i < n + 1 ; ++i)
            graph1[i] = new ArrayList<Integer>();
        for(int i = 0 ; i < n + 1 ; ++i)
            graph2[i] = new ArrayList<Integer>();
        for(int i = 1 ; i < n + 1 ; ++i)
            state[i] = nextInt();
        for(int i = 0 ; i < m ; ++i){
            int a = nextInt();
            int b = nextInt();
            graph1[a].add(b);
            graph2[b].add(a);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(state[i] == 1 && !vis1[i])
                dfs_source(i);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(state[i] == 2 && !vis2[i])
                dfs_dest(i);
        }
        for(int i = 1 ; i < n + 1 ; ++i){
            if(vis1[i] && vis2[i])
                System.out.println(1);
            else
                System.out.println(0);
        }
    }
}


import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class R3_D2_D {
    static ArrayList<Integer>[] edge;
    static ArrayList<Integer>[] revEdge;
    static boolean vis1[];
    static boolean vis2[];

    public static void dfs1(int index) {
        if (!vis1[index]) {
            vis1[index] = true;
            for (int a : edge[index])
                dfs1(a);
        }
    }

    public static void dfs2(int index) {
        if (!vis2[index]) {
            vis2[index] = true;
            for (int a : revEdge[index])
                dfs2(a);
        }
    }

    public static void main(String[] args) {
        // BufferedReader in = new BufferedReader(new
        // InputStreamReader(System.in));

        InputReader in = new InputReader(System.in);
        int n = in.readInt();
        int m = in.readInt();
        vis1 = new boolean[n];
        vis2 = new boolean[n];
        int[] inp = new int[n];
        for (int i = 0; i < inp.length; i++) {
            inp[i] = in.readInt();
        }
        edge = new ArrayList[n];
        revEdge = new ArrayList[n];
        for (int j = 0; j < inp.length; j++) {
            edge[j] = new ArrayList<Integer>();
            revEdge[j] = new ArrayList<Integer>();
        }
        for (int i = 0; i < m; i++) {
            int a = in.readInt() - 1;
            int b = in.readInt() - 1;
            if(inp[b]==1)
                continue;
            edge[a].add(b);
            revEdge[b].add(a);
        }
        for (int i = 0; i < inp.length; i++) {
            if (inp[i] == 1)
                dfs1(i);
        }
        for (int i = 0; i < inp.length; i++) {
            if (inp[i] == 2)
                dfs2(i);
        }
        for (int i = 0; i < inp.length; i++) {
            if(vis1[i] && vis2[i])
                System.out.println(1);
            else
                System.out.println(0);
        }
    }

    public static class tr {
        int x;
        int y;
        int z;

        public tr(int a, int b, int c) {
            x = a;
            y = b;
            z = c;
        }
    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1000];
        private int curChar, numChars;

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

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

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

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

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuffer res = new StringBuffer();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

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

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

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

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

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

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

}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class CF_164D {

	public static void main(String[] args) {
		new CF_164D().solve();
	}

	private void solve() {
		Scanner in = new Scanner(System.in);
		int numNodes = in.nextInt();
		int numEdges = in.nextInt();

		boolean[] rfs = new boolean[numNodes];
		boolean[] rfe = new boolean[numNodes];
		int[] type = new int[numNodes];

		HashMap<Integer, List<Integer>> fwdEdges = new HashMap<Integer, List<Integer>>();
		HashMap<Integer, List<Integer>> revEdges = new HashMap<Integer, List<Integer>>();

		Stack<Integer> startNodes = new Stack<Integer>();
		Stack<Integer> endNodes   = new Stack<Integer>();

		// read nodes
		for(int i = 0; i < numNodes; i++) {
			type[i] = in.nextInt();
			fwdEdges.put(i, new ArrayList<Integer>());
			revEdges.put(i, new ArrayList<Integer>());

			if(type[i] == 1) {
				startNodes.push(i);
			} else if (type[i] == 2) {
				endNodes.push(i);
			}
		}

		// read edges
		for(int i = 0; i < numEdges; i++) {
			int a = in.nextInt() - 1;
			int b = in.nextInt() - 1;
			fwdEdges.get(a).add(b);
			revEdges.get(b).add(a);
		}

		// find all nodes reachable from start nodes without visiting an end node
		// (traverse forward edges)
		while(!startNodes.empty()) {
			int node = startNodes.pop();
			if(rfs[node]) {
				continue;
			}

			rfs[node] = true;
			//if(type[node] == 2) {
			//	continue;
			//}
			for(int next : fwdEdges.get(node)) {
				startNodes.push(next);
			}
		}

		// find all nodes reachable from end nodes without visiting a start node
		// (traverse reverse edges)
		while(!endNodes.empty()) {
			int node = endNodes.pop();
			if(rfe[node]) {
				continue;
			}

			rfe[node] = true;
			if(type[node] == 1) {
				continue;
			}
			for(int next : revEdges.get(node)) {
				endNodes.push(next);
			}
		}

		for(int i = 0; i < numNodes; i++) {
			System.out.println(rfs[i] && rfe[i] ? "1" : "0");
		}
	}
}


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

public class Solver {

    StringTokenizer st;
    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws NumberFormatException, IOException {
        Solver solver = new Solver();
        solver.open();
        solver.solve();
        solver.close();
    }

    public void open() throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
    }

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

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

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

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

    enum State{
        IGNORE,ASSIGN,USE;

        public static State getState(int v){
            switch(v){
                case 0:
                    return IGNORE;
                case 1:
                    return ASSIGN;
                case 2:
                    return USE;
                default:
                        return null;
            }
        }
    }

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

        State[] states = new State[n];
        List<List<Integer>> child = new ArrayList<List<Integer>>(n);
        List<List<Integer>> rev = new ArrayList<List<Integer>>(n);
        List<Integer> whenUsed = new ArrayList<Integer>();
        List<Integer> whenAssi = new ArrayList<Integer>();
        boolean[] forward = new boolean[n];
        boolean[] back = new boolean[n];

        for (int i=0;i<n;i++){
            child.add(new ArrayList<Integer>());
            rev.add(new ArrayList<Integer>());
            int vertex = nextInt();
            State state = State.getState(vertex);
            states[i] = state;
            if (state==State.USE){
                whenUsed.add(i);
            }else if(state==State.ASSIGN){
                whenAssi.add(i);
            }
        }

        for (int i=0;i<m;i++){
            int from = nextInt()-1;
            int to = nextInt()-1;

            child.get(from).add(to);
            rev.get(to).add(from);
        }

        while (whenAssi.size()>0){
            List<Integer> tmp = new ArrayList<Integer>();
            for (int vert:whenAssi){
                if (!forward[vert]){
                    forward[vert] = true;
                    tmp.addAll(child.get(vert));
                }
            }
            whenAssi = tmp;
        }

        while (whenUsed.size()>0){
            List<Integer> tmp = new ArrayList<Integer>();
            for (int vert:whenUsed){
                if (!back[vert]){
                    back[vert] = true;
                    if (states[vert]!=State.ASSIGN){
                        tmp.addAll(rev.get(vert));
                    }
                }
            }
            whenUsed = tmp;
        }

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

    public void close() {
        out.flush();
        out.close();
    }

}


import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.max;
import static java.lang.System.exit;
import static java.util.Arrays.fill;

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

public class G {

	static final long inf = Long.MAX_VALUE / 2;

	static void solve() throws Exception {
		int k = scanInt();
		long f[] = new long[6];
		for (int i = 0; i < 6; i++) {
			f[i] = scanLong();
		}
		long dyn[] = new long[1000000], ndyn[] = new long[1000000];
		fill(dyn, 1, 1000000, -inf);
		int p10 = 1;
		int smpos[] = new int[1000000];
		for (int p = 0; p < 6; p++) {
			fill(ndyn, -inf);
			long cf = f[p];
			int s = 3 * p10;
			for (int i = 0; i < 1000000; i++) {
				dyn[i] -= i / s * cf;
			}
			for (int m = 0; m < s; m++) {
				int smhead = 0, smtail = 0;
				for (int i = m; i < 1000000; i += s) {
					while (smtail > smhead && dyn[i] >= dyn[smpos[smtail - 1]]) {
						--smtail;
					}
					smpos[smtail++] = i;
					long v = dyn[smpos[smhead]] + i / s * cf;
					ndyn[i] = max(ndyn[i], v);
					if (i + p10 < 1000000) {
						ndyn[i + p10] = max(ndyn[i + p10], v);
					}
					if (i + 2 * p10 < 1000000) {
						ndyn[i + 2 * p10] = max(ndyn[i + 2 * p10], v);
					}
					if (smpos[smhead] == i - (long) (9 * k - 9) * p10) {
						++smhead;
					}
				}
			}
			for (int i = 0; i < 1000000; i++) {
				for (int ss = 9 * k - 6; ss <= 9 * k; ss++) {
					if (i - (long) ss * p10 >= 0) {
						ndyn[i] = max(ndyn[i], dyn[i - ss * p10] + ((i - ss * p10) / s + (ss % 3 == 0 ? ss / 3 : 3 * k - 3)) * cf);
					}
				}
			}
			p10 *= 10;
			long t[] = dyn;
			dyn = ndyn;
			ndyn = t;
		}
		int q = scanInt();
		for (int qq = 0; qq < q; qq++) {
			out.println(dyn[scanInt()]);
		}
	}

	static int scanInt() throws IOException {
		return parseInt(scanString());
	}

	static long scanLong() throws IOException {
		return parseLong(scanString());
	}

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

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

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


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

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

    static class TaskE1 {
        static final int DENOM = 100;
        static final long MODULO = (long) 1e9 + 7;
        private static final long INVDENOM = BigInteger.valueOf(DENOM).modInverse(BigInteger.valueOf(MODULO)).longValue();
        int n;
        long[][] p;
        int[][] s;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            p = new long[n][n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    p[i][j] = in.nextInt() * INVDENOM % MODULO;
                }
            }
            int[] match = new int[n];
            Arrays.fill(match, -1);
            s = new int[n][n];
            int[] stack = new int[n];
            int[] via = new int[n];
            int[] ptr = new int[n];
            long res = rec(match, stack, via, ptr, -1, 0);
            out.println(res);
        }

        private long rec(int[] match, int[] stack, int[] via, int[] ptr, int sp, int next) {
            for (int i = 0; i < sp; ++i)
                if (via[stack[i]] == -1) {
                    throw new RuntimeException();
                }
            if (sp == 0) return 0;
            if (sp == -1) {
                if (next >= n) {
                    return 1;
                }
                Arrays.fill(via, -1);
                Arrays.fill(ptr, 0);
                Arrays.fill(stack, -1);
                stack[0] = next;
                via[next] = -2;
                return rec(match, stack, via, ptr, 1, next);
            } else {
                int cur = stack[sp - 1];
                int dest = ptr[cur];
                if (dest < n && match[dest] < 0) {
                    if (s[cur][dest] == 0) {
                        s[cur][dest] = 1;
                        long res = p[cur][dest] * rec(match, stack, via, ptr, sp, next);
                        s[cur][dest] = 2;
                        res += (1 - p[cur][dest]) * rec(match, stack, via, ptr, sp, next);
                        res %= MODULO;
                        if (res < 0) res += MODULO;
                        s[cur][dest] = 0;
                        return res;
                    }
                    if (s[cur][dest] == 1) {
                        int[] nmatch = match.clone();
                        int[] nstack = new int[n];
                        int[] nvia = new int[n];
                        int[] nptr = new int[n];
                        for (int i = 1; i < sp; ++i) {
                            nmatch[via[stack[i]]] = stack[i - 1];
                        }
                        nmatch[dest] = cur;
                        return rec(nmatch, nstack, nvia, nptr, -1, next + 1);
                    }
                }
                int ndest = dest - n;
                if (ndest >= 0 && ndest < n && match[ndest] >= 0 && via[match[ndest]] == -1) {
                    if (s[cur][ndest] == 0) {
                        s[cur][ndest] = 1;
                        long res = p[cur][ndest] * rec(match, stack, via, ptr, sp, next);
                        s[cur][ndest] = 2;
                        res += (1 - p[cur][ndest]) * rec(match, stack, via, ptr, sp, next);
                        res %= MODULO;
                        if (res < 0) res += MODULO;
                        s[cur][ndest] = 0;
                        return res;
                    }
                    if (s[cur][ndest] == 1) {
                        int md = match[ndest];
                        via[md] = ndest;
                        stack[sp] = md;
                        long res = rec(match, stack, via, ptr, sp + 1, next);
                        stack[sp] = -1;
                        via[md] = -1;
                        return res;
                    }
                }
                if (dest >= 2 * n) {
                    long res = rec(match, stack, via, ptr, sp - 1, next);
                    stack[sp - 1] = cur;
                    return res;
                } else {
                    ptr[cur] = dest + 1;
                    long res = rec(match, stack, via, ptr, sp, next);
                    ptr[cur] = dest;
                    return res;
                }
            }
        }

    }

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

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

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

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

    }
}


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

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

	int Q;

	void solve()
	{
		int n = ni();
		int[][] ps = new int[n][];
		for(int i = 0;i < n;i++){
			ps[i] = na(n);
		}

		if(n % 2 == 1){
			n++;
			int[][] nps = new int[n][n];
			nps[n-1][n-1] = 100;
			for(int i = 0;i < n-1;i++){
				for(int j = 0;j < n-1;j++){
					nps[i][j] = ps[i][j];
				}
			}
			ps = nps;
		}

		if(n == 6)Q = 20;
		if(n == 4)Q = 6;
		if(n == 2)Q = 2;

		long ih = invl(100, mod);
		for(int i = 0;i < n;i++){
			for(int j = 0;j < n;j++){
				ps[i][j] = (int)(ps[i][j] * ih % mod);
			}
		}

		int h = n/2;
		long[] l = go(Arrays.copyOfRange(ps, 0, h));
		long[] r = go(Arrays.copyOfRange(ps, h, n));
		long[] nl = new long[l.length];
		for(int i = 0;i < l.length;i++){
			int ii = i;
			for(int j = 0, k = Q-1;j < k;j++,k--){
				if((i>>>j&1) != (i>>>k&1)){
					ii ^= 1<<j|1<<k;
				}
			}
			nl[ii] = l[i];
		}
		l = nl;

		long[] zl = zetaTransform(l);
		long[] zr = zetaTransform(r);
		for(int i = 0;i < zl.length;i++){
			zl[i] = zl[i] * zr[i] % mod;
		}
		long[] me = inverseZetaTransform(zl);
		long ans = 0;
		for(int i = 1;i < me.length;i++){
			ans += me[i];
		}
		out.println(ans%mod);
	}

	public static long invl(long a, long mod) {
		long b = mod;
		long p = 1, q = 0;
		while (b > 0) {
			long c = a / b;
			long d;
			d = a;
			a = b;
			b = d % b;
			d = p;
			p = q;
			q = d - c * q;
		}
		return p < 0 ? p + mod : p;
	}

	public long[] zetaTransform(long[] f)
	{
		int H = Integer.numberOfTrailingZeros(f.length);
		for(int i = 0;i < H;i++){
			for(int j = 0;j < 1<<H;j++){
				if(j<<~i>=0){
					f[j] += f[j|1<<i];
					if(f[j] >= mod)f[j] -= mod;
				}
			}
		}
		return f;
	}

	public long[] inverseZetaTransform(long[] f)
	{
		int H = Integer.numberOfTrailingZeros(f.length);
		for(int i = 0;i < H;i++){
			for(int j = 0;j < 1<<H;j++){
				if(j<<~i>=0){
					f[j] -= f[j|1<<i];
					if(f[j] < 0)f[j] += mod;
				}
			}
		}
		return f;
	}

	int mod = 1000000007;

	long[] go(int[][] ps)
	{
		int h = ps.length;
		int n = ps[0].length;
		long[] l = new long[1<<Q];
		for(int i = 0;i < 1<<h*n;i++){
			long P = 1;
			for(int j = 0;j < h;j++){
				for(int k = 0;k < n;k++){
					if(i<<~(j*n+k)<0){
						P = P * ps[j][k] % mod;
					}else{
						P = P * (mod+1-ps[j][k]) % mod;
					}
				}
			}
			int ptn = 0;
			int p = 0;
			for(int j = 0;j < 1<<n;j++){
				if(Integer.bitCount(j) == h){
					int[] ds = toArray(j);
					int[] ord = ds;
					inner:
					do{
						for(int k = 0;k < h;k++){
							if(i<<~(k*n+ds[k])>=0)continue inner;
						}
						ptn |= 1<<p;
						break;
					}while(nextPermutation(ord));
					p++;
				}
			}
			l[ptn] += P;
			if(l[ptn] >= mod)l[ptn] -= mod;
		}
		return l;
	}

	public static int[] toArray(long x)
	{
		int[] ret = new int[5];
		int p = 0;
		for(;x != 0;x &= x-1){
			ret[p++] = Long.numberOfTrailingZeros(x);
		}
		return Arrays.copyOf(ret, p);
	}

	public static boolean nextPermutation(int[] a) {
		int n = a.length;
		int i;
		for (i = n - 2; i >= 0 && a[i] >= a[i + 1]; i--)
			;
		if (i == -1)
			return false;
		int j;
		for (j = i + 1; j < n && a[i] < a[j]; j++)
			;
		int d = a[i];
		a[i] = a[j - 1];
		a[j - 1] = d;
		for (int p = i + 1, q = n - 1; p < q; p++, q--) {
			d = a[p];
			a[p] = a[q];
			a[q] = d;
		}
		return true;
	}

	void run() throws Exception
	{
//		int n = 6, m = 99999;
//		Random gen = new Random();
//		StringBuilder sb = new StringBuilder();
//		sb.append(n + " ");
//		for (int i = 0; i < n*n; i++) {
//			sb.append(i + " ");
//		}
//		INPUT = sb.toString();

		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

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

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

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

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

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

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

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

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

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

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

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

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

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

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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

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

    static class TaskC {
        public String get(long x) {
            String res = "";
            while (x >= 9) {
                res += '9';
                x -= 9;
            }
            if (x > 0)
                res += (char) ('0' + x);
            return res;
        }

        int get_length(long x) {
            if (x == 0)
                return 1;
            int cnt = 0;
            while (x > 0) {
                cnt++;
                x /= 10;
            }
            return cnt;
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            long a = in.nextLong();
            if (a < 45) {
                for (int i = 0; i < a; i++)
                    out.print(1);
                out.print(' ');
                for (int i = 0; i < a; i++)
                    out.print(1);
                out.println();
                return;
            }
            long len = 0;
            for (long x = 1; x <= 16; x++) {
                long cnt = x * 45;
                for (int i = 0; i < x - 1; i++)
                    cnt *= 10;
                if (cnt <= a)
                    len = x;
            }
            long sum = len * 45, cnt = 10;
            for (int i = 0; i < len - 1; i++) {
                sum *= 10;
                cnt *= 10;
            }
            a -= sum;
            long l = 0, r = cnt - 1;
            l += a % cnt;
            r += a % cnt;
            String add = get(a / cnt);
            if (a / cnt == 0 && l == 0)
                l++;
            out.print(add);
            if (a / cnt != 0)
                for (int i = 0; i < get_length(r) - get_length(l); i++)
                    out.print(0);
            out.print(l + " ");
            out.print(add);
            out.println(r);
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

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

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

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

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

        public void print(char i) {
            writer.print(i);
        }

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

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

        public void print(int i) {
            writer.print(i);
        }

    }

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

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

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

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

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

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

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

        }

    }
}


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

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

        BigInteger mod = sc.nextBigInteger();
        BigInteger l = new BigInteger("1");
        BigInteger r = new BigInteger("45");
        BigInteger ten = new BigInteger("10");
        for (int i = 0; i < 20; i++) {
        	r = r.multiply(new BigInteger("10")).add(ten.multiply(new BigInteger("45")));
        	ten = ten.multiply(new BigInteger("10"));
        }
        r = r.add(l);
        BigInteger rem = mod.subtract(r.mod(mod));
        BigInteger end = new BigInteger("1000000000000000000000");
        l = l.add(rem);
        end = end.add(rem);
        pw.println(l + " " + end);

        pw.close();
    }
    static class FastScanner {
    	private boolean finished = false;

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

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

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

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

        public String nextString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                if (Character.isValidCodePoint(c)) {
                    res.appendCodePoint(c);
                }
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

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

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

        private String readLine0() {
            StringBuilder buf = new StringBuilder();
            int c = read();
            while (c != '\n' && c != -1) {
                if (c != '\r') {
                    buf.appendCodePoint(c);
                }
                c = read();
            }
            return buf.toString();
        }
        public String readLine() {
            String s = readLine0();
            while (s.trim().length() == 0) {
                s = readLine0();
            }
            return s;
        }
        public String readLine(boolean ignoreEmptyLines) {
            if (ignoreEmptyLines) {
                return readLine();
            } else {
                return readLine0();
            }
        }

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

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

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

        public boolean isExhausted() {
            int value;
            while (isSpaceChar(value = peek()) && value != -1) {
                read();
            }
            return value == -1;
        }
    public String next() {
            return nextString();
        }

        public SpaceCharFilter getFilter() {
            return filter;
        }

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

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
        public int[] nextIntArray(int n){
            int[] array=new int[n];
            for(int i=0;i<n;++i)array[i]=nextInt();
            return array;
        }
        public int[] nextSortedIntArray(int n){
            int array[]=nextIntArray(n);
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
            for(int i = 0; i < n; i++){
                pq.add(array[i]);
            }
            int[] out = new int[n];
            for(int i = 0; i < n; i++){
                out[i] = pq.poll();
            }
            return out;
        }
        public int[] nextSumIntArray(int n){
            int[] array=new int[n];
            array[0]=nextInt();
            for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
            return array;
        }
        public ArrayList<Integer>[] nextGraph(int n, int m){
            ArrayList<Integer>[] adj = new ArrayList[n];
            for(int i = 0; i < n; i++){
                adj[i] = new ArrayList<Integer>();
            }
            for(int i = 0; i < m; i++){
                int u = nextInt(); int v = nextInt();
                u--; v--;
                adj[u].add(v); adj[v].add(u);
            }
            return adj;
        }
        public ArrayList<Integer>[] nextTree(int n){
            return nextGraph(n, n-1);
        }

        public long[] nextLongArray(int n){
            long[] array=new long[n];
            for(int i=0;i<n;++i)array[i]=nextLong();
            return array;
        }
        public long[] nextSumLongArray(int n){
            long[] array=new long[n];
            array[0]=nextInt();
            for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
            return array;
        }
        public long[] nextSortedLongArray(int n){
            long array[]=nextLongArray(n);
            Arrays.sort(array);
            return array;
        }
    }
	static void shuffle(int[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(a.length);
			int temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}
	static void shuffle(long[] a) {
		Random get = new Random();
		for (int i = 0; i < a.length; i++) {
			int r = get.nextInt(a.length);
			long temp = a[i];
			a[i] = a[r];
			a[r] = temp;
		}
	}
}


import java.math.BigInteger;
import java.io.BufferedWriter;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

  // 1   - 9    -> 45
  // 10  - 99   -> pre + pre * 9 + pre * 10 = 900
  // 100 - 1000 -> 900 + (900 * 9) + (45 * 100) -> pre * 10 + 45 * 100

  private static BigInteger TEN = BigInteger.valueOf(10);
  private static BigInteger HUNDRED = BigInteger.valueOf(100);
  private static BigInteger FORTYFIVE = BigInteger.valueOf(45);

  // ZhouYuChen's idea
  private void solve() throws Exception {
    Scanner scanner = new Scanner(System.in);
    BigInteger k = scanner.nextBigInteger();

    BigInteger x = TEN.pow(100).subtract(BigInteger.ONE);
    BigInteger t = k.subtract(TEN.pow(99).multiply(FORTYFIVE.multiply(HUNDRED)).mod(k));
    System.out.println(t.toString() + " " + t.add(x).toString());
  }

  public static void main(String... args) {

    try {
      new Main().solve();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }
}


import java.math.BigInteger;
import java.io.BufferedWriter;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

  // 1   - 9    -> 45
  // 10  - 99   -> pre + pre * 9 + pre * 10 = 900
  // 100 - 1000 -> 900 + (900 * 9) + (45 * 100) -> pre * 10 + 45 * 100

  private static BigInteger TEN = BigInteger.valueOf(10);
  private static BigInteger HUNDRED = BigInteger.valueOf(100);
  private static BigInteger FORTYFIVE = BigInteger.valueOf(45);

  private void solve() throws Exception {
    Scanner scanner = new Scanner(System.in);
    BigInteger k = scanner.nextBigInteger();

    BigInteger x = TEN.pow(100).subtract(BigInteger.ONE);
    BigInteger t = k.subtract(TEN.pow(99).multiply(FORTYFIVE.multiply(HUNDRED)).mod(k));
    System.out.println(t.toString() + " " + t.add(x).toString());
  }

  public static void main(String... args) {

    try {
      new Main().solve();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }
}


//package round116;
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 = "";
	int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};

	void solve()
	{
		int b = ni(), d = ni();

		int v;
		if((v = isType2(b, d)) > 0){
			out.println("2-type");
			out.println(v);
		}else if(isType3(b, d)){
			out.println("3-type");
		}else if(isType11(b, d)){
			out.println("11-type");
		}else if(isType6(b, d)){
			out.println("6-type");
		}else{
			out.println("7-type");
		}
	}

	int isType2(int b, int d)
	{
		int[][] fb = factor(b, primes);
		int emax = 0;
		for(int[] f : fb){
			int e = 0;
			while(d % f[0] == 0){
				d /= f[0];
				e++;
			}
			emax = Math.max(emax, (e+f[1]-1)/f[1]);
		}
		return d != 1 ? 0 : emax;
	}

	boolean isType3(int b, int d)
	{
		if(b == 2)return false;
		return (b-1) % d == 0;
	}

	boolean isType11(int b, int d)
	{
		return (b+1) % d == 0;
	}

	boolean isType6(int b, int d)
	{
		int[][] fd = factor(d, primes);
		for(int[] f : fd){
			int mul = 1;
			for(int i = 0;i < f[1];i++){
				mul *= f[0];
			}
			if(isType2(b, mul) > 0 || isType3(b, mul) || isType11(b, mul)){
			}else{
				return false;
			}
		}
		return true;
	}

	public static int[][] factor(int n, int[] primes)
	{
		int[][] ret = new int[9][2];
		int rp = 0;
		for(int p : primes){
			if(p * p > n)break;
			int i;
			for(i = 0;n % p == 0;n /= p, i++);
			if(i > 0){
				ret[rp][0] = p;
				ret[rp][1] = i;
				rp++;
			}
		}
		if(n != 1){
			ret[rp][0] = n;
			ret[rp][1] = 1;
			rp++;
		}
		return Arrays.copyOf(ret, rp);
	}

	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.math.*;
import java.util.*;
import java.util.stream.*;

public class D {

	long myDiv(long a, long b) {
		return Math.floorDiv(a + b - 1, b);
	}

	long go2(long n, long s, long k) {
		long ans1 = -1;
		for (long c2 = n; c2 >= 0; c2--) {
			long full = n + c2;

			long x = (k - 1) / full;

			long high = c2;
			long low = -1;
			while (high - low > 1) {
				long mid = (low + high) >> 1;
				if ((k - 1) / (n + mid) == x) {
					high = mid;
				} else {
					low = mid;
				}
			}

			long cLow = high;
			long cHigh = c2;

			// c = c2, c2 - 1, ..., c3

			// last = k - x * (n + c)
			// last2 = k - x * (n + c) - s
			// rest2 = c - k + x * (n + c) + s

			// 0 <= k - x * (n + c) - s <= s
			// 0 <= c - k + x * (n + c) + s <= n - s

			if (x == 0) {
				if (!(0 <= k - s && k - s <= s)) {
					cLow = Long.MAX_VALUE;
				}
				cLow = Math.max(cLow, k - s);
				cHigh = Math.min(cHigh, n + k - s - s);
			} else {

				// c2 <= c <= c3
				// (k - nx - 2s) / x <= c <= (k - nx - s) / x
				// (k - nx - s) / (x + 1) <= c <= (k - nx + n - 2s) / (x + 1)

				cLow = Math.max(cLow, myDiv(k - n * x - 2 * s, x));
				cLow = Math.max(cLow, myDiv(k - n * x - s, x + 1));

				cHigh = Math.min(cHigh, Math.floorDiv(k - n * x - s, x));
				cHigh = Math.min(cHigh,
						Math.floorDiv(k - n * x + n - 2 * s, x + 1));
			}
			if (cLow <= cHigh) {
				ans1 = cHigh;
				break;
			}
			c2 = high;
		}

		k++;
		long ans2 = -1;

		for (long c2 = n; c2 >= 0; c2--) {
			long full = n + c2;

			long x = (k - 1) / full;

			long high = c2;
			long low = -1;
			while (high - low > 1) {
				long mid = (low + high) >> 1;
				if ((k - 1) / (n + mid) == x) {
					high = mid;
				} else {
					low = mid;
				}
			}

			long cLow = high;
			long cHigh = c2;

			// c = c2, c2 - 1, ..., c3

			// last = k - x * (n + c)
			// last2 = k - x * (n + c) - s
			// rest2 = c - k + x * (n + c) + s

			// 1 <= k - x * (n + c) - s <= s
			// 0 <= c - k + x * (n + c) + s <= n - s

			if (x == 0) {
				if (!(1 <= k - s && k - s <= s)) {
					cLow = Long.MAX_VALUE;
				}
				cLow = Math.max(cLow, k - s);
				cHigh = Math.min(cHigh, n + k - s - s);
			} else {
				// c2 <= c <= c3
				// (k - nx - 2s) / x <= c <= (k - nx - s - 1) / x
				// (k - nx - s) / (x + 1) <= c <= (k - nx + n - 2s) / (x + 1)

				cLow = Math.max(cLow, myDiv(k - n * x - 2 * s, x));
				cLow = Math.max(cLow, myDiv(k - n * x - s, x + 1));

				cHigh = Math.min(cHigh, Math.floorDiv(k - n * x - s - 1, x));
				cHigh = Math.min(cHigh,
						Math.floorDiv(k - n * x + n - 2 * s, x + 1));
			}
			if (cLow <= cHigh) {
				ans2 = cHigh;
				break;
			}
			c2 = high;
		}

		return Math.max(ans1, ans2);
	}

	long go1(long n, long s, long k) {

		// no overeating
		long ans1 = -1;
		for (long c2 = n; c2 >= 0; c2--) {
			long full = n + c2;

			long last = k % full;
			if (last == 0) {
				last = full;
			}

			long last2 = last - s;
			long rest2 = c2 - last2;

			if (!(0 <= last2 && last2 <= s && 0 <= rest2 && rest2 <= n - s)) {
				continue;
			}

			ans1 = c2;
			break;
		}

		long ans2 = -1;
		// overeating!
		for (long c2 = n; c2 > 0; c2--) {
			long full = n + c2;

			long last = (k + 1) % full;
			if (last == 0) {
				last = full;
			}

			long last2 = last - s;
			long rest2 = c2 - last2;

			if (!(1 <= last2 && last2 <= s && 0 <= rest2 && rest2 <= n - s)) {
				continue;
			}

			ans2 = c2;
			break;
		}

		return Math.max(ans1, ans2);
	}

	void submit() {
		long n = nextLong();
		long l = nextLong();
		long r = nextLong();
		long k = nextLong();

		long s;
		if (l <= r) {
			s = r - l + 1;
		} else {
			s = r - l + 1 + n;
		}

		// out.println(go2(n, s, k));

		if (n <= C) {
			out.println(go1(n, s, k));
		} else {
			out.println(go2(n, s, k));
		}
	}

	void test() {
		long big = BigInteger.TEN.pow(11).longValue();
		go2(big / 134, big / 2, big / 23);
	}

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

	D() throws IOException {
		is = System.in;
		out = new PrintWriter(System.out);
		submit();
		// stress();
		// test();
		out.close();
	}

	static final Random rng = new Random();
	static final int C = 10_000_000;

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

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

	private InputStream is;
	PrintWriter out;

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

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

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

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

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

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

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

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

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

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