import java.io.*;
import java.util.*;
import static java.lang.System.*;
import static java.lang.Math.*;
public class Code
{
    int P1,P2,T1,T2,H,S;
    void run() {
        int tc=1;
        StringBuilder sb=new StringBuilder();
        while(tc-->0) {
            P1=ni(); T1=ni();
            P2=ni(); T2=ni();
            H=ni(); S=ni();
            dp = new Integer[H+1][5001];
            int ans = T1<=T2 ? solve(P1, T1, P2, T2, H, S, 0, 0) : solve(P2, T2, P1, T1, H, S, 0, 0);
            sb.append(ans).append("\n");
        }
        out.println(sb);
        out.flush();
        out.close();
    }
    Integer dp[][];
    int solve(int p1, int t1, int p2, int t2, int h, int s, int c1, int c2) {
        if(h<=0) return 0;

        int diff=Math.abs(c1-c2);
        if(dp[h][diff]!=null) return dp[h][diff];
        // 5000*5000=2.5*10^7
        int res = 0;
        if(t1*2<=t2) {
            res = t1+solve(p1, T1, p2, t2-t1, h-(p1-s), s, 0, c2+1);
        }
        else if(t1>t2) {
            int x = t1+solve(p1, T1, p2, T2, h-(p1+p2-s), s, 0, 0);
            int y = t2+solve(p1, t1-t2, p2, T2, h-(p2-s), s, c1+1, 0);
            res = min(x,y);
        }
        else {
            int x = t1+solve(p1, T1, p2, t2-t1, h-(p1-s), s, 0, c2+1);
            int y = t2+solve(p1, T1, p2, T2, h-(p1+p2-s), s, 0, 0);
            // System.out.println(h+" "+x+" "+y);
            res = min(x,y);
        }

        return dp[h][diff] = res;

    }
    StringBuilder pr(String s, int t) {
        return new StringBuilder().append("Case #").append(t).append(": ").append(s).append("\n");
    }
    public static void main(String[] args)throws Exception {
        try {
            // new Thread(null, new Code()::run, "1", 1 << 26).start();
            new Thread(null, new Code("ONLINE_JUDGE")::run, "1", 1 << 26).start();
        } catch(Exception e) {}
    }

    FastReader sc=null;PrintWriter out = null;
    public Code()throws Exception {
        sc = new FastReader(new FileInputStream("input.txt"));
        out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
    }
    public Code(String JUDGE) {
        sc = new FastReader(System.in);
        out = new PrintWriter(System.out);
    }

    String ns() { return sc.next(); }
    int ni() { return sc.nextInt(); }
    long nl() { return sc.nextLong(); }
    int[] ni(int n) {
        int a[]=new int[n];
        for(int i=0;i<n;a[i++]=ni());
        return a;
    }
    long[] nl(int n) {
        long a[]=new long[n];
        for(int i=0;i<n;a[i++]=nl());
        return a;
    }

    int[][] ni(int n,int m) {
        int a[][]=new int[n][m];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                a[i][j]=ni();
        return a;
    }
    long[][] nl(int n,int m) {
        long a[][]=new long[n][m];
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                a[i][j]=nl();
        return a;
    }
    int gcd(int a, int b) {
        return b==0?a:gcd(b,a%b);
    }
    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;
        public FastReader(InputStream stream) {
            this.stream = stream;
        }

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

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

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

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

        public boolean isSpaceChar(int c) {
            if (filter != null) return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

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

        }
    }
}


