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

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

public class Main {
    static long mod = 998244353;

    static long pow(long a, int n) {
        if (n == 0) return 1;
        if ((n & 1) == 0) return (pow(a, n / 2) % mod * pow(a, n / 2) % mod) % mod;
        return a % mod * pow(a, n - 1) % mod;
    }

    public static void main(String[] args) throws IOException {
        FastScanner in = new FastScanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int k = in.nextInt();
//        if(n == 5 && k == 5){
//            out.println(1000);
//            out.close();
//            return;
//        }
        array a = new array(n);
        a.scan(in);
        long h[] = a.a;
        long _h[] = a.right_shift(1);
        int eq = 0;
        for (int i = 0; i < n; i++) {
            if (h[i] == _h[i]) ++eq;
        }
        long f = max(1, pow(k, eq));
        int N = n - eq;
        long c[][] = new long[N + 1][N + 1];

        for (int i = 1; i < N + 1; i++) {
            c[i][1] = i;
        }
        for (int nn = 2; nn < N + 1; nn++) {
            for (int kk = 2; kk < N + 1; kk++) {
                c[nn][kk] = c[nn - 1][kk - 1] + c[nn - 1][kk];
                c[nn][kk] %= mod;
            }
        }
        for (int i = 0; i < N + 1; i++) {
            for (int j = 0; j < N + 1; j++) {
                if (c[i][j] == 0) c[i][j] = 1;
            }
        }
        long ans = 0;
        for (int i = 0; i <= N; i++) {
            long q = c[N][i] * pow(k - 2,i);
            if(i == 0)q = 1;
            int lft = N - i;
            long s = 0;
            for (int j = 0; j <= lft; j++) {
                if (j >= lft - j) break;
                s += c[lft][lft - j];
                s%=mod;
            }
            ans += (q%mod * s%mod);
            ans%=mod;
        }
        out.println(ans * f % mod);
        out.close();
    }
}

class RANDOMIZER {
    static Random rnd = new Random();

    static int randomize() {
        return rnd.nextInt();
    }
}

class array {
    long a[];

    array(long a[]) {
        this.a = a;
    }

    array(int n) {
        a = new long[n];
    }

    void shuffle() {
        for (int i = 0; i < a.length; i++) {
            int id1 = ((RANDOMIZER.randomize() % a.length) + a.length) % a.length;
            int id2 = ((RANDOMIZER.randomize() % a.length) + a.length) % a.length;
            long t = a[id1];
            a[id1] = a[id2];
            a[id2] = t;
        }
    }

    void reverse(int l, int r) {
        for (int i = l; i < l + (r - l + 1) >> 1; i++) {
            long t = a[i];
            a[i] = a[r - i];
            a[r - i] = t;
        }
    }

    long[] right_shift(int shift) {
        long aa[] = new long[a.length];
        for (int i = 0; i < a.length; i++) {
            aa[(i + shift) % a.length] = a[i];
        }
        return aa;
    }

    void add(int l, int r, long val) {
        for (int i = l; i <= r; i++) {
            a[i] += val;
        }
    }

    void print(PrintWriter out) {
        for (int i = 0; i < a.length; i++) {
            out.print(a[i] + " ");
        }
    }

    void copy(long t[]) {
        for (int i = 0; i < a.length; i++) {
            a[i] = t[i];
        }
    }

    void scan(FastScanner in) throws IOException {
        for (int i = 0; i < a.length; i++) {
            a[i] = in.nextLong();
        }
    }

    long getSum() {
        long sum = 0;
        long md = (long) 1e16;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
            sum %= md;
        }
        return sum;
    }

    long getMin() {
        long min = Long.MAX_VALUE;
        for (int i = 0; i < a.length; i++) {
            min = min(min, a[i]);
        }
        return min;
    }

    long getMax() {
        long max = Long.MIN_VALUE;
        for (int i = 0; i < a.length; i++) {
            max = max(max, a[i]);
        }
        return max;
    }

    int ceilingID(long val) {
        int l = 0;
        int r = a.length - 1;
        while (l + 1 != r) {
            int m = (l + r) >> 1;
            if (a[m] >= val) r = m;
            else l = m;
        }
        int pr = l;
        if (pr > 0 && a[pr - 1] >= val) pr--;
        if (a[pr] < val) pr++;
        if (pr < a.length && a[pr] < val) pr++;
        return pr;
    }
}

class dsu {
    int p[];
    int max[];

    dsu(int n) {
        p = new int[n];
        max = new int[n];
        for (int i = 0; i < n; i++) {
            p[i] = i;
            max[i] = i;
        }
    }

    int get(int a) {
        if (p[a] == a) return a;
        return p[a] = get(p[a]);
    }

    void merge(int a, int b) {
        a = get(a);
        b = get(b);
        if (a != b) {
            p[a] = b;
            max[b] = max(max[a], max[b]);
        }
    }
}

class vertex {
    int next[];
}

class trie {
    vertex t[];
    int sz = 1;
    int k;

    trie(int k) {
        this.k = k;
        t = new vertex[300000];
        for (int i = 0; i < t.length; i++) {
            t[i] = new vertex();
            t[i].next = new int[k];
            for (int j = 0; j < k; j++) {
                t[i].next[j] = -1;
            }
        }
    }

    void add(String s, int id) {
        int v = 0;
        for (int i = 0; i < s.length(); i++) {
            char rc = (char) (s.charAt(i) - 'a');
            if (t[v].next[rc] == -1) {
                t[v].next[rc] = sz++;
            }
            v = t[v].next[rc];
        }
    }
}

class StringHelper {
    char[] s;
    long hash[];
    long px[];
    long mod = (int) 1e9 + 7;
    long x = 255;
    int n;

    public StringHelper(String s) {
        this.s = s.toCharArray();
        n = s.length();
    }

    int[] pi() {
        int pi[] = new int[n];
        for (int i = 1; i < n; i++) {
            int j = pi[i - 1];
            while (j > 0 && s[i] != s[j]) j = pi[j - 1];
            pi[i] = s[i] == s[j] ? j + 1 : j;
        }
        return pi;
    }

    void calcHash() {
        hash = new long[n + 1];
        px = new long[n + 3];
        px[0] = 1;
        for (int i = 1; i < n + 3; i++) {
            px[i] = px[i - 1] * x % mod;
        }
        for (int i = 1; i < n + 1; i++) {
            hash[i] = (hash[i - 1] * x % mod + s[i - 1] + mod) % mod;
        }
    }

    long getHash(int l, int r) {
        return (hash[r + 1] - hash[l] * px[r - l + 1] % mod + mod) % mod;
    }
}

class IMPLICITDT {
    long val;
    int y;
    int sz;
    IMPLICITDT l, r;

    static int getSize(IMPLICITDT t) {
        return t == null ? 0 : t.sz;
    }

    private static void recalc(IMPLICITDT t) {
        if (t == null) return;
        int LSZ = t.l == null ? 0 : t.l.sz;
        int RSZ = t.r == null ? 0 : t.r.sz;
        t.sz = LSZ + RSZ + 1;
    }

    IMPLICITDT() {
    }

    IMPLICITDT(long cost, int y, IMPLICITDT l, IMPLICITDT r) {
        this.val = cost;
        this.y = y;
        this.l = l;
        this.r = r;
        recalc(this);
    }

    IMPLICITDT(long cost, int y) {
        this.val = cost;
        this.y = y;
        recalc(this);
    }

    static long get(IMPLICITDT t, int id) {
        int LSZ = getSize(t.l);
        if (LSZ == id) return t.val;
        if (LSZ < id) return get(t.r, id - LSZ - 1);
        return get(t.l, id);
    }

    static IMPLICITDT split(IMPLICITDT T, int x) {
        IMPLICITDT RES = new IMPLICITDT();
        if (T == null) {
            return RES;
        }
        if (getSize(T.l) > x) {
            IMPLICITDT lsplit = split(T.l, x);
            RES.l = lsplit.l;
            RES.r = T;
            T.l = lsplit.r;
        } else {
            IMPLICITDT rsplit = split(T.r, x - getSize(T.l) - 1);
            RES.r = rsplit.r;
            RES.l = T;
            T.r = rsplit.l;
        }
        recalc(RES);
        recalc(T);
        return RES;
    }

    static IMPLICITDT merge(IMPLICITDT L, IMPLICITDT R) {
        if (L == null) return R;
        if (R == null) return L;
        if (L.y > R.y) return new IMPLICITDT(L.val, L.y, L.l, merge(L.r, R));
        else return new IMPLICITDT(R.val, R.y, merge(L, R.l), R.r);
    }

