import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;

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

    static class TaskB3 {
        public void solve(int testNumber, FastScanner in, FastPrinter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[][] a = new int[n][n];
            for (int[] e : a) Arrays.fill(e, Integer.MAX_VALUE);
            for (int i = 0; i < m; i++) {
                int from = in.nextInt() - 1;
                int to = in.nextInt() - 1;
                a[from][to] = a[to][from] = 1;
            }
            for (int i = 0; i < n; i++) {
                a[i][i] = 0;
            }
            for (int k = 0; k < n; k++) {
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (a[i][k] != Integer.MAX_VALUE && a[k][j] != Integer.MAX_VALUE) {
                            a[i][j] = Math.min(a[i][j], a[i][k] + a[k][j]);
                        }
                    }
                }
            }
            int s = in.nextInt();
            int b = in.nextInt();
            int k = in.nextInt();
            TaskB3.Ship[] ships = new TaskB3.Ship[s];
            for (int i = 0; i < s; i++) {
                ships[i] = new TaskB3.Ship(in.nextInt() - 1, in.nextInt(), in.nextInt(), in.nextInt());
            }
            TaskB3.Base[] bases = new TaskB3.Base[b];
            for (int i = 0; i < b; i++) {
                bases[i] = new TaskB3.Base(in.nextInt() - 1, in.nextInt(), in.nextInt());
            }
            TaskB3.DinicGraph g = new TaskB3.DinicGraph(s + 2);
            long INF = 1L << 60;
            long MAX = 1L << 40;
            int src = s;
            int tar = src + 1;
            for (int i = 0; i < s; i++) {
                TaskB3.Ship e = ships[i];
                int best = Integer.MIN_VALUE;
                for (int j = 0; j < b; j++) {
                    TaskB3.Base f = bases[j];
                    if (f.d > e.a || e.f < a[e.x][f.x]) continue;
                    best = Math.max(best, f.g);
                }
                if (best == Integer.MIN_VALUE) {
                    g.addEdge(i, tar, INF);
                    g.addEdge(src, i, MAX);
                } else {
                    g.addEdge(i, tar, MAX + (e.p - best));
                    g.addEdge(src, i, MAX);
                }
            }
            for (int i = 0; i < k; i++) {
                int s1 = in.nextInt() - 1;
                int s2 = in.nextInt() - 1;
                g.addEdge(s1, s2, INF);
            }
            long have = g.getMaxFlow(src, tar);
            out.println(-(have - MAX * s));
        }

        public static class DinicGraph {
            public ArrayList<TaskB3.DinicGraph.Edge>[] edges;
            int[] cur;
            int[] q;
            public int[] d;
            int n;

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

            public TaskB3.DinicGraph.Edge addEdge(int from, int to, long cap) {
                TaskB3.DinicGraph.Edge e1 = new TaskB3.DinicGraph.Edge(from, to, 0, cap);
                TaskB3.DinicGraph.Edge e2 = new TaskB3.DinicGraph.Edge(to, from, 0, 0);
                e1.rev = e2;
                e2.rev = e1;
                edges[from].add(e1);
                edges[to].add(e2);
                return e1;
            }

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

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

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

            public static class Edge {
                public int from;
                public int to;
                public long flow;
                public long cap;
                public TaskB3.DinicGraph.Edge rev;

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

            }

        }

        static class Ship {
            int x;
            int a;
            int f;
            int p;

            public Ship(int x, int a, int f, int p) {
                this.x = x;
                this.a = a;
                this.f = f;
                this.p = p;
            }

        }

        static class Base {
            int x;
            int d;
            int g;

            public Base(int x, int d, int g) {
                this.x = x;
                this.d = d;
                this.g = g;
            }

        }

    }

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

        public FastPrinter(Writer out) {
            super(out);
        }

    }

    static class FastScanner extends BufferedReader {
        public FastScanner(InputStream is) {
            super(new InputStreamReader(is));
        }

        public int read() {
            try {
                int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
                return ret;
            } catch (IOException e) {
                throw new InputMismatchException();
            }
        }

        static boolean isWhiteSpace(int c) {
            return c >= 0 && c <= 32;
        }

        public int nextInt() {
            int c = read();
            while (isWhiteSpace(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int ret = 0;
            while (c >= 0 && !isWhiteSpace(c)) {
                if (c < '0' || c > '9') {
                    throw new NumberFormatException("digit expected " + (char) c
                            + " found");
                }
                ret = ret * 10 + c - '0';
                c = read();
            }
            return ret * sgn;
        }

        public String readLine() {
            try {
                return super.readLine();
            } catch (IOException e) {
                return null;
            }
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;

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

    static class TaskB3 {
        public void solve(int testNumber, FastScanner in, FastPrinter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[][] a = new int[n][n];
            for (int[] e : a) Arrays.fill(e, Integer.MAX_VALUE);
            for (int i = 0; i < m; i++) {
                int from = in.nextInt() - 1;
                int to = in.nextInt() - 1;
                a[from][to] = a[to][from] = 1;
            }
            for (int i = 0; i < n; i++) {
                a[i][i] = 0;
            }
            for (int k = 0; k < n; k++) {
                for (int i = 0; i < n; i++) {
                    for (int j = 0; j < n; j++) {
                        if (a[i][k] != Integer.MAX_VALUE && a[k][j] != Integer.MAX_VALUE) {
                            a[i][j] = Math.min(a[i][j], a[i][k] + a[k][j]);
                        }
                    }
                }
            }
            int s = in.nextInt();
            int b = in.nextInt();
            int k = in.nextInt();
            TaskB3.Ship[] ships = new TaskB3.Ship[s];
            for (int i = 0; i < s; i++) {
                ships[i] = new TaskB3.Ship(in.nextInt() - 1, in.nextInt(), in.nextInt(), in.nextInt());
            }
            TaskB3.Base[] bases = new TaskB3.Base[b];
            for (int i = 0; i < b; i++) {
                bases[i] = new TaskB3.Base(in.nextInt() - 1, in.nextInt(), in.nextInt());
            }
            TaskB3.DinicGraph g = new TaskB3.DinicGraph(s + 2);
            long INF = 1L << 60;
            long MAX = 1L << 40;
            int src = s;
            int tar = src + 1;
            for (int i = 0; i < s; i++) {
                TaskB3.Ship e = ships[i];
                int best = Integer.MIN_VALUE;
                for (int j = 0; j < b; j++) {
                    TaskB3.Base f = bases[j];
                    if (f.d > e.a || e.f < a[e.x][f.x]) continue;
                    best = Math.max(best, f.g);
                }
                if (best == Integer.MIN_VALUE) {
                    g.addEdge(i, tar, INF);
                    g.addEdge(src, i, MAX);
                } else {
                    g.addEdge(i, tar, MAX + (e.p - best));
                    g.addEdge(src, i, MAX);
                }
            }
            for (int i = 0; i < k; i++) {
                int s1 = in.nextInt() - 1;
                int s2 = in.nextInt() - 1;
                g.addEdge(s1, s2, INF);
            }
            long have = g.getMaxFlow(src, tar);
            out.println(-(have - MAX * s));
        }

        public static class DinicGraph {
            public ArrayList<TaskB3.DinicGraph.Edge>[] edges;
            int[] cur;
            int[] q;
            public int[] d;
            int n;

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

            public TaskB3.DinicGraph.Edge addEdge(int from, int to, long cap) {
                TaskB3.DinicGraph.Edge e1 = new TaskB3.DinicGraph.Edge(from, to, 0, cap);
                TaskB3.DinicGraph.Edge e2 = new TaskB3.DinicGraph.Edge(to, from, 0, 0);
                e1.rev = e2;
                e2.rev = e1;
                edges[from].add(e1);
                edges[to].add(e2);
                return e1;
            }

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

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

            public long getMaxFlow(int source, int target) {
                long flow = 0;
                while (bfs(source, target)) {
                    Arrays.fill(cur, 0);
                    while (true) {
                        long add = dfs(source, target, Long.MAX_VALUE);
                        if (add == 0) {
                            break;
                        }
                        flow += add;
                    }
                }
                return flow;
            }

            public static class Edge {
                public int from;
                public int to;
                public long flow;
                public long cap;
                public TaskB3.DinicGraph.Edge rev;

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

            }

        }

        static class Ship {
            int x;
            int a;
            int f;
            int p;

            public Ship(int x, int a, int f, int p) {
                this.x = x;
                this.a = a;
                this.f = f;
                this.p = p;
            }

        }

        static class Base {
            int x;
            int d;
            int g;

            public Base(int x, int d, int g) {
                this.x = x;
                this.d = d;
                this.g = g;
            }

        }

    }

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

        public FastPrinter(Writer out) {
            super(out);
        }

    }

    static class FastScanner extends BufferedReader {
        public FastScanner(InputStream is) {
            super(new InputStreamReader(is));
        }

        public int read() {
            try {
                int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
                return ret;
            } catch (IOException e) {
                throw new InputMismatchException();
            }
        }

        static boolean isWhiteSpace(int c) {
            return c >= 0 && c <= 32;
        }

        public int nextInt() {
            int c = read();
            while (isWhiteSpace(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int ret = 0;
            while (c >= 0 && !isWhiteSpace(c)) {
                if (c < '0' || c > '9') {
                    throw new NumberFormatException("digit expected " + (char) c
                            + " found");
                }
                ret = ret * 10 + c - '0';
                c = read();
            }
            return ret * sgn;
        }

        public String readLine() {
            try {
                return super.readLine();
            } catch (IOException e) {
                return null;
            }
        }

    }
}


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

public class  Main{
	static class base implements Comparable<base>{
		int d,g;
		base(int dd,int gg){
			d=dd;g=gg;
		}
		@Override
		public int compareTo(base o) {
			return d-o.d;
		}

	}
	static int inf=(int)1e9+7;
	static int[][]adj;

	static int V, s, t;static long res[][];			//input
	static ArrayList<Integer>[] adjList;	//input
	static int[] ptr, dist;

	static long dinic()						//O(V^2E)
	{
		long mf = 0;
		while(bfs())
		{
			ptr = new int[V];
			long f;
			while((f = dfs(s, inf)) != 0)
				mf += f;
		}
		return mf;
	}

	static boolean bfs()
	{
		dist = new int[V];
		Arrays.fill(dist, -1);
		dist[s] = 0;
		Queue<Integer> q = new LinkedList<Integer>();
		q.add(s);
		while(!q.isEmpty())
		{
			int u = q.remove();
			if(u == t)
				return true;
			for(int v: adjList[u])
				if(dist[v] == -1 && res[u][v] > 0)
				{
					dist[v] = dist[u] + 1;
					q.add(v);
				}
		}
		return false;
	}

	static long dfs(int u, long flow)
	{
		if(u == t)
			return flow;
		for(int i = ptr[u]; i < adjList[u].size(); i = ++ptr[u])
		{
			int v = adjList[u].get(i);
			if(dist[v] == dist[u] + 1 && res[u][v] > 0)
			{
				long f = dfs(v, Math.min(flow, res[u][v]));
				if(f > 0)
				{
					res[u][v] -= f;
					res[v][u] += f;
					return f;
				}
			}
		}
		return 0;

	}
	public static void main(String[] args) throws Exception{
		MScanner sc=new MScanner(System.in);
		PrintWriter pw=new PrintWriter(System.out);
		int n=sc.nextInt(),m=sc.nextInt();
		adj=new int[n][n];
		for(int []i:adj)Arrays.fill(i, inf);
		for(int i=0;i<m;i++) {
			int x=sc.nextInt()-1,y=sc.nextInt()-1;
			adj[x][y]=1;
			adj[y][x]=1;
		}
		for(int i=0;i<n;i++)adj[i][i]=0;
		for(int k=0;k<n;k++) {
			for(int i=0;i<n;i++) {
				for(int j=0;j<n;j++) {
					adj[i][j]=Math.min(adj[i][j], adj[i][k]+adj[k][j]);
				}
			}
		}
		int ss=sc.nextInt(),b=sc.nextInt(),k=sc.nextInt();
		int[][]spaceShips=new int[ss][5];
		for(int i=0;i<ss;i++) {
			for(int j=0;j<4;j++) {
				spaceShips[i][j]=sc.nextInt();
			}
			spaceShips[i][0]--;
			spaceShips[i][4]=i;
		}
		Arrays.sort(spaceShips,(x,y) -> x[1]-y[1]);

		TreeSet<base>[]planets=new TreeSet[n];
		for(int i=0;i<n;i++) {
			planets[i]=new TreeSet<base>();
		}
		for(int i=0;i<b;i++) {
			planets[sc.nextInt()-1].add(new base(sc.nextInt(), sc.nextInt()));
		}

		long[]maxProfit=new long[ss];
		int[]maxSoFar=new int[n];
		Arrays.fill(maxSoFar, -inf);
		for(int i=0;i<ss;i++) {
			int curAtt=spaceShips[i][1],curFuel=spaceShips[i][2],curPrice=spaceShips[i][3],curLoc=spaceShips[i][0];
			int profit=-inf;
			for(int p=0;p<n;p++) {
				int dist=adj[curLoc][p];
				if(dist>curFuel)continue;

				while(!planets[p].isEmpty() && curAtt>=planets[p].first().d) {
					maxSoFar[p]=Math.max(maxSoFar[p], planets[p].pollFirst().g);
				}
				profit=Math.max(profit, maxSoFar[p]);

			}
			maxProfit[spaceShips[i][4]]=profit-curPrice;
		}
		long ans=0;

		HashSet<Integer>dep=new HashSet<Integer>();
		int[][]depend=new int[k][2];
		for(int i=0;i<k;i++) {
			int x=sc.nextInt()-1,y=sc.nextInt()-1;
			dep.add(x);dep.add(y);
			depend[i][0]=x;depend[i][1]=y;
		}

		V=dep.size()+2;
		res=new long[V][V];
		adjList=new ArrayList[V];
		for(int i=0;i<V;i++)adjList[i]=new ArrayList<Integer>();

		t=V-1;
		HashMap<Integer, Integer>ids=new HashMap<>();
		int id=1;

		for(int i=0;i<k;i++) {
			int x=depend[i][0],y=depend[i][1];
			int idx,idy;
			if(ids.containsKey(x)) {
				idx=ids.get(x);
			}
			else {
				idx=id++;
			}
			if(ids.containsKey(y)) {
				idy=ids.get(y);
			}
			else {
				idy=id++;
			}

			adjList[idx].add(idy);
			adjList[idy].add(idx);
			res[idx][idy]=inf;

			ids.put(x, idx);ids.put(y, idy);

		}

		for(int i=0;i<ss;i++) {
			if(dep.contains(i)) {
				if(maxProfit[i]>=0) {
					int curID=ids.get(i);
					adjList[s].add(curID);
					adjList[curID].add(s);
					res[s][curID]=maxProfit[i];
				}
				else {
					int curID=ids.get(i);
					adjList[t].add(curID);
					adjList[curID].add(t);
					res[curID][t]=-maxProfit[i];
				}
			}
			ans+=Math.max(0, maxProfit[i]);
		}
		pw.println(ans-dinic());
		pw.flush();
	}
	static class MScanner {
		StringTokenizer st;
		BufferedReader br;
		public MScanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public MScanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public int[] intArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public long[] longArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public int[] intSortedArr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		public long[] longSortedArr(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        shuffle(in);
	        Arrays.sort(in);
	        return in;
		}
		static void shuffle(int[]in) {
			for(int i=0;i<in.length;i++) {
				int idx=(int)(Math.random()*in.length);
				int tmp=in[i];
				in[i]=in[idx];
				in[idx]=tmp;
			}
		}
		static void shuffle(long[]in) {
			for(int i=0;i<in.length;i++) {
				int idx=(int)(Math.random()*in.length);
				long tmp=in[i];
				in[i]=in[idx];
				in[idx]=tmp;
			}
		}
		public Integer[] IntegerArr(int n) throws IOException {
	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public Long[] LongArr(int n) throws IOException {
	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

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

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
	static void addX(int[]in,int x) {
		for(int i=0;i<in.length;i++)in[i]+=x;
	}
	static void addX(long[]in,int x) {
		for(int i=0;i<in.length;i++)in[i]+=x;
	}
}


/**
 * Created by IntelliJ IDEA.
 * User: aircube
 * Date: 31.03.11
 * Time: 23:46
 * To change this template use File | Settings | File Templates.
 */

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;
import java.util.Vector;

public class taskD {

    class Card {
        int value ;
        int suite ;

        Card(String input) {
            this.value = getValue(input);
            this.suite = getSuite(input);
        }

        Card(int value, int suite) {
            this.value = value;
            this.suite = suite;
        }

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

            Card card = (Card) o;

            if (suite != card.suite) return false;
            if (value != card.value) return false;

            return true;
        }

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

        @Override
        public String toString() {
            return "Card{" +
                    "value=" + value +
                    ", suite=" + suite +
                    '}';
        }
    }
    int getValue(String input) {
        char ch = input.charAt(0);
        char ch0 = input.charAt(1);
        if (ch >= '2' && ch <= '9') return ch - '0';
        //«T», «J», «Q», «K» и «A»
        if (ch == 'T') return 10;
        if (ch == 'J' && (ch0 == 'C' || ch0 == 'D' || ch0 == 'H' || ch0 == 'S')) return 11;
        if (ch == 'Q') return 12;
        if (ch == 'K') return 13;
        if (ch == 'A') return 14;
        return 15;
    }
    int getSuite(String input) {
        char ch = input.charAt(0);
        char ch0 = input.charAt(1);
        //(ch0 == 'C' || ch0 == 'D' || ch0 == 'H' || ch0 == 'S')) return 11;
        if (ch0 == 'C') return 0;
        if (ch0 == 'D') return 1;
        if (ch0 == 'H') return 2;
        if (ch0 == 'S') return 3;
        if (ch0 == '1') return 4;
        if (ch0 == '2') return 5;
        throw new RuntimeException();
    }
    String cardToString(Card card) {
        String ans = "";
        if (card.value >= 2 && card.value <= 9) {
            ans += Integer.toString(card.value);
        } else if (card.value == 10) {
            ans += "T";
        } else if (card.value == 11) {
            ans += "J";
        } else if (card.value == 12) {
            ans += "Q";
        } else if (card.value == 13) {
            ans += "K";
        } else if (card.value == 14) {
            ans += "A";
        } else {
            throw new RuntimeException();
        }
        ans += toSuite(card.suite);
        return ans ;
    }

    private String toSuite(int suite) {
        char s[] = new char[] {'C', 'D', 'H', 'S'};
        return Character.toString(s[suite]);
    }

    void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        Card table[][] = new Card[n][m];
        Set<Card> set = new HashSet<Card> ();

        Vector<Integer> x = new Vector<Integer> () ;
        Vector<Integer> y = new Vector<Integer>() ;
        Vector<Integer> num = new Vector<Integer> () ;
        for (int i = 0; i < n; ++i) {
            for (int j =0 ; j < m; ++j) {
                table[i][j] = new Card(nextToken());
                set.add(table[i][j]);
                if (table[i][j].value == 15) {
                    x.add(j);
                    y.add(i);
                    num.add(table[i][j].suite == 4 ? 1 : 2);
                }
            }
        }

        if (x.size() == 0) {
            int a[] = new int[4];
            if (goodTable(table, a)) {
                out.println("Solution exists.");
                out.println("There are no jokers.");
                out.println("Put the first square to (" + (a[1] + 1) + ", " + (a[0] + 1) + ").");
                out.println("Put the second square to ("+(a[3]+1)+", "+(a[2]+1)+").");
            } else {
                out.println("No solution.");
            }
        } else {
            if (x.size() == 1) {
                int a[] = new int[4];
                for (int val = 2; val <= 14; ++val) {
                    for (int suite = 0; suite <= 4; ++suite) {
                        if (!set.contains(new Card(val, suite))) {
                            table[y.get(0)][x.get(0)] = new Card(val, suite);
                            if (goodTable(table, a)) {
                                out.println("Solution exists.");
                                out.println("Replace J" + (num.get(0)) + " with " + cardToString(new Card(val, suite)) + ".");
                                out.println("Put the first square to (" + (a[1] + 1) + ", " + (a[0] + 1) + ").");
                                out.println("Put the second square to ("+(a[3]+1)+", "+(a[2]+1)+").");
                                return;
                            }
                        }
                    }
                }
                out.print("No solution.");
            } else {
                int a[] = new int[4];
                for (int val = 2; val <= 14; ++val) {
                    for (int suite = 0; suite <= 3; ++suite) {
                        if (!set.contains(new Card(val, suite))) {
                            table[y.get(0)][x.get(0)] = new Card(val, suite);
                            for (int val0 = 2; val0 <= 14; val0 ++) {
                                for (int suite0 = 0; suite0 <= 3; ++suite0) {
                                    if (!set.contains(new Card(val0, suite0)) && !(new Card(val0, suite0)).equals(table[y.get(0)][x.get(0)])){
                                        table[y.get(1)][x.get(1)] = new Card(val0, suite0);
                                        if (goodTable(table, a)) {
                                            out.println("Solution exists.");
                                            Card card0 = table[y.get(0)][x.get(0)];
                                            Card card1 = table[y.get(1)][x.get(1)];
                                            //Replace J1 with x and J2 with y.
                                            out.println("Replace J1 with " + (cardToString((num.get(0)==1?card0:card1))) + " and J2 with " + (cardToString((num.get(0)==2?card0:card1))) + ".");
                                            out.println("Put the first square to (" + (a[1] + 1) + ", " + (a[0] + 1) + ").");
                                            out.println("Put the second square to ("+(a[3]+1)+", "+(a[2]+1)+").");
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                out.print("No solution.");
            }
        }

    }
    boolean goodTable(Card[][] table, int [] positions) {
        boolean ok = false;
        for (int Y = 0; Y < table.length - 2; ++Y) {
            for (int X = 0; X < table[0].length - 2; ++X) {
                for(int U = Y ; U < table.length - 2 ; ++U)
                    for (int V = X ; V < table[0].length - 2; ++V) {
                        if (U - Y < 3 && V - X < 3) continue;
                        if (goodSquare(X, Y, table) && goodSquare(V, U, table)) {
                            positions[0] = X;
                            positions[1] = Y;
                            positions[2] = V;
                            positions[3] = U;
                            return true;
                        }
                    }
            }
        }
        return false;
    }
    boolean goodSquare(int X, int Y, Card[][] table) {
        Set<Integer> suites = new HashSet<Integer> () ;
        Set<Integer> values = new HashSet<Integer> () ;
        for (int dx = 0; dx < 3; ++dx) {
            for (int dy = 0; dy < 3; ++dy) {
                suites.add(table[Y + dy][X + dx].suite);
                values.add(table[Y + dy][X + dx].value);
            }
        }
        return suites.size() == 1 || values.size() == 9;
    }
    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;

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

    void run() throws IOException {
        /*out = new PrintWriter("input.txt");
        out.println(100000);
        for (int i =0 ; i < 100000; ++i) {
            out.print("0 ");
        }
        out.close();*/
        br = new BufferedReader(new InputStreamReader(System.in));
        //br = new BufferedReader(new FileReader("input.txt"));
        st = null;
        out = new PrintWriter(System.out);
        solve();
        br.close();
        out.close();
    }

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

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

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

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


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

public class D {
    static Point Fst;
    static Point Snd;

    public static int rank(char x) {
        if (Character.isDigit(x))
            return x - '0';
        switch (x) {
        case 'A':
            return 0;
        case 'K':
            return 1;
        case 'Q':
            return 10;
        case 'J':
            return 11;
        default:
            return 12;
        }
    }

    public static int suite(char x) {
        if (Character.isDigit(x))
            return x - '0';
        switch (x) {
        case 'S':
            return 0;
        case 'C':
            return 1;
        case 'H':
            return 2;
        default:
            return 3;
        }
    }

    public static boolean Can(Card[][] A) {
        int n = A.length;
        int m = A[0].length;
        boolean[][] V = new boolean[n][m];
        for (int i = 0; i + 3 <= n; i++)
            for (int j = 0; j + 3 <= m; j++) {
                int[] S = new int[4];
                int[] R = new int[13];
                int s = 0;
                int r = 0;
                for (int k = 0; k < 3; k++)
                    for (int l = 0; l < 3; l++) {
                        S[A[i + k][j + l].suite]++;
                        R[A[i + k][j + l].rank]++;
                    }
                for (int k = 0; k < 4; k++)
                    if (S[k] != 0)
                        s++;
                for (int k = 0; k < 13; k++)
                    if (R[k] > 1)
                        r++;
                V[i][j] = (s == 1) | (r == 0);
            }
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                for (int k = i; k < n; k++)
                    for (int l = j; l < n; l++) {
                        if (k < i + 3 && l < j + 3)
                            continue;
                        if (V[i][j] && V[k][l]) {
                            Fst = new Point(i + 1, j + 1);
                            Snd = new Point(k + 1, l + 1);
                            return true;
                        }
                    }
            }
        return false;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        char[] C = new char[13];
        C[0] = 'A';
        C[1] = 'K';
        C[10] = 'Q';
        C[11] = 'J';
        C[12] = 'T';
        for (int i = 2; i < 10; i++)
            C[i] = (char) (i + '0');
        char[] Su = new char[4];
        Su[0] = 'S';
        Su[1] = 'C';
        Su[2] = 'H';
        Su[3] = 'D';
        String[] S = in.readLine().split(" ");
        int n = Integer.parseInt(S[0]);
        int m = Integer.parseInt(S[1]);
        Card[][] A = new Card[n][m];
        boolean[][] Done = new boolean[4][13];
        Point[] J = new Point[2];
        int jo = 0;
        for (int i = 0; i < n; i++) {
            S = in.readLine().split(" ");
            for (int j = 0; j < m; j++) {
                A[i][j] = new Card(rank(S[j].charAt(0)), suite(S[j].charAt(1)));
                Done[A[i][j].suite][A[i][j].rank] = true;
                if (A[i][j].rank == 11) {
                    J[jo++] = new Point(i, j);
                }
            }
        }
        if (jo == 0) {
            if (Can(A)) {
                System.out.println("Solution exists.\nThere are no jokers.");
                System.out.println("Put the first square to (" + Fst.x + ", "
                        + Fst.y + ").");
                System.out.println("Put the second square to (" + Snd.x + ", "
                        + Snd.y + ").");
            } else
                System.out.println("No solution.");
        } else {
            if (jo == 1) {
                int j1 = A[J[0].x][J[0].y].suite;
                for (int i = 0; i < 4; i++)
                    for (int j = 0; j < 13; j++) {
                        if (Done[i][j])
                            continue;
                        A[J[0].x][J[0].y] = new Card(j, i);
                        if (Can(A)) {
                            System.out.println("Solution exists.");
                            System.out.println("Replace J" + j1 + " with "
                                    + C[j] + Su[i] + ".");
                            System.out.println("Put the first square to ("
                                    + Fst.x + ", " + Fst.y + ").");
                            System.out.println("Put the second square to ("
                                    + Snd.x + ", " + Snd.y + ").");
                            System.exit(0);
                        }
                    }
                System.out.println("No solution.");
            } else if (jo == 2) {
                int j1 = A[J[0].x][J[0].y].suite;
                int j2 = A[J[1].x][J[1].y].suite;
                for (int i = 0; i < 4; i++)
                    for (int j = 0; j < 13; j++)
                        for (int k = 0; k < 4; k++)
                            for (int l = 0; l < 13; l++) {
                                if (Done[i][j] || Done[k][l])
                                    continue;
                                A[J[0].x][J[0].y] = new Card(j, i);
                                A[J[1].x][J[1].y] = new Card(l, k);
                                if (Can(A)) {
                                    System.out.println("Solution exists.");
                                    System.out.println("Replace J" + j1
                                            + " with " + C[j] + Su[i] + ".");
                                    System.out.println("Replace J" + j2
                                            + " with " + C[l] + Su[k] + ".");
                                    System.out
                                            .println("Put the first square to ("
                                                    + Fst.x
                                                    + ", "
                                                    + Fst.y
                                                    + ").");
                                    System.out
                                            .println("Put the second square to ("
                                                    + Snd.x
                                                    + ", "
                                                    + Snd.y
                                                    + ").");
                                    System.exit(0);
                                }
                            }
                System.out.println("No solution.");
            }
        }
    }
}

class Card {
    int rank;
    int suite;

    public Card(int x, int y) {
        rank = x;
        suite = y;
    }
}


import java.util.*;

public class Main{

    int n,m;
    String a[][];

    public void run(){
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		m = in.nextInt();

		a = new String[n][m];
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
				a[i][j] = in.next();

		int cnt = 0;
		int i1 = -1, i2 = -1, j1 = -1, j2 = -1;
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++){
				if (a[i][j].equals("J1")){
					cnt++;
					i1 = i;j1 = j;
				}else if (a[i][j].equals("J2")){
					i2 = i;j2 = j;
					cnt++;
				}
			}

		if (cnt == 0){
			for(int i=0;i<=n-3;i++){
				for(int j=0;j<=m-3;j++){
					if (check(i, j)){
						for(int k=0;k<=n-3;k++){
							for(int l=0;l<=m-3;l++){
								if (isIn(i, j, k, l)) continue;
								if (check(k,l)){
									System.out.println("Solution exists.");
									System.out.println("There are no jokers.");
									System.out.println("Put the first square to (" + (k + 1) + ", " + (l + 1) + ").");
									System.out.println("Put the second square to (" + (i + 1) + ", " + (j + 1) + ").");
									return;
								}
							}
						}
					}
				}
			 }
		}else if (cnt == 1){
			HashSet<String> set = new HashSet<String>();
			String mast[] = new String[]{"C", "D", "H", "S"};
			String dost[] = new String[]{"2", "3","4","5","6","7","8","9","T","J","Q","K","A"};
			for(int i=0;i<mast.length;i++)
				for(int j=0;j<dost.length;j++)
					set.add(dost[j]+mast[i]);

			for(int i=0;i<n;i++)
			  for(int j=0;j<m;j++)
				set.remove(a[i][j]);

			for(String s1:set){
				String tmp = a[i1][j1];
				a[i1][j1] = s1;
				for(int i=0;i<=n-3;i++){
					for(int j=0;j<=m-3;j++){
						if (check(i,j)){
							for(int k=0;k<=n-3;k++){
								for(int l=0;l<=m-3;l++){
									if (isIn(i, j, k, l)) continue;
								  	if (check(k, l)){
								  		System.out.println("Solution exists.");
								  		System.out.println("Replace " + tmp + " with " + s1 + ".");
								  		System.out.println("Put the first square to (" + (k+1) + ", " + (l + 1) + ").");
								  		System.out.println("Put the second square to (" + (i+1) + ", " + (j + 1) + ").");
								  		return;
								  	}
								}
							}
						}
					}
				}
				a[i1][j1] = tmp;
			}
		}else{
		 	HashSet<String> set = new HashSet<String>();
			String mast[] = new String[]{"C", "D", "H", "S"};
			String dost[] = new String[]{"2", "3","4","5","6","7","8","9","T","J","Q","K","A"};
			for(int i=0;i<mast.length;i++)
				for(int j=0;j<dost.length;j++)
					set.add(dost[j]+mast[i]);

			for(int i=0;i<n;i++)
			  for(int j=0;j<m;j++)
				set.remove(a[i][j]);

			for(String s1:set){
				for(String s2:set){
					if (s1.equals(s2)) continue;
					String tmp1 = a[i1][j1];
					String tmp2 = a[i2][j2];
					a[i1][j1] = s1;a[i2][j2] = s2;
					for(int i=0;i<=n-3;i++){
						for(int j=0;j<=m-3;j++){
							if (check(i, j)){
								for(int k=0;k<=n-3;k++)
								  for(int l=0;l<=m-3;l++){
								  	if (isIn(i, j, k, l)) continue;
								  	if (check(k, l)){
								  		System.out.println("Solution exists.");
								  		System.out.println("Replace J1 with " + s1 + " and J2 with " + s2 + ".");
								  		System.out.println("Put the first square to (" + (k+1) + ", " + (l + 1) + ").");
								  		System.out.println("Put the second square to (" + (i+1) + ", " + (j + 1) + ").");
								  		return;
								  	}
								  }
							}
						}
					}
					a[i1][j1] = tmp1;a[i2][j2] = tmp2;
				}
			}
		}
		System.out.println("No solution.");
    }

    private boolean check(int x, int y){
		int cnt = 0;
		for(int i=x;i<x+3;i++)
			for(int j=y;j<y+3;j++)
			if (a[i][j].charAt(1) != a[x][y].charAt(1))
				cnt++;

		if (cnt == 9) return true;
		HashSet<String> set = new HashSet<String>();
		for(int i=x;i<x+3;i++)
			for(int j=y;j<y+3;j++)
				set.add(""+a[i][j].charAt(0));

		if (set.size() == 9) return true;
		return false;
    }
	private boolean isIn(int x1, int y1, int x2, int y2){
		if (x1 <= x2 && x2 <= x1 + 2 && y1 <= y2 && y2 <= y1 + 2) return true;
		return false;
	}
    public static void main(String args[]){
		new Main().run();
    }
}


import java.util.*;

public class c71d
{
    private final Scanner sc;
    private static final boolean debug = true;

    static void debug(Object ... objects)
    {
        if(debug)
            System.err.println(Arrays.toString(objects));
    }

    c71d()
    {
        sc = new Scanner(System.in);
    }

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

    int xx[],yy[];

    boolean check(String [][] grid)
    {
        int n = grid.length;
        int m = grid[0].length;
        ArrayList<Integer> p = new ArrayList<Integer>();
        for(int i=0;i<n-2;i++)
            for(int j=0;j<m-2;j++)
            {
                String v = grid[i][j];
                boolean ok = true;
                boolean val[] = new boolean[256];
                for(int k=0;k<3;k++)
                    for(int r=0;r<3;r++)
                        if(grid[i+k][j+r].charAt(1) != v.charAt(1))
                        {
                            ok = false;
                            break;
                        }
                for(int k=0;k<3;k++)
                    for(int r=0;r<3;r++)
                        val[grid[i+k][j+r].charAt(0)] = true;

                int cnt=0;

                for(int k=0;k<val.length;k++)
                    if(val[k]) cnt++;
                if(cnt == 9)
                    ok = true;

                if(ok)
                    p.add(i*1000+j);
            }

        debug(p);

        for(int i=0;i<p.size();i++)
            for(int j=i+1;j<p.size();j++)
            {
                int x = p.get(i);
                int y = p.get(j);
                if(Math.abs(x%1000-y%1000) >= 3 || Math.abs(x/1000-y/1000) >=3)
                {
                    xx[0] = x/1000;xx[1] = y/1000;
                    yy[0] = x%1000;yy[1] = y%1000;
                    return true;
                }
            }

        return false;
    }

    void solve()
    {
        int n = sc.nextInt(), m = sc.nextInt();
        HashMap<String, Integer> val = new HashMap<String, Integer>();
        xx = new int[2];
        yy = new int[2];

        String [] suit = new String[]{"C", "D", "H", "S"};
        String [] rank =  new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "T", "Q", "K", "A"};
        HashSet<String> all = new HashSet<String>();
        for(int i=0;i<rank.length;i++)
            for(int j=0;j<suit.length;j++)
                all.add(rank[i]+suit[j]);

        sc.nextLine();
        String grid[][] = new String[n][m];
        int jokers[][] = new int[2][2];
        for(int i=0;i<2;i++)
            Arrays.fill(jokers[i],-1);

        int jcount = 0;

        for(int i=0;i<n;i++)
        {
            String [] b = sc.nextLine().split(" ");
            for(int j=0;j<b.length;j++)
            {
                grid[i][j] = b[j];
                all.remove(b[j]);
                if(b[j].charAt(0) == 'J')
                {
                    int r = b[j].charAt(1) - '1';
                    jokers[r][0] = i; jokers[r][1] = j;
                    jcount++;
                }
            }
        }

        boolean solve = false;
        if(jcount == 0)
            solve = check(grid);
        else
        {
            if(jcount == 2)
            {
                for(String i: all)
                {
                    grid[jokers[0][0]][jokers[0][1]] = i;
                    for(String j:all)
                    {
                        grid[jokers[1][0]][jokers[1][1]] = j;
                        if(check(grid))
                        {
                            solve = true;
                            break;
                        }
                    }
                    if(solve)
                        break;
                }
            }
            else
            {
                int r=0;
                if(jokers[1][0] != -1)
                    r=1;
                for(String i: all)
                {
                    grid[jokers[r][0]][jokers[r][1]] = i;
                    if(check(grid))
                    {
                        solve = true;
                        break;
                    }
                }
            }
        }

        if(solve)
        {
            System.out.println("Solution exists.");
            if(jcount == 0)
                System.out.println("There are no jokers.");
            if(jcount == 1)
            {
                int r=0;
                if(jokers[1][0] != -1) r=1;
                String v1 = grid[jokers[r][0]][jokers[r][1]];
                System.out.println("Replace J"+  Integer.toString(i+1)+ " with " + v1+".");
            }

            if(jcount ==2)
            {
                String v1 = grid[jokers[0][0]][jokers[0][1]];
                String v1 = grid[jokers[1][0]][jokers[1][1]];
                System.out.println("Replace J1 with "+v1+" and J2 with "+v2+".");
            }

            String [] f = {"first", "second"};
            for(int i=0;i<2;i++)
                System.out.println("Put the "+ f[i]+" square to (" + (xx[i]+1) +", " + (yy[i]+1) +").");
        }
        else
            System.out.println("No solution.");
    }

}


import java.io.*;
import java.lang.*;
import java.util.*;
public class A {
    public static void main(String[[] args) {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        if(n % 4 == 1) {
            System.out.println(0 + " A");
        } else if(n % 4 == 2) {
            System.out.println(1 + " B");
        } else if(n % 4 == 3) {
            System.out.println(2 + " A");
        } else if(n % 4 == 0) {
            System.out.println(1 + " A");
        }
    }
}


import java.util.Scanner;

public class Main {

    public static final void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
//        for (int i = 0; i < n; i++) {
//            String[] s = in.nextLine().split(" ");
//            long intRes = (Long.parseLong(s[0]) + Long.parseLong(s[1]) + Long.parseLong(s[2])) / 2;
//            System.out.println(intRes);
//        }
        if (n % 4 == 1) {
            System.out.println("0 A");
        } else if (n % 4 == 3) {
            System.out.println("2 A");4
        } else if (n % 4 == 2) {
            System.out.println("1 B");
        } else {
            System.out.println("1 A");
        }
    }
}


import java.util.Scanner;

public class enhancement{
	public static void main(String[] args){

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int hpVal = Integer.parseInt(br.readLine());

		// Scanner input = new Scanner(System.in);
		// int hpVal = input.nextInt();

		if(hpVal%4==1){
			System.out.println("0 A");
		}

		if(hpVal%4==2){
			System.out.println("1 B");
		}

		if(hpVal%4==3){
			System.out.println("2 A");
		}

		if(hpVal%4==0){
			System.out.println("1 A");
		}
	}
}


import java.util.*;

public class Solution{
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		if(n%4==2){
		System.out.println("1 B");
		}
		if else(n%4==0)
		{
		System.out.println("1 A");
		}
		if else(n%4==1)
		{
		System.out.println("0 A");
		}
		if else(n%4==3)
		{
		System.out.println("2 A");
		}
	}
}


import java.io.*;
import java.util.*;
public class Main{
	public static void main(String[] args)throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String s=br.readLine();
		StringTokenizer st=new StringTokenizer(s);
		int n=Integer.parseInt(st.nextToken());
		int k=Integer.parseInt(st.nextToken());
		int[] group=new int[k];
		String s1=br.readLine();
		StringTokenizer st1=new StringTokenizer(s1);
		for(int i=0;i<k;i++){
			group[i]=Integer.parseInt(st1.nextToken());
		}
		int[] have=new int[5];
		have[2]=2*n;
		have[4]=n;
		int[] grp=new int[5];
		for(int i=0;i<k;i++){
			while(group[i]>=3){
				if(have[4]>0){
					have[4]--;
					x-=4;
				}
				else if(have[2]>0){
					have[2]--;
					x-=2;
				}
				else{
					System.out.println("NO");
					break;
				}
			}
			if(x>0)
				grp[x]++;
		}
		while(grp[2]>0){
			if(have[2]>0){
				have[2]--;
				grp[2]--;
			}
			else{
				if(have[4]>0){
					grp[2]--;
					have[4]--;
					have[1]++;
				}
				else{
					grp[2]--;
					grp[1]+=2;
				}
			}
		}
		if(grp[1]>have[1]+have[2]+2*have[4])
			System.out.println("NO");
		else
			System.out.println("YES");
	}
}


import java.util.*;
import java.io.*;
public class B {
    void solve(BufferedReader in) throws Exception {
        int[] xx = toInts(in.readLine());
        int n = xx[0], k = xx[1];
        int[] a = toInts(in.readLine());
        int fours = n;
        int twos = 2*n;
        int ones = 0;
        for(int y: a) {
            int x = y;
            int sub4 = Math.min(x/4, fours);
            fours -= sub4;
            x -= sub4*4;
            int sub2 = Math.min(x/2, twos);
            twos -= sub2;
            x -= sub2*2;
            if(x>0) {
                if(x == 1 && ones != 0) {
                    x = 0;
                    ones--;
                }else if(x <= 2 && twos != 0) {
                    twos--;
                    x = 0;
                }else if(x <= 4 && fours != 0) {

                    fours--;
                    if(x == 2) ones++;
                    if(x == 1) twos++;
                    x = 0;
                }
            }
            if(x > 0) {
                System.out.println("NO");
                return;
            }        }
        System.out.println("YES");
    }
    int toInt(String s) {return Integer.parseInt(s);}
    int[] toInts(String s) {
        String[] a = s.split(" ");
        int[] o = new int[a.length];
        for(int i = 0; i<a.length; i++) o[i] = toInt(a[i]);
        return o;
    }
    void e(Object o) {
        System.err.println(o);
    }
    public static void main(String[] args) throws Exception{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        (new B()).solve(in);
    }
}


import java.io.IOException;

public class Kek
{
    static class Scan
    {
        final private int BUF_SIZE = 1 << 16;
        private int cur_size = 0;
        private int pointer = 0;
        private java.io.DataInputStream in;
        private byte buffer[] = new byte[BUF_SIZE];

        Scan(java.io.InputStream input)
        {
            in = new java.io.DataInputStream(input);
        }

        // fills the buffer with characters
        private void fill() throws java.io.IOException
        {
            cur_size = in.read(buffer, 0, BUF_SIZE);
            if (cur_size == -1) buffer[0] = 0;
            pointer = 0;
        }

        private byte read() throws java.io.IOException
        {
            if (pointer == cur_size) fill();
            return buffer[pointer++];
        }

        int readInt() throws java.io.IOException
        {
            int res = 0;
            byte c;
            while ((c = read()) <= ' ');
            boolean negate = c == '-';
            if (negate) c = read();
            while (c >= '0' && c <= '9')
            {
                res = res * 10 + c - '0';
                c = read();
            }
            return negate ? -res : res;
        }

        long readLong() throws java.io.IOException
        {
            long res = 0;
            byte c;
            while ((c = read()) <= ' ') ;
            boolean negate = c == '-';
            if (negate) c = read();
            while (c >= '0' && c <= '9') {
                res = res * 10 + c - '0';
                c = read();
            }
            return negate ? -res : res;
        }

        double readDouble() throws java.io.IOException
        {
            byte c;
            while ((c = read()) <= ' ');
            boolean negate = c == '-';
            if (negate)
                c = read();
            int power = 0;
            long res = 0;
            boolean dot_flag = false;
            for (;(c >= '0' && c <= '9') || c == '.'; c = read())
            {
                if (dot_flag)
                    power++;
                if (c == '.')
                    dot_flag = true;
                else
                    res = res * 10 + c - '0';
            }
            double ret = res / Math.pow(10, power);
            return negate ? -ret : ret;
        }

        // skip defines whether ' ', '\n', '\r' must be skipped in readChar method
        char readChar(boolean skip) throws java.io.IOException
        {
            if (skip)
            {
                byte c;
                while ((c = read()) == ' ' || c == '\n' || c == '\r');
                return (char) c;
            }
            return (char) read();
        }

        // skip defines whether current string must be skipped in readString and readText methods

        /* If exact length is known, in terms of efficiency
         it is better to specify it while using readText, readString and readWord methods */

        String readWord() throws java.io.IOException
        {
            byte c;
            while ((c = read()) == '\n' || c == ' ' || c == '\r');
            StringBuilder s = new StringBuilder();
            s.append((char)c);
            for (;(c = read()) != '\n' && c != ' ' && c != '\r' && c != 0; s.append((char)c));
            return s.toString();
        }

        String readWord(int LEN) throws java.io.IOException
        {
            byte[] s = new byte[LEN];
            byte c;
            while ((c = read()) == '\n' || c == ' ' || c == '\r');
            s[0] = c;
            for (int i = 1; (c = read()) != ' ' && c != '\n' && c != '\r' && c != 0; s[i++] = c);
            return new String(s);
        }

        String readString(boolean skip, int LEN) throws java.io.IOException
        {
            byte[] s = new byte[LEN];
            byte c;
            if (skip)
                while ((c = read()) != '\n');
            for (int i = 0; (c = read()) != '\n' && c != '\r' && c != 0; s[i++] = c);
            read();
            return new String(s);
        }

        String readString(boolean skip) throws java.io.IOException
        {
            StringBuilder s = new StringBuilder("");
            byte c;
            if (skip)
                while ((c = read()) != '\n');
            for (;(c = read()) != '\n' && c != '\r' && c != 0; s.append((char)c));
            read();
            return s.toString();
        }

        String readText(boolean skip, int LEN) throws java.io.IOException
        {
            byte[] s = new byte[LEN];
            byte c;
            if (skip)
                while ((c = read()) != '\n');
            for (int i = 0; (c = read()) != 0; s[i++] = c);
            return new String(s);
        }

        String readText(boolean skip) throws java.io.IOException
        {
            StringBuilder s = new StringBuilder("");
            byte c;
            if (skip)
                while ((c = read()) != '\n');
            for (;(c = read()) != 0; s.append((char)c));
            return s.toString();
        }
    }

    public static void main(String args[]) throws IOException
    {
        Scan in = new Scan(System.in);
        int n = in.readInt(), k = in.readInt(), l = 2 * n, c4 = n, c2 = 0, c1 = 0;
        for (int i = 0; i < k; i++)
        {
            int a = in.readInt();
            while (a > 0 && l > 0)
            {
                l--;
                a -= 2;
            }
            while (a > 2 && c4 > 0)
            {
                a -= 4;
                c4--;
            }
            while (a > 1 && c2 > 0)
            {
                a -= 2;
                c2--;
            }
            while (a > 1 && c4 > 0)
            {
                a -= 2;
                c4--;
                c1++;
            }
            while (a > 0 && c1 > 0)
            {
                a--;
                c1--;
            }
            while (a > 0 && c2 > 0)
            {
                a--;
                c2--;
            }
            while (a > 0 && c4 > 0)
            {
                a--;
                c4--;
                c2++;
            }
            if (a > 0)
            {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }
}


import java.util.*;

public class cf428_b
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int k = sc.nextInt();
      int pair = 2*n;
      int four = n;
      for (int j = 0; j < k; j++)
      {
         int next = sc.nextInt();
         while(next >= 4 && four > 0)
         {
            next-=4;
            four--;
         }
         if (next%4 == 3 && four > 0)
         {
            next-=3;
            four--;
         }
         if (next%4 == 1 && four > 0)
         {
            next--;
            four--;
            pair++;
         }
         while(next >= 2 && pair > 0)
         {
            next-=2;
            pair--;
         }
         if (next == 1 && pair > 0)
         {
            next--;
            pair--;
         }
         if (next > 0)
         {
            System.out.println("NO");
            System.exit(0);
         }
      }
      System.out.println("YES");
   }
}


import com.sun.deploy.util.ArrayUtil;

import java.util.*;

public class AbondonedSentimentPast {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        Integer[] a, b;
        a = new Integer[n];
        b = new Integer[k];
        for(int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        for(int i = 0; i < k; i++) {
            b[i] = scanner.nextInt();
        }
        Arrays.sort(b, Collections.reverseOrder());
        int j= 0;
        for(int i = 0; i < n; i++) {
            if (a[i] == 0) {
                a[i] = b[j++];
            }
        }
        boolean ans = false;
        for(int i = 0; i < n-1; i++) {
            if (a[i] > a[i+1])
                ans = true;
        }
        if (ans) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}


import java.util.*;

public class MissingSequence{
   public static void main(String args[]) {
	   Scanner scanner = new Scanner(System.in);
	   int parentLength = scanner.nextInt();
	   int childLength = scanner.nextInt();
	   int[] parent = new int[100];
	   int[] child = new int[100];
	   for(int i=0;i<parentLength ;i++) {
		   int element = scanner.nextInt();
		   parent[i]=element;
	  }
	  for(int j=0;j<childLength;j++){
		  int element = scanner.nextInt();
		   child[i]=element;
      }
      Arrays.sort(child);
      int index=child.length()-1;
      for(int i=0;i<parentLength;i++){
		  if(parent[i]==0){
			  parent[i]=child[index];
			  index--;
		  }
      }
      boolean increasing=true;
      for(int i=0;i<parent.length()-1;i++){
		  if(parent[i]<parent[i-1]){
			  increasing=false;
		  }
	 }
	 if(!increasing){
		 System.out.println("No");
	} else {
		System.out.println("Yes");
    }
   }
}


public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] one = new int[2];
        for (int i = 0; i < one.length; i++) {
            one[i] = in.nextInt();
        }

        int k = 0;

        int[] two = new int[one[0]];
        for (int i = 0; i < two.length; i++) {
            two[i] = in.nextInt();
            if(two[i] == 0){
                k = i;
            }
        }

        int[] three = new int[one[1]];
        for (int i =0; i < three.length; i++){
            three[i] = in.nextInt();
        }

        if (three.length > 2) {
            System.out.println("Yes");
        }
        else if(three.length == 1){
            if (two[k-1] > three[0] || two[k+1] < three[0]){
                System.out.println("Yes");
            }
        }
        else {
            System.out.println("No");
        }

    }
}


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

public class abandoned {
    static void comparetwo(int[] arr,int[] mix,int k,int jusval){
        if(k>1){
            System.out.println("Yes");
            return;
        }
        else{
            int high;
            int low;
            if(jusval>0 && arr[arr.length-1]!=0){
                low = jusval-1;
                high = jusval+1;
                if(arr[low]<mix[0] && mix[0]<arr[high]){
                    arr[jusval] = mix[0];
                    int kval=0;

                    for(int i=0;i<arr.length-1;i++){
                        if(arr[i]>=arr[i+1]){
                            kval++;
                            break;
                        }
                    }
                    if(kval==0){
                        System.out.println("No");
                        return;
                    }
                    else{
                        System.out.println("Yes");
                        return;
                    }

                }
                else{
                    System.out.println("Yes");
                    return;
                }
            }
            else if (arr[arr.length-1]==0){
                low = jusval-1;
                if(arr[low]<mix[0]){
                    System.out.println("No");
                    return;
                }
                else {
                    System.out.println("Yes");
                    return;
                }
            }
            else{
                high = jusval+1;
                if(arr[high]<mix[0]){
                    System.out.println("Yes");
                    return;
                }
                else{
                    System.out.println("No");
                    return;
                }

            }

        }
        return;

    }
    public static void main(String[] args){
        int n,k;
        FastReader fastReader=new FastReader();
        n=fastReader.nextInt();
        k= fastReader.nextInt();
        int[] test = new int[n];
        int[] mix = new int[k];
        int count=0;
        for (int i=0;i<n;i++){
            test[i] = fastReader.nextInt();
            if(test[i]==0){
                count=i;
            }
        }
        for (int i=0;i<k;i++){
            mix[i] = fastReader.nextInt();
        }
        comparetwo(test,mix,k,count);

    }
}
class FastReader {
    public static BufferedReader br;
    public static StringTokenizer st;
    public FastReader(){
        br = new BufferedReader(new InputStreamReader(System.in));
    }
    static String next() {
        while(st==null || !st.hasMoreElements()) try {
            st = new StringTokenizer(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return st.nextToken();
    }
    public static int nextInt(){
        return  Integer.parseInt(next());
    }
}


import java.util.*;
public class Task894 {
	public static void main(String[] args){
		int prime = 1000000007;
		int order = 500000003;

		Scanner sc = new Scanner(System.in);

		long n = sc.nextInt();

		long m = sc.nextInt();

		m = (m-1) % order;
		n = (n-1) % order;

		long exponent = (m * n) % order;

		int ans = 1;
		for(int i = 1; i <= exponent; i++){
			ans = ans*2;
			ans = ans % prime;
		}

		System.out.print(ans);
		sc.close();
	}
}


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

public class C447PB {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    StringTokenizer st = new StringTokenizer(in.readLine());
    long n = Integer.parseInt(st.nextToken());
    long m = Integer.parseInt(st.nextToken());
    int k = Integer.parseInt(st.nextToken());
    int counter = 1;

    for (int i = 0; i < (n - 1) * (m - 1); i++) {
      counter *= 2;
      counter %= (1000000007);
    }
    System.out.println(counter);

    in.close();
  }
}


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

public class Main {

    static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
    static Reader fastInput = new Reader();

    public static void main(String[] args) throws IOException {
        long n = input.nextLong();
        long m = input.nextLong();
        long k = input.nextLong();
        if (k == -1 && n % 2 != m % 2) {
            System.out.println(0);
        } else {
            long res = 1;
            for (int i = 0; i < (n - 1) * (m - 1); i++) {
                res = (res * 2) % 1_000_000_007;
            }
            System.out.println(res);
        }
    }

    static class Reader {

        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') {
                    break;
                }
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (neg) {
                return -ret;
            }
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) {
                return -ret;
            }
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg) {
                c = read();
            }

            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg) {
                return -ret;
            }
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) {
                buffer[0] = -1;
            }
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            if (din == null) {
                return;
            }
            din.close();
        }
    }
}


import java.util.*;
public class Task894 {
	public static void main(String[] args){
		int prime = 1000000007;
		int order = 500000003;

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		long m = sc.nextInt();
		long k = sc.nextInt(); //irrelevant infromation

		m = m-1 % order;
		n = n-1 % order;
		long exponent = m * n % order;

		long ans = 1;
		for(int i = 1; i <= exponent; i++){
			ans = 2 * ans;
			ans %= prime;
		}

		System.out.print(ans);
	}
}


import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
    static class Reader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(s()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
    }

           //       |----|       /\      |    |   -----   |
           //       |   /       /  \     |    |     |     |
           //       |--/       /----\    |----|     |     |
           //       |   \     /      \   |    |     |     |
           //       |    \   /        \  |    |   -----   -------

    static int d,n,x1,y1;
    static int arr[][];
    public static int dfs(int x,int y,int chance,int flip1,int flip2)
    {
        if(Math.sqrt(x*x+y*y)>d)
        return 1;
        for(int i=0;i<n;i++)
        {
            if(dfs(x+arr[i][0],y+arr[i][1],chance^1,flip1,flip2)==0)
            return 1;
        }
        if(chance==0&&flip1==0)
        if(dfs(y,x,chance^1,1,flip2)==0)
        return 1;
        if(chance==1&&flip2==0)
        if(dfs(y,x,chance^1,flip1,1)==0)
        return 1;
        return 0;
    }
    public static void main(String[] args)throws IOException
    {
        PrintWriter out= new PrintWriter(System.out);
        Reader sc=new Reader();
        x1=sc.i();y1=sc.i();n=sc.i();d=sc.i();
        arr=new int[n][2];
        for(int i=0;i<n;i++)
        {
            arr[i][0]=sc.i();
            arr[i][1]=sc.i();
        }
        if(dfs(x1,y1,0,0,0)==1)
        out.println("Anton");
        else
        out.println("Dasha");
        out.flush();
    }
}