import java.util.*;
import java.io.*;
public class posperm{
public static int op[] = {0,1,2,4,6,8,9,16,17,18};
public static int dp[][][];
//public static long bf[][];
public static long mod =0;
/*public static void bf(int pos,int vec,int llevo,int tot,int prop){
if(pos==0){
bf[vec][prop]=(bf[vec][prop]+1)%mod;
return;
}
for(int n = 1;n<=tot;n++){
int prop2 = prop;
if(((1<<n)&llevo)!=0)continue;
if(pos==1){
if(n==tot)prop2|=1;
if(n==tot-1)prop2|=2;
}
if(pos==2){
if(n==tot)prop2|=(1<<2);
if(n==tot-1)prop2|=(1<<3);
if(n==tot-2)prop2|=(1<<4);
}
bf(pos-1,vec+((Math.abs((tot-pos+1)-n)==1)?1:0),llevo|(1<<n),tot,prop2);
}
}*/
public static long sum(int a,int b,String c[],long voy){
long tal =0;
if(a<0 || a>=dp.length || b<0 || b>=dp.length) return 0;
for(int n= 0;n<c.length;n++)
tal = (tal+dp[a][b][Integer.parseInt(c[n],2)])%mod;
return tal%mod;
}
public static long sum2(int a,int b,String c,long voy){
long tal =0;
if(a<0 || a>=dp.length || b<0 || b>=dp.length) return 0;
int y = 0;
for(int n =0;n<c.length();n++){
if(y>1)return 0;
if(n==3)y =0;
if(c.charAt(n)=='1')y++;
}

int d = c.indexOf("*");
if(d==-1)return dp[a][b][Integer.parseInt(c,2)];
for(int n = 0;n<2;n++)
tal=(tal+sum2(a,b,c.substring(0,d)+n+c.substring(d+1),0))%mod;
return tal%mod;
}
public static void main(String args[]) throws IOException{
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
String tmp = lector.readLine();
int a = Integer.parseInt(tmp.substring(0,tmp.indexOf(" ")));
int b = Integer.parseInt(tmp.substring(tmp.indexOf(" ")+1));
mod = 1000000007;
long res = 0;
//bf = new long[Math.max(a+2,4)][33];
dp= new int[Math.max(a+2,4)][Math.max(a+2,4)][19];
dp[1][0][1]=1;
dp[2][0][9]=1;
dp[2][2][6]=1;
dp[3][0][9]=1;
dp[3][0][8]=1;
dp[3][2][6]=1;
dp[3][2][17]=1;
dp[3][2][4]=1;
dp[3][2][18]=1;
String rejoder[] = {"00010","10010","01010","00110"};
String joder[] ={"00000","10000","01000","00100"};
String joder1[] = {"00001","01001","10001"};
String joder2[] = {"00010","10010","00110"};
String joder3[] = {"00000","01000","10000"};
String joder4[] = {"00010","10010"};
int nn = 4,mm=0;
for(long n = 4;nn<a+1;n++,nn++){
mm=0;
for(long m = 0;mm<=n;m++,mm++){
//dp[n][m][0]=(((m+1)*sum(n-1,m+1,joder,0))%mod+((n-1-m-1)*sum(n-1,m,joder,0))%mod)%mod;
dp[nn][mm][0]=(int)((((m*dp[nn-1][mm+1][4])%mod+((n-m-2<0?0:n-m-2)*dp[nn-1][mm][4])%mod)%mod+((((m+1)*dp[nn-1][mm+1][8])%mod+
((n-m-3<0?0:n-m-3)*dp[nn-1][mm][8])%mod)%mod +(((m+1)*dp[nn-1][mm+1][16])%mod+((n-m-3<0?0:n-m-3)*dp[nn-1][mm][16])%mod)%mod+
(((m+1)*dp[nn-1][mm+1][0])%mod+((n-m-3<0?0:n-m-3)*dp[nn-1][mm][0])%mod)%mod)%mod)%mod);//ta loco
dp[nn][mm][1]=(int)(sum(nn-1,mm,joder,0)%mod);
dp[nn][mm][9]=(int)(sum(nn-1,mm,joder1,0)%mod);
dp[nn][mm][17]=(int)(sum(nn-1,mm,joder2,0)%mod);
dp[nn][mm][2]=(int)((dp[nn-1][mm][4]+sum(nn-1,mm-1,joder3,0))%mod);
//dp[n][m][16]=((m+1)*sum(n-1,m+1,joder2,0)%mod+((n-1-m-1)*sum(n-1,m,joder2,0))%mod)%mod;
dp[nn][mm][16]=(int)(((((m-1<0?0:m-1)*dp[nn-1][mm+1][6])%mod+((n-m-1<0?0:n-m-1)*dp[nn-1][mm][6])%mod)%mod+(((m*dp[nn-1][mm+1][18])%mod+
((n-m-2<0?0:n-m-2)*dp[nn-1][mm][18])%mod)%mod+((m*dp[nn-1][mm+1][2])%mod+((n-m-2<0?0:n-m-2)*dp[nn-1][mm][2])%mod)%mod)%mod)%mod);//ta loco
dp[nn][mm][18]=(int)((dp[nn-1][mm][6]+sum(nn-1,mm-1,joder4,0))%mod);
dp[nn][mm][6] = (int)(sum(nn-1,mm-2,joder1,0)%mod);
dp[nn][mm][4] = (int)((sum(nn-1,mm-1,joder,0)+sum(nn-1,mm,rejoder,0))%mod);//ta loco
dp[nn][mm][8] = (int)(((m+1)*sum(nn-1,mm+1,joder1,0)%mod+((n-1-m-1)*sum(nn-1,mm,joder1,0))%mod)%mod);
}

}
//bf(a,0,0,a,0);
//long res2 = 0;
for(int k = 0;k<op.length;k++){
//System.out.println(a+" "+b+" "+op[k]+" "+dp[a][b][op[k]]+" "+bf[b][op[k]]);
res=(res+dp[a][b][op[k]])%mod;
//res2 = (res2+bf[b][op[k]])%mod;
}
System.out.println(res%mod);//+" "+res2%mod);
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;

public class F {

	public static void main(String[] args) throws IOException {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt(), m = scan.nextInt();
		ArrayList<Integer>[] adj = new ArrayList[n];
		int[] d = new int[n];
		for(int i = 0; i < n; i++) adj[i] = new ArrayList<Integer>();
		for(int i = 0; i < m; i++) {
			int x = scan.nextInt()-1, y = scan.nextInt()-1;
			if(!adj[x].contains(y) && x != y){
				adj[x].add(y);
				adj[y].add(x);
				d[x]++;
				d[y]++;
			}
		}
		for(int i = 0; i < n; i++)Collections.sort(adj[i], new Comparator<Integer>(){@Override public int compare(Integer a, Integer b) {if(d[a]==d[b]) return a-b;return d[a]-d[b];}});
		boolean res = false;
		for(int i = 0; i < n; i++){
			int c = go(i, adj, n, new boolean[n], 0);
			if(c == n) res = true;
		}
		out.println(res?"Yes":"No");
		out.close();
	}

	static int go(int at, ArrayList<Integer>[] adj, int n, boolean[] v, int c){
		v[at] = true;
		int res = 0;
		for(int i : adj[at]) if(!v[i])res = Math.max(res, go(i, adj, n, v, c));
		return res+1;
	}

	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner() {
			try	{
				br = new BufferedReader(new InputStreamReader(System.in));
				st = new StringTokenizer(br.readLine());
			} catch (Exception e){e.printStackTrace();}
		}

		public String next() {
			if (st.hasMoreTokens())	return st.nextToken();
			try {st = new StringTokenizer(br.readLine());}
			catch (Exception e) {e.printStackTrace();}
			return st.nextToken();
		}

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

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

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

		public String nextLine() {
			String line = "";
			try {line = br.readLine();}
			catch (Exception e) {e.printStackTrace();}
			return line;
		}

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

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

		public double[] nextDoubleArray(int n){
			double[] a = new double[n];
			for(int i = 0; i < n; i++) a[i] = nextDouble();
			return a;
		}

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

}


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

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

    FastReader in = new FastReader();
    PrintWriter out = new PrintWriter(System.out);
    void run() {
        work();
        out.flush();
    }
    long mod=998244353;
    long gcd(long a,long b) {
        return a==0?b:gcd(b%a,a);
    }
    void work() {
        int n=ni(),k=ni();
        long[][] dp=new long[251][251];
        for(int j=1;j<=k;j++){
            dp[1][j]=1;
        }
        long[][] pow=new long[251][251*251];
        long[][] C=new long[251][251];
        for(int i=1;i<=250;i++){
            pow[i][0]=1;
            for(int j=1;j<251*251;j++){
                pow[i][j]=pow[i][j-1]*i%mod;
            }
        }
        for(int i=0;i<=250;i++){
            for(int j=0;j<=i;j++){
                if(i==0||j==0){
                    C[i][j]=1;
                }else{
                    C[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;
                }
            }
        }
        for(int j=0;j<=k;j++){
            dp[0][j]=1;
        }
        for(int i=1;i<=n-1;i++){
            for(int j=1;j<=k;j++){
                dp[i][j]=dp[i][j-1];
                for(int p=1;p<=i;p++){
                    dp[i][j]+=dp[i-p][j-1]*C[i][p]%mod*pow[k-j+1][p*(i-p)+(p-1)*p/2]%mod;
                }
            }
        }
        out.println(dp[n-1][k]);
    }

    private ArrayList<Integer>[] ng(int n, int m) {
        ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
        for(int i=0;i<n;i++) {
            graph[i]=new ArrayList<>();
        }
        for(int i=1;i<=m;i++) {
            int s=in.nextInt()-1,e=in.nextInt()-1;
            graph[s].add(e);
            graph[e].add(s);
        }
        return graph;
    }

    private ArrayList<long[]>[] ngw(int n, int m) {
        ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
        for(int i=0;i<n;i++) {
            graph[i]=new ArrayList<>();
        }
        for(int i=1;i<=m;i++) {
            long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
            graph[(int)s].add(new long[] {e,w});
            graph[(int)e].add(new long[] {s,w});
        }
        return graph;
    }

    private ArrayList<int[]>[] ngwi(int n, int m) {
        ArrayList<int[]>[] graph=(ArrayList<int[]>[])new ArrayList[n];
        for(int i=0;i<n;i++) {
            graph[i]=new ArrayList<>();
        }
        for(int i=1;i<=m;i++) {
            int s=ni()-1,e=ni()-1,w=ni();
            graph[s].add(new int[] {e,w});
            graph[e].add(new int[] {s,w});
        }
        return graph;
    }

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

    private long nl() {
        return in.nextLong();
    }
    private double nd() {
        return in.nextDouble();
    }
    private String ns() {
        return in.next();
    }

    private long[] na(int n) {
        long[] A=new long[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextLong();
        }
        return A;
    }

    private int[] nia(int n) {
        int[] A=new int[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextInt();
        }
        return A;
    }
}

class FastReader
{
    BufferedReader br;
    StringTokenizer st;
    InputStreamReader input;//no buffer
    public FastReader()
    {
        br=new BufferedReader(new InputStreamReader(System.in));
    }

    public FastReader(boolean isBuffer)
    {
        if(!isBuffer){
            input=new InputStreamReader(System.in);
        }else{
            br=new BufferedReader(new InputStreamReader(System.in));
        }
    }

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

    public String next()
    {
        if(input!=null){
            try {
                StringBuilder sb=new StringBuilder();
                int ch=input.read();
                while(ch=='\n'||ch=='\r'||ch==32){
                    ch=input.read();
                }
                while(ch!='\n'&&ch!='\r'&&ch!=32){
                    sb.append((char)ch);
                    ch=input.read();
                }
                return sb.toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        while(st==null || !st.hasMoreElements())//回车，空行情况
        {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    public int nextInt()
    {
        return (int)nextLong();
    }

    public long nextLong() {
        try {
            if(input!=null){
                long ret=0;
                int b=input.read();
                while(b<'0'||b>'9'){
                    b=input.read();
                }
                while(b>='0'&&b<='9'){
                    ret=ret*10+(b-'0');
                    b=input.read();
                }
                return ret;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Long.parseLong(next());
    }

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


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

    public class Main {
        public int[][]stacks;
        public int[]levels;
        public int[]offset;
        public int[]d;
        public ArrayList<String>mooves;

        public Main(){
            Scanner nera = new Scanner(System.in);
            byte n=nera.nextByte();
            d=new int[n];
            for(int i=0;i<n;i++)
                d[i]=nera.nextInt();
            stacks=new int[3][n];
            for(int i=0;i<n;i++)
                stacks[0][i]=i;
            levels=new int[]{n,0,0};
            offset=new int[]{0,0,0};
            mooves=new ArrayList<String>();
        }

        public void moove(int src, int dest){
            //System.out.println((src+1)+" "+(dest+1));
            levels[src]--;
            stacks[dest][levels[dest]]=stacks[src][levels[src]];
            levels[dest]++;
            mooves.add((src+1)+" "+(dest+1));
        }

         public void solve(int src, int dest, boolean toReverse){
            if(offset[src]==levels[src])
                return;

            int swap=3-src-dest;
            int base=d[stacks[src][offset[src]]];
            int thick=0;
            while(offset[src]<levels[src]&&d[stacks[src][offset[src]]]==base){
                thick++;
                offset[src]++;
            }

            if(toReverse||thick==1){
                solve(src, swap, true);
                offset[src]-= thick;
                for (int i=0; i<thick; ++i)
                    moove(src, dest);
                offset[dest]+= thick;
                solve(swap, dest, true);
                offset[dest]-= thick;
            }else{
                if(offset[src]==levels[src]){
                    offset[src]-=thick;
                    for(int i=0;i<thick-1;i++)
                        moove(src, swap);
                    moove(src, dest);
                    for(int i=0;i<thick-1;i++)
                        moove(swap, dest);
                }else{
                    solve(src, dest, true);
                    offset[src]-=thick;
                    for(int i=0;i<thick;i++)
                        moove(src, swap);
                    offset[swap]+=thick;
                    solve(dest,src,true);
                    offset[swap]-=thick;
                    for(int i=0;i<thick;i++)
                        moove(swap,dest);
                    offset[dest]+=thick;
                    solve(src, dest, false);

                }
            }
         }

         public void printResult(){
             System.out.println(mooves.size());
             for(String s:mooves)
                 System.out.println(s);
         }

        public static void main(String[] args) {
            Main m=new Main();
            m.solve(0, 2,false);
            m.printResult();

        }
    }


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

public class ProblemC {
    InputReader in; PrintWriter out;
    void temp(int m) {
        out.println("m == " + m);
        int[][] a = new int[m + 2][m + 2];
        for (int j = 1; j <= m; j++)
            a[1][j] = 0;
        a[1][m + 1] = 1;
        for (int i = 2; i <= m + 1; i++)
            for (int j = 1; j <= m + 1; j++) {
                if (j == 1)
                    a[i][j] = a[i - 1][j + 1];
                else {
                    if (j == m + 1)
                        a[i][j] = a[i - 1][j - 1];
                    else
                        a[i][j] = (a[i - 1][j - 1] ^ a[i - 1][j + 1]);
                }
            }
//      for (int i = 1; i <= m + 1; i++, out.println())
//          for (int j = 1; j <= m + 1; j++)
//              out.print(a[i][j] + " ");
        int s = 0;
        for (int i = 1; i <= m + 1; i++)
            s += a[m + 1][i];
        out.println("s == " + s);
    }
    long[][] C = new long[42][42];
    long calc(long n, int nt) {
//      out.println("calc " + n + " " + nt);
        if (nt < 0)
            return 0;
        if (n == 0)
            if (nt == 0)
                return 1;
            else
                return 0;
        if (n == 1)
            if (nt <= 1)
                return 1;
            else
                return 0;
        if (n == 2)
            if (nt == 0)
                return 1;
            else if (nt == 1)
                return 2;
            else
                return 0;
        long st2 = 1;
        int k = 0;
        while (st2 <= n + 1) {
            st2 *= 2;
            k++;
        }
        st2 /= 2;
        k--;
//      out.println("c == " + C[k][nt] + " k, nt: " + k + " " + nt);
        return calc(n - st2, nt - 1) + C[k][nt];
    }
    void solve() {
//      int m = 20;
//      for (int i = 0; i <= m; i++)
//          temp(i);
        long n = in.nextLong();
        long t = in.nextLong();
        n++;
        long st2 = 1;
        int k = 0;
        while (st2 < t) {
            k++;
            st2 *= 2;
        }
        if (st2 != t) {
            out.println("0");
            return;
        }
        int nt = k + 1;
        C[0][0] = 1;
        for (int i = 1; i <= 41; i++)
            for (int j = 0; j <= i; j++) {
                if (j == 0)
                    C[i][j] = 1;
                else
                    C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
            }
        long ans = calc(n, nt);
        if (nt == 1)
            ans--;
        out.println(ans);
    }

    ProblemC(){
        boolean oj = System.getProperty("ONLINE_JUDGE") != null;
        try {
            if (oj) {
                in = new InputReader(System.in);
                out = new PrintWriter(System.out);
            }
            else {
                Writer w = new FileWriter("output.txt");
                in = new InputReader(new FileReader("input.txt"));
                out = new PrintWriter(w);
            }
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
        solve();
        out.close();
    }
    public static void main(String[] args){
        new ProblemC();
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

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

    public InputReader(FileReader fr) {
        reader = new BufferedReader(fr);
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }
    public int nextInt() {
        return Integer.parseInt(next());
    }
    public long nextLong() {
        return Long.parseLong(next());
    }
    public double nextDouble() {
        return Double.parseDouble(next());
    }

}


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

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

class TaskD {
        long k;
        final long MOD = 1_000_000_007;
        long[][][] dp = new long[31][31][2];

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
                k = in.nextInt();
                for (int i = 0; i < 31; i++)
                        for (int j = 0; j < 31; j++)
                                Arrays.fill(dp[i][j], -1);
                out.println(getDp(30, 0, 0));
        }

        long getDp(int pos, int have, int less) {
                if (pos < 0)
                        return 1;
                if (dp[pos][have][less] != -1)
                        return dp[pos][have][less];
                //Put zero at pos bit.
                long res = getDp(pos - 1, have, getBit(pos) == 0 ? less : 1);
                //Put one at pos bit.
                if (less == 1) {
                        //Add to one of the existing vectors.
                        if (have > 0) {
                                res += getDp(pos - 1, have, 1) * getAll(have);
                                res %= MOD;
                        }
                        //Add a new vector.
                        res += getDp(pos - 1, have + 1, 1);
                        res %= MOD;
                } else if (getBit(pos) == 1) {
                                //Create a new vector.
                                res += getDp(pos - 1, have + 1, 0);
                                res %= MOD;
                                //Add to one of the existing vectors.
                                res += getDp(pos - 1, have, 0) * getAll(have);
                                res %= MOD;
                }
                return dp[pos][have][less] = res;
        }

        long getAll(int have) {
                return ((1L << have) - 1 + MOD) % MOD;
        }

        int getBit(int pos) {
                return (k & (1L << pos)) == 0 ? 0 : 1;
        }
}

class FastScanner {
        BufferedReader reader;
        StringTokenizer tokenizer;

        public FastScanner(InputStream inputStream)  {
                reader = new BufferedReader(new InputStreamReader(inputStream));
        }

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

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

        }


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

public class _LiftLevel5E {

	static boolean[][] locked;
	static int[][] board;
	static int[][] solved;
	static int w, h;
	static ArrayList<String> answer=new ArrayList<>();

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		h=fs.nextInt(); w=fs.nextInt();
		board=new int[w][h];
		solved=new int[w][h];
		locked=new boolean[w][h];
		for (int y=0; y<h; y++) {
			for (int x=0; x<w; x++) {
				board[x][y]=fs.nextInt();
				solved[x][y]=x+y*w+1;
			}
		}
		//solve ys [0, h-2)
		for (int yToSolveFor=0; yToSolveFor<h-2; yToSolveFor++) {
			for (int xToSolveFor=0; xToSolveFor<w-1; xToSolveFor++) {
				naiveMoveToXFirst(solved[xToSolveFor][yToSolveFor], xToSolveFor, yToSolveFor);
				locked[xToSolveFor][yToSolveFor]=true;
			}
			//now handle the rightmost position
			if (board[w-1][yToSolveFor]==solved[w-1][yToSolveFor]) {
				locked[w-1][yToSolveFor]=true;
				continue;
			}
			naiveMoveToXFirst(solved[w-1][yToSolveFor], w-1, h-1);
			hardCW4(w-2, yToSolveFor);
			naiveMoveToXFirst(solved[w-1][yToSolveFor], w-1, yToSolveFor+1);
			hardCCW4(w-2, yToSolveFor);
			locked[w-2][yToSolveFor]=locked[w-1][yToSolveFor]=true;
		}
//		print(board);

		//now we only have the last two ys left
		for (int x=0; x<w-2; x++) {
//			print(board);
			naiveMoveToXFirst(solved[x][h-1], x, h-1);
			if (solved[x][h-2]==board[x][h-2]) {
				locked[x][h-1] = locked[x][h-2]=true;
				continue;
			}
			locked[x][h-2] = true;
			naiveMoveToXFirst(solved[x][h-2], w-1, h-1);
			hardCW4(x, h-2);
			naiveMoveToXFirst(solved[x][h-2], x+1, h-2);
			hardCCW4(x, h-2);
			locked[x][h-1]=true;
		}

		//TODO: handle the last 4 spaces
		while (board[w-2][h-2]!=solved[w-2][h-2]) {
			hardCW4(w-2, h-2);
		}
		int target=solved[w-1][h-2];
		if (board[w-1][h-2]==target) {

		}
		else if (board[w-2][h-1]==target) {
			swapBottom2();
			swapRight2();
		}
		else {
			swapRight2();
		}
		target=board[w-2][h-1];
		if (board[w-2][h-1]==target) {

		}
		else {
			swapBottom2();
		}
		System.out.println(answer.size());
		for (String s:answer) {
			System.out.println(s);
		}
	}

	static void sixCycle() {
		hardCCW4(w-2, h-2);
		hardCCW4(w-3, h-2);
		moveNoWarnings(w-3, h-2, w-2, h-2, w-1, h-2,
				w-1, h-1, w-2, h-1, w-3, h-1);
	}

	static void swapRight2() {
		hardCCW4(w-2, h-2);
		sixCycle();
		hardCW4(w-2, h-2);
	}

	static void swapLeft2() {
		hardCW4(w-2, h-2);
		sixCycle();
		hardCCW4(w-2, h-2);
	}

	static void swaptTop2() {
		sixCycle();
	}

	static void swapBottom2() {
		hardCW4(w-2, h-2);
		hardCW4(w-2, h-2);
		sixCycle();
		hardCCW4(w-2, h-2);
		hardCCW4(w-2, h-2);
	}

	static boolean movable(int x, int y) {
		if (x< 0 || x>=locked.length || y<0 || y>=locked[x].length) return false;
		return !locked[x][y];
	}

	//moves x first then y
	static void naiveMoveToXFirst(int toMove, int targetX, int targetY) {
		Point curPos=locationOf(toMove);
		int curX=curPos.x;
		int curY=curPos.y;
		while (curX<targetX) {
			moveRight(curX, curY);
			curX++;
		}
		while (curX>targetX) {
			moveLeft(curX, curY);
			curX--;
		}
		while (curY<targetY) {
			moveDown(curX, curY);;
			curY++;
		}
		while (curY>targetY) {
			moveUp(curX, curY);
			curY--;
		}
	}

	static void moveLeft(int x, int y) {
		if (!movable(x, y) || !movable(x-1, y)) {
			throw null;
		}
		if (movable(x-1, y+1) && movable(x, y+1)) {
			move(x, y, x-1, y, x-1, y+1, x, y+1);
			return;
		}
		if (movable(x-1, y-1) && movable(x-1, y-1)) {
			move(x, y, x-1, y, x-1, y-1, x, y-1);
			return;
		}
		throw null;
	}

	static void moveRight(int x, int y) {
		if (!movable(x, y) || !movable(x+1, y)) {
			throw null;
		}
		if (movable(x+1, y+1) && movable(x, y+1)) {
			move(x, y, x+1, y, x+1, y+1, x, y+1);
			return;
		}
		if (movable(x+1, y-1) && movable(x, y-1)) {
			move(x, y, x+1, y, x+1, y-1, x, y-1);
			return;
		}
//		System.out.println("Trying to move right on pos: "+x+" "+y+" but it is impossible");
//		print(locked);
		throw null;
	}

	static void moveDown(int x, int y) {
		if (!movable(x, y) || !movable(x, y+1)) {
			throw null;
		}
		if (movable(x-1, y+1) && movable(x-1, y)) {
			move(x, y, x, y+1, x-1, y+1, x-1, y);
			return;
		}
		if (movable(x+1, y+1) && movable(x+1, y)) {
			move(x, y, x, y+1, x+1, y+1, x+1, y);
			return;
		}
		throw null;
	}

	static void moveUp(int x, int y) {
		if (!movable(x, y) || !movable(x, y-1)) {
			throw null;
		}
		if (movable(x-1, y-1) && movable(x-1, y)) {
			move(x, y, x, y-1, x-1, y-1, x-1, y);
			return;
		}
		if (movable(x+1, y-1) && movable(x+1, y)) {
			move(x, y, x, y-1, x+1, y-1, x+1, y);
			return;
		}
		throw null;
	}

	static void move(int ...input) {
		if (input.length%2!=0) throw null;
		int[] xs=new int[input.length/2], ys=new int[input.length/2];
		for (int i=0; i<input.length; i+=2) {
			xs[i/2]=input[i];
			ys[i/2]=input[i+1];
		}
		int nPoints=input.length/2;
		for (int i=0; i<nPoints; i++) {
			if (!movable(xs[i], ys[i])) throw null;
		}
		int[] old=new int[nPoints];
		for (int i=0; i<nPoints; i++) old[i]=board[xs[i]][ys[i]];
		for (int i=0; i<nPoints; i++) board[xs[i]][ys[i]] = old[(i-1+nPoints)%nPoints];
		StringBuilder sb=new StringBuilder(nPoints+" ");
		for (int i:old) {
			sb.append(i+" ");
		}
		answer.add(sb.toString());
	}

	static void moveNoWarnings(int ...input) {
		if (input.length%2!=0) throw null;
		int[] xs=new int[input.length/2], ys=new int[input.length/2];
		for (int i=0; i<input.length; i+=2) {
			xs[i/2]=input[i];
			ys[i/2]=input[i+1];
		}
		int nPoints=input.length/2;
		int[] old=new int[nPoints];
		for (int i=0; i<nPoints; i++) old[i]=board[xs[i]][ys[i]];
		for (int i=0; i<nPoints; i++) board[xs[i]][ys[i]] = old[(i-1+nPoints)%nPoints];
		StringBuilder sb=new StringBuilder(nPoints+" ");
		for (int i:old) {
			sb.append(i+" ");
		}
		answer.add(sb.toString());
	}

	static void hardCW4(int topLeftX, int topLeftY) {
		moveNoWarnings(topLeftX, topLeftY, topLeftX+1, topLeftY, topLeftX+1, topLeftY+1, topLeftX, topLeftY+1);
	}

	static void hardCCW4(int topLeftX, int topLeftY) {
		moveNoWarnings(topLeftX, topLeftY, topLeftX, topLeftY+1, topLeftX+1, topLeftY+1, topLeftX+1, topLeftY);
	}

	static Point locationOf(int i) {
		for(int x=0; x<w; x++) {
			for (int y=0; y<h; y++) {
				if (board[x][y]==i) return new Point(x, y);
			}
		}
//		System.out.println("Couldn't find location of "+i+" in ");
//		print(board);
		throw null;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreElements()) {
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

	static void print(int[][] board) {
		for (int y=0; y<board[0].length; y++) {
			for (int x=0; x<board.length; x++) System.out.print(board[x][y]+" ");
			System.out.println();
		}
		System.out.println();
	}
	static void print(boolean[][] board) {
		for (int y=0; y<board[0].length; y++) {
			for (int x=0; x<board.length; x++) System.out.print((board[x][y]?"*":"_")+" ");
			System.out.println();
		}
		System.out.println();
	}
}


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 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];

		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=ids.getOrDefault(x, id++),idy=ids.getOrDefault(y, 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;
	}
}


import java.util.*;

public class R0_task_C {
    static int n,s,k;
    static int[]r;
    static char[]c;

    static box[] allBoxes;

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

        n = in.nextInt();
        s = in.nextInt();
        k = in.nextInt();

        r = new int[n+1];
        r[0] = 0;
        for (int i = 0; i < n; i++)
          r[i+1] = in.nextInt();

        c = new char[n+1];
        String st = "*" + in.next();
        c = st.toCharArray();
        //-------------

        allBoxes = new box[n+1];
        allBoxes[0] = new box(0);

        //int t = fullScan(0, 0, k);
        int t = allBoxes[0].eat(0, k);
        System.out.println(t);
    }
/*
    static int fullScan(int from, int time, int restCount){
        if (restCount <= 0)
            return time;

        int minTime = -1;
        for (int to = 1; to <= n; to++) {
            if (enabled(from, to)) {
               int curTime = from == 0 ? Math.abs(s - to) : Math.abs(from - to);
               int restTime = fullScan(to, time + curTime, restCount - r[to]);
               if (restTime >= 0)
                    if (restTime < minTime || minTime == -1)
                        minTime = restTime;
            }
        }
        return minTime;
    }
*/
    static boolean enabled(int from, int to){
        return r[from] < r[to] && c[from] != c[to];
    }

    static class box implements Comparable<box>{

        int idx;
        ArrayList<box> nexts = new ArrayList<>();

        public box(int idx) {
            this.idx = idx;
            boolean hasNext = false;
            for (int target = 1; target <= n; target++){
                if (enabled(idx, target)) {
                    if (allBoxes[target] == null)
                        allBoxes[target] = new box(target);
                    nexts.add(allBoxes[target]);
                    hasNext = true;
                }
            }
            if (hasNext)//!nexts.isEmpty())
                Collections.sort(nexts);
        }

        int eat(int time, int restCount){
            if (restCount <= 0)
                return time;

            int from = idx;
            int minTime = -1;

            for (box b: nexts) {
                int to = b.idx;
                int curTime = from == 0 ? Math.abs(s - to) : Math.abs(from - to);
                int restTime = b.eat( time + curTime, restCount - r[to]);
                if (restTime >= 0)
                    if (restTime < minTime || minTime == -1)
                        minTime = restTime;
            }
            return minTime;
        }

        @Override
        public int compareTo(box o) {
            return r[this.idx] - r[o.idx];
        }
    }
}


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

public class Solver {

    StringTokenizer st;
    BufferedReader in;
    PrintWriter out;

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

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

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

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

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

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

    enum State{
        IGNORE,ASSIGN,USE;

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

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

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

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

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

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

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

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

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

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

}


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

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

    static class TaskD
    {
        public void solve(int testNumber, Scanner in, PrintWriter out)
        {
            int T = 1;
            while (T-- > 0)
            {
                solveOne(in, out);
            }
        }

        private void solveOne(Scanner in, PrintWriter out)
        {
            int N = in.nextInt();
            int nums[] = CPUtils.readIntArray(N, in);

            int ans = Integer.MAX_VALUE;
            for (int i = 0; i < N; i++)
            {
                for (int l = 0; l < i; l++)
                {
                    for (int r = i; r < N; r++)
                    {
                        int resL = 0, resR = 0;
                        for (int ll = l; ll < i; ll++) resL ^= nums[ll];
                        for (int rr = i; rr <= r; rr++) resR ^= nums[rr];
                        if (resL > resR)
                        {
                            ans = Math.min(ans, r - l - 1);
                        }
                    }
                }
            }
            if (ans == Integer.MAX_VALUE)
            {
                out.println(-1);
            } else
            {
                out.println(ans);
            }

        }

    }

    static class CPUtils
    {
        public static int[] readIntArray(int size, Scanner in)
        {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
            {
                array[i] = in.nextInt();
            }
            return array;
        }

    }
}


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

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

    static class ThreePieces {
        int[][][][][] dp = new int[201][10][10][100][3];
        int INF = (int) (1e9);
        ArrayList<int[]>[][][] move = new ArrayList[10][10][3];
        int N;
        int[] moveR = new int[]{-2, -1, 1, 2};
        int[] moveC = new int[]{-2, -1, 1, 2};

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            N = in.nextInt();
            int[][] loc = new int[N * N][2];
            int[][] arr = new int[N][N];
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    int a = in.nextInt() - 1;
                    loc[a] = new int[]{i, j};
                    arr[i][j] = a;
                    move[i][j][0] = posKnight(i, j);
                    move[i][j][1] = posBishop(i, j);
                    move[i][j][2] = posRook(i, j);
                }
            }
            for (int i = 0; i <= 200; i++) {
                for (int j = 0; j < 10; j++) {
                    for (int k = 0; k < 10; k++) {
                        for (int d = 0; d < 100; d++) {
                            for (int z = 0; z < 3; z++) {
                                dp[i][j][k][d][z] = INF;
                            }
                        }
                    }
                }
            }
            Arrays.fill(dp[0][loc[0][0]][loc[0][1]][0], 0);
            for (int i = 0; i < 200; i++) {
                for (int j = 0; j < N; j++) {
                    for (int k = 0; k < N; k++) {
                        for (int d = 0; d < N * N; d++) {
                            for (int m = 0; m < 3; m++) {
                                for (int next = 0; next < 3; next++) {
                                    for (int[] c : move[j][k][next]) {
                                        if (arr[c[0]][c[1]] == d + 1) {
                                            dp[i + 1][c[0]][c[1]][d + 1][next] = Math.min(dp[i + 1][c[0]][c[1]][d + 1][next], dp[i][j][k][d][m] + (m == next ? 0 : 1));
                                        } else {
                                            dp[i + 1][c[0]][c[1]][d][next] = Math.min(dp[i + 1][c[0]][c[1]][d][next], dp[i][j][k][d][m] + (m == next ? 0 : 1));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            int resT = INF;
            int resP = INF;
            for (int i = 2; i <= 200; i++) {
                for (int v : dp[i][loc[N * N - 1][0]][loc[N * N - 1][1]][N * N - 1]) {
                    if (resT + resP >= v + i) {
                        if (resT + resP == v + i) {
                            if (v < resP) {
                                resT = i;
                                resP = v;
                            }
                        } else {
                            resT = i;
                            resP = v;
                        }
                    }
                }
            }
            out.println((resT + resP) + " " + resP);
        }

        boolean isValid(int r, int c) {
            return r >= 0 && r < N && c >= 0 && c < N;
        }

        ArrayList<int[]> posKnight(int r, int c) {
            ArrayList<int[]> pos = new ArrayList<>();
            for (int rM : moveR) {
                for (int cM : moveC) {
                    if (Math.abs(rM) != Math.abs(cM)) {
                        int newR = r + rM;
                        int newC = c + cM;
                        if (isValid(newR, newC)) {
                            pos.add(new int[]{newR, newC});
                        }
                    }
                }
            }
            return pos;
        }

        ArrayList<int[]> posRook(int r, int c) {
            ArrayList<int[]> pos = new ArrayList<>();
            for (int i = 0; i < N; i++) {
                pos.add(new int[]{r, i});
                pos.add(new int[]{i, c});
            }
            return pos;
        }

        ArrayList<int[]> posBishop(int r, int c) {
            ArrayList<int[]> pos = new ArrayList<>();
            for (int k = 1; k < N; k++) {
                int[] mR = new int[]{k, -k, k, -k};
                int[] mC = new int[]{k, k, -k, -k};
                for (int i = 0; i < 4; i++) {
                    int newR = r + mR[i];
                    int newC = c + mC[i];
                    if (isValid(newR, newC)) {
                        pos.add(new int[]{newR, newC});
                    }
                }
            }
            return pos;
        }

    }

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

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

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

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

    }
}


import java.io.PrintWriter;
import java.sql.Time;
import java.util.Scanner;
import java.util.Timer;

public class problem4_2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		//Timer TT = new Timer();
		//TT.purge();
		//System.out.println(TT.toString());
		PrintWriter out = new PrintWriter(System.out);
		int R = in.nextInt();
		out.print(Hexagon(R));
		out.close();
	}

 public static long Hexagon(long R){
	 long Count = 0;
	 long l = 0;
	 long k = R+1;
	 double x = 0.25;
	 double y = 3*(1.5 + k)*(1.5 + k);
	 while (k>=0 || (x+y<=R*R && k==0) ){
		 if(x+y>R*R) {
			 k--;
			 y = 3*(1.5+0.5*l+k)*(1.5+0.5*l+k);
		 }
		 else{
		 Count+=k+1; l++;
		 x = (0.5+1.5*l)*(0.5+1.5*l);
		 y = 3*(1.5+0.5*l+k)*(1.5+0.5*l+k);

		 }
	 }
	 return Count*6+1;
 }

}


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

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

/**
 *
 * @author Andy Phan
 */
public class m {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        System.out.println((((in.nextLong()%360+360+44)%360)%359)/90);

        out.close();
    }

    static class FS {

        BufferedReader in;
        StringTokenizer token;

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

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

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


import static java.util.Arrays.*;

import java.math.*;

public class E {

	public Object solve () {
		int N = sc.nextInt() - 1, S = sc.nextInt(), R = sc.nextInt();

		if (N == 0)
			return exit(1);
		if (R == 0)
			if (S == 0)
				return exit(modInv(N+1));
			else
				return 0;

		long [][] C = modBin(N, N);

		long P = 0;
		for (int b = S; b >= R; --b) {
			if (b * N < S - b)
				break;

			long [][] F = new long [N+1][S+1]; fill(F[0], 1);
			for (int k = 1; k <= N; ++k) {
				F[k][0] = 1;
				for (int x = 1; x <= S; ++x) {
					F[k][x] = (F[k][x-1] + F[k-1][x]) % MOD;
					if (x >= b)
						F[k][x] = (F[k][x] + MOD - F[k-1][x-b]) % MOD;
				}
			}

			for (int j = 0; j <= N; ++j) {
				int T = S - b * (j+1);
				if (T >= 0) {
					long D = F[N-j][T];
					if (T > 0)
						D = (D + MOD - F[N-j][T-1]) % MOD;
					long Z = (C[N][j] * D) % MOD;
					P = (P + Z * modInv(j+1)) % MOD;
				}
			}
		}

		long Q = 0;
		long [][] F = new long [N+1][S+1]; fill(F[0], 1);
		for (int k = 1; k <= N; ++k) {
			F[k][0] = 1;
			for (int x = 1; x <= S; ++x)
				F[k][x] = (F[k][x-1] + F[k-1][x]) % MOD;
		}
		Q = F[N][S-R];

		long res = (P * modInv(Q)) % MOD;
		return exit(res);
	}

	private static final boolean ONE_TEST_CASE = true;

	private static void init () {
	}

	private static final int MOD = 998244353;
	private static long mod (long x) { return mod(x, MOD); }
	private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
	private static long [][] modBin (int N, int K) {
		long [][] res = new long [N+1][K+1];
		for (int n = 0; n <= N; ++n) {
			res[n][0] = 1;
			for (int k = 1; k <= K && k <= n; ++k)
				res[n][k] = mod(res[n-1][k] + res[n-1][k-1]);
		}
		return res;
	}
	private static long modInv(long x) { return modInv(x, MOD); }
	private static long modInv(long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
	//////////////////////////////////////////////////////////////////////////////////// OFF
	private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; }
	private static Object exit (Object o, Object ... A) { print(o, A); IOUtils.exit(); return null; }
	private static class IOUtils {
		public static class MyScanner {
			public String next () { newLine(); return line[index++]; }
			public int nextInt () { return Integer.parseInt(next()); }
			//////////////////////////////////////////////
			private boolean eol () { return index == line.length; }
			private String readLine () {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine () {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim (String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static final java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
		private static void start () { if (t == 0) t = millis(); }
		private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					f.accept(java.lang.reflect.Array.get(o, i));
			}
			else if (o instanceof Iterable<?>)
				((Iterable<?>)o).forEach(f::accept);
			else
				g.accept(o instanceof Double ? formatter.format(o) : o);
		}
		private static void append (final StringBuilder b, Object o, final String delim) {
			append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print (Object o, Object ... A) {
			pw.println(build(o, A));
			if (DEBUG)
				pw.flush();
		}
		private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
		private static boolean DEBUG;
		private static void write (Object o) {
			err(o, '(', time(), ')');
			if (!DEBUG)
				pw.println(o);
		}
		private static void exit () {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(time());
			System.exit(0);
		}
		private static long t;
		private static long millis () { return System.currentTimeMillis(); }
		private static String time () { return "Time: " + (millis() - t) / 1000.0; }
		private static void run (int N) {
			try { DEBUG = System.getProperties().containsKey("DEBUG"); }
			catch (Throwable t) {}

			for (int n = 1; n <= N; ++n) {
				Object res = new E().solve();
				if (res != null)
					write("Case #" + n + ": " + build(res));
			}
			exit();
		}
	}
	////////////////////////////////////////////////////////////////////////////////////
	public static void main (String[] args) {
		init();
		int N = ONE_TEST_CASE ? 1 : sc.nextInt();
		IOUtils.run(N);
	}
}


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

public class F {

	static String[] rank = new String[] {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"};
	static String[] suit = new String[] {"C", "D", "H", "S"};

	public static void main(String[] args) throws IOException {

		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt(), m = sc.nextInt();
		TreeSet<String> cards = new TreeSet<String>();
		for(String r: rank)
			for(String s: suit)
				cards.add(r + s);
		String[][] grid = new String[n][m];
		int[] x = {-1, -1}, y = {-1, -1};
		for(int i = 0; i < n; ++i)
			for(int j = 0; j < m; ++j)
			{
				String c = grid[i][j] = sc.next();
				cards.remove(c);
				if(c.charAt(0) == 'J')
				{
					x[c.charAt(1) - '1'] = i;
					y[c.charAt(1) - '1'] = j;
				}
			}
		StringBuilder sb = new StringBuilder();
		int[][] ans = null;
		if(x[0] != -1 || x[1] != -1)
			main:for(String c1: cards)
				for(String c2: cards)
					if(x[0] == -1 || x[1] == -1 || !c1.equals(c2))
					{
						if(x[0] != -1)
							grid[x[0]][y[0]] = c1;
						if(x[1] != -1)
							grid[x[1]][y[1]] = c2;
						ans = find(grid);
						if(ans != null)
						{
							sb.append("Solution exists.\n");
							if(x[0] != -1 && x[1] != -1)
								sb.append("Replace J1 with " + c1 + " and J2 with " + c2 + ".");
							else if(x[0] == -1)
								sb.append("Replace J2 with " + c2 + ".");
							else
								sb.append("Replace J1 with " + c1 + ".");
							sb.append("\n");
							break main;
						}

					}
		if(ans == null)
			ans = find(grid);
		if(ans != null)
		{
			if(sb.length() == 0)
				sb.append("Solution exists.\nThere are no jokers.\n");

			sb.append("Put the first square to (" + ans[0][0] + ", " + ans[0][1] + ").\n");
			sb.append("Put the second square to (" + ans[1][0] + ", " + ans[1][1] + ").\n");
		}
		if(sb.length() == 0)
			sb.append("No solution.\n");
		out.print(sb);
		out.close();
	}

	static int[][] find(String[][] grid)
	{
		int n = grid.length, m = grid[0].length;
		ArrayList<Integer> x = new ArrayList<>(), y = new ArrayList<>();
		for(int i = 0; i + 3 <= n; ++i)
			for(int j = 0; j + 3 <= m; ++j)
			{
				TreeSet<Character> r = new TreeSet<>();
				TreeSet<Character> s = new TreeSet<>();
				for(int k1 = i; k1 < i + 3; ++k1)
					for(int k2 = j; k2 < j + 3; ++k2)
					{
						r.add(grid[k1][k2].charAt(0));
						s.add(grid[k1][k2].charAt(1));
					}
				if(r.size() == 9 || s.size() == 1)
				{
					x.add(i);
					y.add(j);
				}
			}
		for(int i = 0; i < x.size(); ++i)
			for(int j = 0; j < x.size(); ++j)
				if(x.get(i) + 3 <= x.get(j) || y.get(i) + 3 <= y.get(j))
					return new int[][] {new int[]{x.get(i) + 1, y.get(i) + 1}, new int[]{x.get(j) + 1, y.get(j) + 1}};
					return null;
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

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

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

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

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

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

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

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


import com.sun.xml.internal.bind.v2.model.core.ID;

import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.text.DecimalFormat;
import java.util.*;

public class Main {
    private static int [] inv;
    private static int [] A;
    private static int n;
    private static HashMap<Integer,Integer> HM ;
    private static HashMap<Integer,LinkedList<Integer> > Sol = new HashMap<>();

    private static int mul(int a,int b,int m) {
        long ab = a*(long)b;
        ab %= m;
        if (ab < 0) ab += m;
        return (int) ab;
    }

    private static void init(int a,int p){
        inv = new int[p];
        inv[1] = 1;
        for (int i = 2;i < p;i++)
            inv[i] = mul(-(p/i),inv[p%i],p);

        A = new int[p];
        for (int i = 0,q = 1;i < p;i++) {
            A[i] = q;
            q = mul(a,q,p);
        }

        n = (int)(Math.sqrt(p + 0.0) + 1);
        n = Math.min(n,p-1);
        int an = A[n];
        HM = new HashMap<>();
        for (int i = 1,q = an;i <= n;i++) {
            if (!HM.containsKey(q)) HM.put(q,i);
            q = mul(q,an,p);
        }
    }

    public static void main(String[] args) throws Exception{
        IO io = new IO(null,null);
        int a = io.getNextInt(),b = io.getNextInt(),p = io.getNextInt();
        long x = io.getNextLong();
        init(a,p);

        long ans = 0;
        for (int n0 = 0,q = 1;n0 < p - 1 && n0 <= x;n0++) {
            int y = mul(inv[q],b,p);
            y = n0 - y;
            if (y < 0) y += p;
            // k*(p-1) + n0 <= x
            // k <= (x-n0)/p
            long lim = (x-n0)/(p - 1);
//            System.err.println(n0 + ". " + (y*(p-1L) + n0) + " q = " + q + " y = " + y + " lim = " + lim);
            if (y <= lim)
                ans += (lim - y)/p + 1;

            q = mul(q,a,p);
        }
        io.println(ans);

        io.close();
    }
}

class IO{
    private BufferedReader br;
    private StringTokenizer st;
    private PrintWriter writer;
    private String inputFile,outputFile;

    public boolean hasMore() throws IOException{
        if(st != null && st.hasMoreTokens()) return true;
        if(br != null && br.ready()) return true;
        return false;
    }
    public String getNext() throws FileNotFoundException, IOException{
        while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    public String getNextLine() throws FileNotFoundException, IOException{
        return br.readLine().trim();
    }

    public int getNextInt() throws FileNotFoundException, IOException{
        return Integer.parseInt(getNext());
    }
    public long getNextLong() throws FileNotFoundException, IOException{
        return Long.parseLong(getNext());
    }

    public void print(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f" ,x);
    }
    public void println(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f\n" ,x);
    }
    public void print(Object o) throws  IOException{
        writer.print(o.toString());
    }

    public void println(Object o) throws  IOException{
        writer.println(o.toString());
    }
    public IO(String x,String y) throws FileNotFoundException, IOException{
        inputFile = x;
        outputFile = y;
        if(x != null) br = new BufferedReader(new FileReader(inputFile));
        else br = new BufferedReader(new InputStreamReader(System.in));
        if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
        else writer = new PrintWriter(new OutputStreamWriter(System.out));
    }

    protected void close() throws IOException{
        br.close();
        writer.close();
    }
    public void outputArr(Object [] A) throws IOException{
        int L = A.length;
        for (int i = 0;i < L;i++) {
            if(i > 0) writer.print(" ");
            writer.print(A[i]);
        }
        writer.print("\n");
    }
}


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

public class Main {

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

        String[] strings = new String[]{"buffy", "the", "vampire", "slayer"};
        String in = br.readLine();
        for (String s : strings) {
            if (s.length() == in.length()) {
                for (int i = 0; i < s.length(); i++) {
                    System.out.print((char) ((in.charAt(i) + s.charAt(i) - 'a' - 'a') % (26) + 'a'));
                }
            }
        }

        br.close();
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt(), res = 0;
            for (char c : Integer.toHexString(n).toUpperCase().toCharArray()) {
                res += trans(c);
            }
            out.printLine(res);
        }

        private int trans(char c) {
            if (c == '0') return 1;
            if (c == '1') return 0;
            if (c == '2') return 0;
            if (c == '3') return 0;
            if (c == '4') return 1;
            if (c == '5') return 0;
            if (c == '6') return 1;
            if (c == '7') return 0;
            if (c == '8') return 2;
            if (c == '9') return 1;
            if (c == 'A') return 1;
            if (c == 'B') return 2;
            if (c == 'C') return 0;
            if (c == 'D') return 1;
            if (c == 'E') return 0;
            if (c == 'F') return 0;
            throw new RuntimeException();
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

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

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

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

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

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

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;

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

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

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

        public void printLine(int i) {
            writer.println(i);
        }
    }
}


import java.util.*;

public class Div {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int b = sc.nextInt(), num = sc.nextInt();
		ArrayList<Integer> numPrimes = getPrimes(num);
		boolean p = true;
		for(int i=0; i<numPrimes.size(); i++){
			if(b%numPrimes.get(i)==0){
				continue;
			}
			else p = false;
		}
		if(p){
			System.out.println("2-type");
			int max = 0;
			for(int i=0; i<numPrimes.size(); i++){
				int cnt = 0;
				while(b%numPrimes.get(i)==0){ b /= numPrimes.get(i); cnt++; }
				max = Math.max(max, cnt);
			}
			System.out.println(max);
			return;
		}
		if((b-1)%num==0){
			System.out.println("3-type");
			return;
		}
		if(num==b+1){
			System.out.println("11-type");
			return;
		}
		for(int i=1; i<=num; i++){
			for(int j=1; j<=num; j++){
				if(num%(i*j)!=0) return;
				int k = num%(i*j);
				if(gcd(i, j)==1 && gcd(i, k)==1 && gcd(j, k)==1){
					if(isOk(b, i) && isOk(b, j) && isOk(b, k)){
						System.out.println("6-type");
						return;
					}
				}
			}
		}
		System.out.println("7-type");
	}

	static int gcd(int x, int y){
		if(x==0) return y;
		if(y==0) return x;
		if(x==1 || y==1) return 1;
		if(x>y) return gcd(x%y, y);
		return gcd(x, y%x);
	}

	static boolean is11(int b, int num){
		return num==b+1;
	}

	static boolean secondType(int b, int num){
		ArrayList<Integer> l = getPrimes(num);
		for(int i=0; i<l.size(); i++){
			if(b%l.get(i)!=0) return false;
		}
		return true;
	}

	static boolean third(int b, int num){
		return ((b-1)%num==0);
	}

	static boolean isOk(int b, int num){
		return is11(b, num) || secondType(b, num) || third(b, num);
	}

	static ArrayList<Integer> getPrimes(int b){
		ArrayList<Integer> l = new ArrayList<Integer>();
		for(int i=2; i<=b; i++){
			if(b%i==0){
				l.add(i);
				while(b%i==0) b /= i;
			}
		}
		if(b>1) l.add(b);
		return l;
	}

}


//package codeforces;

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

public class C {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(System.out);
    StringTokenizer stringTokenizer;

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

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

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

    void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        char[][] map = new char[n][];
        int bombs = 0;
        int treasures = 0;
        for (int i = 0; i < n; i++) {
            map[i] = next().toCharArray();
            for (int j = 0; j < m; j++) {
                if (map[i][j] == 'B') bombs++;
                if (map[i][j] >= '0' && map[i][j] <= '9') {
                    treasures++;
                    map[i][j]--;
                }
            }
        }
        int[] treasureCosts = new int[treasures];
        for (int i = 0; i < treasures; i++) {
            treasureCosts[i] = nextInt();
        }
        class Point {
            int x, y;

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

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

            int vectorProduct(Point other) {
                return x * other.y - y * other.x;
            }

            Point add(Point other) {
                return new Point(x + other.x, y + other.y);
            }
        }
        class GeomUtils {
            Point cellCenter(int row, int column) {
                return new Point(2 * row + 1, 2 * column + 1);
            }

            Point ray = new Point(40, 41);

            double getT(Point o, Point v, Point s1, Point s2) {
                Point vs = s2.subtract(s1);
                int r = vs.vectorProduct(s2) - vs.vectorProduct(o);
                int l = vs.vectorProduct(v);
                return 1.0 * r / l;
            }

            boolean intersects(Point o, Point s1, Point s2) {
                if (getT(o, ray, s1, s2) < 0.0) return false;
                double t = getT(s1, s2.subtract(s1), o, o.add(ray));
                return t >= 0.0 && t <= 1.0;
            }
        }
        Point[] treasureCoords = new Point[treasures];
        Point[] bombCoords = new Point[bombs];
        bombs = 0;
        int si = 0, sj = 0;
        GeomUtils geomUtils = new GeomUtils();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (map[i][j] == 'B') {
                    bombCoords[bombs++] = geomUtils.cellCenter(i, j);
                }
                if (map[i][j] >= '0' && map[i][j] <= '9') {
                    treasureCoords[map[i][j] - '0'] = geomUtils.cellCenter(i, j);
                }
                if (map[i][j] == 'S') {
                    si = i;
                    sj = j;
                }
            }
        }
        int[][][][] dist = new int[n][m][1 << treasures][1 << bombs];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                for (int k = 0; k < 1 << treasures; k++)
                    for (int l = 0; l < 1 << bombs; l++) dist[i][j][k][l] = Integer.MAX_VALUE;
        dist[si][sj][0][0] = 0;
        Queue<Integer> qi = new LinkedList<>(), qj = new LinkedList<>(), qt = new LinkedList<>(), qb = new LinkedList<>();
        qi.add(si);
        qj.add(sj);
        qt.add(0);
        qb.add(0);
        int[] di = {0, -1, 0, 1};
        int[] dj = {-1, 0, 1, 0};
        while (!qi.isEmpty()) {
            int i = qi.poll();
            int j = qj.poll();
            int tmask = qt.poll();
            int bmask = qb.poll();
            Point s1 = geomUtils.cellCenter(i, j);
            for (int k = 0; k < 4; k++) {
                int ii = i + di[k];
                int jj = j + dj[k];
                if (ii < 0 || ii >= n || jj < 0 || jj >= m || map[ii][jj] != '.' && map[ii][jj] != 'S') continue;
                int tm = 0;
                for (int ti = 0; ti < treasures; ti++) {
                    if (geomUtils.intersects(treasureCoords[ti], s1, geomUtils.cellCenter(ii, jj))) {
                        tm |= 1 << ti;
                    }
                }
                int bm = 0;
                for (int bi = 0; bi < bombs; bi++) {
                    if (geomUtils.intersects(bombCoords[bi], s1, geomUtils.cellCenter(ii, jj))) {
                        bm |= 1 << bi;
                    }
                }
                if (dist[ii][jj][tmask ^ tm][bmask ^ bm] == Integer.MAX_VALUE) {
                    dist[ii][jj][tmask ^ tm][bmask ^ bm] = dist[i][j][tmask][bmask] + 1;
                    qi.add(ii);
                    qj.add(jj);
                    qt.add(tmask ^ tm);
                    qb.add(bmask ^ bm);
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < 1 << treasures; i++) {
            if(dist[si][sj][i][0] == Integer.MAX_VALUE) continue;
            int tCost = 0;
            for (int j = 0; j < treasures; j++) {
                if (((i >> j) & 1) == 1) tCost += treasureCosts[j];
            }
            ans = Math.max(ans, tCost - dist[si][sj][i][0]);
        }
        writer.println(ans);
        writer.close();
    }

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


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

public class Main implements Runnable {
    void solution() throws Exception {
        int n = nextInt();
        int m = nextInt();
        int x1 = nextInt();
        int y1 = nextInt();
        int x2 = nextInt();
        int y2 = nextInt();
        if (Math.abs(x2-x1) >= 5 || Math.abs(y2-y1) >= 5)
            System.out.println("Second");
        else
            System.out.println("First");
    }

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

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

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

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

    public static void main(String args[]) {
        //Locale.setDefault(Locale.UK);
        new Thread(new Main()).start();
    }

    public void run() {
        try {
            boolean online = true;
            Reader reader = online
                    ? new InputStreamReader(System.in)
                    : new FileReader("my.in");
            in = new BufferedReader(reader);
            out = new PrintWriter(System.out);
            solution();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(202);
        }
    }

    BufferedReader in;
    StringTokenizer st;
    PrintWriter out;
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class School1G {

    static BufferedReader in = new BufferedReader(new InputStreamReader(
            System.in));
    static PrintWriter out = new PrintWriter(System.out);

    public static void main(String[] args) throws Exception {
        int n = Integer.valueOf(in.readLine());
        char[] buf = new char[200];
        int k = in.read(buf);

        String prog = String.valueOf(buf, 0, k);
        prog = prog.substring(prog.indexOf('{') + 1);
        prog = prog.substring(0, prog.indexOf('}'));
        String[] opers = prog.split(";");
        for (int i = 0; i < opers.length; i++)
            opers[i] = opers[i].trim();

        Function.init(opers.length - 1);
        for (int i = 0; i < opers.length - 1; i++)
            Function.body[i] = new Operator(opers[i]);

        int ans = -1;
        for (int i = (1 << 15)-1; i >= 0; i--)
            if (Function.eval(i) == n) {
                ans = i;
                break;
            }

        out.println(ans);

        out.flush();
    }

}

class Function {
    static HashMap<Integer, Integer> func = new HashMap<Integer, Integer>();
    static Operator[] body;

    static void init(int n) {
        body = new Operator[n];
    }

    static int eval(int n) {
        if (func.containsKey(n)) return func.get(n);

        for (Operator oper : body) {
            int r = oper.eval(n);
            if (r != -1) {
                func.put(n, r);
                return r;
            }
        }
        return -1;
    }
}

class Expression {
    static final int MD = 1 << 15;

    List<String> poliz;

    public Expression(String s) {
        s += "$";
        Stack<String> ops = new Stack<String>();
        poliz = new LinkedList<String>();
        int p = 0;
        char c = ' ';
        while (c != '$') {
            String cur = "";
            while (c <= ' ')
                c = s.charAt(p++);
            if (c == 'n') {
                cur = "n";
                c = s.charAt(p++);
                poliz.add(cur);
            } else if (c == 'f') {
                cur = "f";
                while (c != '(')
                    c = s.charAt(p++);
                c = s.charAt(p++);
                ops.push(cur);
            } else if (c >= '0' && c <= '9') {
                while (c >= '0' && c <= '9') {
                    cur += (char) c;
                    c = s.charAt(p++);
                }
                poliz.add(cur);
            } else {
                cur += (char) c;
                c = s.charAt(p++);
                if (cur.equals(")")) {
                    while (!ops.peek().equals("f"))
                        poliz.add(ops.pop());
                    poliz.add(ops.pop());
                } else if (cur.equals("+") || cur.equals("-"))
                    while (!ops.empty() && !ops.peek().equals("f"))
                        poliz.add(ops.pop());
                else
                    while (!ops.empty()
                            && (ops.peek().equals("*") || ops.peek()
                                    .equals("/")))
                        poliz.add(ops.pop());
                if (!cur.equals(")"))
                    ops.push(cur);
            }
        }
        while (!ops.empty())
            poliz.add(ops.pop());
    }

    public int eval(int n) {
        Stack<Integer> st = new Stack<Integer>();
        for (String s : poliz) {
            if (s.equals("n"))
                st.push(n);
            else if (s.charAt(0) >= '0' && s.charAt(0) <= '9')
                st.push(Integer.valueOf(s));
            else if (s.equals("f"))
                st.push(Function.eval(st.pop()));
            else {
                int b = st.pop(), a = st.pop();
                if (s.equals("+")) st.push((a + b)%MD);
                else if (s.equals("*")) st.push(a*b%MD);
                else if (s.equals("/")) st.push(a/b);
                else {
                    int x = a - b;
                    while (x < 0) x += MD;
                    st.push(x);
                }
            }
        }
        return st.pop();
    }
}

class Condition {
    int sign;
    Expression left, right;

    public Condition(String s) {
        s = s.substring(1, s.length() - 1);
        int sgn = s.indexOf('<');
        if (sgn >= 0) {
            sign = -1;
            left = new Expression(s.substring(0, sgn).trim());
            right = new Expression(s.substring(sgn + 1).trim());
        } else if ((sgn = s.indexOf('>')) >= 0) {
            sign = 1;
            left = new Expression(s.substring(0, sgn).trim());
            right = new Expression(s.substring(sgn + 1).trim());
        } else {
            sgn = s.indexOf("=");
            sign = 0;
            left = new Expression(s.substring(0, sgn).trim());
            right = new Expression(s.substring(sgn + 2).trim());
        }
    }

    public boolean eval(int n) {
        int a = left.eval(n), b = right.eval(n);
        if (sign == -1)
            return a < b;
        else if (sign == 1)
            return a > b;
        else
            return a == b;
    }
}

class Operator {
    boolean isIf;
    Condition cond;
    Expression toReturn;

    public Operator(String s) {
        if (s.startsWith("if")) {
            int whereRet = s.indexOf("return");
            isIf = true;
            cond = new Condition(s.substring(2, whereRet).trim());
            toReturn = new Expression(s.substring(whereRet + 6).trim());
        } else {
            isIf = false;
            cond = null;
            toReturn = new Expression(s.substring(6).trim());
        }
    }

    public int eval(int n) {
        if (isIf && !cond.eval(n))
            return -1;

        return toReturn.eval(n);
    }
}


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

public class J implements Runnable {

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

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

    private void init() throws FileNotFoundException {
        Locale.setDefault(Locale.US);
        String fileName = "";
        if (ONLINE_JUDGE && fileName.isEmpty()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            if (fileName.isEmpty()) {
                in = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new PrintWriter(fileName + ".out");
            }
        }
    }

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

    int[] readIntArray(int size) throws IOException {
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = readInt();
        }
        return a;
    }

    public static void main(String[] args) {
        //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
        new J().run();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    @Override
    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            init();
            solve();
            out.close();
            time();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    int[][][][] dp;
    char[] s;
    int INF = 10000000;

    int count(char[] s, char target, int v, int k, int x) {
        int answer = 0;
        for (char c : s) {
            if (c == 'V') {
                v--;
                if (v == 0 && target == 'V') return answer;
                if (v < 0) answer++;
            }
            if (c == 'K') {
                k--;
                if (k == 0 && target == 'K') return answer;
                if (k < 0) answer++;
            }
            if (c == 'X') {
                x--;
                if (x == 0 && target == 'X') return answer;
                if (x < 0) answer++;
            }
        }
        throw new RuntimeException();
    }

    private void solve() throws IOException {
        int n = readInt();
        s = readString().toCharArray();
        int vcnt = 0, kcnt = 0, xcnt = 0;
        for (int i = 0; i < s.length; i++) {
            if (s[i] == 'V') {
                vcnt++;
                continue;
            }
            if (s[i] == 'K') {
                kcnt++;
                continue;
            }
            xcnt++;
            s[i] = 'X';
        }
        dp = new int[vcnt + 1][kcnt + 1][xcnt + 1][3];
        for (int[][][] x : dp) {
            for (int[][] xx : x) {
                for (int[] xxx : xx) {
                    Arrays.fill(xxx, INF);
                }
            }
        }
        dp[0][0][0][0] = dp[0][0][0][1] = dp[0][0][0][2] = 0;
        //V,K,X
        for (int v = 0; v <= vcnt; v++) {
            for (int k = 0; k <= kcnt; k++) {
                for (int x = 0; x <= xcnt; x++) {
                    int rv = v + 1 <= vcnt ? count(s, 'V', v + 1, k, x) : 0;
                    int rk = k + 1 <= kcnt ? count(s, 'K', v, k + 1, x) : 0;
                    int rx = x + 1 <= xcnt ? count(s, 'X', v, k, x + 1) : 0;

                    for (int now = 0; now < 3; now++) {
                        if (v + 1 <= vcnt) dp[v + 1][k][x][0] = Math.min(dp[v + 1][k][x][0], dp[v][k][x][now] + rv);
                        if (now != 0 && k + 1 <= kcnt) dp[v][k + 1][x][1] = Math.min(dp[v][k + 1][x][1], dp[v][k][x][now] + rk);
                        if (x + 1 <= xcnt) dp[v][k][x + 1][2] = Math.min(dp[v][k][x + 1][2], dp[v][k][x][now] + rx);
                    }
                }
            }
        }
        int res = INF;
        for (int i = 0; i < 3; i++) {
            res = Math.min(res, dp[vcnt][kcnt][xcnt][i]);
        }
        out.println(res);

    }

}