    static IMPLICITDT insert(IMPLICITDT T, long val, int id) {
        if (T == null) return new IMPLICITDT(val, RANDOMIZER.randomize());
        IMPLICITDT _T = split(T, id);
        IMPLICITDT _TR = new IMPLICITDT(val, RANDOMIZER.randomize());
        IMPLICITDT NEWTREAP = merge(_T.l, _TR);
        IMPLICITDT TREAP = merge(NEWTREAP, _T.r);
        recalc(TREAP);
        return TREAP;
    }
}

class stSUM {
    int t[];
    int a[];

    stSUM(int a[]) {
        this.a = a;
        t = new int[a.length * 4];
    }

    void build(int v, int l, int r) {
        if (l == r) t[v] = a[l];
        else {
            int m = (l + r) >> 1;
            build(v * 2, l, m);
            build(v * 2 + 1, m + 1, r);
            t[v] = t[v * 2] + t[v * 2 + 1];
        }
    }

    void upd(int v, int l, int r, int pos, int x) {
        if (l == r) t[v] = x;
        else {
            int m = (l + r) >> 1;
            if (pos <= m) upd(v * 2, l, m, pos, x);
            else upd(v * 2 + 1, m + 1, r, pos, x);
            t[v] = t[v * 2] + t[v * 2 + 1];
        }
    }

    int query(int v, int l, int r, int ql, int qr) {
        if (ql <= l && r <= qr) return t[v];
        if (l > qr || ql > r) return 0;
        int m = (l + r) >> 1;
        return query(v * 2, l, m, ql, qr) + query(v * 2 + 1, m + 1, r, ql, qr);
    }
}

class stMIN {
    int t[];
    int a[];

    stMIN(int a[]) {
        this.a = a;
        t = new int[a.length * 4];
    }

    void build(int v, int l, int r) {
        if (l == r) t[v] = a[l];
        else {
            int m = (l + r) >> 1;
            build(v * 2, l, m);
            build(v * 2 + 1, m + 1, r);
            t[v] = min(t[v * 2], t[v * 2 + 1]);
        }
    }

    void upd(int v, int l, int r, int pos, int x) {
        if (l == r) t[v] = x;
        else {
            int m = (l + r) >> 1;
            if (pos <= m) upd(v * 2, l, m, pos, x);
            else upd(v * 2 + 1, m + 1, r, pos, x);
            t[v] = min(t[v * 2], t[v * 2 + 1]);
        }
    }

    int query(int v, int l, int r, int ql, int qr) {
        if (ql <= l && r <= qr) return t[v];
        if (l > qr || ql > r) return Integer.MAX_VALUE;
        int m = (l + r) >> 1;
        return min(query(v * 2, l, m, ql, qr), query(v * 2 + 1, m + 1, r, ql, qr));
    }
}

class DT {
    long val;
    int x, y;
    int sz;
    DT l, r;

    DT() {
        recalc(this);
    }

    DT(int x, int y, long val) {
        this.x = x;
        this.y = y;
        this.val = val;
        recalc(this);
    }

    DT(int x, int y, DT l, DT r, long val) {
        this.x = x;
        this.y = y;
        this.l = l;
        this.r = r;
        this.val = val;
        recalc(this);
    }

    static DT split(DT t, int x) {
        DT res = new DT();
        if (t == null) {
            res.l = null;
            res.r = null;
            return res;
        }
        if (x < t.x) {
            DT lsplit = split(t.l, x);
            res.l = lsplit.l;
            res.r = t;
            t.l = lsplit.r;
        } else {
            DT rsplit = split(t.r, x);
            res.r = rsplit.r;
            res.l = t;
            t.r = rsplit.l;
        }
        recalc(t);
        recalc(res);
        return res;
    }

    static DT merge(DT t1, DT t2) {
        if (t1 == null || t2 == null)
            return t1 == null ? t2 : t1;
        if (t1.y < t2.y) {
            t1.r = merge(t1.r, t2);
            recalc(t1);
            return t1;
        } else {
            t2.l = merge(t1, t2.l);
            recalc(t2);
            return t2;
        }
    }

    static void recalc(DT t) {
        if (t == null) return;
        int lsz = t.l == null ? 0 : t.l.sz;
        int rsz = t.r == null ? 0 : t.r.sz;
        t.sz = lsz + rsz + 1;
    }

    static DT insert(DT t, int x, long val) {
        try {
            if (t == null) {
                DT ret = new DT(x, RANDOMIZER.randomize(), val);
                recalc(ret);
                return ret;
            }
            DT split = split(t, x);
            DT prelast = merge(split.l, new DT(x, RANDOMIZER.randomize(), val));
            DT newtreap = merge(prelast, split.r);
            recalc(newtreap);
            return newtreap;
        } catch (Exception e) {
            System.exit(0);
            return new DT();
        }
    }

    static long find_kth(DT t, int k) {
        if (t.l == null && k == 1)
            return t.val;
        if (t.l != null && t.l.sz == k - 1)
            return t.val;
        if (t.l != null && t.l.sz >= k)
            return find_kth(t.l, k);
        else
            return find_kth(t.r, k - (t.l == null ? 0 : t.l.sz) - 1);
    }

}

class FT {
    private int[] a;
    private long[] t;

    FT(int[] a) {
        this.a = a;
        t = new long[a.length];
    }

    void inc(int i, int delta) {
        for (; i < a.length; i = (i | (i + 1)))
            t[i] += delta;
    }

    long sum(int l, int r) {
        return sum(r) - sum(l - 1);
    }

    private long sum(int r) {
        long sum = 0;
        for (; r >= 0; r = (r & (r + 1)) - 1) {
            sum += t[r];
        }
        return sum;
    }
}

class LAZY_ST {
    long min[], sum[], set[];
    int last;
    long not_set = Long.MAX_VALUE;

    LAZY_ST(long a[]) {
        int n = a.length;
        last = n - 1;
        min = new long[4 * n];
        sum = new long[4 * n];
        set = new long[4 * n];
        for (int i = 0; i < 4 * n; i++) {
            set[i] = not_set;
        }
        build(0, 0, last, a);
    }

    void build(int v, int l, int r, long a[]) {
        if (l == r) {
            min[v] = a[l];
            return;
        }
        int m = ((l + r) >> 1);
        build(v * 2 + 1, l, m, a);
        build(v * 2 + 2, m + 1, r, a);
        min[v] = Math.min(min[v * 2 + 1], min[v * 2 + 2]);
    }

    void push(int v) {
        if (set[v] != not_set) {
            min[v] = set[v];
            sum[v * 2 + 1] = sum[v * 2 + 2] = 0;
            set[v * 2 + 1] = set[v * 2 + 2] = set[v];
            set[v] = not_set;
        }

        min[v] += sum[v];
        sum[v * 2 + 1] += sum[v];
        sum[v * 2 + 2] += sum[v];
        sum[v] = 0;
    }

    void upd(int v) {
        min[v] = Math.min(get_el(v * 2 + 1), get_el(v * 2 + 2));
    }

    long get_el(int v) {
        return (set[v] == not_set ? min[v] : set[v]) + sum[v];
    }

    void set(int l, int r, long x) {
        set(0, 0, last, l, r, x);
    }

    void set(int v, int l, int r, int left, int right, long x) {
        if (l > right || r < left) return;
        if (l >= left && r <= right) {
            sum[v] = 0;
            set[v] = x;
            return;
        }
        push(v);
        int m = ((l + r) >> 1);

        set(v * 2 + 1, l, m, left, right, x);
        set(v * 2 + 2, m + 1, r, left, right, x);

        upd(v);
    }

    void add(int l, int r, long x) {
        add(0, 0, last, l, r, x);
    }

    void add(int v, int l, int r, int left, int right, long x) {
        if (l > right || r < left) return;
        if (l >= left && r <= right) {
            sum[v] += x;
            return;
        }
        push(v);
        int m = ((l + r) >> 1);

        add(v * 2 + 1, l, m, left, right, x);
        add(v * 2 + 2, m + 1, r, left, right, x);

        upd(v);
    }

    long get(int l, int r) {
        return get(0, 0, last, l, r);
    }

    long get(int v, int l, int r, int left, int right) {
        if (l > right || r < left) return (long) 1e17;

        if (l >= left && r <= right) {
            return get_el(v);
        }
        push(v);
        int m = ((l + r) >> 1);

        long ans = Math.min(get(v * 2 + 1, l, m, left, right), get(v * 2 + 2, m + 1, r, left, right));
        upd(v);
        return ans;
    }

}

class multiset {
    TreeMap<Long, Integer> t;

    void insert(long val) {
        t.put(val, t.getOrDefault(val, 0) + 1);
    }

    void erase(long val) {
        int nw = t.getOrDefault(val, 1);
        if (nw == 1) t.remove(val);
        else t.put(val, nw - 1);
    }

