import java.util.*;
import java.io.*;
public class Main {
    static class Scan {
        private byte[] buf=new byte[1024];
        private int index;
        private InputStream in;
        private int total;
        public Scan()
        {
            in=System.in;
        }
        public int scan()throws IOException
        {
            if(total<0)
            throw new InputMismatchException();
            if(index>=total)
            {
                index=0;
                total=in.read(buf);
                if(total<=0)
                return -1;
            }
            return buf[index++];
        }
        public int scanInt()throws IOException
        {
            int integer=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    integer*=10;
                    integer+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            return neg*integer;
        }
        public double scanDouble()throws IOException
        {
            double doub=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n)&&n!='.')
            {
                if(n>='0'&&n<='9')
                {
                    doub*=10;
                    doub+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            if(n=='.')
            {
                n=scan();
                double temp=1;
                while(!isWhiteSpace(n))
                {
                    if(n>='0'&&n<='9')
                    {
                        temp/=10;
                        doub+=(n-'0')*temp;
                        n=scan();
                    }
                    else throw new InputMismatchException();
                }
            }
            return doub*neg;
        }
        public String scanString()throws IOException
        {
            StringBuilder sb=new StringBuilder();
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            while(!isWhiteSpace(n))
            {
                sb.append((char)n);
                n=scan();
            }
            return sb.toString();
        }
        private boolean isWhiteSpace(int n)
        {
            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
            return true;
            return false;
        }
    }

    public static void sort(int arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(int arr[],int l1,int r1,int l2,int r2) {
        int tmp[]=new int[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void sort(long arr[],int l,int r) {    //sort(arr,0,n-1);
        if(l==r) {
            return;
        }
        int mid=(l+r)/2;
        sort(arr,l,mid);
        sort(arr,mid+1,r);
        merge(arr,l,mid,mid+1,r);
    }
    public static void merge(long arr[],int l1,int r1,int l2,int r2) {
        long tmp[]=new long[r2-l1+1];
        int indx1=l1,indx2=l2;
        //sorting the two halves using a tmp array
        for(int i=0;i<tmp.length;i++) {
            if(indx1>r1) {
                tmp[i]=arr[indx2];
                indx2++;
                continue;
            }
            if(indx2>r2) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            if(arr[indx1]<arr[indx2]) {
                tmp[i]=arr[indx1];
                indx1++;
                continue;
            }
            tmp[i]=arr[indx2];
            indx2++;
        }
        //Copying the elements of tmp into the main array
        for(int i=0,j=l1;i<tmp.length;i++,j++) {
            arr[j]=tmp[i];
        }
    }

    public static void main(String args[]) throws IOException {
        Scan input=new Scan();
        double s=input.scanInt();
        double a=input.scanInt();
        double b=input.scanInt();
        double c=input.scanInt();
        if(a==0 && b==0 && c==0) {
            System.out.println(0+" "+0+" "+0);
            return;
        }
        System.out.print((a*s)/(a+b+c));
        System.out.print(" ");
        System.out.print((b*s)/(a+b+c));
        System.out.print(" ");
        System.out.print((c*s)/(a+b+c));
        System.out.println();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Main {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BigInteger A = new BigInteger(bf.readLine().trim());
		List<BigInteger> pow = new ArrayList<BigInteger>();
		pow.add(BigInteger.ONE);
		BigInteger twl = new BigInteger("12");
		for (int i=1; i<600; i++) {
			pow.add(pow.get(i-1).multiply(twl));
		}
		int n = -1;
		for (int i=0;i<600;i++) {
			for (int j=0;j<=i/2;j++) {
				if (pow.get(j).add(pow.get(i-j)).compareTo(A) == 0) {
					n = i;
					break;
				}
			}
		}
		if (n == -1) {
			System.out.println("NO");
		} else {
			System.out.printf("YES\n1\n%d\n%d\n", n + 1, n/2);

			for (int j=n/2; j>=0; j--) {
				if (pow.get(j).add(pow.get(n-j)).compareTo(A) != 0) {
					System.out.println(pow.get(j).add(pow.get(n-j)));
				}
			}
		}
	}

}


import java.util.Scanner;

public class CF67E {
	static int[] x, y;

	static long cross(int i, int j, int k) {
		long x1=x[j] - x[i];
		long x2=x[k] - x[i];
		long y1=y[j] - y[i];
		long y2=y[k] - y[i];
		return x1 * y2 - x2 * y1;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		x = new int[n];
		y = new int[n];
		for (int i = 0; i < n; i++) {
			x[i] = sc.nextInt();
			y[i] = sc.nextInt();
		}

		boolean flip = x[0] < x[1];
		int X = x[1], Y = y[1];
		for (int i = 0; i < n; i++) {
			x[i] -= X;
			y[i] -= Y;
			if (flip) {
				x[i] = -x[i];
				y[i] = -y[i];
			}
		}

		int l = 0, r = x[0];
		for (int i = 2; i + 1 < n; i++) {
			long cr = cross(i, i + 1, 0);
			long cl = cross(i, i + 1, 1);
			if (cr > 0 && cl > 0) {
				System.out.println(0);
				return;
			}
			int x0 = x[i], y0 = y[i], x1 = x[i + 1], y1 = y[i + 1];
			if (cr > 0 || cl > 0) {
				long p = (long) x0 * (y1 - y0) - (long) y0 * (x1 - x0);
				long q = y1 - y0;
				if (q < 0) {
					p = -p; q = -q;
				}
				if (cr > 0)
					r = Math.min(r, (int) (p / q));
				else
					l = Math.max(l, (int) ((p + q - 1) / q));
			}
		}
		System.out.println(l <= r ? r - l + 1 : 0);

	}
}


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

    static class DTowers {
        int MAXN = 5005;
        PrintWriter out;
        InputReader in;
        int n;
        long[] pf = new long[MAXN];
        long[][] dp = new long[MAXN][MAXN];

        long go(int ind, int last) {
            if (ind == n + 1)
                return 0;
            if (dp[ind][last] != -1)
                return dp[ind][last];
            long val = 1 + go(ind + 1, last);
            long last_sum = pf[ind - 1] - pf[last];
            int lo = ind, hi = n - 1;
            while (lo <= hi) {
                int mid = (lo + hi) >> 1;
                if (pf[mid] - pf[ind - 1] < last_sum)
                    lo = mid + 1;
                else
                    hi = mid - 1;
            }
            lo++;
            //System.out.println(ind +" "+lo+" "+last);
            long nxt_sum = pf[lo - 1] - pf[ind - 1];
            if (pf[n] - pf[lo - 1] >= nxt_sum) {
                int len = lo - ind;
                long cost = len - 1;
                val = Math.min(val, go(lo, ind - 1) + cost);
            } else {
                int len = n + 1 - ind;
                long cost = len - 1;
                val = Math.min(val, go(n + 1, ind - 1) + cost);
            }
            dp[ind][last] = val;
            return val;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            this.out = out;
            this.in = in;
            n = ni();
            int i = 0;
            for (i = 1; i <= n; i++)
                pf[i] = pf[i - 1] + nl();
            for (i = 0; i <= n; i++)
                Arrays.fill(dp[i], -1);
            long min = (int) 1e9;
            if (n == 1) {
                pn(0);
                return;
            }
            for (i = 1; i <= n; i++) {
                //pn(i);
                if (pf[n] - pf[i] >= pf[i]) {
                    int len = i;
                    long cost = len - 1;
                    min = Math.min(min, go(i + 1, 0) + cost);
                } else {
                    int len = n;
                    long cost = len - 1;
                    min = Math.min(min, go(n + 1, 0) + cost);
                }
            }
            pn(min);
        }

        int ni() {
            return in.nextInt();
        }

        long nl() {
            return in.nextLong();
        }

        void pn(long zx) {
            out.println(zx);
        }

    }

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

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

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

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

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

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

    }
}


// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
	//Fast IO class
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
        	boolean env=System.getProperty("ONLINE_JUDGE") != null;
        	if(!env) {
        		try {
					br=new BufferedReader(new FileReader("src\\input.txt"));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
        	}
        	else br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static long MOD=1000000000+7;
    //debug
    static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
    // Pair
    static class pair{
    	long x,y;
    	pair(long a,long b){
    		this.x=a;
    		this.y=b;
    	}
    	public boolean equals(Object obj) {
    		if(obj == null || obj.getClass()!= this.getClass()) return false;
            pair p = (pair) obj;
            return (this.x==p.x && this.y==p.y);
        }
    	public int hashCode() {
            return Objects.hash(x,y);
        }
    }
    static FastReader sc=new FastReader();
    static PrintWriter out=new PrintWriter(System.out);
    //Main function(The main code starts from here)
    static int n,k;
    static long val=0;
    static long a[];
    static boolean check(int x) {
    	long sum=0;
    	val=a[x-1];
    	for(int i=0;i<x;i++) sum+=a[i];
    	if(val*x-sum<=k) return true;
    	for(int i=x;i<n;i++) {
    		sum=sum+a[i]-a[i-x];
    		val=a[i];
    		if(val*x-sum<=k) return true;
    	}
    	return false;
    }
    public static void main (String[] args) throws java.lang.Exception {
    	int test=1;
    	//test=sc.nextInt();
    	while(test-->0){
    		n=sc.nextInt();k=sc.nextInt();a=new long[n];
    		for(int i=0;i<n;i++) a[i]=sc.nextLong();
    		Arrays.parallelSort(a);
    		int l=1,r=n,ans=1;
    		while(l<=r) {
    			int mid=l+(r-l)/2;
    			if(check(mid)) {
    				ans=mid;
    				l=mid+1;
    			}
    			else r=mid-1;
    		}
    		check(ans);
    		out.println(ans+" "+val);
    	}
        out.flush();
        out.close();
    }
}


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

public class Rooms implements Runnable {
    static class Door {
        int a;
        int b;
    }

    static class Component {
        Set<String> names = new HashSet<String>();
        Set<Door> keys = new HashSet<Door>();

        public int size() {
            return names.size() + keys.size();
        }
    }

    private void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        int k = nextInt();
        Door[] door = new Door[m];
        for (int i = 0; i < m; ++i) {
            door[i] = new Door();
            door[i].a = nextInt() - 1;
            door[i].b = nextInt() - 1;
        }
        Component[][] res = new Component[2][];
        for (int step = 0; step < 2; ++step) {
            Component[] where = new Component[n];
            for (int i = 0; i < n; ++i) {
                where[i] = new Component();
            }
            for (int i = 0; i < k; ++i) {
                String name = nextToken();
                int room = nextInt() - 1;
                Component cur = where[room];
                cur.names.add(name);
                int cnt = nextInt();
                for (int j = 0; j < cnt; ++j) {
                    cur.keys.add(door[nextInt() - 1]);
                }
            }
            while (true) {
                boolean changed = false;
                for (Door d : door) {
                    if (where[d.a] == where[d.b])
                        continue;
                    if (where[d.a].keys.contains(d) || where[d.b].keys.contains(d)) {
                        changed = true;
                        Component a = where[d.a];
                        Component b = where[d.b];
                        a.keys.addAll(b.keys);
                        a.names.addAll(b.names);
                        for (int i = 0; i < n; ++i)
                            if (where[i] == b)
                                where[i] = a;
                    }
                }
                if (!changed)
                    break;
            }
            res[step] = where;
        }
        boolean result = true;
        for (int i = 0; i < n; ++i) {
            Component a = res[0][i];
            Component b = res[1][i];
            if (a.names.equals(b.names) && a.keys.equals(b.keys))
                continue;
            result = false;
            break;
        }
        if (result)
            writer.println("YES");
        else
            writer.println("NO");

    }

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

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

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

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

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

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

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


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

public class ConvexHull {

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

    static long cross(Point a, Point b, Point c){
       return (long) (b.x - a.x) * (c.y - a.y) - (long) (b.y - a.y)*(c.x - a.x);
    }

    static boolean isItOut(Point a, Point b, Point c, boolean upper){
        if(a == null || b == null) {
            return true;
        }
        if(upper && (a == b && a.y < c.y || cross(a,b,c) > 0)){
            return true;
        }
        if(!upper && (a == b && a.y > c.y || cross(a,b,c) < 0)){
            return true;
        }
        return false;
    }

    static void removePoint(TreeSet<Point> t, Point p, boolean right, boolean upper){
        Point a = right ? t.ceiling(p) : t.floor(p);
        if(a == null){
            return;
        }
        if(a.x == p.x){
            t.remove(a);
            a = right ? t.ceiling(p) : t.floor(p);
        }
        if(a == null){
            return;
        }
        Point b = right ? t.higher(a) : t.lower(a);
        int sign = upper ? 1 : -1;
        sign = right ? sign * 1 : sign * -1;
        while(b != null && cross(p, a, b) * sign >= 0){

            t.remove(a);
            a = b;
            b = right ? t.higher(a) : t.lower(a);

        }
    }

    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int q = Integer.parseInt(br.readLine());
        //upper hull
        TreeSet<Point> upper = new TreeSet<>((a,b) -> a.x - b.x);
        //lower hull
        TreeSet<Point> lower = new TreeSet<>((a,b) -> a.x - b.x);

        while(q > 0){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int t = Integer.parseInt(st.nextToken());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            Point p = new Point(x,y);
            Point ul = upper.floor(p);
            Point ur = upper.ceiling(p);
            Point ll = lower.floor(p);
            Point lr = lower.ceiling(p);

            boolean outupper = isItOut(ul, ur, p, true);
            boolean outlower = isItOut(ll, lr, p, false);

            if(t == 1){
                //add to convex hull
                if(outupper){
                    removePoint(upper, p, true, true);
                    removePoint(upper, p, false, true);
                    upper.add(p);
                }
                if(outlower){
                    removePoint(lower, p, true, false);
                    removePoint(lower, p, false, false);
                    lower.add(p);
                }

            }else{
                //see if in convex hull
                //is it right or left?
                System.out.println(outupper || outlower ? "NO" : "YES");
                //above top curve

                //below bottom curve

            }
            //Point[] up = upper.toArray();
            //System.out.printf("UPPER:  ");
            //for(int i = 0; i < up.length; i ++){
            //    System.out.printf("%d %d   ", up[i].x, up[i].y);
            //}

            //Object[] low = lower.toArray();
            //System.out.printf("\nLOWER:  ");
            //for(int i = 0; i < low.length; i ++){
            //    System.out.printf("%d %d   ", low[i].x, low[i].y);
            //}
            //System.out.println();

            q--;
        }

    }

}


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

public class Dot {