import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;

public class BetaRound63_Div2_D implements Runnable {

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

	public static void main(String[] args) {
		new Thread(null, new BetaRound63_Div2_D(), "", 256 * (1L << 20)).start();
	}

	public void run() {
		try {
			long t1 = System.currentTimeMillis();
			if (System.getProperty("ONLINE_JUDGE") != null) {
				in = new BufferedReader(new InputStreamReader(System.in));
				out = new PrintWriter(System.out);
			} else {
				in = new BufferedReader(new FileReader("input.txt"));
				out = new PrintWriter("output.txt");
			}
			Locale.setDefault(Locale.US);
			solve();
			in.close();
			out.close();
			long t2 = System.currentTimeMillis();
			System.err.println("Time = " + (t2 - t1));
		} catch (Throwable t) {
			t.printStackTrace(System.err);
			System.exit(-1);
		}
	}

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

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

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

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

	// solution

	final int shift = 500, size = 2*shift + 1;

	int sx, sy, n, d;
	int[] vx, vy;

	boolean[][][][] dp;
	boolean[][][][] vis;

	boolean ok(int x, int y) {
		return (x - sx) * (x - sx) + (y - sy) * (y - sy) > d * d;
	}

	int get(int x, int y, boolean used1, boolean used2) {
		if (ok(x, y)) {
			return true;
		}
		if (vis[used1][used2][x][y]) {
			return dp[used1][used2][x][y];
		}

		boolean result = false;
		if (!used1) {
			result |= !get(y, x, used2, true);
		}
		for (int i = 0; i < n; i++) {
			result |= !get(x + vx[i], y + vy[i], used2, used1);
		}

		vis[used1][used2][x][y] = true;
		return dp[used1][used2][x][y] = result;
	}