    long ceiling(long val) {
        return t.ceilingKey(val);
    }

    long floor(long val) {
        return t.floorKey(val);
    }

    long higher(long val) {
        return t.higherKey(val);
    }

    long lower(long val) {
        return t.lowerKey(val);
    }

    int count(long val) {
        return t.getOrDefault(val, 0);
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    FastScanner(File f) throws FileNotFoundException {
        br = new BufferedReader(new FileReader(f));
    }

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

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

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

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

class tree {
    ArrayList<Integer> g[];
    int n;
    ArrayList<Integer> order;
    int first[];
    int h[];
    int t[];
    int rt;

    tree(ArrayList<Integer> g[]) {
        this.g = g;
        this.n = g.length;
        order = new ArrayList<>();
        first = new int[n];
        fill(first, -1);
        h = new int[n];
        rt = 0;
        dfs(rt, -1);
        prepare();
    }

    void dfs(int v, int p) {
        if (first[v] == -1) first[v] = order.size();
        order.add(v);
        for (int to : g[v]) {
            if (to == p) continue;
            h[to] = h[v] + 1;
            dfs(to, v);
            order.add(v);
        }
    }

    void prepare() {
        t = new int[order.size() * 4];
        build(1, 0, order.size() - 1);
    }

    void build(int v, int l, int r) {
        if (l == r) t[v] = order.get(l);
        else {
            int m = (l + r) >> 1;
            build(v * 2, l, m);
            build(v * 2 + 1, m + 1, r);
            t[v] = h[t[v * 2]] < h[t[v * 2 + 1]] ? t[v * 2] : t[v * 2 + 1];
        }
    }

    int query(int v, int l, int r, int ql, int qr) {
        if (l > qr || ql > r) return Integer.MAX_VALUE;
        if (ql <= l && r <= qr) return t[v];
        int m = (l + r) >> 1;
        int v1 = query(v * 2, l, m, ql, qr);
        int v2 = query(v * 2 + 1, m + 1, r, ql, qr);
        if (v1 == Integer.MAX_VALUE) return v2;
        if (v2 == Integer.MAX_VALUE) return v1;
        return h[v1] < h[v2] ? v1 : v2;
    }

    int lca(int a, int b) {
        int l = first[a];
        int r = first[b];
        return query(1, 0, order.size() - 1, min(l, r), max(l, r));
    }
}


import java.util.Scanner;

public class CodeForces2 {

    public static void main(String[] args) {
        //  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        Scanner sc = new Scanner(System.in);
        //A. Tricky Alchemy
        long a = sc.nextInt(); long b = sc.nextInt();
        int x = sc.nextInt(); int y = sc.nextInt(); int z = sc.nextInt();
        long sum = a+b;
          while(x !=0 || y!=0 || z!= 0){
              if(x!= 0){
                  x--;
                  a -=2;
              } if(y!= 0){
                  y--;
                  a--;
                  b--;
              } if(z!= 0){
                  z--;
                  b -=3;
              }
        }
        System.out.println(Math.abs(a+b));
    }
}


import java.util.Scanner;

public class WaterTheGarden {

	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		long y = input.nextInt();
		long b = input.nextInt();
		long ye = input.nextInt();
		long g =input.nextInt();
		long blu = input.nextInt();

		while(ye!=0)
		{
			y-=2;
			ye--;
		}
		while(g!=0)
		{

			y--;
			b--;
			g--;
		}
		while(blu!=0)
		{
			b-=3;
			blu--;
		}
		System.out.println(Math.abs(b+y));

	}
}


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

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

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

    public static void main(String[] args) throws FileNotFoundException, IOException {
//        BufferedReader br=new BufferedReader(new FileReader("x.in"));
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        while(br.ready()){
            System.out.println(1);
        }
    }
}


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

    static class TaskC {
        int n;
        char[] colorCard;
        int[] costRedToken;
        int[] costBlueToken;
        final int inf = (int) 1e9;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            colorCard = new char[n];
            costRedToken = new int[n];
            costBlueToken = new int[n];

            int overRed = 0;
            int overBlue = 0;

            for (int i = 0; i < n; i++) {
                colorCard[i] = in.readCharacter();

                costRedToken[i] = in.readInt();
                costBlueToken[i] = in.readInt();

                overRed += Math.max(costRedToken[i] - n, 0);
                overBlue += Math.max(costBlueToken[i] - n, 0);

                costRedToken[i] = Math.min(n, costRedToken[i]);
                costBlueToken[i] = Math.min(n, costBlueToken[i]);
            }

            int over = Math.max(overRed, overBlue);

            int[][][] dp = new int[2][n * n + 1][1 << n];
            ArrayUtils.fill(dp, inf);

            if (overRed < overBlue) {
                dp[0][Math.min(over - overRed, n * n)][0] = 0;
            } else {
                dp[1][Math.min(over - overBlue, n * n)][0] = 0;
            }

            for (int msk = 0; msk < (1 << n); msk++) {
                for (int typeRemToken = 0; typeRemToken < 2; typeRemToken++) {
                    for (int countRemTokens = 0; countRemTokens <= n * n; countRemTokens++) {

                        if (dp[typeRemToken][countRemTokens][msk] == inf) {
                            continue;
                        }

                        int countRedCard = 0;
                        int countBlueCard = 0;
                        for (int card = 0; card < n; card++) {
                            if (((msk >> card) & 1) == 1) {
                                if (colorCard[card] == 'R') {
                                    ++countRedCard;
                                } else if (colorCard[card] == 'B') {
                                    ++countBlueCard;
                                } else {
                                    throw new RuntimeException();
                                }
                            }
                        }

                        for (int card = 0; card < n; card++) {
                            if (((msk >> card) & 1) == 1) {
                                continue;
                            }

                            int countHaveRedToken = typeRemToken == 0 ? countRemTokens : 0;
                            int countHaveBlueToken = typeRemToken == 1 ? countRemTokens : 0;

                            int costRed = Math.max(costRedToken[card] - countRedCard, 0);
                            int costBlue = Math.max(costBlueToken[card] - countBlueCard, 0);

                            int countBuyToken = Math.max(Math.max(costRed - countHaveRedToken, 0), Math.max(costBlue -
                                    countHaveBlueToken, 0));

                            int remRedToken = countBuyToken + countHaveRedToken - costRed;
                            int remBlueToken = countBuyToken + countHaveBlueToken - costBlue;

                            int toMsk = msk | (1 << card);
                            int toTypeRemToken = remRedToken == 0 ? 1 : 0;
                            int toCountRemTokens = Math.max(remRedToken, remBlueToken);

                            dp[toTypeRemToken][toCountRemTokens][toMsk] = Math.min
                                    (dp[toTypeRemToken][toCountRemTokens][toMsk],
                                            dp[typeRemToken][countRemTokens][msk] + countBuyToken);

                        }
                    }
                }
            }

            int curAns = inf;
            for (int typeRemToken = 0; typeRemToken < 2; typeRemToken++) {
                for (int countRemTokens = 0; countRemTokens <= n * n; countRemTokens++) {
                    curAns = Math.min(curAns, dp[typeRemToken][countRemTokens][(1 << n) - 1]);
                }
            }
            out.printLine(n + over + curAns);
//        out.printLine(dp[0][1][0b1]);
//        out.printLine(dp[0][1][0b11]);
//        out.printLine(dp[0][1][0b111]);
        }

    }

    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 char readCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

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

    }

    static class ArrayUtils {
        public static void fill(int[][] array, int value) {
            for (int[] row : array) {
                Arrays.fill(row, value);
            }
        }

        public static void fill(int[][][] array, int value) {
            for (int[][] subArray : array) {
                fill(subArray, value);
            }
        }

    }
}


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

public class D {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		int t = s.nextInt();
		int[] nos = new int[n];
		for (int i=0; i<n; i++) {
			nos[i] = s.nextInt();
		}
		//Arrays.setAll(nos, i->s.nextInt());
		int[] dp = new int[t*n];
		dp[0] = 1;
		int ans = 0;
		for (int i=1; i<t*n; i++) {
			int best = 1;
			for (int j=i-1; j>=Math.max(0, i-n); j--) {
				if (nos[i%n]>=nos[j%n]) {
					best = Math.max(best, dp[j]+1);
				}
			}
			dp[i] = best;
			ans = Math.max(ans, best);
		}
		System.out.println(ans);
	}
}


import com.radium4ye.cf.round481.div3.C_978_G;

import java.util.*;

/**
 * @author radium4ye
 */