    static int N, D;
    static int[] vx, vy;
    static Boolean[][][][] dp;

    static long sq(long x) {
	return x * x;
    }

    static boolean solve(int p1, int p2, int x, int y) {
	if (sq(x) + sq(y) > sq(D))
	    return true;
	if (dp[p1][p2][x + 200][y + 200] != null)
	    return dp[p1][p2][x + 200][y + 200];
	boolean ans = false;
	if (p1 == 0)
	    ans |= !solve(p2, 1, y, x);
	for (int i = 0; i < N; i++)
	    ans |= !solve(p2, p1, x + vx[i], y + vy[i]);
	return dp[p1][p2][x + 200][y + 200] = ans;
    }

    public static void main(String[] args) throws IOException {
	MyScanner sc = new MyScanner(System.in);
	PrintWriter out = new PrintWriter(System.out);
	int x = sc.nextInt(), y = sc.nextInt();
	N = sc.nextInt();
	D = sc.nextInt();
	vx = new int[N];
	vy = new int[N];
	for (int i = 0; i < N; i++) {
	    vx[i] = sc.nextInt();
	    vy[i] = sc.nextInt();
	}
	dp = new Boolean[2][2][402][402];
	out.println(solve(0, 0, x, y) ? "Anton" : "Dasha");
	out.flush();
	out.close();
    }

    static class MyScanner {

	BufferedReader br;
	StringTokenizer st;

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

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

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

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

	boolean ready() throws IOException {
	    return br.ready();
	}
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.ArrayDeque;
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;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        final int INF = 0x3f3f3f3f;
        String[] matrix;
        int[][] zoneIndex;
        int zones;
        int[] dx = new int[]{-1, 0, 1, 0};
        int[] dy = new int[]{0, 1, 0, -1};
        int blackNodes;
        List<Integer>[] graph;

        @SuppressWarnings("unchecked")
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt(), m = in.nextInt();
            matrix = new String[n];
            for (int i = 0; i < n; ++i)
                matrix[i] = in.next();

            zoneIndex = new int[n][m];
            for (int[] p : zoneIndex) Arrays.fill(p, -1);
            zones = 0;
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    if (matrix[i].charAt(j) == 'B' && zoneIndex[i][j] == -1) {
                        dfs(i, j);
                        zones++;
                    }
                }
            }
            blackNodes = zones;
            if (zones <= 1) {
                out.println(zones);
                return;
            }
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    if (matrix[i].charAt(j) == 'W' && zoneIndex[i][j] == -1) {
                        dfs(i, j);
                        zones++;
                    }
                }
            }

            graph = new List[zones];
            for (int i = 0; i < zones; ++i)
                graph[i] = new ArrayList<>();
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    getEdges(i, j);
                }
            }
            for (int i = 0; i < zones; ++i) {
                Collections.sort(graph[i]);
                List<Integer> adj = new ArrayList<>();
                int prev = -1;
                for (int p : graph[i]) {
                    if (p != prev) {
                        adj.add(p);
                        prev = p;
                    }
                }
                graph[i] = adj;
            }

            Queue<Integer> q = new ArrayDeque<>();
            int ans = INF;
            for (int i = 0; i < zones; ++i) {
                int[] dist = new int[zones];
                dist[i] = 1;
                q.add(i);
                int mdist = 1;
                while (!q.isEmpty()) {
                    int node = q.poll();
                    mdist = dist[node];
                    for (int p : graph[node]) {
                        if (dist[p] == 0) {
                            dist[p] = dist[node] + 1;
                            q.add(p);
                        }
                    }
                }
                if (i >= blackNodes) mdist &= ~1;
                else mdist -= (mdist & 1) ^ 1;
                ans = Math.min(ans, mdist);
            }

            out.println(ans);
        }

        private void dfs(int x, int y) {
            zoneIndex[x][y] = zones;
            for (int k = 0; k < 4; ++k) {
                int nx = x + dx[k], ny = y + dy[k];
                if (0 <= nx && nx < matrix.length &&
                        0 <= ny && ny < matrix[0].length() &&
                        matrix[x].charAt(y) == matrix[nx].charAt(ny) &&
                        zoneIndex[nx][ny] == -1) {
                    dfs(nx, ny);
                }
            }
        }

        private void getEdges(int x, int y) {
            int node = zoneIndex[x][y];
            for (int k = 0; k < 4; ++k) {
                int nx = x + dx[k], ny = y + dy[k];
                if (!(0 <= nx && nx < matrix.length &&
                        0 <= ny && ny < matrix[0].length())) continue;
                int p = zoneIndex[nx][ny];
                if (p != node) {
                    graph[node].add(p);
                }
            }
        }

    }

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

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

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

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

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

    }
}


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

public final class Solution {

    private final static boolean USE_FILE_IO = false;

    Reader reader;
    Writer writer;

    Solution(Reader reader, Writer writer) {
        this.reader = reader;
        this.writer = writer;
    }

    long solve() throws java.lang.Exception {
        int n = reader.nextInt();
        int[] x = new int[n];
        int[] y = new int[n];
        for (int i=0; i<n; i++) {
            x[i] = reader.nextInt();
            y[i] = reader.nextInt();
        }
        long ans = 0;
        HashMap<Long, Integer> slopes = new HashMap<Long, Integer>();
        HashSet<Line> lines = new HashSet<Line>();
        for (int i=0; i<n-1; i++) {
            for (int j=i+1; j<n; j++) {
                Line line = new Line(x[i], y[i], x[j], y[j]);
                if (lines.add(line)) {
                    ans += (long)lines.size() - 1;
                    long slope = line.getSlope();
                    int count = slopes.getOrDefault(slope, 0);
                    ans -= (long)count;
                    slopes.put(slope, count + 1);
                }
            }
        }
        return ans;
    }

    class Line {
        int a, b, c;
        Line(int x1, int y1, int x2, int y2) {
            a = y2 - y1;
            b = x1 - x2;
            c = y1 * x2 - y2 * x1;
            if (a < 0 || (a==0 && b < 0)) {
                a = -a;
                b = -b;
                c = -c;
            }
            int gcd = gcd(gcd(Math.abs(a), Math.abs(b)), Math.abs(c));
            a /= gcd;
            b /= gcd;
            c /= gcd;
        }

        long getSlope() {
            return (long)a * 100000L + (long)b;
        }

        @Override
        public int hashCode() {
            return a ^ b ^ c;
        }

        @Override
        public boolean equals(Object o) {
            if (o == this) return true;
            if (o.getClass() != Line.class) return false;
            Line other = (Line) o;
            return other.a == this.a && other.b == this.b && other.c == this.c;
        }
    }

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