	void solve() throws IOException {
		sx = readInt() + shift;
		sy = readInt() + shift;
		n = readInt();
		d = readInt();
		vx = new int[n];
		vy = new int[n];
		for (int i = 0; i < n; i++) {
			vx[i] = readInt() + shift;
			vy[i] = readInt() + shift;
		}
		// used 1, used 2, x, y
		dp = new boolean[2][2][size][size];
		boolean ans = get(x, y, false, false);
		out.println(ans ? "Anton" : "Dasha");
	}

}


import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;

public class BetaRound63_Div2_D implements Runnable {

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

	public static void main(String[] args) {
		new Thread(null, new BetaRound63_Div2_D(), "", 256 * (1L << 20)).start();
	}

	public void run() {
		try {
			long t1 = System.currentTimeMillis();
			if (System.getProperty("ONLINE_JUDGE") != null) {
				in = new BufferedReader(new InputStreamReader(System.in));
				out = new PrintWriter(System.out);
			} else {
				in = new BufferedReader(new FileReader("input.txt"));
				out = new PrintWriter("output.txt");
			}
			Locale.setDefault(Locale.US);
			solve();
			in.close();
			out.close();
			long t2 = System.currentTimeMillis();
			System.err.println("Time = " + (t2 - t1));
		} catch (Throwable t) {
			t.printStackTrace(System.err);
			System.exit(-1);
		}
	}

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

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

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

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