public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int m = s.nextInt();

        //每日的安排
        int[] day = new int[n + 1];

        List<C_978_G.Exam> list = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            C_978_G.Exam exam = new C_978_G.Exam(i + 1, s.nextInt(), s.nextInt(), s.nextInt());
            list.add(exam);
            day[exam.examTime] = m + 1;
        }

        list.sort(Comparator.comparing(C_978_G.Exam::getExamTime));

        //考试最早的优先
        for (int i = 0; i < m; i++) {
            C_978_G.Exam exam = list.get(i);

            int prepareDay = exam.prepareDay;
            for (int j = exam.startTime; j < exam.examTime; j++) {
                //准备完毕
                if (prepareDay == 0) {
                    break;
                }

                //第j天休息
                if (day[j] == 0) {
                    prepareDay--;
                    day[j] = exam.num;
                }
            }

            //没时间准备
            if (prepareDay > 0) {
                System.out.println("-1");
                return;
            }
        }

        for (int i = 1; i <= n; i++) {
            System.out.printf(day[i] + " ");
        }

    }

    public static class Exam {
        int num;
        int startTime;
        int examTime;
        int prepareDay;

        public Exam(int num, int startTime, int examTime, int prepareDay) {
            this.num = num;
            this.startTime = startTime;
            this.examTime = examTime;
            this.prepareDay = prepareDay;
        }

        public int getExamTime() {
            return examTime;
        }
    }
}


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

/**
 *
 * @author 3mara
 */
public class Main {

    public static String getTernary(int x) {

        String returnVal = "";
        int result = x;
        while (result > 0) {
            returnVal = (result % 3) + returnVal;
            result = result / 3;
        }
        return returnVal;
    }

    public static void read2() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            try {
                String ar;
                if (!(ar = br.readLine()).equals("")) {
                    String[] array = ar.split(" ");
                    int a = Integer.parseInt(array[0]);
                    int c = Integer.parseInt(array[1]);
                    String aString = "";
                    String cString = "";
                    String result = "";

                    aString = getTernary(a);
                    cString = getTernary(c);

                    while (aString.length() < cString.length()) {
                        aString = "0" + aString;
                    }
                    while (aString.length() > cString.length()) {
                        cString = "0" + cString;
                    }
                    for (int i = 0; i < aString.length(); i++) {
                        if (aString.charAt(i) > cString.charAt(i)) {
                            result += (cString.charAt(i) + 3 - aString.charAt(i));
                        } else {
                            result += (cString.charAt(i) - aString.charAt(i));
                        }
                    }
                    int finalval = 0;
                    int index = 0;
                    for (int i = result.length() - 1; i >= 0; i--) {
                        finalval += ((Math.pow(3.0, index)) * Integer.parseInt((result.charAt(i) + "")));
                        index++;
                    }

                    System.out.println(finalval);
                }
            } catch (NumberFormatException e) {
            }
        } catch (ArrayIndexOutOfBoundsException e) {
        } catch (IOException ex) {
        }
    }

        */
    public static void main(String[] args) {
        // TODO code application logic here
        read2();
    }
}


import java.util.Scanner;

/**
 *
 * @author HP-PC
 */
public class JavaApplication16 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner s = new Scanner (System.in);
      int n= s.nextInt() , k = s.nextInt();
      for (int i=0 ; ; i++ ){
      if(i>n && i%k==0)
      {
          System.out.println((long)i);
      break;}

      }


//package codeforces;

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

public final class SolutionLottery {

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int[] de = new int[n];
		de[0] = 1; de[1] = 5; de[2] = 10; de[3] = 20; de[4] = 100;
		int len = 5;
		int[] mem = new int[n+1];
		Arrays.fill(mem,Integer.MAX_VALUE);
		int min = check(de,len,n,mem);
		System.out.println(min);

	}

	public static int check(int[] de,int len,int n,int[] mem)
	{
		if(n<=0)
			return 0;
		if(mem[n]!=Integer.MAX_VALUE)
			return mem[n];
		int min = Integer.MAX_VALUE;
		for(int i=0;i<len;i++)
		{
			if(de[i]>n)
				break;
			min = Math.min(min,1+check(de,len,n-de[i],mem));
		}
		return mem[n]=min;
	}

}


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

public class A {

	public static void main(String[] args) {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt();
		int[] a = scan.nextIntArray(n);
		int d = a[1]-a[0];s
		boolean good = true;
		for(int i = 2; i < n; i++) if(a[i]-a[i-1] != d) good = false;
		out.println(good?a[n-1]+d:a[n-1]);
		out.close();
	}

	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 = "";
			if(st.hasMoreTokens()) line = st.nextToken();
			else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
			while(st.hasMoreTokens()) line += " "+st.nextToken();
			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.Scanner;

/**
 *
 * @author Andrew
 */
public class C {

    public static boolean poln(int i, int[][] mas) {
        for (int j = 0; j < mas[0].length; j++) {
            if (mas[i][j] == 1) {
                return true;
            }
        }
        return false;
    }

    public static boolean eq(int i, int[][] mas) {
        if ((i == 0) && (poln(0, mas))) {
            return false;
        }
        if ((i == 0) && (!poln(0, mas))) {
            return true;
        }
        for (int j = 0; j < mas[0].length; j++) {
            if (((mas[i][j] != mas[i - 1][j])) && (mas[i][j] != 2)) {
                return false;
            }
        }
        return true;
    }

    public static int number(int[][] mas, int u) {
        int t = 0;
        int k = 0;
        for (int i = 0; i < mas.length; i++) {
            if ((poln(i, mas)) || (i == 0)) {
                if (!eq(i, mas)) {
                    k = 1;
                    t++;
                }
            }
            if ((!poln(i, mas)) && (k == 1) && (i != 0) && (u == 1)) {
                return t;
            }

        }
        return t;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int a = sc.nextInt();
        int b = sc.nextInt();
        int tt;
        if (n % m == 0) {
            tt = n / m;
        } else {
            tt = n / m + 1;
        }

        int[][] mas = new int[tt][m];
        int[][] mas2 = new int[m][tt];

        for (int i = 0; i < tt; i++) {
            for (int j = 0; j < m; j++) {
                if (((i * m + j) >= a - 1) && ((i * m + j) <= b - 1)) {
                    mas[i][j] = 1;
                    mas2[j][i] = 1;

                }
                if ((i * m + j) >= n) {
                    mas[i][j] = 2;
                    mas2[j][i] = 2;
                }
            }
        }

        int t1 = number(mas, 1);
        int t2 = number(mas2, 0);
        if (t1 < t2) {
            System.out.print(t1);
        } else {
            System.out.print(t2);
        }

    }
}


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

public class S {

	public static void main(String[] args) {
		FastReader in = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		int k = in.nextInt();
		StringBuilder str = new StringBuilder("codeforces");
		for(int i = 1; i<k; i++) {
			str.append('s');
		}
		out.print(str);

		out.close();

    }

	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

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

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

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

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

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

}


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

public class Main {
  BufferedReader br;
  int a, b, m, vx, vy, vz;
  BigDecimal t, x, z, x0, z0;

  public void go() throws Exception {
    br = new BufferedReader(new InputStreamReader(System.in));
    String[] ss = br.readLine().split(" ");
    a = Integer.parseInt(ss[0]);
    b = Integer.parseInt(ss[1]);
    m = Integer.parseInt(ss[2]);
    ss = br.readLine().split(" ");
    vx = Integer.parseInt(ss[0]);
    vy = Integer.parseInt(ss[1]);
    vz = Integer.parseInt(ss[2]);

    t = new BigDecimal(-m).divide(new BigDecimal(vy), 50, RoundingMode.UP);
    x = new BigDecimal(a).divide(new BigDecimal(2), 50, RoundingMode.UP).add(new BigDecimal(vx).multiply(t));
    z = new BigDecimal(vz).multiply(t);

    if (vx >= 0) {
      x0 = x.divideAndRemainder(new BigDecimal(2*a))[1];
      if (x0.intValue() > a)
        x0 = new BigDecimal(2*a).subtract(x0);
    }
    else {
      x = x.negate();
      x0 = x.divideAndRemainder(new BigDecimal(2*a))[1];
      if (x0.intValue() > a)
        x0 = new BigDecimal(2*a).subtract(x0);
    }

    z0 = z.divideAndRemainder(new BigDecimal(2*b))[1];
    if (z0.intValue() > b)
      z0 = new BigDecimal(2*b).subtract(z0);

    System.out.format("%.10f %.10f%n", x0.doubleValue(), z0.doubleValue());
  }

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


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

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

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

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

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

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

	static double EPS = 1E-10;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

public class FindColor
{
	Scanner in;
	PrintWriter out;

	FindColor()
	{
		in = new Scanner(System.in);
		out = new PrintWriter(System.out);
	}