    public static void main(String[] args) throws java.lang.Exception {
        Reader reader = null;
        Writer writer = null;
        try {
            if (USE_FILE_IO) {
                reader = new Reader(new FileInputStream("input.txt"));
                writer = new Writer(new FileOutputStream("output.txt"));
            } else {
                reader = new Reader(System.in);
                writer = new Writer(System.out);
            }
            writer.writeLine(new Solution(reader, writer).solve());
        } finally {
            if (reader != null)
                reader.close();
            if (writer != null)
                writer.close();
        }
    }

    static class Writer {
        BufferedWriter bw;

        public Writer(OutputStream out) {
            bw = new BufferedWriter(new OutputStreamWriter(out));
        }

        void write(String s) throws java.lang.Exception {
            bw.write(s);
        }

        void write(int x) throws java.lang.Exception {
            write(String.valueOf(x));
        }

        void write(long x) throws java.lang.Exception {
            write(String.valueOf(x));
        }

        void write(char c) throws java.lang.Exception {
            bw.write(c);
        }

        void newLine() throws java.lang.Exception {
            bw.newLine();
        }

        void writeLine(String s) throws java.lang.Exception {
            write(s);
            newLine();
        }

        void writeLine(int n) throws java.lang.Exception {
            writeLine(String.valueOf(n));
        }

        void writeLine(long n) throws java.lang.Exception {
            writeLine(String.valueOf(n));
        }

        void writeLine() throws java.lang.Exception {
            writeLine("");
        }

        void close() throws java.lang.Exception {
            bw.flush();
            bw.close();
        }
    }

    static class Reader {
        BufferedReader br;
        StringTokenizer st;

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

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

        String[] nextTokens(int n) {
            String[] a = new String[n];
            for (int i=0; i<n; i++) {
                a[i] = nextToken();
            }
            return a;
        }

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

        int[] nextInts(int n) {
            int[] a = new int[n];
            for (int i=0; i<n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

        long[] nextLongs(int n) {
            long[] a = new long[n];
            for (int i=0; i<n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

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

        void close() throws java.lang.Exception {
            br.close();
        }
    }
}


import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.text.*;
public class cf1 {
    static long mod = (long)1e9 + 7;
    static long mod1 = 998244353;
    static FastScanner f;
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner S = new Scanner(System.in);
    static long x0; static long y0;
    static int inf = (int)(1e9);
    static long iinf = (long)(1e18);
    static void solve()throws IOException {
        long a = f.nl(); long b = f.nl(); long x = f.nl(); long y = f.nl();
        long g = gcd(x , y);
        x /= g; y /= g;
        a = Math.min(a / x , b / y);
        pn(x * a + " " + y * a);
    }
    public static void main(String[] args)throws IOException {
        init();
        int t = 1;
        while(t --> 0) {solve();}
        pw.flush();
        pw.close();
    }

/******************************END OF MAIN PROGRAM*******************************************/
    public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
    public static class FastScanner {
        BufferedReader br;StringTokenizer st;
        FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
        FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
        String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
        String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}
    }
    public static void pn(Object o){pw.println(o);}
    public static void p(Object o){pw.print(o);}
    public static void pni(Object o){pw.println(o);pw.flush();}
    static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
    static long gcd(long a,long b){if(b==0l)return a;else{return gcd(b,a%b);}}
    static long lcm(long a,long b){return (a*b/gcd(a,b));}
    static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
    static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
    static long mpow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=((res%mod)*(a%mod))%mod;b>>=1;a=((a%mod)*(a%mod))%mod;}return res;}
    static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
    static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
    static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> ans=new HashSet<Long>();for(Long i:ff)if(isPrime(i))ans.add(i);return ans;}
    static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> ans=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))ans.add(i);return ans;}
    static int[] inpint(int n){int arr[]=new int[n];for(int i=0;i<n;i++){arr[i]=f.ni();}return arr;}
    static long[] inplong(int n){long arr[] = new long[n];for(int i=0;i<n;i++){arr[i]=f.nl();}return arr;}
    static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
    static int gnv(char c){return Character.getNumericValue(c);}//No. of integers less than equal to i in ub
    static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
    static int upperbound(int a[],int i){int lo=0,hi=a.length-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a[mid]<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;}
    static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(ArrayList<Integer> a){Collections.sort(a);}//!Precompute fact in ncr()!
}


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

/*
 * 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.
 */
/**
 *
 * @author Andy Phan
 */
public class b {

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

        int n = in.nextInt();
        VecL[] a = new VecL[n];

        for(int i = 0; i < n; i++) a[i] = new VecL(in.nextInt(), in.nextInt());

        TreeMap<Long, SegL> upper = new TreeMap<>();
        TreeMap<Long, SegL> lower = new TreeMap<>();

        for(int i = 0; i < n; i++) {
            SegL seg = new SegL(a[i], a[(i+1)%n]);
            if(a[i].x < a[(i+1)%n].x || (a[i].x == a[(i+1)%n].x && a[i].y > a[(i+1)%n].y)) upper.put(a[i].x, seg);
            else lower.put(a[i].x, seg);
        }

        int m = in.nextInt();
        for(int i = 0; i < m; i++) {
            VecL vec = new VecL(in.nextInt(), in.nextInt());
            Map.Entry<Long, SegL> upperE = upper.floorEntry(vec.x);
            Map.Entry<Long, SegL> lowerE = lower.ceilingEntry(vec.x);
            if(upperE == null || upperE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
            if(lowerE == null || lowerE.getValue().side(vec) != -1) {
                System.out.println("NO");
                return;
            }
        }

        System.out.println("YES");

        out.close();
    }

    static class SegL {

        VecL from, to, dir;

        public SegL(VecL from, VecL to) {
            this.from = from;
            this.to = to;
            dir = to.sub(from);
        }

        //check if the segment contains the point
        public boolean contains(VecL p) {
            VecL d = p.sub(from);
            if (d.cross(dir) != 0) {
                return false;
            }
            long dot = d.dot(dir);
            return dot >= 0 && dot <= dir.mag2();
        }

        //(assuming I go left to right)
        //returns:
        //	1 if point is above me
        //	0 if point is on me
        //	-1 if point is below me
        public long side(VecL o) {
            long cross = dir.cross(o.sub(from));
            return cross == 0 ? 0 : cross / Math.abs(cross);
        }

        //returns true if this segl intersects the other, including at endpoints
        //note: returns false if the two segments lie on the same line
        public boolean intersects(SegL o) {
            return side(o.from) != side(o.to) && o.side(from) != o.side(to);
        }

        public String toString() {
            return from + " -> " + to;
        }

        //#
        static long gcd(long a, long b) {
            a = Math.abs(a);
            b = Math.abs(b);
            return b == 0 ? a : gcd(b, a % b);
        }
        //$

        //returns the lattice point of intersection or null if it is nonlattice or does not exist
        public VecL latticeIntersect(SegL o) {
            if (!intersects(o)) {
                return null;
            }
            long dirGCD = gcd(dir.x, dir.y), oDirGCD = gcd(o.dir.x, o.dir.y);
            VecL va= new VecL(dir.x / dirGCD, dir.y / dirGCD), vb = new VecL(o.dir.x / oDirGCD, o.dir.y / oDirGCD);
            if (va.x < 0 && va.y < 0) {
                va.x *= -1;
                va.y *= -1;
            }
            if (vb.x < 0 && vb.y < 0) {
                vb.x *= -1;
                vb.y *= -1;
            }
            if (va.equals(vb)) {
                return null;
            }
            long bottomScalar = va.x / gcd(va.x, va.y);
            long topScalar = va.y / gcd(va.x, va.y);
            long t2Scalar = -bottomScalar * vb.y + topScalar * vb.x;
            long t2Ans = bottomScalar * (o.from.y - from.y) - topScalar * (o.from.x - from.x);
            if (t2Ans % t2Scalar != 0) {
                return null;
            }
            long t2 = t2Ans / t2Scalar;
            return new VecL(t2 * vb.x + o.from.x, t2 * vb.y + o.from.y);
        }
    }

    static class VecL implements Comparable<VecL> {

        long x, y;

        public VecL(long x, long y) {
            this.x = x;
            this.y = y;
        }

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

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

        public VecL scale(long s) {
            return new VecL(x * s, y * s);
        }

        public long dot(VecL o) {
            return x * o.x + y * o.y;
        }

        public long cross(VecL o) {
            return x * o.y - y * o.x;
        }

        public long mag2() {
            return dot(this);
        }

        public VecL rot90() {
            return new VecL(-y, x);
        }

        public VecL rot270() {
            return new VecL(y, -x);
        }

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

        public int hashCode() {
            return Long.hashCode(x << 13 ^ (y * 57));
        }

        public boolean equals(Object oo) {
            VecL o = (VecL) oo;
            return x == o.x && y == o.y;
        }

        public int compareTo(VecL o) {
            if (x != o.x) {
                return Long.compare(x, o.x);
            }
            return Long.compare(y, o.y);
        }

        //origin->q1, axes-> quadrant in ccw direction
        public int quadrant() {
            if (x == 0 || y == 0) {
                if (y == 0) {
                    if (x >= 0) {
                        return 1;
                    } else {
                        return 3;
                    }
                } else if (y >= 0) {
                    return 2;
                } else {
                    return 4;
                }
            }
            if (x > 0) {
                if (y > 0) {
                    return 1;
                } else {
                    return 4;
                }
            } else if (y > 0) {
                return 2;
            } else {
                return 3;
            }
        }

        public int radialCompare(VecL o) {
            if (quadrant() == o.quadrant()) {
                return -Long.signum(cross(o));
            }
            return Integer.compare(quadrant(), o.quadrant());
        }
    }

    static class FS {

        BufferedReader in;
        StringTokenizer token;

        public FS(InputStream str) {
            in = new BufferedReader(new InputStreamReader(str));
        }

        public String next() {
            if (token == null || !token.hasMoreElements()) {
                try {
                    token = new StringTokenizer(in.readLine());
                } catch (IOException ex) {
                }
                return next();
            }
            return token.nextToken();
        }

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


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.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.io.InputStream;

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

  static class DStroka {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      String s = in.next();
      long answer = new DStroka.Solve(s).solve();
      out.print(answer);
    }

    static long sum(long n) {
      return n * (n + 1) / 2;
    }

    static class Solve {
      int n;
      char[] s;
      int[] order;
      int[] type;
      int[] lcp;

      Solve(String s) {
        s += "$";
        this.s = s.toCharArray();
        n = s.length();
      }

      long solve() {
        initSuffixArray();
        initLCP();
        DS ds = new DS();
        for (int i = 1; i < n; i++) ds.update(i);
        return ds.finish();
      }

      void updateTypes(int len) {
        int[] type2 = new int[n];
        type2[order[0]] = 0;
        for (int i = 1, j = 0; i < n; i++) {
          int left1 = type[order[i]];
          int left2 = type[order[i - 1]];
          int right1 = type[(order[i] + len) % n];
          int right2 = type[(order[i - 1] + len) % n];
          if (left1 != left2 || right1 != right2) j++;
          type2[order[i]] = j;
        }
        System.arraycopy(type2, 0, type, 0, n);
      }