	// solution

	final int shift = 401, size = 2*shift + 1;

	int sx, sy, n, d;
	int[] vx, vy;

	boolean[][][][] dp;
	boolean[][][][] vis;

	boolean ok(int x, int y) {
		return (x - sx) * (x - sx) + (y - sy) * (y - sy) > d * d;
	}

	int get(int x, int y, int used1, int used2) {
		if (ok(x, y)) {
			return true;
		}
		if (vis[used1][used2][x][y]) {
			return dp[used1][used2][x][y];
		}

		boolean result = false;
		if (used1 == 0) {
			result |= !get(y, x, used2, 1);
		}
		for (int i = 0; i < n; i++) {
			result |= !get(x + vx[i], y + vy[i], used2, used1);
		}

		vis[used1][used2][x][y] = true;
		return dp[used1][used2][x][y] = result;
	}

	void solve() throws IOException {
		sx = readInt() + shift;
		sy = readInt() + shift;
		n = readInt();
		d = readInt();
		vx = new int[n];
		vy = new int[n];
		for (int i = 0; i < n; i++) {
			vx[i] = readInt() + shift;
			vy[i] = readInt() + shift;
		}
		// used 1, used 2, x, y
		dp = new boolean[2][2][size][size];
		boolean ans = get(x, y, 0, 0);
		out.println(ans ? "Anton" : "Dasha");
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.HashMap;
import java.util.TreeSet;

public class Main {
	private static StreamTokenizer in = new StreamTokenizer(new BufferedReader(
			new InputStreamReader(System.in)));
	private static PrintWriter out = new PrintWriter(System.out);

	private static int nextInt() throws Exception {
		in.nextToken();
		return (int) in.nval;
	}

	private static String nextString() throws Exception {
		in.nextToken();
		return in.sval;
	}

	public static void main(String[] args) throws Exception {
		int x = nextInt(), y = nextInt();
		int n = nextInt();
		d = nextInt();
		v = new int[n][];
		for (int i = 0; i < n; i++) {
			v[i] = new int[] { nextInt(), nextInt() };
		}
		dp = new int[d+1][d+1][2][2];
		out.println(f(x, y, 1, 1) == 1 ? "Anton" : "Dasha");
		out.flush();
	}

	private static int[][] v;
	private static int[][][][] dp;
	private static int d;

	private static int f(int x, int y, int cani, int cano) { //1 - I win, 2 - I lose
		if (Math.sqrt(x*x + y*y) > d) {
			return 1;
		}
		if (dp[x][y][cani][cano] > 0) {
			return dp[x][y][cani][cano];
		}

		for (int[] vector : v) {
			if (f(x + vector[0], y + vector[1], cano, cani) == 2) {
				return dp[x][y][cani][cano] = 1;
			}
		}

		if (cani == 1) {
			cani = 0;
			if (f(y, x, cano, cani) == 2) {
				return dp[x][y][cani][cano] = 1;
			}
		}

		return dp[x][y][cani][cano] = 2;
	}
}


/**
 * Created by IntelliJ IDEA.
 * User: Taras_Brzezinsky
 * Date: 10/27/11
 * Time: 5:55 PM
 * To change this template use File | Settings | File Templates.
 */

import sun.misc.Sort;

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

public class TaskC extends Thread {
    public TaskC(int type) {
        try {
            if (type == 0) {
                this.input = new BufferedReader(new InputStreamReader(System.in));
                this.output = new PrintWriter(System.out);
            } else {
                this.input = new BufferedReader(new FileReader(INPUT_FILE));
                this.output = new PrintWriter(OUTPUT_FILE);
            }
            this.setPriority(Thread.MAX_PRIORITY);
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(666);
        }
    }

    static boolean isLucky(int value) {
        char []now = Integer.toString(value).toCharArray();
        for (char c : now) {
            if (c != '4' && c != '7') {
                return false;
            }
        }
        return true;
    }

    static void generate(long now, long length) {
        if (length == 10) {
            return;
        }
        luckies.add(now * 10 + 4);
        luckies.add(now * 10 + 7);
        generate(now * 10 + 4, length + 1);
        generate(now * 10 + 7, length + 1);
    }

    //12 ! - max
    private void solve() throws Throwable {
        long facts[] = new long[14];
        facts[0] = 1;
        for (int i = 1; i < facts.length; ++i) {
            facts[i] = facts[i - 1] * i;
        }
        int n = nextInt();
        long k = nextLong();
        if (n <= 12) {
            if (facts[n] < k) {
                output.println(-1);
                return;
            }
        }
        int result = 0;

        int N = 1;
        while (facts[N] < k) {
            ++N;
        }
        long MAX = (long) n - N;
        int index = 0;
        while (values.get(index) <= MAX) {
            ++result;
            ++index;
        }

        int values[] = new int[N];
        boolean used[] = new boolean[N];
        Arrays.fill(values, -1);
        for (int i = 0; i < N; ++i) {
            for (int wanted = 0; wanted < N; ++wanted) {
                if (used[wanted]) {
                    continue;
                }
                long remaining = facts[N - 1 - i];
                if (remaining < k) {
                    k -= remaining;
                } else {
                    values[i] = wanted + 1;
                    used[wanted] = true;
                    break;
                }
            }
        }
        for (int i = 0; i < N; ++i) {
            int pos = (int)MAX + i + 1;
            if (isLucky(pos) && isLucky((int) MAX + values[i])) {
                ++result;
            }
        }
        output.println(result);

    }

    public void run() {
        try {
            solve();
        } catch (Throwable e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(666);
        } finally {
            output.flush();
            output.close();
        }
    }

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

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

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

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

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

    static ArrayList<Long> values = new ArrayList<Long>();
    static HashSet<Long> luckies = new HashSet<Long>();

    static {
        generate(0, 1);
        values.addAll(luckies);
        Collections.sort(values);
    }

    private static final String INPUT_FILE = null;
    private static final String OUTPUT_FILE = null;
    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer tokens = null;
}


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

public class Main {
    static BufferedReader newInput() throws IOException {
        return new BufferedReader(new InputStreamReader(System.in));
    }
    static PrintWriter newOutput() throws IOException {
        return new PrintWriter(System.out);
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = newInput();
        PrintWriter out = newOutput();
        function(in, out);
        out.flush();
    }
    public static void function(BufferedReader in, PrintWriter out) throws IOException {
        //StringTokenizer t = new StringTokenizer(in.readLine());
        String[] nk = in.readLine().split(" ");
        long n = Integer.parseInt(nk[0]);
        long k = Long.parseLong(nk[1]);
        ArrayList<Integer> nums = new ArrayList<>();
        for (int i = 1; i <= (int)n; i++) {
            nums.add(i);
        }
        int lucks = 0;
        long fact = factorial(Math.min(n, 14));
        long x = Math.min(n, 14);
        for (int i = 1; i < Math.max(1, (int)n-13); i++) {
            if (isLucky((int)i)){
                lucks++;
            }
        }
        for (int i = Math.max(1, (int)n-13); i <= n; i++) {
            fact /= x;
            x--;
            int b = (int)((k-1)/fact);
            if (b >= n){
                out.println("-1");
                return;
            }
            k -= (b*fact);
            b += Math.max(1, (int)n-13)-1;
            int num = nums.get(b);
            nums.remove(b);
            if (isLucky(num) && isLucky(i)){
                lucks++;
            }
        }
        out.println(lucks);
    }
    public static long factorial(long num){
        long x = num;
        num--;
        for (;num != 0; num--) {
            x *= num;
        }
        return x;
    }
    public static boolean isLucky(int x){
        for (; x != 0; x /= 10) {
            int b = x % 10;
            if (b != 7 && b != 4){
                return false;
            }
        }
        return true;
    }
}


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

public class Main {
    static BufferedReader newInput() throws IOException {
        return new BufferedReader(new InputStreamReader(System.in));
    }
    static PrintWriter newOutput() throws IOException {
        return new PrintWriter(System.out);
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = newInput();
        PrintWriter out = newOutput();
        function(in, out);
        out.flush();
    }
    public static void function(BufferedReader in, PrintWriter out) throws IOException {
        //StringTokenizer t = new StringTokenizer(in.readLine());
        String[] nk = in.readLine().split(" ");
        long n = Integer.parseInt(nk[0]);
        long k = Long.parseLong(nk[1]);
        ArrayList<Integer> nums = new ArrayList<>();
        for (int i = Math.max(1, (int)n-13); i <= (int)n; i++) {
            nums.add(i);
        }
        int lucks = 0;
        long fact = factorial(Math.min(n, 14));
        long x = Math.min(n, 14);
        for (int i = 4; i < Math.max(1, (int)n-13); i += 10) {
            if (isLucky(i)){
                lucks++;
            }
        }
        for (int i = 7; i < Math.max(1, (int)n-13); i += 10) {
            if (isLucky(i)){
                lucks++;
            }
        }
        for (int i = Math.max(1, (int)n-13); i <= n; i++) {
            fact /= x;
            x--;
            int b = (int)((k-1)/fact);
            if (b >= n){
                out.println("-1");
                return;
            }
            k -= (b*fact);
            int num = nums.get(b);
            nums.remove(b);
            if (isLucky(num) && isLucky(i)){
                lucks++;
            }
        }
        out.println(lucks);
    }
    public static long factorial(long num){
        long x = num;
        num--;
        for (;num != 0; num--) {
            x *= num;
        }
        return x;
    }
    public static boolean isLucky(int x){
        for (; x != 0; x /= 10) {
            int b = x % 10;
            if (b != 7 && b != 4){
                return false;
            }
        }
        return true;
    }
}


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

/**
 * Author -
 * User: kansal
 * Date: 10/27/11
 * Time: 8:49 PM
 */
public class CF91E {
    public static void main(String[] args) {
        reader = new BufferedReader(new InputStreamReader(System.in));

        List<Integer> luckyNums = genAll();
        long[] f = new long[14];
        f[0] = 1;
        for(int i = 1; i < 14; ++i) {
            f[i] = i * f[i-1];
        }

        int n = nextInt(), k = nextInt();
        if (k > f[n]) {
            System.out.println(-1);
            return;
        }

        int x = 1;
        for(; f[x] < k; ++x);

        int res = 0;
        for(int lucky: luckyNums) {
            if (lucky < n-x+1) ++res;
        }

        int[] p = getKthPerm(k-1, n-x+1, n, x, f);
        for(int i = 0; i < x; ++i) {
            if (isLucky(p[i]) && isLucky(n-x+1+i)) {
                ++res;
            }
        }

        System.out.println(res);
    }

    private static int[] getKthPerm(int k, int a, int b, int n, long[] fac) {
        int[] res = new int[n];
        for(int i = a; i <= b; ++i) {
            res[i-a] = i;
        }

        for(int i = 0; i < n; ++i) {
            int x = (int)(k / fac[n-i-1]);
            int y = res[x+i];
            for(int j = x + i - 1; j >= i; --j) {
                res[j+1] = res[j];
            }
            res[i] = y;
            k = (int)(k % fac[n-i-1]);
        }

        return res;
    }

    private static boolean isLucky(int x) {
        if (x == 0) return false;
        while (x > 0) {
            if (x % 10 != 4 && x % 10 != 7) return false;
            x /= 10;
        }
        return true;
    }

    private static List<Integer> genAll() {
        List<Integer> ret = new ArrayList<Integer>();
        for(int i = 1; i < 10; ++i) {
            for(int set = 0; set < (1 << i); ++set) {
                int x = 0;
                for(int j = i-1; j >= 0; --j) {
                    if (((set >> j) & 1) == 1) {
                        x = x * 10 + 7;
                    }
                    else {
                        x = x * 10 + 4;
                    }
                }
                ret.add(x);
            }
        }
        return ret;
    }

    public static BufferedReader reader;

    public static StringTokenizer tokenizer = null;

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

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

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

    static public String next() {
        return nextToken();
    }

    static public String nextLine() {
        try {
            return reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}


import java.util.Scanner;
public class Morwords {
	public static void main(String[]args) {
		Scanner sc = new Scanner (System.in);
		int n = sc.nextInt();
		String s = sc.next();
		char [] arr = s.toCharArray();
		String vowels = "aeiouy";
		for (int i=0;i<arr.length;i++){
			if(vowels.contains(arr[i]+"")){
				int temp = i;
				while(i+1 <arr.length && vowels.contains(letters[i+1]+"")){
					i++;
				}
				System.out.print(arr[temp]);
				if(!vowels.contains(arr[i]+"")){
					System.out.print(arr[i]);
				}

			}
		}
	}
}


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

                    Scanner sc=new Scanner(System.in);
                    n=sc.nextInt();
                    s=sc.next();
                    boolean flag=false;
                    char x;
                    for(int i=0;i<s.length();i++){
                    x=s.charAt(i);
                    if(!isVowels(x)){
                            flag=false;
                            System.out.print(x);
                            continue;
                    }
                    else{ if(flag==true){

                         continue;
                    }
                    else{
                              flag=true;
                              System.out.print(x);
                              continue;
                    }

                    }return ;
          }
          public static boolean isVowels(char x){
                    if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')return true;
                    return false;
          }
}


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

                    char x;
                    int c=0;
                    Scanner sc=new Scanner(System.in);
                    n=sc.nextInt();
                    s=sc.next();

                    for(int i=0;i<s.length();i++){
                             x= s.charAt(i);
                    if(!isVowels()){
                              System.out.print(s.charAt(i));
                              i++;
                    }
                    else if(isVowels()&&firstOrnot){
                              System.out.print(s.charAt(i));
                              i++;

                    }
                    else{
                              i++;
                    }

                    }
                    return;
          }
          public static boolean isVowels(char x){
                    if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')return true;
                    return false;
          }

          public static boolean firstOrnot(int c){
                    if(c==0){
                              c++;
                              return true;
                    }
                    else{
                              c--;
                              return false;
                    }
          }
}


import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        in.nextInt();
        char a[] = (in.next()).toCharArray();
        char ans[] = new char[a.length];
        for(int i=1; i<a.length; i++){
            if((a[i]=='a'||a[i]=='e'||a[i]=='i'||a[i]=='o'||a[i]=='u'||a[i]=='y') && (a[i-1]=='a'||a[i-1]=='e'||a[i-1]=='i'||a[i-1]=='o'||a[i-1]=='u'||a[i-1]=='y')){
                ans[i] = '';
            }
            else{
                ans[i] = a[i];
            }
        }
        for(int i=0; i<a.length; i++){
            System.out.print(ans[i]);
        }
        System.out.println();
    }
}