	FindColor(String i, String o) throws FileNotFoundException
	{
		in = new Scanner(new File(i));
		out = new PrintWriter(new File(o));
	}

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

	void solve()
	{
		int
			x = in.nextInt(),
			y = in.nextInt();
		double d = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));

		//if the distance from origin is integral, it's black
		if(d == (int)d)
			out.println("black");
		else
		{
			//if one point is on the origin, it's black
			if(x * y == 0)
				out.println("black");
			//if it is in 1st or 3rd quadrant
			else if(x * y > 0)
				//if the distance is 'even' it's black
				if((int)r % 2 == 0)
					out.println("black");
				//else white
				else
					out.println("white");
			//if it is in 2nd or 4th quadrant
			else
				//if the distance is 'even' it's white
				if((int)r % 2 == 0)
					out.println("white");
				//else black
				else
					out.println("black");
		}
	}

	public static void main(String[] args) throws FileNotFoundException
	{
		FindColor t = new FindColor();
		t.solve();
		t.finalize();
	}
}


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

public class Beach {
  static class State {
    public final int tide;
    public final int pos;
    public final boolean down;
    public State(int pos, int tide, boolean down) {
      this.tide = tide;
      this.pos = pos;
      this.down = down;
    }

    @Override
    public int hashCode() {
      return Arrays.deepHashCode(new Object[] {pos, tide, down});
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof State)) {
        return false;
      }

      State o = (State)other;
      if (this.tide == o.tide && this.pos == o.pos && this.down == o.down) {
        return true;
      } else {
        return false;
      }

    }
  }

  public static boolean dp(int pos, int tide, boolean down, Set<State> memo, int n, int k, int l, int[] depth) {
    // System.out.println(pos +" " + tide + " " + down);
    State state = new State(pos, tide, down);
    if (memo.contains(state)) {
      return false;
    }

    if (pos > n) {
      return true;
    }

    memo.add(state);

    tide += down ? -1 : +1;
    if (tide == 0) {
      down = false;
    }
    if (tide == k) {
      down = true;
    }

    // stay at current position
    if (depth[pos] + tide <= l && dp(pos, tide, down, memo, n, k, l, depth)) {
      return true;
    }
    if (depth[pos+1] + tide <= l && dp(pos+1, tide, down, memo, n,k,l,depth)) {
      return true;
    }
    return false;
  }
  public static void main(String[] args) throws NumberFormatException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int test = Integer.parseInt(br.readLine()); // 3 elements
    while (test-- > 0) {
      String[] s = br.readLine().split(" ");
      int n = Integer.parseInt(s[0]); // length of the shore
      int k = Integer.parseInt(s[1]); // seconds of tide for each wave
      int l = Integer.parseInt(s[2]); // maximum depth Koa can swim

      // depths array
      String[] sd = br.readLine().split(" ");
      int[] depth = new int[n+1];
      for (int i=0; i<n; i++) {
        depth[i+1] = Integer.parseInt(sd[i]);
      }
      depth[0] = -k;
      depth[n] = -k;

      /* main work: use dynamic programming, we use tuple (int pos, int tide, boolean down) represents
      the status of Koa, each time he can transfer to two status, either stay at same position (pos, tide + (int) down, down)
      or swim to next position (pos+1, tide?, down?)
      */
      Set<State> memo = new HashSet<>(); // record unsuccessful results

      if (dp(0, 0, false, memo, n, k, l, depth)) {
        System.out.println("YES");
      } else {
        System.out.println("NO");
      }

    }
    br.close();
  }
}


import java.io.*;
import java.util.StringTokenizer;
import java.util.*;
import java.math.*;
import java.lang.Integer;

public class Solution {

	public static void main(String[] args) throws Exception {
		FastScanner cin = new FastScanner(System.in);
		String str = cin.nextLine();
		String str1=str.substring(0,1);
		String str2=str.substring(0,2);

		String[] checklist={"H", "HE", "LI", "BE", "B", "C", "N", "O", "F", "NE", "NA", "MG", \
				"AL", "SI", "P", "S", "CL", "AR", "K", "CA", "SC", "TI", "V", "CR", \
				"MN", "FE", "CO", "NI", "CU", "ZN", "GA", "GE", "AS", "SE", "BR", \
				"KR", "RB", "SR", "Y", "ZR", "NB", "MO", "TC", "RU", "RH", "PD", \
				"AG", "CD", "IN", "SN", "SB", "TE", "I", "XE", "CS", "BA", "LA", \
				"CE", "PR", "ND", "PM", "SM", "EU", "GD", "TB", "DY", "HO", "ER", \
				"TM", "YB", "LU", "HF", "TA", "W", "RE", "OS", "IR", "PT", "AU", \
				"HG", "TL", "PB", "BI", "PO", "AT", "RN", "FR", "RA", "AC", "TH", \
				"PA", "U", "NP", "PU", "AM", "CM", "BK", "CF", "ES", "FM", "MD", \
				"NO", "LR", "RF", "DB", "SG", "BH", "HS", "MT", "DS", "RG", "CN", \
				"NH", "FL", "MC", "LV", "TS", "OG"};

		String res= "NO";

		for (int i = 0; i < checklist.length; i++) {
			if (str1==checklist[i]){
				res = "YES";
				break;
			}
			if (str2==checklist[i]){
				res = "YES";
				break;
			}
		}

		System.out.println(res);
	}

	static class FastScanner {
		private BufferedReader reader = null;
		private StringTokenizer tokenizer = null;

		public FastScanner(InputStream in) {
			reader = new BufferedReader(new InputStreamReader(in));
			tokenizer = null;
		}

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

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

			return tokenizer.nextToken("\n");
		}

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

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

	}
}


    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.*;
    import java.math.*;
    import java.lang.Integer;

    public class Solution {

    	public static boolean test(String s) {

    		boolean res=false;

    		if (s.length()<=2){
    			res=check(s);
    		}

    		if (s.length()>1&check(s.substring(0,1))){

    			res=res|test(s.substring(1,s.length()));
    		}

    		if (res) {return res;}

    		if (s.length()>2&check(s.substring(0,2))){

    			res=res|test(s.substring(2,s.length()));

    		}

    		return res;
    	}

    	public static boolean check(String s) {

    		boolean res=false;

    		String[] checklist={"H", "HE", "LI", "BE", "B", "C", "N", "O", "F", "NE", "NA","MG",
    				"AL", "SI", "P", "S", "CL", "AR", "K", "CA", "SC", "TI", "V", "CR",
    				"MN", "FE", "CO", "NI", "CU", "ZN", "GA", "GE", "AS", "SE", "BR",
    				"KR", "RB", "SR", "Y", "ZR", "NB", "MO", "TC", "RU", "RH", "PD",
    				"AG", "CD", "IN", "SN", "SB", "TE", "I", "XE", "CS", "BA", "LA",
    				"CE", "PR", "ND", "PM", "SM", "EU", "GD", "TB", "DY", "HO", "ER",
    				"TM", "YB", "LU", "HF", "TA", "W", "RE", "OS", "IR", "PT", "AU",
    				"HG", "TL", "PB", "BI", "PO", "AT", "RN", "FR", "RA", "AC", "TH",
    				"PA", "U", "NP", "PU", "AM", "CM", "BK", "CF", "ES", "FM", "MD",
    				"NO", "LR", "RF", "DB", "SG", "BH", "HS", "MT", "DS", "RG", "CN",
    				"NH", "FL", "MC", "LV", "TS", "OG"};

    		for (int i = 0; i < checklist.length; i++) {
    			if (s.equals(checklist[i])){
    				res = true;
    				break;
    			}
    		}

    		return res;
    	}

    	public static void main(String[] args) throws Exception {
    		FastScanner cin = new FastScanner(System.in);
    		String str = cin.nextLine();

    		boolean res= test(str);

    		if (res){
    			System.out.println("YES");
    		} else{
    			System.out.println("NO");
    		}

    	}

    	static class FastScanner {
    		private BufferedReader reader = null;
    		private StringTokenizer tokenizer = null;

    		public FastScanner(InputStream in) {
    			reader = new BufferedReader(new InputStreamReader(in));
    			tokenizer = null;
    		}

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

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

    			return tokenizer.nextToken("\n");
    		}

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

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

    	}
    }


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

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        String input = sc.next();
        String[] handle = input.split("/");
        if (input.contains("//") || handle.length > 2 || input.charAt(input.length() - 1) == '/' || (handle.length == 2 && !isUserName(handle[1].toCharArray())) || handle[0].charAt(handle[0].length() - 1) == '@' || handle[0].contains("@@")) {
            System.out.println("NO");
            return;
        }
        String[] one = handle[0].split("@");
        if (one.length != 2 || !isUserName(one[0].toCharArray()) || one[1].length() > 32 || one[1].charAt(0) == '.' || one[1].charAt(one[1].length() - 1) == '.' || one[1].contains("..")) {
            System.out.println("NO");
            return;
        }
        String[] three = one[1].split(".");
        for (String x : three)
            if (!isUserName(x.toCharArray())) {
                System.out.println("NO");
                return;
            }
        System.out.println("YES");
        out.close();
        out.flush();
    }

    static boolean isUserName(char[] x) {
        if (x.length == 0 || x.length > 16) return false;

        for (char c : x) {
            if (c != '_' && !isDigit(c) && !isLetter(c)) {
                return false;
            }
        }
        return true;
    }

    static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    static boolean isLetter(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

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

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

        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 int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

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

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

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

        public short nextShort() throws IOException {
            return Short.parseShort(next());
        }

    }

}import java.io.*;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        String input = sc.next();
        String[] handle = input.split("/");
        if (input.contains("//") || handle.length > 2 || input.charAt(input.length() - 1) == '/' || (handle.length == 2 && !isUserName(handle[1].toCharArray())) || handle[0].charAt(handle[0].length() - 1) == '@' || handle[0].contains("@@")) {
            System.out.println("NO");
            return;
        }
        String[] one = handle[0].split("@");
        if (one.length != 2 || !isUserName(one[0].toCharArray()) || one[1].length() > 32 || one[1].charAt(0) == '.' || one[1].charAt(one[1].length() - 1) == '.' || one[1].contains("..")) {
            System.out.println("NO");
            return;
        }
        String[] three = one[1].split(".");
        for (String x : three)
            if (!isUserName(x.toCharArray())) {
                System.out.println("NO");
                return;
            }
        System.out.println("YES");
        out.close();
        out.flush();
    }

    static boolean isUserName(char[] x) {
        if (x.length == 0 || x.length > 16) return false;

        for (char c : x) {
            if (c != '_' && !isDigit(c) && !isLetter(c)) {
                return false;
            }
        }
        return true;
    }

    static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    static boolean isLetter(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

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

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

        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 int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

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

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

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

        public short nextShort() throws IOException {
            return Short.parseShort(next());
        }

    }

}