      void countSort(int typeCount, int len) {
        int[] count = new int[typeCount];
        for (int t : type) count[t]++;
        for (int i = 0, j = 0; i < typeCount; i++) {
          int x = count[i];
          count[i] = j;
          j += x;
        }
        int[] order2 = new int[n];
        for (int x : order) order2[count[type[x]]++] = x;
        System.arraycopy(order2, 0, order, 0, n);
        updateTypes(len);
      }

      void initSuffixArray() {
        order = new int[n];
        type = new int[n];
        for (int i = 0; i < n; i++) order[i] = i;
        for (int i = 0; i < n; i++) type[i] = s[i];
        countSort(1 << 8, 0);
        for (int len = 1, typeCount; (typeCount = type[order[n - 1]] + 1) < n; len <<= 1) {
          for (int i = 0; i < n; i++) order[i] = (order[i] - len + n) % n;
          countSort(typeCount, len);
        }
      }

      void initLCP() {
        lcp = new int[n];
        for (int i = 0, k = 0; i < n - 1; i++) {
          int pi = type[i];
          int j = order[pi - 1];
          while (s[i + k] == s[j + k]) k++;
          lcp[pi] = k;
          if (k > 0) k--;
        }
      }

      class DS {
        Deque<IntIntPair> q;
        long total = 0;

        DS() {
          q = new ArrayDeque<>();
          q.add(IntIntPair.makePair(-1, 0));
        }

        void drop(int at) {
          while (q.peekLast().first > at) {
            IntIntPair cur = q.pollLast();
            if (q.peekLast().first == cur.first) {
              q.addLast(IntIntPair.makePair(cur.first, cur.second + q.pollLast().second));
              continue;
            }
            int left = Math.max(q.peekLast().first, at) + 1;
            int right = cur.first;
            int len = right - left + 1;
            total += len * sum(cur.second);
            q.addLast(IntIntPair.makePair(left - 1, cur.second));
          }
        }

        void update(int i) {
          drop(lcp[i] - 1);
          int lastIndex = n - 2 - order[i];
          q.addLast(IntIntPair.makePair(lastIndex, 1));
        }

        long finish() {
          drop(-1);
          return total;
        }

      }

    }

  }

  static class IntIntPair implements Comparable<IntIntPair> {
    public final int first;
    public final int second;

    public static IntIntPair makePair(int first, int second) {
      return new IntIntPair(first, second);
    }

    public IntIntPair(int first, int second) {
      this.first = first;
      this.second = second;
    }

    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      IntIntPair pair = (IntIntPair) o;

      return first == pair.first && second == pair.second;
    }

    public int hashCode() {
      int result = first;
      result = 31 * result + second;
      return result;
    }

    public String toString() {
      return "(" + first + "," + second + ")";
    }

    public int compareTo(IntIntPair o) {
      int value = Integer.compare(first, o.first);
      if (value != 0) {
        return value;
      }
      return Integer.compare(second, o.second);
    }

  }

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

    public String next() {
      return readString();
    }

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

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

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

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

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

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

  }
}

[{'input': 'aaaa\r\n', 'output': ['20\r\n']}, {'input': 'abcdef\r\n', 'output': ['21\r\n']}, {'input': 'abacabadabacaba\r\n', 'output': ['188\r\n']}, {'input': 'tkth\r\n', 'output': ['11\r\n']}, {'input': 'eqkrqe\r\n', 'output': ['23\r\n']}, {'input': 'cwuiax\r\n', 'output': ['21\r\n']}, {'input': 'hhhhqhqh\r\n', 'output': ['59\r\n']}, {'input': 'gmxfmcgp\r\n', 'output': ['38\r\n']}, {'input': 'eleellleeee\r\n', 'output': ['104\r\n']}, {'input': 'usussubuubbbbs\r\n', 'output': ['138\r\n']}, {'input': 'lhmpaugvnqzrfxke\r\n', 'output': ['136\r\n']}, {'input': 'xkkkkkkkkkkkkkkkkxkkkk\r\n', 'output': ['1098\r\n']}, {'input': 'pprppppriiriiiirprppprriir\r\n', 'output': ['512\r\n']}, {'input': 'jsoxkutcvyshsinfmtrpujedcbmyqlojzco\r\n', 'output': ['646\r\n']}, {'input': 'emcegmekgnlefkeguqkfffnduqhfhhhndlfhlfdqdncefnn\r\n', 'output': ['1227\r\n']}, {'input': 'ffffdjfddffdjdfffddjfffffffjfffjdjfffjfjfdjjfjdjjdjjjdffd\r\n', 'output': ['2564\r\n']}, {'input': 'cxvhmeyouudwuglhbwndzwmjjsgrnuwnzwaycfspyyrdckjcidfsabvdxzjkvm\r\n', 'output': ['2023\r\n']}, {'input': 'cahdktuxuukmbuqcqactqhqdcxpkqcuumckttdpmpqxxkacpappxuqkxbuahqdphhddhquthqaapm\r\n', 'output': ['3258\r\n']}, {'input': 'hhwhhwhhhwhwwhhwwwhwhhhwhwwwhhwhwhhhhhhwhwhwwwhhwwwhhwhhhhwhwwhwhwwwwhhwwhwhwwwhhhwwhwhwhhwwwhwhhhwwwhwhw\r\n', 'output': ['10856\r\n']}, {'input': 'cnrkvxbljhitbvoysdpghhhnymktvburpvxybnvugkzudmnmpuhevzyjpbtraaepszhhssmcozkgbjayztrvqwdfmjlhtvarkkdsbnjrabqexpfjozmjzfbmdsihovoxmmtjgtfyaisllysnekdxozhdwu\r\n', 'output': ['12399\r\n']}, {'input': 'qasiyhdivaiyyhdqiqsvqhtqsetxqvaeqatxesxehisyqiivhvayaxvsxhsydiesaxydysqhedxqhsqivvidqtsitiiveexiehsqdteahyxtsyqetahviyhqvytexethsqssxiytqhxxxdihxietsyxqhtitheyeateeyhythxhhqaad\r\n', 'output': ['17103\r\n']}, {'input': 'ggwgwwgwwkggwgwwkgwwwggwwwggkgkgwkwgkkgkwwgwkkggwggkwgwgkgwwkwkkkkwggwwkwkkkgwkwwwwwgwkwkkwkggwwgggkkwwkgkgkwgkgkwggkwgggwwkgkwgkwkkgwkkkkggwwwgkggkwwgkwkgwgggkggkkkwwwwwkkgkwggwgkwwwwggwwgkkggwkkwkkgkwggggggkkwkkgkkkwkwwkwggwkkwggggwg\r\n', 'output': ['41166\r\n']}, {'input': 'tmoqyzoikohtgkybnwjizgjypzycmtstmsizrqrmczmqmpewxiwlqzcaufxkchqyjegktxihlksisbgogpyxkltioovelwaqcbebgcyygxsshsirkwvtsvhpqtbomueaszkrlixueyeiccvfiuoogomjlhjkacnxtimkprmjttpmeaminvmcqagrpjighsvaosojymcjoyopsvkrphzbnckcvvckicmjwpvawjuzkofnuvcahwhzjpfngwyobiufivsjnekjcloobvzawrvosnkvalmr\r\n', 'output': ['42165\r\n']}, {'input': 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrbrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\r\n', 'output': ['2214420\r\n']}, {'input': 'zzzzooozzzoozozoozzzzzzozooozoozoozzozzozoooozzzzzzoooozzozooozoozzzozozoooooozzzozozooooozozozozzooozozzooozzzzozozoozoozzzozooozzzzoozzzzozzzzoooozozozozozzoooozzzooozzoooooooozozzozozooozzzooooozozooozozzozozoozzozzzzooozzoozozozzozozoozozzzoozozoooozzooozozooooozzzzzoozoozzzozzzoozzoozozzooozzzzzzoozzozzoozzzoozozzooozoozzzozooozozzoozoozozzzzzoozoozzzooooozooooooozooooozzoozoozzzooooozoozozozozzzoozzzzzoozzzzzzooooooozzzzozzozzo\r\n', 'output': ['190205\r\n']}]


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

    static class TaskC {
        long[][] dp;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            long y = in.nextLong() - 2000;
            int m = in.nextInt();

            final String noSolution = "The times have changed";

            boolean[][] graph = new boolean[n][n];
            for (int i = 0; i < m; ++i) {
                int x = in.nextInt() - 1, t = in.nextInt() - 1;
                graph[x][t] = true;
            }

            boolean[][] accesible = new boolean[n][n];
            for (int i = 0; i < n; ++i) {
                dfs(graph, accesible[i], i);
            }

            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (i != j && accesible[i][j] && accesible[j][i]) {
                        out.println(noSolution);
                        return;
                    }
                }
            }

            int[] g = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (accesible[i][j])
                        g[i] |= 1 << j;
                }
            }

            dp = new long[n + 1][1 << n];
            int[] pos = new int[n];
            Arrays.fill(pos, -1);

            if (count(pos, g) < y) {
                out.println(noSolution);
                return;
            }

            int[] fans = new int[n];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (pos[j] != -1) continue;

                    pos[j] = i;
                    long x = count(pos, g);
                    if (x < y) {
                        y -= x;
                    } else {
                        fans[i] = j;
                        break;
                    }
                    pos[j] = -1;
                }
            }

            for (int i = 0; i < n; ++i)
                out.print((fans[i] + 1) + " ");
            out.println();
        }

        private void dfs(boolean[][] graph, boolean[] accesible, int node) {
            accesible[node] = true;
            for (int i = 0; i < graph.length; ++i) {
                if (graph[node][i] && !accesible[i]) {
                    dfs(graph, accesible, i);
                }
            }
        }

        private long count(int[] pos, int[] g) {
            int n = pos.length;
            int used = 0;
            for (int i = 0; i < n; ++i) {
                if (pos[i] != -1)
                    used |= 1 << pos[i];
            }
            for (long[] p : dp) {
                Arrays.fill(p, 0);
            }
            dp[0][0] = 1;
            for (int i = 0; i < n; ++i) {
                for (int conf = 0; conf < 1 << n; ++conf) {
                    if (dp[i][conf] == 0) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((conf & g[j]) != 0) continue;
                        if ((pos[i] == -1 && (used & (1 << j)) == 0) ||
                                pos[i] == j) {
                            dp[i + 1][conf | (1 << j)] += dp[i][conf];
                        }
                    }
                }
            }
            return dp[n][(1 << n) - 1];
        }

    }

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

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

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

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

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

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

    }
}