import java.util.Scanner;
public class sample{
	public static void main(String[] args){
	Task prog = new Task();
	prog.solve();
	}

	static class Task {
		public void solve() {
			Scanner kbd = new Scanner(System.in);
	           	int num = kbd.nextInt();
	                int[] nums = new int[num];
	           	for (int i = 0; i < k; ++i){
	           		nums[i] = in.nextInt();
	           	}
	            	Arrays.sort(r);
	            	int refused = nums[num - 1];
	            	out.println(Math.max(0, refused - 25));
        	}
	}

    }

}


public class Problem_A {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s=new Scanner(System.in);
		int k=s.nextInt();
            int max=0;
             for(int i=0;i<k;i++)
                {
                  int n=s.nextInt();
                  max=Math.max(max, n);

                 }

           if(max<=25)
           {
        	   System.out.println("0");
           }
           else{
	System.out.println(max-25);
           }
           }
}


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

// **** D. The Beatles ****

public class D {
	static char [] in = new char [100000];
	public static void main (String [] arg) throws Throwable {
		long n = nextInt();
		long k = nextInt();
		long a = nextInt();
		long b = nextInt();
		long min = n*k;
		long max = 0;
		long [] values = new long [4];
		values[0] = ((b) + (a) + k) % k;
		values[1] = ((b) + k - (a) + k) % k;
		values[2] = (k - (b) + (a) + k) % k;
		values[3] = (k - (b) + k - (a) + k) % k;
		long nk = n*k;
		for (long v : values) {
			for (int m = (v == 0) ? 1 : 0; m <= n; ++m) {
				long tmpL = v + m*k;
				long ord = nk / gcd(nk, tmpL);
				min = Math.min(ord, min);
				max = Math.max(ord, max);
			}
		}
		System.out.println(min + " " + max);
	}

	/************** FAST IO CODE FOLLOWS *****************/
	public static long nextLong() throws Throwable {
		long i = System.in.read();boolean neg = false;while (i < 45) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48;
		int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i;
	}
	public static int nextInt() throws Throwable {return (int)nextLong();}
	public static String next() throws Throwable {
		int i = 0; while (i < 42 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 42) { in[cptr++] = (char)i; i = System.in.read();}
		return new String(in, 0,cptr);
	}
	/**** LIBRARIES ****/
	public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;}
	public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;}
	public static int[] sieve(int LIM) {
		int i,count = 0;
		boolean [] b = new boolean [LIM];
		for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;}
		int [] primes = new int[count];
		for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i;
		return primes;
	}
	public static int[] numPrimeFactors(int LIM) {
		int i,count = 0;
		int [] b = new int [LIM];
		for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;}
		return b;
	}
}

/* Full Problem Text:

Recently a Golden Circle of Beetlovers was found in Byteland.
It is a circle route going through n \cdot k cities.
The cities are numerated from 1 to n \cdot k, the distance between the neighboring cities is exactly 1 km.
Sergey does not like beetles, he loves burgers.
Fortunately for him, there are n fast food restaurants on the circle, they are located in the 1-st, the (k + 1)-st, the (2k + 1)-st, and so on, the ((n-1)k + 1)-st cities, i.e. the distance between the neighboring cities with fast food restaurants is k km.
Sergey began his journey at some city s and traveled along the circle, making stops at cities each l km (l > 0),
until he stopped in s once again.
Sergey then forgot numbers s and l, but he remembers that the distance from the city s to the nearest fast food restaurant was a km, and the distance from the city he stopped at after traveling the first l km from s to the nearest fast food restaurant was b km.
Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.
Now Sergey is interested in two integers.
The first integer x is the minimum number of stops (excluding the first) Sergey could have done before returning to s.
The second integer y is the maximum number of stops (excluding the first) Sergey could have done before returning to s.

 */


/**
 * Created by IntelliJ IDEA.
 * User: piyushd
 * Date: 3/18/11
 * Time: 9:28 PM
 * To change this template use File | Settings | File Templates.
 */
public class TaskA {

    void run(){
        int x = nextInt(), y = nextInt(), z = nextInt(), k = nextInt();

       long res = 1;
        if (x + y + z - 3 <= k) {
            res = 1L * x * y * z;
        } else {
            int[] cnt = new int[3];
            cnt[0] = x - 1;
            cnt[1] = y - 1;
            cnt[2] = z - 1;

            int axis = 0;
            while (k > 0 && (cnt[0] > 0 || cnt[1] > 0 || cnt[2] > 0)) {
                --k;
                while (cnt[axis] == 0) axis = (axis + 1) % 3;
                cnt[axis]--;
                ++axis;
            }

            res *= x - cnt[0];
            res *= y - cnt[1];
            res *= z - cnt[2];
        }

        System.out.println(res);
    }

    int nextInt(){
        try{
            int c = System.in.read();
            if(c == -1) return c;
            while(c != '-' && (c < '0' || '9' < c)){
                c = System.in.read();
                if(c == -1) return c;
            }
            if(c == '-') return -nextInt();
            int res = 0;
            do{
                res *= 10;
                res += c - '0';
                c = System.in.read();
            }while('0' <= c && c <= '9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }

    long nextLong(){
        try{
            int c = System.in.read();
            if(c == -1) return -1;
            while(c != '-' && (c < '0' || '9' < c)){
                c = System.in.read();
                if(c == -1) return -1;
            }
            if(c == '-') return -nextLong();
            long res = 0;
            do{
                res *= 10;
                res += c-'0';
                c = System.in.read();
            }while('0' <= c && c <= '9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }

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

    String next(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(Character.isWhitespace(c))
                c = System.in.read();
            do{
                res.append((char)c);
            }while(!Character.isWhitespace(c=System.in.read()));
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

    String nextLine(){
        try{
            StringBuilder res = new StringBuilder("");
            int c = System.in.read();
            while(c == '\r' || c == '\n')
                c = System.in.read();
            do{
                res.append((char)c);
                c = System.in.read();
            }while(c != '\r' && c != '\n');
            return res.toString();
        }catch(Exception e){
            return null;
        }
    }

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


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

public class Main {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            int n = Integer.parseInt(reader.readLine());
            HashMap<Integer, Integer> dels = new HashMap<>();
            int del = 2;
            if(n == 1) {
                println("1 0");
                return;
            }
            while(n > 1) {
                if(n % del == 0) {
                    if(dels.containsKey(del)) {
                        dels.put(del, dels.get(del) + 1);
                    } else {
                        dels.put(del, 1);
                    }
                    n /= del;
                    //println("here2");
                } else
                    del++;
                //println("here1");
            }
            int minNum = 1;
            long two = 1;
            int b = 0;
            HashSet<Integer> set = new HashSet<>();
            for(int i : dels.keySet()) {
                minNum *= i;
                while(two < dels.get(i)) {
                    two *= 2;
                }
                set.add(two);
                if(dels.get(i) != two)
                    b = 1;
            }
            //println(two);
            int ans = 0;
            while(two > 1) {
                two /= 2;
                ans++;
            }
            int add = 1;
            if(b == 0 || set.size() > 1) add = 0;
            println(minNum + " " + (ans + add));

        } catch (IOException e) {
        }
    }

    static String reverse(String s) {
        String ans = "";
        char[] c = s.toCharArray();
        for(int i = s.length() - 1; i >= 0; i--) {
            ans += c[i];
        }
        return ans;
    }

    static long fac(int deg) {
        long ans = 1;
        for(int i = 2; i <= deg; i++) {
            ans *= i;
        }
        return ans;
    }

    static int r(int a, int b) {
        int ans = a / b;
        if(a % b != 0)
            ans++;
        return ans;
    }

    static void print(Object o) {
        System.out.print(o.toString());
    }

    static void println(Object o) {
        System.out.println(o.toString());
    }
}


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

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

    static class TaskE {
        boolean[][] visited;
        long[][] dp;

        long rec(int pos, int rem_weight, long[] cnt, int pack) {
            if (pos == 8) {
                return rem_weight == 0 ? 0 : -1;
            }

            if (visited[pos][rem_weight] == true) {
                return dp[pos][rem_weight];
            }
            visited[pos][rem_weight] = true;
            long res = -1;
            int used = 0;
            while (used <= cnt[pos] && used * (pos + 1) < pack && rem_weight - used * (pos + 1) >= 0) {
                long counter = ((cnt[pos] - used) * (pos + 1)) / pack;
                long cur_res = rec(pos + 1, rem_weight - used * (pos + 1), cnt, pack) + counter;
                if (cur_res != -1) {
                    assert (cur_res >= 0);
                    res = Math.max(res, cur_res + counter);
                }

                used += 1;
            }

            dp[pos][rem_weight] = res;
            return res;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long W = in.nextLong();
            long[] cnt = new long[8];
            for (int i = 0; i < 8; i++) {
                cnt[i] = in.nextLong();
            }
            int pack = 840;
            visited = new boolean[8][8 * pack];
            dp = new long[8][8 * pack];

            long ans = 0;
            for (int i = 0; i <= Math.min(8 * pack, W); i++) {
                long res = rec(0, i, cnt, pack);
                long bound = Math.min((W - res) / pack, res);
                ans = Math.max(ans, bound * pack + i);
            }
            out.println(ans);
            return;
        }

    }

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

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

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

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

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

    }
}


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

import static java.lang.Math.*;

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

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

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

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

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

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

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }
    public void run() {
        InputReader sc = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);

        long weight = sc.nextLong();

        long cnt[] = new long[9];
        for(int i = 1; i <= 8; ++i)
            cnt[i] = sc.nextLong();

        long cycle = 840, possCycles = 0;
        int possSum = 0;
        for(int i = 1; i <= 8; ++i) {
            long reqEle = cycle / i;
            long curCycle = cnt[i] / reqEle;

            possCycles += max(0, curCycle - 1);
            cnt[i] -= possCycles * reqEle;
            possSum += (int)cnt[i] * i;
        }

        long dp[][] = new long[9][possSum + 1];
        dp[0][0] = 1;
        for(int i = 0; i <= possSum; ++i) {
            for(int j = 1; j <= 8; ++j) {
                for(int k = 0; k <= cnt[j]; ++k) {
                    if(i - k * j < 0)
                        break;
                    dp[j][i] |= dp[j - 1][i - j * k];
                }
            }
        }

        long ans = 0;
        for(int i = 0; i <= possSum; ++i) {
            if(i <= weight && dp[8][i] == 1) {
                long left = weight - i;
                long ansCycles = min(possCycles, left / cycle);
                long cans = i + ansCycles * cycle;
                ans = max(ans, cans);
            }
        }

        w.print(ans);

        w.close();
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        long N = in.nextLong(), K = in.nextLong();

        if(K == 1) {
            System.out.println(N);
            return;
        }

        int tim = -1;
        while (N > 0) {
            N /= 2;
            tim++;
        }

        long ans = 0;

        for (int i = 0; i < K && tim >= 0; i++, tim--) {
            ans += pow(tim);
        }

        System.out.println(ans);
    }

    private static long pow(int tim) {
        long ans = 1;
        for (int i = 1; i <= tim; i++) {
            ans *= 2;
        }
        return ans;
    }
}
close


/**
 * @author: Mehul Raheja
 */
import java.util.*;
import java.io.*;

public class E {

    /*
        Runtime = O()
     */
    static int N, M, K;
    static String s;
    static StringTokenizer st;
    static int[] d;

    static long ans = 0;

    static void dis(long N) {
        if(N == 1){
            return;
        }
        long low = 1<< ((long)((Math.log(N-0.1))/Math.log(2)));
        ans += low;
        dis(low);
        dis(N-low);
    }

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        long N = Long.parseLong(br.readLine());
        dis(N);
        System.out.println(ans);
    }
}


/*
 *
 * @author Mukesh Singh
 *
 */

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
@SuppressWarnings("unchecked")
public class AB
{
	void solve() throws Exception
	{
		int T = in.nextInt();
		for(int t= 1 ; t <= T  ;t++)
		{
			solveT(t);
		}
	}
	//solve test cases
	void solveT(int tid) throws Exception
	{
		int n = in.nextInt();
		int ar[] = new int[n];
		for(int i = 0 ; i < n ; i++)
			ar[i] = in.nextInt();
		LinkedList<Integer> ls1 = new LinkedList<Integer>();
		int left = 1 ;
		int right = n-1 ;
		boolean flag1 = false ;
		boolean flag2 = false ;
		ls1.add(ar[0]);
		for(int i= 1 ; i < n ; i++)
		{
			if(ls1.getFirst()-1==ar[left])
			{
				ls1.addFirst(ar[left]);
				left++ ;
			}
			else if(ls1.getFirst()-1==ar[right])
			{
				ls1.addFirst(ar[right]);
				right-- ;
			}
			else if(ls1.getLast()+1==ar[left])
			{
				ls1.addLast(ar[left]);
				left++ ;
			}
			else if(ls1.getLast()+1==ar[right])
			{
				ls1.addLast(ar[right]);
				right-- ;
			}
			else
			{
				flag1 = true ;
				break ;
			}
		}

		LinkedList<Integer> ls2 = new LinkedList<Integer>();
		ls2.add(ar[n-1]);
		left = 0 ;
		right = n-2 ;
		for(int i= 1 ; i < n ; i++)
		{
			if(ls2.getFirst()-1==ar[left])
			{
				ls2.addFirst(ar[left]);
				left++ ;
			}
			else if(ls2.getFirst()-1==ar[right])
			{
				ls2.addFirst(ar[right]);
				right-- ;
			}
			else if(ls2.getLast()+1==ar[left])
			{
				ls2.addLast(ar[left]);
				left++ ;
			}
			else if(ls2.getLast()+1==ar[right])
			{
				ls2.addLast(ar[right]);
				right-- ;
			}
			else
			{
				flag2 = true ;
				break ;
			}
		}
		out.print("Case #"+tid+": ");
		if(flag1 && flag2)
			out.println("no");
		else
			out.println("yes");
	}
	//@ main function
	public static void main(String[] args) throws Exception
	{
		new AB();
	}

	InputReader in;
	PrintStream out ;
	DecimalFormat df ;
	AB()
	{
		try
		{
			File defaultInput = new File("file.in");
			if (defaultInput.exists())
				in = new InputReader("file.in");
			else
				in = new InputReader();
			defaultInput = new File("file.out");
			if (defaultInput.exists())
				out = new PrintStream(new FileOutputStream("file.out"));
			else
				out = new PrintStream(System.out);
			df = new DecimalFormat("######0.00");
			solve();
			out.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(261);
		}
	}

	class InputReader {
		BufferedReader reader;
		StringTokenizer tokenizer;

		InputReader() {
			reader = new BufferedReader(new InputStreamReader(System.in));
		}

		InputReader(String fileName) throws FileNotFoundException {
			reader = new BufferedReader(new FileReader(new File(fileName)));
		}

		String readLine() throws IOException {
			return reader.readLine();
		}

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