import java.util.Scanner;

public class frames {
public static void main(String args[]){
	Scanner s = new Scanner(System.in);
	int n = s.nextInt(),m=s.nextInt(),a=s.nextInt(),b=s.nextInt();
	if(a<=m&&b<=m){
		System.out.println(1);
	}
	else if(m==1||a==b){
		System.out.println(1);
	}
	else if(b-a<m&&(b/m-1==a/m)&&b%m==0){

	System.out.println(1);
	}
	else if(b-a<m&&(b/m==a/m)&&a%m!=0){

		System.out.println(1);
	}
	else if(a%m==1&&n==b){
		System.out.println(1);
	}
	else if (a%m==1&&b%m==0){
		System.out.println(1);
	}
	else if (a%m!=1&&b%m==0){
		System.out.println(2);
	}
	else if (a%m==1&&b%m!=0){
		System.out.println(2);
	}
	else if (a%m!=1&&b==n||(a%m==0&&(b%m==m-1))){

		System.out.println(2);
	}
	else if (a%m-b%m==1){
		System.out.println(2);
	}
	else if(a%m==0&&b%m!=0&&a/m==b/m){

		System.out.println(2);
	}
	else if(a%m!=0&&b%m!=0&&a/m==b/m-1){
		System.out.println(2);

	}

	else
		System.out.println(3);

}
}


n, x, y = input().split()

n=int(n)
x=int(x)
y=int(y)

a = y-n+1
if a<=0:
    print(-1)
else:
    if a**2 + n - 1 >= x:
        print(a)
        for i in range(n-1):
            print(1)
    else:
        print(-1)


from math import *
n,vb,vs,d,xu,yu = *list(map(int,input().split())), list(map(int,input().split())), *list(map(int,input().split()))
print( min([  ( d[i]/vb+hypot(xu-d[i],yu)/vs, hypot(xu-d[i],yu), i+1)  for i in range(1,len(d))])[2])


n = input()
p = map(int, raw_input().split())
cost = map(int, raw_input().split())

balance = 0
quantity = [0] * 5
for b in p:
      balance += b
      while balance >= cost[0]:
            for j in range(4, -1, -1):
                  if balance >= cost[j]:
                        quantity[j] += balance // cost[j]
                        balance %= cost[j]
                        break
print ' '.join(str(x) for x in quantity)
print balance


#1 1 1 1
#1 1 1 2
#1 1 2 3
#1 2 3 3
#2 3 3 3
#3 3 3 3

def checkIfAllSame(l, r):
  for n in l:
    if n != r:
      return False

  return True

nk = raw_input()
n = int(nk.split()[0].strip())
k = int(nk.split()[1].strip())

ranksraw = raw_input().split()
ranksint = [int(x) for x in ranksraw]

round = 0

while not checkIfAllSame(ranksint, k):

  round = round + 1

  mp = {}

  for i in reversed(range(len(ranksint))):
    if ranksint[i] in mp:
      pass
    elif ranksint[i] == k:
      pass
    else:
      mp[ranksint[i]] = 1
      ranksint[i] = ranksint[i] + 1

print round


import math
n = int(input())
front = dict()
back = dict()
for i in range(n):
    a, b = map(int,input().split())
    if a in front:
        front[a] += 1
    else:
        front[a] = 1

    if b != a:
       if b in back:
          back[b] += 1
       else:
          back[b] = 1

ans = -1
m = dict()
for key, value in front.items():
    if value >= n/2:
        ans = 0
        break
    elif key in back and front[key] + back[key] >= n/2:
        m[key] = math.ceil(n/2) - front[key]

else:
    if len(m) > 0:
        ans = min(sorted(m.values()))
    else:
        for key, value in back.items():
            if value >= n/2:
                ans = math.ceil(n/2)
                break
        else:
            ans = -1
print(ans)


a=int(input())
b=list(map(int,input().split()))
d,e=map(int,input().split())
k=int(0)
x=d+1
while x<=e:
    k=k+b[x-2]
    x=x+1
print(k)


n = input()
a = xrange(n)
k,j = 1,0
for i in xrange(n-1):
    print a[(k+j)%n]+1,
    j += 1
    k += j


n = int(input())

mod = 10**9 +7

def power_2_k(k):
    if k == 0:
        return 1
    if k % 2 == 0:
        lower = power_2_k(k // 2)
        return (lower * lower) % mod
    else:
        k -= 1
        lower = power_2_k(k // 2)
        return (((lower * lower) % mod) * 2) % mod

p = power_2_k(n)
print((p * (p + 1) // 2) % mod)


# prob B

n = input()
seq = raw_input()

seq = [int(i) for i in seq.split()]
seq.sort()

tot = 0
right_seq = range(1, n+1)
for num in seq:
    if num in right_seq:
        right_seq.remove(num)
    else:
        tot += 1

print tot


forwardStations = input()
firstStations = input()
lastStation = input()

# function that checks if the order exists
def get_direction(stations):

    if firstStations in stations:
        # csearching for index
        indexOfFirsChar = stations.index(firstStations)
        # dindex of the last element
        indexOfLastChar = indexOfFirsChar + len(firstStations) - 1
        # if the last sequrnce seen by the boy is in the second part of the string
        # returns True
        if lastStation in stations[indexOfLastChar + 1:]:
            return True
    # otherwise it is false
    return False

# functions call
forward = get_direction(forwardStations)
backward = get_direction(forwardStations[::-1])

# print the result

if forward and backward:
    print('both')
elif forward:
    print('forward')
elif backward:
    print('backward')
else:
    print('fantasy')

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


n = int(input())
a = list(map(int,input().split()))

m = max(a)

#algo
days = 0
middle = False
ends = False
i=1
while i <= m:

	for j in range(len(a)):
		if a[j] is not 0:
			a[j] = a[j] - 1
	#print (a)
	if a[0] is 0 or a[len(a)-1] is 0:
		days = i
		ends= True
		break
	for j in range(1,len(a)-1):
		if a[j] == 0 and a[j-1] == 0:
			days = i
			middle = True
			break
	if middle == True or ends == True:
		break
	i+=1
print (days)


I=lambda:map(int,input().split())
n,m=I()
N=list(I())
p=set()
for i in range(m):
	x,y=I();x-=1;y-=1
	p.add((x,y)if x<y else(y,x))
r=1e9
for i in range(n):
	for j in range(i):
		for k in range(j):
			if(j,i)in p and(k,i)in p and(k,j)in p:
				r = min(r,N[i]+N[j]+N[k])
print(-1 if r>1e8 else r)


n,m = [int(_) for _ in raw_input().strip().split(' ')]

d = dict((i, []) for i in range(n))

for i in range(m):
    a,b = [int(_) for _ in raw_input().strip().split(' ')]
    d[a-1].append(b-1)
    d[b-1].append(a-1)

n = 0

while sum(1 for x in d if len(d[x]) == 1) > 0:
    n += 1
    r = [x for x in d if len(d[x]) == 1]
    for x in r:
        for y in d[x]:
            d[y].remove(x)
    for x in r:
        del d[x]

print n


n = int(input())
l = list(map(int,input().split()))
l.append(l[0])
# print(l)
m = abs(l[1]-l[0])
# print(m)
a = 1
for i in range(2,n+1):
    if(abs(l[i]-l[i-1]))<m:
        # print(abs(l[i]-l[i-1])
        m = abs(l[i]-l[i-1])
        a = i
if(a==n):
    print(a,1)
else:
    print(a,a+1)


class Piet:

    inc = [{'x':0,'y':-1},{'x':1,'y':0},{'x':0,'y':1},{'x':-1,'y':0}]

    def __init__(self):

        self.BP = {'x':0,'y':0}

        self.DP = 1

        self.CP = 0

        self.getdata()

        self.go()

    def getdata(self):

        in_line = raw_input().split()

        self.m = int(in_line[0])

        self.n = int(in_line[1])

        self.pixels = []

        for i in range(self.m):

            self.pixels.append(raw_input())

    def is_out_limit(self,x,y):

        if x >= len(self.pixels[0]) or y >= self.m or x<0 or y<0:

            return True

        else:

            return False

    def go(self):

        ans = []

        info = []

        for t in xrange(self.n):

            while True:

                if self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']):

                    break

                curr_color = self.pixels[self.BP['y']][self.BP['x']]

                new_color = self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']]

                if curr_color == new_color:

                    self.BP['x'] += Piet.inc[self.DP]['x']

                    self.BP['y'] += Piet.inc[self.DP]['y']

                else:

                    break

            while True:

                if self.is_out_limit(self.BP['x']+Piet.inc[self.CP]['x'],self.BP['y']+Piet.inc[self.CP]['y']):

                    break

                curr_color = self.pixels[self.BP['y']][self.BP['x']]

                new_color = self.pixels[self.BP['y']+Piet.inc[self.CP]['y']][self.BP['x']+Piet.inc[self.CP]['x']]

                if curr_color == new_color:

                    self.BP['x'] += Piet.inc[self.CP]['x']

                    self.BP['y'] += Piet.inc[self.CP]['y']

                else:

                    break

            if  self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']) or self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']] == '0':

                if self.DP == (self.CP + 1)%4:

                    self.CP = (self.CP + 2)%4

                else:

                    self.DP = (self.DP + 1)%4

                    self.CP = (self.DP - 1)%4

            else:

                self.BP['x'] += Piet.inc[self.DP]['x']

                self.BP['y'] += Piet.inc[self.DP]['y']

            #print(self.BP['x'],self.BP['y'],self.DP,self.CP)

            if (self.BP['x'],self.BP['y'],self.DP,self.CP) in info:

                dot = info.index( (self.BP['x'],self.BP['y'],self.DP,self.CP) )

                print ans[dot-1+(self.n-dot)%(len(ans)-dot)]

                break

            else:

                ans.append(self.pixels[self.BP['y']][self.BP['x']])

                info.append( (self.BP['x'],self.BP['y'],self.DP,self.CP) )

        else:

            print ans[-1]

def main():

    p = Piet()

if __name__ == '__main__':

    main()

# Made By Mostafa_Khaled


from sys import stdin
input = stdin.readline

inp = lambda : list(map(int,input().split()))

N = 20

def solve(mask):

    if(mask == (1 << N) - 1):return 0
    if(dp[mask] != -1):return dp[mask]

    p = 0
    for i in range(N):
        if(mask >> i & 1):
            p += count[i]

    ans = float('inf')
    for i in range(N):
        if(mask >> i & 1):continue

        addval = total[i]
        for j in range(N):
            if(mask >> j & 1 == 0 and i != j):continue
            addval -= val[i][j]

        ans = min(ans , solve(mask | (1 << i)) + addval)

    dp[mask] = ans
    return ans

def answer():

    global dp , val , total , count

    total = [0 for i in range(N)]
    val = [[0 for i in range(N)] for j in range(N)]
    count = [0 for i in range(N)]
    for i in range(n):

        for j in range(N):
            val[a[i]][j] += count[j]

        total[a[i]] += i
        count[a[i]] += 1

    dp = [-1 for i in range(1 << N)]

    ans = solve(0)
    return ans

for T in range(1):

    n = int(input())
    a = inp()

    for i in range(n):
        a[i] -= 1

    print(answer())


class Graph:
    def __init__(self, n, m):
        self.nodes = n
        self.edges = m
        self.adj = [[] for i in range(n)]
        self.color = [1 for i in range(m)]
        self.vis = [0 for i in range(n)]
        self.colors = 1

    def add_edge(self, u, v, i):
        self.adj[u].append((i, v))

    def dfs(self, u):
        self.vis[u] = 1
        for i, v in self.adj[u]:
            if self.vis[v] == 1:
                self.colors = 2
                self.color[i] = 2
            if self.vis[v] == 0:
                self.dfs(v)
        self.vis[u] = 2

    def solve(self):
        for i in range(self.nodes):
            if self.vis[i] == 0:
                self.dfs(i)
        print(self.colors)
        print(' '.join(map(str, self.color)))

n, m = map(int, input().split(' '))
graph = Graph(n, m)
for i in range(m):
    u, v = map(int, input().split(' '))
    graph.add_edge(u-1, v-1, i)
graph.solve()


import itertools
import math
import time
from builtins import input
from math import gcd as gcd
import sys
import queue
import itertools
import collections
from heapq import heappop, heappush
import random
import os
from random import randint
import decimal

# from sys import stdin, stdout
# input, print = stdin.readline, stdout.write

decimal.getcontext().prec = 18

def solve():
    n, t = map(int, input().split())

    # dp[len][kol_gorbov][vozrast?][poslednya_cifra]

    # pc_i < pc_i-1
    # dp[l][g][pg = 0][pc] += dp[l - 1][g][pg = 1][pc] + dp[l - 1][g][pg = 0][pc]
    # dp[l][g][pg = 1][pc] += 0

    # pc_i > pc_i-1
    # dp[l][g][pg = 1][pc] = dp[l - 1][g - 1][pg = 0][pc]
    # dp[l][g][pg = 0][pc] = dp[l - 1][g][pg = 0][pc]

    # answer in dp[n][t][0][1 <= i <= 4]

    dp = [[[[0 for l in range(4)] for k in range(2)] for j in range(t + 2)] for i in range(n)]

    for i in range(4):
        dp[0][0][1][i] = 1

    for l in range(1, n):
        for g in range(t + 2):
            for curr_last in range(4):
                for prev_last in range(4):
                    if curr_last == prev_last:
                        continue
                    if curr_last < prev_last:
                        dp[l][g][0][curr_last] += dp[l - 1][g][0][prev_last]
                        if g > 0 and l > 1:
                            dp[l][g][0][curr_last] += dp[l - 1][g - 1][1][prev_last]
                    else:
                        dp[l][g][1][curr_last] += dp[l - 1][g][0][prev_last] + dp[l - 1][g][1][prev_last]

    print(sum([dp[n - 1][t][0][i] for i in range(4)]))

if __name__ == '__main__':
    multi_test = 0

    if multi_test == 1:
        t = int(sys.stdin.readline())
        for _ in range(t):
            solve()
    else:
        solve()


from math import floor,ceil
n = input()
x,y = zip(*[map(int,raw_input().split()) for _ in xrange(n)])
nr,mr=min(x[:2]),max(x[:2])
for j in xrange(3,n):
    i = j-1
    dx = x[j]-x[i]
    dy = y[j]-y[i]
    t = 1.*(y[0]-y[i])*dx;
    r = t/dy+x[i] if dy else 1e9
    if t-dy*(mr-x[i])>0 and r<mr: mr=r;
    if t-dy*(nr-x[i])>0 and r>nr: nr=r;
mr = floor(mr)-ceil(nr)
print "%.0f"%(0. if mr<-1e-14 else mr+1.1)


'''
Hala Madrid!
https://www.zhihu.com/people/li-dong-hao-78-74
'''

import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def I():
    return input()
def II():
    return int(input())
def MI():
    return map(int, input().split())
def LI():
    return list(input().split())
def LII():
    return list(map(int, input().split()))
def GMI():
    return map(lambda x: int(x) - 1, input().split())

#------------------------------FastIO---------------------------------

from bisect import *
from heapq import *
from collections import *
from functools import *
from itertools import *
from time import *
from random import *
from math import log, gcd, sqrt, ceil

'''
æåæ é²æ¢recursion limit
æ³¨æè¦ç¨yield ä¸è¦ç¨return
'''
from types import GeneratorType
def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

'''
max(***), mpå¯è½ä¸ºç©º -> error
'''
class Prime:
    def prime_sieve(self, n):
        """returns a sieve of primes >= 5 and < n"""
        flag = n % 6 == 2
        sieve = bytearray((n // 3 + flag >> 3) + 1)
        for i in range(1, int(n**0.5) // 3 + 1):
            if not (sieve[i >> 3] >> (i & 7)) & 1:
                k = (3 * i + 1) | 1
                for j in range(k * k // 3, n // 3 + flag, 2 * k):
                    sieve[j >> 3] |= 1 << (j & 7)
                for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
                    sieve[j >> 3] |= 1 << (j & 7)
        return sieve

    def prime_list(self, n):
        """returns a list of primes <= n"""
        res = []
        if n > 1:
            res.append(2)
        if n > 2:
            res.append(3)
        if n > 4:
            sieve = self.prime_sieve(n + 1)
            res.extend(3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not (sieve[i >> 3] >> (i & 7)) & 1)
        return res

    def __init__(self, n) -> None:
        self.primes = self.prime_list(n)

    def dissolve(self, num):
        '''prime factor decomposition of num'''
        lst = []
        idx = -1
        for prime in self.primes:
            if prime > num:
                break

            if num % prime == 0:
                lst.append([prime, 0])
                idx += 1

            while num % prime == 0:
                lst[idx][1] += 1
                num //= prime

        if num != 1:
            lst.append([num, 1])

        return lst

    #æ±å¾å¤§çæ°å¼çåç¹çphiç¨ï¼è¿ç»åºé´è¿æ¯ç¨å¶ä»çæ¹æ³#
    def get_phi(self, num):
        res = num
        for a, b in self.dissolve(num):
            res -= res // a
        return res

pri = Prime(10 ** 5 + 10)

def solve():
    #æ¬§æéå¹#
    b, n, c = LI()
    c = int(c)
    pw = [1 for _ in range(10 ** 6 + 10)]
    phi = pri.get_phi(c)
    #print('phi', phi)
    pw_phi = [1 for _ in range(10 ** 6 + 10)]
    for i in range(1, 10 ** 6 + 10):
        pw[i] = pw[i - 1] * 10 % c
        pw_phi[i] = pw_phi[i - 1] * 10 % phi

    #(b ^ n - b ^ (n - 1)) % c = (b - 1) * (b ^ (n - 1)) % c#

    #è®¡ç®b % c#
    b2 = 0
    lb = len(b)
    idx = 0
    for i in range(lb - 1, -1, -1):
        b2 += int(b[i]) * pw[idx]
        idx += 1
        b2 %= c
    #print('b2', b2)

    #å¤æphiä¸n-1çå³ç³»#
    sphi = str(phi)
    if len(n) > len(sphi) + 1:
        flag = True
    elif len(n) < len(sphi):
        flag = False
    else:
        if int(n) - 1 >= phi:
            flag = True
        else:
            flag = False

    #è®¡ç®n % phi(c)#
    n2 = 0
    ln = len(n)
    idx = 0
    for i in range(ln - 1, -1, -1):
        n2 += int(n[i]) * pw_phi[idx]
        idx += 1
        n2 %= phi
    #print('n2', n2)

    res = (b2 - 1) % c
    n2 = (n2 - 1) % phi
    #print('res n2', res, n2)
    if not flag:
        res *= pow(b2, n2, c)
    else:
        res *= pow(b2, n2 + phi, c)
        #print('pow', pow(b2, n2 + phi, c))
    res %= c
    if res:
        print(res)
    else:
        print(c)

for _ in range(1):solve()


import sys
from array import array  # noqa: F401
from itertools import combinations
from collections import deque

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n, m, k = map(int, input().split())
chars = (
    ['}' * (m + 2)]
    + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' else c for c in input().rstrip()) + '}' for _ in range(n)]
    + ['}' * (m + 2)]
)
cbit = [[1 << (ord(c) - 97) for c in chars[i]] for i in range(n + 2)]

si, sj, ti, tj = 0, 0, 0, 0
for i in range(1, n + 1):
    for j in range(1, m + 1):
        if chars[i][j] == '{':
            si, sj = i, j
            cbit[i][j] = 0
        if chars[i][j] == '|':
            ti, tj = i, j

ans = inf = '*' * (n * m)

for comb in combinations([1 << i for i in range(26)], r=k):
    enabled = sum(comb)

    dp = [[inf] * (m + 2) for _ in range(n + 2)]
    dp[ti][tj] = ''
    dq = deque([(ti, tj, '')])
    while dq:
        i, j, s = dq.popleft()
        if dp[i][j] < s:
            continue
        for di, dj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
            if (cbit[di][dj] & enabled) != cbit[di][dj]:
                continue
            pre = chars[di][dj] if cbit[di][dj] else ''
            l = 1 if cbit[di][dj] else 0
            if (len(dp[di][dj]) > len(s) + l or len(dp[di][dj]) == len(s) + l and dp[di][dj] > pre + s):
                dp[di][dj] = pre + s
                if l:
                    dq.append((di, dj, pre + s))

    if len(ans) > len(dp[si][sj]) or len(ans) == len(dp[si][sj]) and ans > dp[si][sj]:
        ans = dp[si][sj]

print(ans if ans != inf else -1)

[{'input': '5 3 2\r\nSba\r\nccc\r\naac\r\nccc\r\nabT\r\n', 'output': ['bcccc\r\n']}, {'input': '3 4 1\r\nSxyy\r\nyxxx\r\nyyyT\r\n', 'output': ['xxxx\r\n']}, {'input': '1 3 3\r\nTyS\r\n', 'output': ['y\r\n']}, {'input': '1 4 1\r\nSxyT\r\n', 'output': ['-1\r\n']}, {'input': '1 3 3\r\nSaT\r\n', 'output': ['a\r\n']}, {'input': '3 4 1\r\nSbbT\r\naaaa\r\nabba\r\n', 'output': ['bb\r\n']}, {'input': '3 5 2\r\nSbcaT\r\nacbab\r\nacccb\r\n', 'output': ['aacccaa\r\n']}, {'input': '3 4 1\r\nSbbb\r\naaaT\r\nabbc\r\n', 'output': ['aaa\r\n']}, {'input': '3 4 2\r\nSbbb\r\naabT\r\nabbc\r\n', 'output': ['aab\r\n']}, {'input': '1 2 1\r\nST\r\n', 'output': ['\r\n']}, {'input': '4 5 3\r\nabaaa\r\nbabaT\r\nSabba\r\naaaaa\r\n', 'output': ['aaba\r\n']}, {'input': '6 6 3\r\npkhipk\r\nmlfmak\r\naqmbae\r\ndlbfSj\r\ndpbjcr\r\naTbqbm\r\n', 'output': ['cbqb\r\n']}, {'input': '1 20 3\r\nacbccbbddbffScTadffd\r\n', 'output': ['c\r\n']}, {'input': '1 30 2\r\nbmjcfldkloleiqqiTnmdjpaSckkijf\r\n', 'output': ['-1\r\n']}, {'input': '1 40 1\r\nfaSfgfTcfadcdfagfbccbffbeaaebagbfcfcgdfd\r\n', 'output': ['-1\r\n']}, {'input': '1 50 3\r\nSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaTaaaaaaaaaaa\r\n', 'output': ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n']}, {'input': '5 10 4\r\naaaaaaaaaa\r\naaaaaTaaaa\r\naaaaaaaSaa\r\naaaaaaaaaa\r\naaaaaaaaaa\r\n', 'output': ['aa\r\n']}, {'input': '5 3 4\r\naaT\r\nacc\r\nbbb\r\nbbc\r\ncSb\r\n', 'output': ['bbbc\r\n']}, {'input': '5 5 1\r\ncaTbc\r\ndccac\r\ndacda\r\naacaS\r\ncdcab\r\n', 'output': ['-1\r\n']}, {'input': '10 8 2\r\nbdcdcbfa\r\ndecffcce\r\ndTffdacb\r\neeedcdbb\r\nfdbbbcba\r\nddabfcda\r\nabdbSeed\r\nbdcdcffa\r\ncadbaffa\r\nfcccddad\r\n', 'output': ['bbbbee\r\n']}, {'input': '20 10 3\r\nebebccacdb\r\neeebccddeT\r\neadebecaac\r\nadeeeaccbc\r\nbaccccdaed\r\ndeabceabba\r\ndadbecbaaa\r\neacbbcedcb\r\naeeScdbbab\r\nbabaecaead\r\nbacdbebeae\r\naacbadbeec\r\nacddceecca\r\nacaeaebaba\r\ncdddeaaeae\r\neabddadade\r\nddddaeaeed\r\nbccbaacadd\r\ndccccbabdc\r\necdaebeccc\r\n', 'output': ['bbbcccaccaac\r\n']}, {'input': '15 10 4\r\nsejwprqjku\r\npnjsiopxft\r\nrsplgvwixq\r\nendglkchxl\r\nftihbbexgh\r\nsxtxbbavge\r\njcdkusfnmr\r\nskgsqvflia\r\nkcxmcxjpae\r\namaiwcfile\r\nnjgjSunmwd\r\nldxvahgreu\r\necmrajbjuT\r\nnaioqigols\r\npbwrmxkltj\r\n', 'output': ['aajbju\r\n']}, {'input': '15 3 4\r\nllv\r\nttT\r\nhbo\r\nogc\r\nkfe\r\ngli\r\nfbx\r\nkfp\r\nspm\r\ncxc\r\nndw\r\nSoa\r\npfh\r\nedr\r\nxmv\r\n', 'output': ['-1\r\n']}, {'input': '15 15 3\r\ncbbdccabdcbacbd\r\nbcabdcacadacdbc\r\ncbcddbbcdbddcad\r\nddcabdbbdcabbdc\r\naabadcccTcabdbb\r\ncbacaaacaabdbbd\r\ndbdcbSdabaadbdb\r\ndbbaddcdddaadbb\r\nbbddcdcbaccbbaa\r\nadadadbdbbddccc\r\ncddbbdaddcbbdcc\r\nbbaadcdbbcaacca\r\nadbdcdbbcbddbcd\r\ncdadbcccddcdbda\r\ncbcdaabdcabccbc\r\n', 'output': ['aaca\r\n']}, {'input': '20 20 2\r\nddadfcdeTaeccbedeaec\r\nacafdfdeaffdeabdcefe\r\nabbcbefcdbbbcdebafef\r\nfdafdcccbcdeeaedeffc\r\ndfdaabdefdafabaabcef\r\nfebdcabacaaaabfacbbe\r\nabfcaacadfdbfdbaaefd\r\ndacceeccddccaccdbbce\r\ncacebecabedbddfbfdad\r\ndacbfcabbebfddcedffd\r\ncfcdfacfadcfbcebebaa\r\nddfbebafaccbebeefbac\r\nebfaebacbbebdfcbcbea\r\ndfbaebcfccacfeaccaad\r\nedeedeceebcbfdbcdbbe\r\nafaacccfbdecebfdabed\r\nddbdcedacedadeccaeec\r\necbSeacbdcccbcedafef\r\ncfdbeeffbeeafccfdddb\r\ncefdbdfbabccfdaaadbf\r\n', 'output': ['-1\r\n']}, {'input': '10 10 2\r\nbaaaaaaaaa\r\nbffacffffa\r\nbggaccggga\r\nbbbSccchha\r\nbdddddccia\r\nbjddccccca\r\nbkkdddTaaa\r\nblllddblla\r\nbmmmmdbmma\r\nbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '10 20 3\r\nbaaaaaaaaaaaaaaaaaaa\r\nbfffffffacfffffffffa\r\nbgggggggaccgggggggga\r\nbbbbbbbbSccchhhhhhha\r\nbiiiiidddddcciiiiiia\r\nbjjjjjjddcccccjjjjja\r\nbkkkkkkkdddTaaaaaaaa\r\nbllllllllddbllllllla\r\nbmmmmmmmmmdbmmmmmmma\r\nbbbbbbbbbbbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '20 10 4\r\nbaaaaaaaaa\r\nbffacffffa\r\nbggaccggga\r\nbhhaccchha\r\nbiiaccccia\r\nbjjaccccca\r\nbkkakkkkka\r\nbllallllla\r\nbbbSmmmmma\r\nbnnnnnnnna\r\nbooooooooa\r\nbpppppTaaa\r\nbqqqqqbqqa\r\nbrrrrrbrra\r\nbdddddbssa\r\nbtddddbtta\r\nbuudddbuua\r\nbvvvddbvva\r\nbwwwwdbwwa\r\nbbbbbbbbbb\r\n', 'output': ['mmmno\r\n']}, {'input': '20 20 2\r\nbaaaaaaaaaaaaaaaaaaa\r\nbfffffffacfffffffffa\r\nbgggggggaccgggggggga\r\nbhhhhhhhaccchhhhhhha\r\nbiiiiiiiacccciiiiiia\r\nbjjjjjjjacccccjjjjja\r\nbkkkkkkkacccccckkkka\r\nblllllllacccccccllla\r\nbbbbbbbbSccccccccmma\r\nbddddddddddcccccccna\r\nbodddddddcccccccccca\r\nbppddddddddTaaaaaaaa\r\nbqqqdddddddbqqqqqqqa\r\nbrrrrddddddbrrrrrrra\r\nbsssssdddddbsssssssa\r\nbttttttddddbttttttta\r\nbuuuuuuudddbuuuuuuua\r\nbvvvvvvvvddbvvvvvvva\r\nbwwwwwwwwwdbwwwwwwwa\r\nbbbbbbbbbbbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '1 2 4\r\nST\r\n', 'output': ['\r\n']}, {'input': '3 3 1\r\naaa\r\naaa\r\nTSa\r\n', 'output': ['\r\n']}, {'input': '2 1 1\r\nS\r\nT\r\n', 'output': ['\r\n']}, {'input': '1 10 2\r\nbaaSaaTacb\r\n', 'output': ['aa\r\n']}, {'input': '2 1 4\r\nS\r\nT\r\n', 'output': ['\r\n']}]


def isvalid(jabberid):
   splitted=jabberid.split('@');
   if len(splitted)!=2:
      return False;

   username=splitted[0];
   for c in username:
      if not(c.isalpha() or c.isdigit() or c=='_'):
         return False;
   if len(username)<1 or len(username)>16:
      return False;
   splitted=splitted[1].split('/');
   if len(splitted)>2:
      return False;

   hostname=splitted[0];
   resource='noresource';
   if len(splitted)>1:
      resource=splitted[1];

   if len(hostname)<1 or len(hostname)>32:
      return False;
   words=hostname.split('.');
   for word in words:
      if len(word)<1 or len(word)>16:
         return False;
      for c in word:
         if not(c.isalpha() or c.isdigit() or c=='_'):
            return False;

   if len(resource)<1 or len(resource)>16:
      return False;
   for c in resource:
      if not(c.isalpha() or c.isdigit() or c=='_'):
         return False;

   return True;

jabberid=input();
if isvalid(jabberid):
   print('YES');
else:
   print('NO');

[{'input': ['mike@codeforces.com\r\n'], 'output': ['YES\r\n']}, {'input': ['john.smith@codeforces.ru/contest.icpc/12\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ri/abacaba\r\n'], 'output': ['YES\r\n']}, {'input': ['@ops\r\n'], 'output': ['NO\r\n']}, {'input': ['this-is-the-test\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@codeforces.commike@codeforces.com\r\n'], 'output': ['NO\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['w@S8/XU.5._R7fHq.@../e.WP!54Ey1L\x7f.9jv\r\n'], 'output': ['NO\r\n']}, {'input': ['lNC9D1L5U@.L!_!CcAOEEx.0z.aiW/S430sbQT\r\n'], 'output': ['NO\r\n']}, {'input': ['@/YTd.K1@lD\r\n'], 'output': ['NO\r\n']}, {'input': ['Fyi!d1l@.OesGopTnRn.81xdSb8q\x7f./MzuI\r\n'], 'output': ['NO\r\n']}, {'input': ['_TlPy65\x7fw/@.Vl@.8k\r\n'], 'output': ['NO\r\n']}, {'input': ['xpS@._s8.e0l\x7fJci/.LdiT\r\n'], 'output': ['NO\r\n']}, {'input': ['lGwo\x7f8.D2@.3\r\n'], 'output': ['NO\r\n']}, {'input': ['Ccz9T5rKZQuEerGo@6l.\r\n'], 'output': ['NO\r\n']}, {'input': ['Y@5nh@8.9P.Bx5AaY.1g.Tc_MK7.g_..0.\r\n'], 'output': ['NO\r\n']}, {'input': ['Q2/6y!SP9s\x7fG@7zIGr.Du_nR8.\r\n'], 'output': ['NO\r\n']}, {'input': ['eWfLL@gW!BEJUxF\x7fh@dghf.d4.FiYp/2.Pr7a/5O6zXdAkikjCEDrb\r\n'], 'output': ['NO\r\n']}, {'input': ['8oI/\x7fa@Q\r\n'], 'output': ['NO\r\n']}, {'input': ['J@Y9Gz550l@\x7fPqVZdQ!u\r\n'], 'output': ['NO\r\n']}, {'input': ['VTE6aTTta@DHe4xeG@6.c2R.J.O7sndWEEW.9j@.l..3Bs\r\n'], 'output': ['NO\r\n']}, {'input': ['aeo2XkK@UX.nQJN!Tg..wGN5YOi68U.oP2Yl3/\r\n'], 'output': ['NO\r\n']}, {'input': ['m13zREg8LbPr@T2.Z9@g.9u.v.A..XNH/1/tloIceXydZf3\r\n'], 'output': ['NO\r\n']}, {'input': ['4@@..f3ZT./oUGZ@\r\n'], 'output': ['NO\r\n']}, {'input': ['G.rVAxwDx@a.PVSe!KtpX4tzs/0yQGzZCPJPJoda\r\n'], 'output': ['NO\r\n']}, {'input': ['SV9T5RR425Sl0b@kzj.XT.PFWc..ho/VE7gjf\r\n'], 'output': ['NO\r\n']}, {'input': ['bgko@1../xwSj_\x7fJ\r\n'], 'output': ['NO\r\n']}, {'input': ['n5ymLC.bE@ukio.im2../.\r\n'], 'output': ['NO\r\n']}, {'input': ['zr.KB_6ZMSwI2GA5@R/4iP1ZKHpszW!YN/\r\n'], 'output': ['NO\r\n']}, {'input': ['@alK@pR\r\n'], 'output': ['NO\r\n']}, {'input': ['al_Y2I4IKp@A_N.\x7fruCw0VL/hRzJtx.S7sp/r!c.n9ffh\r\n'], 'output': ['NO\r\n']}, {'input': ['C1rE26_rTAVzLm@6@X5OGX.ibJ9./kkBEVlcU\r\n'], 'output': ['NO\r\n']}, {'input': ['feGSXP@eyUfr\x7f8.x4Re.JL.6B.r/fX_\r\n'], 'output': ['NO\r\n']}, {'input': ['Ht15T@50eo.E@.\r\n'], 'output': ['NO\r\n']}, {'input': ['k9MITs_Ar.JL2RRs4@VRq.wCuJ.6..amF.fE4.5I.6fJ7gz7\r\n'], 'output': ['NO\r\n']}, {'input': ['Mi\x7fWPE8@fc./IViqq4T4PSUuMdhH\r\n'], 'output': ['NO\r\n']}, {'input': ['pxSCmv!NbMvz2@pTQ.t!.Ntz/QEh_sl\r\n'], 'output': ['NO\r\n']}, {'input': ['s@mH@RO\x7f_/iWD\r\n'], 'output': ['NO\r\n']}, {'input': ['UP51i49wX@pvx@2LWm8w/G4M3J./9L6Szy\r\n'], 'output': ['NO\r\n']}, {'input': ['xC_5Vx8NgF..\x7fln@X1.drRTX..1vx.Xb3of@/PQYPeq@_y8!h_iF\r\n'], 'output': ['NO\r\n']}, {'input': ['qG3@LKp\r\n'], 'output': ['YES\r\n']}, {'input': ['flTq1knyb@2!Mtfss\r\n'], 'output': ['NO\r\n']}, {'input': ['/pqi7WXQPJFM4q1@hxUyUy\x7f/_pWo0n\r\n'], 'output': ['NO\r\n']}, {'input': ['zXme@.Dq.TWBs.fB.M\r\n'], 'output': ['NO\r\n']}, {'input': ['o3EaAnc3K6@h\r\n'], 'output': ['YES\r\n']}, {'input': ['G/AZdVMTzRLV4Ucm@eQ!..pq!..tRTi5.Ejkqa/HGpFYk\r\n'], 'output': ['NO\r\n']}, {'input': ['.c_V@L.1v!AFAEk7glM\x7fq.ag8Sy8@0.Qm/OLKoJpZlac\r\n'], 'output': ['NO\r\n']}, {'input': ['WKxNIM79u\x7f@I.RM\r\n'], 'output': ['NO\r\n']}, {'input': ['POTjlYcxAZsbyZPDh@sPm.z6aVaO.H1wEUhD9YvROQFUk/M_jTHS_6!\r\n'], 'output': ['NO\r\n']}, {'input': ['pbRIiuA@KZ2hVed2fMikA.@ebd.tE2Y\r\n'], 'output': ['NO\r\n']}, {'input': ['OlS_OwxYhH@im.0A7o/juNlxB\r\n'], 'output': ['YES\r\n']}, {'input': ['xkjHHDRBEFwgNP@G9TGStEs2Lu.BJge3EBXw3c9EfE\r\n'], 'output': ['YES\r\n']}, {'input': ['bK@8X7tQO.pXBHJpDewD\r\n'], 'output': ['YES\r\n']}, {'input': ['kKUXy6@0WefbXz39ywP.Q3r7uF\r\n'], 'output': ['YES\r\n']}, {'input': ['SllbRLdZ6@.T.E3x.BE2nIv.5db_.38./zgVGNjpldr\r\n'], 'output': ['NO\r\n']}, {'input': ['4lBJkY8c097oa@ZYmVbtiyyYN.gbj\r\n'], 'output': ['YES\r\n']}, {'input': ['F@JX4.SI1/0EY3XmYatfY\r\n'], 'output': ['YES\r\n']}, {'input': ['oLo01@B77Pu.9R.vtAZG0.HQSunv0J.\r\n'], 'output': ['NO\r\n']}, {'input': ['xLEctap0T@22U9W_fA/7iQeJGFu1lSgMZ\r\n'], 'output': ['YES\r\n']}, {'input': ['WYh@yUWfOQiF.gOK9k8aEa\r\n'], 'output': ['YES\r\n']}, {'input': ['BPxNVANhtEh@Oh_go.\r\n'], 'output': ['NO\r\n']}, {'input': ['mGIY@cHRNC8GlJ/2pcl3LYxpi3PaKGs\r\n'], 'output': ['YES\r\n']}, {'input': ['x6yfn7BGwqWd@.N/UXC\r\n'], 'output': ['NO\r\n']}, {'input': ['cUIr@cP.eGQC2xJXvI1X7\r\n'], 'output': ['YES\r\n']}, {'input': ['MLZ6e1vgZ4hOI@ktWk.Ro.o6C4/i8cnKHT\r\n'], 'output': ['YES\r\n']}, {'input': ['XCJIa@jFaP.Eu28YaoT9Z.Epk.Z/4TBzLWf724zE1r\r\n'], 'output': ['YES\r\n']}, {'input': ['Cz1U1xjg6iW0U@.97HoVA.YG.Qd.eI.DCXxtibi6HG.GV/0sN\r\n'], 'output': ['NO\r\n']}, {'input': ['nrKbWV@P0irxQoRxDsNvG/69WxCwCsfB\r\n'], 'output': ['YES\r\n']}, {'input': ['yI1nRv3FbuhgaI@.Y9vKe.8oc.BLi.6JfYT/tT5d36\r\n'], 'output': ['NO\r\n']}, {'input': ['IGsma3L6YTJRrXS@1g.yR3mC.c.xoCns7Wo1.9C.Oe.5ebkR/_97Ltj3\r\n'], 'output': ['YES\r\n']}, {'input': ['Uu538LDu9Bye@Gu0W0P5a.b9zA9nSaNhzB_TQ2.z/qfi5CZrH\r\n'], 'output': ['YES\r\n']}, {'input': ['bdHl525me@XzR_iO23v.YFXbnHUybbgw.i/WVEhm\r\n'], 'output': ['YES\r\n']}, {'input': ['NQsZ0K@eE8VMB.w2nYtKImB.4nUF\r\n'], 'output': ['YES\r\n']}, {'input': ['186@E.MmBaKLj.WYpt4wPZkzv93\r\n'], 'output': ['YES\r\n']}, {'input': ['hmhYxkGtWYRJFtBU@Drg3L7WKujE.lU61Ljqxv./FJ4X\r\n'], 'output': ['NO\r\n']}, {'input': ['t1RIUz9l3FA15@tOL9.rv.NjhouD.\r\n'], 'output': ['NO\r\n']}, {'input': ['_I4ytjyccT@q.WIc.Cqn\r\n'], 'output': ['YES\r\n']}, {'input': ['LwHHRYq@whOoq.e9b6i0xnoWBl7z.SGJiJe/iUij1x7\r\n'], 'output': ['YES\r\n']}, {'input': ['Yesx@9_KiJq2cBI6.\r\n'], 'output': ['NO\r\n']}, {'input': ['Zu5VFUtSbIw@ner5e\r\n'], 'output': ['YES\r\n']}, {'input': ['test@test.\r\n'], 'output': ['NO\r\n']}, {'input': ['test@.test\r\n'], 'output': ['NO\r\n']}, {'input': ['est.@test\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ru/\r\n'], 'output': ['NO\r\n']}, {'input': ['asd@asd@\r\n'], 'output': ['NO\r\n']}, {'input': ['@\r\n'], 'output': ['NO\r\n']}, {'input': ['/\r\n'], 'output': ['NO\r\n']}, {'input': ['.\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@\r\n'], 'output': ['NO\r\n']}, {'input': ['@mike\r\n'], 'output': ['NO\r\n']}, {'input': ['@mail.ru\r\n'], 'output': ['NO\r\n']}, {'input': ['test.me\r\n'], 'output': ['NO\r\n']}, {'input': ['$@ru\r\n'], 'output': ['NO\r\n']}, {'input': ['testme@o.o.o.o.o/ooooo\r\n'], 'output': ['YES\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['mail.ru/a\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@mail.ru/aaa\r\n'], 'output': ['YES\r\n']}, {'input': ['mike@mike.mike\r\n'], 'output': ['YES\r\n']}]


n = int(input())
segments = []

for _ in range(n):
    l, r = sorted(map(int, input().split()))
    segments.append([l, r])

segments.sort(key = lambda s: s[1])

pinz = []

for l, r in segments:
    if len(pinz) == 0 or l > pinz[-1]:
        pinz.append(r)

print(len(pinz))
print(*pinz)