		boolean hasMoreTokens() throws IOException {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				String s = readLine();
				if (s == null)
					return false;
				tokenizer = new StringTokenizer(s);
			}
			return true;
		}

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

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

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


import java.util.Scanner;

public class Text_Document_Analysis {

	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		StringBuffer string=new StringBuffer(scanner.next());
		scanner.close():
		StringBuffer underScore=new StringBuffer();
		StringBuffer Bracket=new StringBuffer();
		int i=0,count=0,max=0,max2=0;
		while(i<n)
		{
			if(string.charAt(i)=='(')
			{
				i++;
				while(string.charAt(i)!=')')
				{
					Bracket.append(string.charAt(i));
					i++;
				}
				i++;
				Bracket.append("_");

			}
			else {
				underScore.append(string.charAt(i));
				i++;
			}
		}
		for(int j=0;j<underScore.length();j++)
		{
			if(underScore.charAt(j)=='_')
			{
				if(count>max) {
					max=count;
				}
				count=0;
			}
			else
				count++;
		}
		count=0;
		for(int j=0;j<Bracket.length();j++)
		{
			if(Bracket.charAt(j)=='_')
			{
				if(count>0) {
					max2++;
				}
				count=0;
			}
			else
				count++;
		}

		System.out.println(max+" "+max2);
	}

}


import java.io.*;
public class test
{

	public static void main(String args[])throws IOException
	{
		int len,cin=0,cout=0,j=0,i=0,c=0,n;
		char ch,ch1;
		DataInputStream d =new DataInputStream(System.in);
		n=Integer.parseInt(d.readLine());
		String str=d.readLine();
		len=n;
		str=str+"  ";
		while(i<len)
		{
			ch=str.charAt(i);
			if(ch=='(')
			{
				j=i+1;
				while((ch1=str.charAt(j)) !=')')
				{
					if(ch1 != '_')
						c++;
					else
					{
						if(c!=0)
							cin++;
						c=0;
					}
					j++;
				}
				i=j+1;
				if(c!=0)
				{
					cin++;
					c=0;
				}
			}
			else
			{
			if((ch!='_' ) )
				c++;
			if((ch=='_') ||(ch1=str.charAt(i+1))!='('))
			{
				if(c>=cout)
					cout=c;
				c=0;
			}
			i++;
			}

			}
		if(c>cout)
		{
			cout=c;
			c=0;
		}
		System.out.print(cout+" "+cin);
	}

}


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

public class C {
    public static void main(String args[]){
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            int a[] = new int[100];
            for(int i = 0 ; i < n ; i++)
                a[i] = in.nextInt();
            Arrays.sort(a);
            for(int i=0;i<n;i++){
                int b = in.nextInt();
                a[b]++;
            }
            int temp = 0 , cavap = 0;
            for(int i=0;i<500;i++){
                temp+=a[i];
                cavap=Math.max(cavap , (temp+i)/(i+1));
            }
            System.out.println(cavap);

    }
}


import java.util.*;

/**
 * Created by imahmoud on 5/13/17.
 */
public class B {
    public void solve(){
        Scanner in =  new Scanner(System.in);
        int N = in.nextInt();

        int[] groups = new int[5];
        int[] seats = new int[]{0, 0, N * 2, 0, N};

        for (int i = 0; i < in.nextInt(); i++) {
            int g = in.nextInt();
            groups[4] += g / 4;
            if(g % 4 != 0)
                groups[g % 4] ++;
        }

        groups[2] += groups[3];
        groups[1] += groups[3];

        if (groups[4] > seats[4]) {
            groups[2] += (groups[4] - seats[4]) * 2;
        } else {
            seats[2] += seats[4] - groups[4] ;
            seats[1] += seats[4] - groups[4] ;
        }

        if (groups[2] > seats[2]) {
            groups[1] += (groups[2] - seats[2]) * 2;
        }else{
            seats[1] += seats[2] - groups[2];
        }

        if(groups[1] > seats[1])
            System.out.println("NO");
        else
            System.out.println("YES");

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.*;
import java.util.Queue;
import java.util.StringTokenizer;
import java.math.BigInteger;

  public class hello2
 {static class FastReader
       {
           BufferedReader br;
           StringTokenizer st;

           public FastReader()
           {
               br = new BufferedReader(new
                        InputStreamReader(System.in));
           }

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

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

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

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

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

       }

    static String sum (String s)
    {
        String s1 = "";

        if(s.contains("a"))
            s1+="a";
        if(s.contains("e"))
            s1+="e";
        if(s.contains("i"))
            s1+="i";
        if(s.contains("o"))
            s1+="o";
        if(s.contains("u"))
            s1+="u";

            return s1;

    }
 static int comb(int n , int r)
	{
		if( r== 0 || n == r)
			return 1;
		else
			return comb(n-1,r)+comb(n-1,r-1);
	}
    public static void main(String[] args)
    {
       FastReader sc =new FastReader();

       int n=sc.nextInt();
       int m=sc.nextInt();
       int t=sc.nextInt();
       long ans = 0;
		for (int i = 4, j = t - i; j >= 1; j--, i++) {
			ans += comb(n, i) * comb(m, j);
		}
        System.out.println(ans);
    }
 }


import java.util.*;

/*
 * 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 Anusha Nigam
 */
public class quesA {
    public static void main(String[] args){
        Scanner sc=new Scanner (System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++){
            int n=sc.nextInt();
            int d=0;
            int a=n;

            int l=n%10;
            while(a>0){

                d++;
                a=a/10;
            }
            int ans=(10*(l-1));
            int b=1;
            while(d>0){
                ans+=b;
                b++;
            }

           System.out.println(ans);
        }
    }

}


// package Div2;

import java.util.Scanner;

public class CF269 {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		long n = input.nextLong();

		input.close();

		long count = 0;
		long m = (long) Math.sqrt(2*n);

		for(int i=1; i<=n; i++){
			if((n+i) % 3 == 0){
				if(3*i*(i+1) <= 2*(n+i)){
					count ++;
				}
			}
		}

		System.out.println(count);

		return;
	}
}


import java.util.*;

public class bac
{
 public static void main(String ags[])
 {
   int b,n=1,i=1;
   Scanner s= new Scanner(System.in);
   b=s.nextInt();
   while(b!=1)
   {
     while(n<=b)
		n=n*2;
	 if(n>b)
	 {
		b=b-(n/2);
		i++;
		n=1;
	 }
	 else
	   break;
   }
   System.out.println(i);
 }
}


import java.util.Scanner;

public class Sol1 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int x = 0;
		int result = 0;

		x= scan.nextInt();

		boolean chk = true;
		int share, left;
		while(chk){
			if(x/2 == 1){
				chk = false;
				result++;
			}

			if(x%2 == 1){
				result++;
			}

			x = x/2;
		}
		System.out.println(result);
	}
}


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

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

    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt(); int x,f;
        for(int i=n+1;i<9000;i++)
        {      x=i; f=1;
            for(int j=0;j<10;j++)
            {     int c=0;
                while(x>0)
                {
                    int d=x%10;
                    if(d==j)
                    {c++;
                    }

                }
                if(c>1)
                {
                    f=0;
                break;

                }

            }
            if(f==1)
            {
            System.out.println(i);
            break;
             }

        }

        }
        }


import java.util.Scanner;

public class Codeforces {
	public static void main(String[] args) {
		Scanner sc = new Scanner (System.in);
		int n = sc.nextInt();
		int[] a = new int[4];
		int flag = n+1, i=n+1;
		outer: for (; i<=9000; i++) {
		     int t=0, indic=0;
		     flag = i;
		     while(i != 0) {
		         a[t++] = i % 10;
		         i /= 10;
		     }
		    for (int p=0; p<3; p++)
		         for (int j=i+1;j<4; j++)
		            if (a[p] == a[j]) {
		                indic = 1;
		                break;
		            }
		    if(indic == 0)
		        break;
		}
		System.out.println(flag);
		sc.close();
	}
}


public class DiagonalWalking {

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

        int length;
        String way;
        Scanner scanner = new Scanner(System.in);
        length = scanner.nextInt();
        way = scanner.next();

        Stack<Character> stack = new Stack<>();
        Character prev = null;
        for (int i = 0; i < way.length(); i++) {
            boolean consumed = false;
            if (stack.isEmpty()) {
                stack.add(way.charAt(i));
            } else {
                if (prev != null) {
                    if ((prev == 'R' && way.charAt(i) == 'U') || (prev == 'U' && way.charAt(i) == 'R')) {
                        stack.pop();
                        stack.add('D');
                        consumed = true;
                    } else {
                        stack.add(way.charAt(i));
                    }
                } else {
                    stack.add(way.charAt(i));
                }
            }
            if (!consumed)
                prev = way.charAt(i);
            else prev = null;
        }

        System.out.println(stack.size());
    }
}