import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            TaskF solver = new TaskF();
            solver.solve(1, in, out);
            out.close();
        }
    }
    static class TaskF {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = in.readInt();
            }

            RandomWrapper random = new RandomWrapper(new Random());
            DigitUtils.BitOperator bo = new DigitUtils.BitOperator();
            SimulatedAnnealing<Integer> sa = new SimulatedAnnealing<Integer>(1e-5, 1, 0.99, random.getRandom()) {

                public Integer next(Integer old, double temperature) {
                    int x = old;
                    do {
                        int i = random.nextInt(0, 29);
                        x = bo.setBit(x, i, bo.bitAt(x, i) == 0);
                        temperature /= 10;
                    } while (temperature >= 1);
                    return x;
                }

                public double eval(Integer status) {
                    double total = 0;
                    for (int i = 0; i < n; i++) {
                        total += Integer.bitCount(a[i] ^ status);
                    }
                    double avg = total / n;
                    double ans = 0;
                    for (int i = 0; i < n; i++) {
                        double diff = Integer.bitCount(a[i] ^ status) - avg;
                        ans += diff * diff;
                    }
                    return -ans;
                }
            };

            long now = System.nanoTime();
            while (System.nanoTime() - now <= 3.5 * 1e9) {
                sa.optimize(10000, random.nextInt(0, (1 << 30) - 1));
            }

            if (sa.weightOfBest() > -1e-6) {
                out.println(sa.getBest());
            } else {
                out.println(-1);
            }
        }

    }
    static class DigitUtils {
        private DigitUtils() {}

        public static class BitOperator {
            public int bitAt(int x, int i) {
                return (x >> i) & 1;
            }

            public int setBit(int x, int i, boolean v) {
                if (v) {
                    x |= 1 << i;
                } else {
                    x &= ~(1 << i);
                }
                return x;
            }

        }

    }
    static class RandomWrapper {
        private Random random;

        public RandomWrapper(Random random) {
            this.random = random;
        }

        public int nextInt(int l, int r) {
            return random.nextInt(r - l + 1) + l;
        }

        public double nextDouble(double l, double r) {
            return random.nextDouble() * (r - l) + l;
        }

        public Random getRandom() {
            return random;
        }

    }
    static abstract class SimulatedAnnealing<S> {
        private S best;
        private double bestWeight;
        private RandomWrapper random;
        private double threshold;
        private double k;
        private double reduce;

        public SimulatedAnnealing(double threshold, double k, double reduce) {
            this(threshold, k, reduce, new Random());
        }

        public SimulatedAnnealing(double threshold, double k, double reduce, Random random) {
            this.threshold = threshold;
            this.k = k;
            this.reduce = reduce;
            this.random = new RandomWrapper(random);
        }

        public abstract S next(S old, double temperature);

        public abstract double eval(S status);

        public void abandon(S old) {}

        public void optimize(double temperature, S init) {
            S now = init;
            double weight = eval(now);
            double t = temperature;
            while (t > threshold) {
                S next = next(now, t);
                double nextWeight = eval(next);
                if (nextWeight > weight || random.nextDouble(0, 1) < Math.exp((nextWeight - weight) / (k * t))) {
                    abandon(now);
                    now = next;
                    weight = nextWeight;
                }
                t *= reduce;
            }

            if (best == null || bestWeight < weight) {
                best = now;
                bestWeight = weight;
            }
        }

        public S getBest() {
            return best;
        }

        public double weightOfBest() {
            return bestWeight;
        }

    }
    static class FastOutput implements AutoCloseable, Closeable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput println(int c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput println(Object c) {
            cache.append(c).append('\n');
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }
}

def main():
    import sys
    input = sys.stdin.readline

    N = int(input())
    A = list(map(int, input().split()))

    dic1 = {}
    dic2 = {}
    A1 = [0] * N
    for i, a in enumerate(A):
        A1[i] = a>>15
    for i in range(2**15):
        tmp = [0] * N
        for j, a in enumerate(A1):
            a ^= i
            tmp[j] = bin(a).count('1')
        t0 = tmp[0]
        for j in range(N):
            tmp[j] -= t0
        dic1[i] = tuple(tmp)

    A2 = [0] * N
    for i, a in enumerate(A):
        A2[i] = a % (2**15)
    for i in range(2 ** 15):
        tmp = [0] * N
        for j, a in enumerate(A2):
            a ^= i
            tmp[j] = -(bin(a).count('1'))
        t0 = tmp[0]
        for j in range(N):
            tmp[j] -= t0
        dic2[tuple(tmp)] = i

    for i in range(2**15):
        if dic1[i] in dic2:
            # ans = i*(2**15) + dic2[dic1[i]]
            # print([bin(a^ans).count('1') for a in A])
            print(i*(2**15) + dic2[dic1[i]])
            exit()
    print(-1)

if __name__ == '__main__':
    main()


import sys
#p = [[] for i in range(N)]
#for i in range(N):
#    p[i] += map(int, sys.stdin.readline().split())
#Q = input()
#for i in range(Q):
#    print(list(map(int, sys.stdin.readline().split())))

n = int(input())
a = [int(c) for c in sys.stdin.readline().split()]
aktmax, d = 0, 0
for i, c in enumerate(a, start=1):
    aktmax = max(aktmax, c)
    if aktmax <= i:
        d += 1
print(d)

#include <bits/stdc++.h>
using namespace std;
int n, ans;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (register int i = 1, tmp, stop = 0; i <= n; ++i) {
    cin >> tmp;
    stop = max(stop, tmp);
    if (stop == i) {
      ++ans;
    }
  }
  printf("%d", ans);
  return 0;
}


from collections import Counter
n, m = map(int, input().split())
B = list(map(int, input().split()))
cnt = Counter(B)
A = sorted(cnt.keys())
n = len(A)
dp = [[0] * 3 for _ in range(3)]
for i, a in enumerate(A):
    dp2 = [[0] * 3 for _ in range(3)]
    for x in range(1 if i >= 2 and a - 2 != A[i - 2] else 3):
        for y in range(1 if i >= 1 and a - 1 != A[i - 1] else 3):
            for z in range(3):
                if x + y + z <= cnt[a]:
                    dp2[y][z] = max(dp2[y][z], dp[x][y] + z + (cnt[a] - x - y - z) // 3)
    dp = dp2
print (dp[0][0])


#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long n, x, y;
  cin >> n >> x >> y;
  long long white = x + y - 2;
  long long black = 2 * n - x - y;
  if (white <= black)
    cout << "White";
  else
    cout << "Black";
  return 0;
}

Black Black Black Black Black Black Black Black Black Black Black Black Black Black Black Black Black Black White Black Black Black Black White Black Black Black White Black Black Black Black Black Black White White Black White White Black White Black Black Black Black Black Black Black Black

a=int(input())
n, m=map(int, input().split())
mh=min(abs(1-n),abs(1-m))
mb=min(abs(a-n),abs(a-m))

if mh<=mb:
    print("White")
else:
    print("Black")


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n = 0, d = 0, m = 0;
  int MasX[100] = {};
  int MasY[100] = {};
  cin >> n >> d >> m;
  for (int i = 0; i < m; i++) {
    cin >> MasX[i] >> MasY[i];
  }
  for (int i = 0; i < m; i++) {
    int x = 0, y = 0;
    x = MasX[i];
    y = MasY[i];
    int modul = (x > y ? x - y : y - x);
    if (modul > d)
      cout << "NO" << endl;
    else if ((x + y) < d || (x + y) > 2 * n - d)
      cout << "NO" << endl;
    else
      cout << "YES" << endl;
  }
}

YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES

NO
NO
NO
NO
NO
NO
NO
NO
YES
NO
NO
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
NO
NO
YES
NO
NO
NO
NO
NO
NO
NO
NO

NO
NO
NO
YES
NO
NO
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
YES
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
YES
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
YES
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
YES
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
YES
YES
NO
NO
NO
NO
YES
YES
YES
YES
YES
NO
NO
NO
NO
NO
NO
YES
YES
YES
NO
NO
NO
NO
NO
NO
NO
NO
YES
NO
NO
NO

n,d = map(int,input().split())
m = int(input())
x = []
y = []
k = 2*n-d
for i in range(m):
  a = list(map(int,input().split()))
  x.append(a[0])
  y.append(a[1])
for i in range(m):
  if x[i] >= 0 and x[i] <= n and y[i] >= 0 and y[i] <= n:
    if y[i] <= d + x[i] and y[i] >= x[i] - d and y[i] >= -x[i]+d and y[i] <= -x[i] + k:
      print("YES")
    else:
      print("NO")
  else:
    print("NO")


n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = ''
for i in a:
    if i in b:
        ans = ans + str(i) + ' '
print(ans)

import java.util.*;
import java.util.Vector;

public class main
{
  public static void main(String ar[])
  {
    Scanner s=new Scanner(System.in);
    int n=s.nextInt();
    int m=s.nextInt();
    int[] a=new int[n];
    int[] b=new int[m];
    List<Integer> v=new ArrayList<Integer>();
    for(int i=0;i<n;i++)
    {
      a[i]=s.nextInt();
    }
    for(int i=0;i<m;i++)
    {
      b[i]=s.nextInt();
    }
    for(int i=0;i<n;i++)
    {
      for(int j=0;j<m;j++)
      {
        if(a[i]==b[j])
        {
          v.add(b[j]);
          //System.out.print(a[i]+" ");
         }
     }
    }
    Set<Integer> hs = new LinkedHashSet<>();
hs.addAll(v);
v.clear();
v.addAll(hs);
    Iterator<Integer> it=v.iterator();
    while(it.hasNext())
    {
        System.out.print(it.next()+" ");
    }
  }
}


import java.util.Scanner;
public class Main
{
  public static void main(String[]args)
  {
    Scanner rbt=new Scanner(System.in);
    String x=rbt.next();
    int o=0, z=0, f=0;
    for(int i=0; i<x.length(); i++)
    {
      if(x.charAt(i)=='0')
      {
        z++;
        o=0;
      }
      else if(x.charAt(i)=='1')
      {
        o++;
        z=0;
      }
      if(o>=7 || z>=7)
      {
        f++;
        break;
      }
    }
    System.out.println((f>0)? "YES":"NO");
  }
}

NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO YES YES NO NO YES YES YES NO NO YES YES NO NO YES NO NO NO YES YES YES NO NO NO NO NO YES

entrada = input()
vez = -1
total = 0
perigo = False
for i in range(len(entrada)):
    aux = int(entrada[i])
    if(vez == aux):
        total += 1
        if(total == 7):
            perigo = True
    else:
        total = 1
        vez = aux
if(perigo):
    print("YES")
else:
    print("NO")


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int arr[n];
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
    if (arr[0] % 2 == 0) {
      cout << "No\n";
      return 0;
    }
  }
  if (n % 2 != 0 && arr[0] % 2 != 0 && arr[n - 1] % 2 != 0)
    cout << "YES\n";
  else
    cout << "NO\n";
  return 0;
}

No Yes Yes No Yes Yes No Yes No Yes No Yes No Yes Yes Yes Yes Yes No No No Yes No No No No No Yes Yes Yes Yes Yes Yes No Yes No No Yes No No Yes Yes Yes No Yes Yes Yes Yes Yes No

import java.util.*;
public class Substr {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=sc.nextInt();
        if(n%2==0 || x%2==0)
            System.out.println("No");
        else{
            for(int i=1;i<n;i++)
                x=sc.nextInt();
            if(x%2==0)
                System.out.println("No");
            else
                System.out.println("Yes");

        }
    }
}


# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def update(tree,pos,diff,si):
    pos += si-1
    while pos:
        tree[pos] += diff
        pos >>= 1

def query(tree,l,r,si):
    ans,l,r = 0,l+si-1,r+si-1
    while l < r:
        if l&1:
            ans += tree[l]
            l += 1
        if not r&1:
            ans += tree[r]
            r -= 1
        l,r = l>>1,r>>1
    return ans+(0 if l!=r else tree[l])

def main():
    n,k = map(int,input().split())
    arr = [int(input()) for _ in range(n)]
    si = 1<<(n.bit_length()-(not n&n-1))
    dp = [[0]*n for _ in range(k+1)]
    dp[0] = [1]*n
    for i in range(1,k+1):
        tree = [0]*(si<<1)
        for j in range(n):
            dp[i][j] = query(tree,1,arr[j],si)
            update(tree,arr[j],dp[i-1][j],si)
    print(sum(dp[-1]))

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

if __name__ == '__main__':
    main()

#include <bits/stdc++.h>
using namespace std;
class FenwickTree {
 private:
  vector<long long> ft;

 public:
  FenwickTree(int n) { ft.assign(n + 1, 0); }
  long long rsq(int b) {
    long long sum = 0;
    for (; b; b -= b & (-b)) sum += ft[b];
    return sum;
  }
  long long rsq(int a, int b) { return rsq(b) - (a == 1 ? 0 : rsq(a - 1)); }
  void adjust(int k, long long v) {
    for (; k < (int)ft.size(); k += k & (-k)) ft[k] += v;
  }
};
int main() {
  int n, k;
  scanf("%d%d", &n, &k);
  vector<int> a(n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  vector<FenwickTree> trees(k, FenwickTree(n));
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    for (int t = k; t >= 0; t--) {
      long long q = (t > 0 ? trees[t - 1].rsq(a[i]) : 1);
      if (t < k)
        trees[t].adjust(a[i], q);
      else
        ans += q;
    }
  }
  printf("%I64d", ans);
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;

public class C {

    static int[][][][] stat;

    static int game(int turn, int odd, int even, int left) {
        if (left == 0) {
            if (turn == 0) {
                return (odd % 2 == 1) ? 1 : -1;
            } else {
                return (odd % 2 == 1) ? -1 : 1;
            }
        }
        if (stat[turn][odd][even][left] != 0)  {
            return stat[turn][odd][even][left];
        }
        boolean win = false;
        if (odd >= 1) {
            int d = game(1-turn, odd-1, even, left-1);
            if (d == -1) {
                win = true;
            }
        }
        if (even >= 1) {
            int d = game(1-turn, odd, even-1, left-1);
            if (d == -1) {
                win = true;
            }
        }
        stat[turn][odd][even][left] = win ? 1 : -1;
        return stat[turn][odd][even][left];
    }

    public static void ex() {
        stat = new int[2][100][100][100];
        int left = 11;
        for (int o = 0 ; o <= 16 ; o++) {
            for (int e = 0 ; e <= 16 ; e++) {
                if (o+e < left) {
                    System.out.print('-');
                    continue;
                }
                int g = game(0, o, e, left);
                System.out.print(g == 1 ? 'W' : 'L');
            }
            System.out.println();
        }
    }

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

        int n = in.nextInt();
        int k = in.nextInt();
        int odd = 0;
        int even = 0;

        for (int i = 0 ; i < n ; i++) {
            int a = in.nextInt();
            if (a % 2 == 1) {
                odd++;
            } else {
                even++;
            }
        }

        boolean win = true;
        int turn = n - k;
        if (turn % 2 == 0) {
            // final turn is opponent
            if (even > turn / 2) {
                win = false;
            } else {
                win = ((odd + even) % 2) == 1;
            }
        } else {
            if (odd <= turn / 2) {
                win = false;
            } else if (even > turn / 2 && odd > turn / 2) {
                win = true;
            } else {
                win = ((odd + even) % 2) == 0;
            }
        }

        if (n == k) {
            win = (odd % 2 == 1);
        } else if (k == 0) {
            win = false;
        }
        out.println(win ? "Stannis" : "Daenerys");
        out.flush();
    }

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

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

        private int next() {
            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 char nextChar() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            if ('a' <= c && c <= 'z') {
                return (char)c;
            }
            if ('A' <= c && c <= 'Z') {
                return (char)c;
            }
            throw new InputMismatchException();
        }

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

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

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

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

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

    static void debug(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }
}

Stannis Daenerys Daenerys Stannis Daenerys Stannis Stannis Stannis Stannis Stannis Daenerys Stannis Stannis Stannis Stannis Stannis Daenerys Daenerys Daenerys Stannis Stannis Stannis Stannis Daenerys Stannis Stannis Stannis Daenerys Stannis Stannis Stannis Stannis Stannis Stannis Stannis Stannis Stannis Stannis Stannis Stannis Daenerys Daenerys Stannis Daenerys Stannis Stannis Daenerys Stannis Daenerys Daenerys Stannis Daenerys Daenerys Daenerys Daenerys Stannis Daenerys Stannis Daenerys Stannis Daenerys Stannis Stannis Stannis Daenerys Stannis Stannis Daenerys Daenerys Stannis Stannis

#include <bits/stdc++.h>
using namespace std;
int n, k, m, a, b;
int flag, x;
int main() {
  flag = 0;
  scanf("%d%d", &n, &k);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &x);
    if (x % 2 == 1)
      a++;
    else
      b++;
  }
  if (k % 2 == 1) {
    if (n % 2 == 1) {
      m = n - (n - k) / 2;
      if (n == k && a % 2 == 1) flag = 1;
      if (a >= m) flag = 1;
    } else {
      m = (n - k + 1) / 2;
      if (a >= m) flag = 1;
    }
  } else {
    if (n % 2 == 1) {
      m = (n - k + 1) / 2;
      x = (n - k + 1) / 2;
      x = n - x;
      if (x >= a && a >= m) flag = 1;
    } else {
      if (n == k && a % 2 == 1) flag = 1;
    }
  }
  if (flag)
    printf("Stannis\n");
  else
    printf("Daenerys\n");
  return 0;
}


#codeforces 42d: strange town: math, constructive algorithm

def readGen(trans):
	while 1:
		for x in input().split():
			yield(trans(x))
readint=readGen(int)

n=next(readint)

def constructRow(n):
	can=[1 for i in range(1001)]
	b=[0 for i in range(n+1)]
	b[2]=1
	b[3]=2
	can[1]=0
	can[2]=0
	for k in range(4,n+1):
		b[k]=b[k-1]+1
		while (not can[b[k]]): b[k]+=1
		can[b[k]]=0
		for i in range(2,k):
			for p in range(2,k):
				can[b[k]+b[p]-b[i]]=0
	return b

def constructMatrix(b,n):
	can=[1 for i in range(1001)]
	for i in range(2,n+1):
		for j in range(2,n+1):
			for p in range(2,n+1):
				can[b[2]+b[3]+b[p]-b[i]-b[j]]=0
	x=1
	while (not can[x]): x+=1
	a=[[0 for j in range(n+1)] for i in range(n+1)]
	for i in range(n+1):
		a[1][i]=a[i][1]=b[i]
	for i in range(2,n+1):
		for j in range(i+1,n+1):
			a[i][j]=a[j][i]=b[i]+b[j]+x-b[2]-b[3]
	return a

b=constructRow(n)
#print(b)

a=constructMatrix(b,n)
for i in range(1,n+1):
	for j in range(1,n+1):
		print("{:4}".format(a[i][j]),end='')
	print()


/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;
public class GFG {
	public static void main (String[] args) throws IOException{
		BufferedReader br = new BufferedReader(
                              new InputStreamReader(System.in));
		String s=br.readLine();
		int q=Integer.parseInt(br.readLine());
		int dp[]=new int[s.length()];
		int k=0;
		for(int i=1;i<s.length();i++){
            if(s.charAt(i)==s.charAt(i-1)){
                k++;
            }
    		dp[i]=k;
		}
		for(int i=0;i<q;i++){
		    String line = br.readLine(); // to read multiple integers line
            String[] strs = line.trim().split("\\s+");
		    int l=Integer.parseInt(strs[0]);
		    int r=Integer.parseInt(strs[1]);
		    System.out.println(dp[r-1]-dp[l-1]);
		}
	}
}

..#...#.
```

Please note that these inputs are randomly generated and may not necessarily produce the correct

#include <bits/stdc++.h>
using namespace std;
const int INF_int = 100000000;
const long long INF_ll = 1000000000000000;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  string a;
  cin >> a;
  int n = a.size();
  int m;
  cin >> m;
  int b[n];
  for (int i = 0; i < n; i++) {
    b[i] = 0;
    if (i != n - 1 && a[i] == a[i + 1]) {
      b[i] = 1;
    }
  }
  int sum[n];
  sum[0] = b[0];
  for (int i = 1; i < n; i++) {
    sum[i] = b[i] + sum[i - 1];
  }
  for (int i = 0; i < m; i++) {
    int x, y;
    cin >> x >> y;
    x--;
    y--;
    if (x != 0)
      cout << sum[y - 1] - sum[x - 1] << "\n";
    else
      cout << sum[y - 1] << "\n";
  }
}


import sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Output.txt','w')
mod=1000000007
# Reading Single Input
def get_int(): return int(sys.stdin.readline().strip())
def get_str(): return sys.stdin.readline().strip()
def get_float(): return float(sys.stdin.readline().strip())
# Reading Multiple Inputs
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_strs(): return map(str, sys.stdin.readline().strip().split())
def get_floats(): return map(float, sys.stdin.readline().strip().split())
# Reading List Of Inputs
def list_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def list_strs(): return list(map(str, sys.stdin.readline().strip().split()))
def list_floats(): return list(map(float, sys.stdin.readline().strip().split()))
# ------------------------------------------------------------------------------------- #

n,k=get_ints()
print((pow(k,k-1,mod)*pow(n-k,n-k,mod))%mod)


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class cf264b {
  public static void main(String[] args) {
    FastScanner in = new FastScanner(System.in);
    int n = in.nextInt();
    int MAX = 100000;
    ArrayList<Integer>[] divs = new ArrayList[MAX+1];
    for(int i=0; i<=MAX; i++)
      divs[i] = new ArrayList<Integer>();
    for(int i=2; i<=MAX; i++)
      for(int j=i+i; j<=MAX; j+=i)
        divs[j].add(i);
    int ans = 1;
    int[] dp = new int[MAX+1];
    int[] dp2 = new int[MAX+1];
    Arrays.fill(dp,1);
    Arrays.fill(dp,1);
    for(int i=0; i<n; i++) {
      int x = in.nextInt();
      for(int y : divs[x])
        dp[x] = Math.max(dp[x],1+dp2[y]);
      dp2[x] = Math.max(dp2[x],dp[x]);
      for(int y : divs[x])
        dp2[y] = Math.max(dp2[y],dp[x]);
      ans = Math.max(ans,dp[x]);
    }
    System.out.println(ans);
  }
  static class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(InputStream in) {
      br = new BufferedReader(new InputStreamReader(in));
      scanLine();
    }
    public void scanLine() {
      try {
        st = new StringTokenizer(br.readLine().trim());
      } catch(Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }
    public int numTokens() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return numTokens();
      }
      return st.countTokens();
    }
    public String next() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return next();
      }
      return st.nextToken();
    }
    public double nextDouble() {
      return Double.parseDouble(next());
    }
    public long nextLong() {
      return Long.parseLong(next());
    }
    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
}

 ######      ###      #######    #######    ##      #     #####        ###     #####
 #     #    #   #          #        #       # #     #    #     #      #   #     ###
 #     #   #     #        #         #       #  #    #   #       #    #     #    ###
 ######   #########      #          #       #   #   #   #           #########    #
 ######   #########     #           #       #    #  #   #           #########    #
 #     #  #       #    #            #       #     # #   #    ####   #       #    #
 #     #  #       #   #             #       #      ##   #    #  #   #       #
 ######   #       #  #######     #######    #       #    #####  #   #       #    #

# from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
from math import *

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()

def getPrimes(x):
	p = []

	if x&1 == 0:
		p.append(2)

	while x&1 == 0:
		x //= 2

	for i in range(3, ceil(sqrt(x))+1):
		if x%i == 0:
			p.append(i)

		while x%i == 0:
			x //= i

	if x > 1:
		p.append(x)

	return p

primes = {}
ans = 1

for v in a:
	maxP = 0
	local_primes = getPrimes(v)
	# print(local_primes, primes)
	for p in local_primes:
		maxP = max(maxP, primes.get(p, 0))

	for p in local_primes:
		primes[p] = maxP+1

	ans = max(maxP+1, ans)

print(ans)


import java.io.*;
import java.security.DigestException;
import java.util.*;

public class Main{

	public static void main(String args[]) throws IOException{
		new Main().mains();
	}
	public int m,n,deg[],L[][];

	public void solve() throws IOException{
		L = new int[200000][2];
		deg = new int[200000];
		m = nextInt(); n = nextInt();
		for (int i = 1; i <= n; i ++){
			int j = nextInt();
			int k = nextInt();
			if (deg[j] < 2) L[j][deg[j]] = k;
			if (deg[k] < 2) L[k][deg[k]] = j;
			deg[j] ++;
			deg[k] ++;
		}
		int ans = 0;
		for (int i = 1;i <= m;i ++){
			ans = ans + (deg[i] & 1);
		}
		for (int i = 1; i <= m; i ++) if (deg[i] == 2){
			int j = L[i][0],k = L[i][1];
			if (j == k){
				deg[j] = 0;
				ans += 2;
				continue;
			}
			L[j][L[j][0] == i ? 0 : 1] = k;
			L[k][L[k][0] == i ? 0 : 1] = j;
		}
		ans /= 2;
		out.println(ans + " " + n);
	}

	void mains() throws IOException{
		reader = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(new OutputStreamWriter(System.out));
		tokenizer = null;
		//File fin = new File("a.in");
		//reader = new BufferedReader(new InputStreamReader(new FileInputStream(fin)));
		//out = new PrintWriter("a.out");
		solve();
		reader.close();
		out.flush();
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter out;
	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

}

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
vector<int> adj[maxn];
int deg[maxn];
int n, m, ret;
void init() {
  scanf("%d%d", &n, &m);
  int u, v;
  for (int i = 0; i < m; i++) {
    scanf("%d%d", &u, &v);
    if (deg[u] < 2) adj[u].push_back(v);
    if (deg[v] < 2) adj[v].push_back(u);
    deg[u]++;
    deg[v]++;
  }
}
void work() {
  for (int i = 1; i <= n; i++) ret += deg[i] & 1;
  ret >>= 1;
  for (int i = 1; i <= n; i++)
    if (deg[i] == 2) {
      int x = adj[i][0], y = adj[i][1];
      if (x == y) {
        deg[x] = 0;
        ret++;
        continue;
      }
      adj[x][adj[x][0] != i] = y;
      adj[y][adj[y][0] != i] = x;
    }
}
void print() { printf("%d %d\n", ret, m); }
int main() {
  init();
  work();
  print();
  return 0;
}


import java.math.BigInteger;
import java.io.*;
import java.util.Scanner;
public class eprime {
	public static void main(String[] args) throws Exception{
		Scanner sc = new Scanner(System.in);
		int found = 0;
		int size = 11184;
		size = sc.nextInt();
		//long[] array = new long[size];

		int start = 13;

//		if(size>11184) {
//			found = 10000;
//			start = 948349;
//		}
//
//		else if(size>8081) {
//			found = 8082;
//			start = 762367+1;
//		}
//		else if(size>6660) {
//			found = 6660;
//			start = 398467;
//		}
//

		troll: for(int a=start;a<Integer.MAX_VALUE;a++){

			if(isPrime(a)){
				int rev = Integer.parseInt(new StringBuilder (a+"").reverse().toString());
				if(isPrime(rev)){
					if(!isPal(rev+"")){
					//	array[found]=a;
						found++;
					//	System.out.println(found);
						if(found == size){
							System.out.println(a);
							break troll;

						}
					}
				}
			}
		}
//		System.out.println("Done");
//		PrintWriter out = new PrintWriter(new FileWriter(("out.txt")));
//		out.print("{");
//		for(int a=0;a<found;a++){
//			out.print(array[a]+",");
//			System.out.println((a+1)+" "+array[a]+",");
//		}
//		out.print("}");

	}

	private static boolean isPrime(long x) {
		int top = (int) Math.sqrt(x)+1;
		for(int a=2;a<=top;a++){
			if(x%a==0)return false;
		}
		return true;
	}

	private static boolean isPal(String rev) {
//		String other = new StringBuilder(rev).reverse().toString();
//		if(other.compareTo(rev)==0)return true;
//		else return false;
		int N = rev.length()/2;
		for(int a=0;a<N;a++){
			if(rev.charAt(a)!=rev.charAt(rev.length()-1-a))return false;
		}
		return true;
	}

}

#include <bits/stdc++.h>
using namespace std;
bool composite[1000000];
vector<int> primes;
void sieve() {
  for (int i = 2; i < 1000000; i++) {
    if (composite[i]) continue;
    primes.push_back(i);
    for (int j = i + i; j < 1000000; j += i) {
      composite[j] = true;
    }
  }
}
int main() {
  long n;
  cin >> n;
  sieve();
  vector<int> emirp;
  for (int i = 0; i < primes.size(); i++) {
    stringstream ss;
    ss << primes[i];
    string s = ss.str();
    for (int j = 0; j < s.length() / 2; j++) {
      char temp = s[j];
      s[j] = s[s.length() - 1 - j];
      s[s.length() - 1 - j] = temp;
    }
    stringstream ss2;
    ss2 << s;
    int x;
    ss2 >> x;
    if (!composite[x] && x != primes[i]) emirp.push_back(primes[i]);
  }
  cout << emirp[n - 1] << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int x, arr[5000], k = 0, m = 0;
  cin >> x;
  for (int i = 0; i < x; i++) {
    cin >> arr[i];
  }
  sort(arr, arr + x);
  if (x == 1 && arr[0] == 1)
    k = 0;
  else if (x == 1 && arr[0] != 1)
    k = 1;
  else if (x > 1) {
    for (int i = 0; i < x; i++) {
      if (arr[i] > x) m++;
    }
    if (m == x) {
      k = m;
    } else if (m == 0) {
      for (int i = 0; i <= x - 2; i++) {
        if (arr[i] == arr[i + 1]) k++;
      }
    } else if (m != 0) {
      for (int i = 0; i <= x - 2; i++) {
        if (arr[i] == arr[i + 1] && arr[i] <= x && arr[i + 1] <= x) k++;
      }
      k += m;
    }
  }
  cout << k << endl;
}

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class B {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Set<Integer> set = new HashSet<Integer>();
        set.clear();
        int ans = 0;
        for (int i = 0; i < n; i ++) {
            int tmp = scanner.nextInt();
            if (tmp > n) {
                ans ++;
            } else {
                set.add(tmp);
            }
        }
        System.out.println(n-ans- set.size() + ans);

    }

}


import java.util.*;

public class Replacement {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int a[] = new int[n];
        for (int k = 0; k < n; k++) {
            a[k] = cin.nextInt();
        }
        int max = a[0];
        int index = 0;
        for (int i = 1; i < n; i++) {
            if (a[i] > max) {
                max = a[i];
                index = i;
            }
        }
        if (a[index] != 1) {
            a[index] = 1;
        } else {
            a[index] = 2;
        }
        Arrays.sort(a);
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
        cin.close();
    }
}

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

ans = [0]*n
ans[0] = 1
f = ans[0] != a[0]
for i in range(1, n):
    ans[i] = a[i-1]
    if ans[i] != a[i]:
        f = True

m = 10**9
if not f:
    for i in range(n-1, -1, -1):
        if ans[i] < m:
            ans[i] += 1
            break

print(' '.join(map(str, ans)))


n = eval(input())
a = list(map(int, input().split()))
odd = False
even = False
for i in range(n):
    if a[i] & 1:
        odd = True
    else:
        even = True
if odd & even:
    a.sort()
for x in a:
    print(x, end=" ")

#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main() {
  int n;
  bool odd = false;
  bool even = false;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    if (a[i] % 2)
      odd = true;
    else
      even = true;
  }
  if (odd && even) sort(a + 1, a + 1 + n);
  for (int i = 1; i <= n; ++i) printf("%d ", a[i]);
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 5;
const int MOD = 1e9 + 7;
int dp[N][N];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int n, i, j;
  cin >> n;
  n++;
  n = n + n;
  dp[1][1] = 1;
  for (i = 2; i <= n; i++) {
    for (j = 0; j <= n; j++) {
      dp[i][j] = dp[i - 1][j + 1];
      if (j > 0) dp[i][j] += dp[i - 1][j - 1];
      if (dp[i][j] >= MOD) dp[i][j] -= MOD;
    }
  }
  int ans = 0;
  for (i = n - 1; i > 0; i -= 2) {
    for (j = 0; j < n - i; j++)
      if ((n - (i + j)) % 2 == 0) {
        ans += dp[i][j];
        if (ans >= MOD) ans -= MOD;
      }
  }
  cout << ans << '\n';
  return 0;
}


a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == d:
  if a > 0 or c == 0:
    print(1)
  else:
    print(0)
else:
  print(0)

#include <bits/stdc++.h>
const int MAX = (const int)(1e5 + 11);
using namespace std;
static void solve(std::int32_t test) {
  int c1, c2, c3, c4;
  cin >> c1 >> c2 >> c3 >> c4;
  if (c1 == 0 && c4 == 0) {
    cout << (c3 == 0);
  } else {
    cout << (c1 == c4);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cout << setprecision(12) << fixed;
  solve(0);
  return 0;
}


n = int(input())
s = input()
k = {}

def choose(a, b):
    if b > a:
        return 0
    p = 1
    for i in range(b):
        p *= a - i
    for i in range(1, b + 1):
        p //= i
    return p

for i in range(n):
    if s[i] in k:
        k[s[i]] += 1
    else:
        k[s[i]] = 1
#print(k)
ans = 0
a = []
for i in k:
#    ans += k[i] + choose(k[i], 2)
    a.append(i*k[i])
print(''.join(a))

k az dd t y pp r v q jj g ee f x aemmnnossu u oo bb j emms o ii aabbccddfgggghhh l llooo m s ff d aaaaaaaabbbbccd gg z b p kk aaabbbccc e nn h i c a ll n cc hh w mm aa eikkllo

#include <bits/stdc++.h>
using namespace std;
vector<int> vv1;
int lim = 1000000;
bool prime[1000000];
void sieve() {
  memset(prime, true, sizeof(prime));
  prime[0] = prime[1] = false;
  for (int i = 2; i * i < lim; i++) {
    if (prime[i]) {
      for (int j = i * i; j < lim; j = j + i) {
        prime[j] = false;
      }
    }
  }
  for (int i = 0; i < lim; i++)
    if (prime[i]) vv1.push_back(i);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  sieve();
  long long tt, cn = 0, cn1 = 0, r = 0, l = 0, h = 0;
  tt = 1;
read:
  while (tt--) {
    vector<long long> vec2, vec1, vec, vec3, vec4, vec11;
    vector<pair<long long, long long>> ve;
    double x1, x2, x3, x4, y1, y2, y3, y4;
    long long a, d, b, c, cn = 0, sum = 0, mx = 0, mx1 = 0, cn1 = 0;
    string s;
    cin >> a >> s;
    sort(s.begin(), s.end());
    cout << s << endl;
  }
  return 0;
}


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

/**
 * @author: zhaoqing
 * @date: 2018/9/12
 * @time: 下午2:29
 */
public class Palindrome {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int  n=sc.nextInt();
        int  a=sc.nextInt();
        int  b=sc.nextInt();
        int min=a>b?b:a;
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<n;i++){
            list.add(sc.nextInt());
        }
        int result=0;
        int len=list.size();
        int helflen=list.size()/2;
        int mid=list.size()%2;
        for(int i=0;i<helflen;i++){
            if(list.get(i)!=2 && list.get(len-1-i)!=2){
                if(!list.get(i).equals(list.get(len - 1 - i))){
                    result=-1;
                    break;
                }
                if(list.get(i).equals(list.get(len - 1 - i))){
                    continue;
                }
            }
            if(list.get(i)==2 && list.get(len-1-i)==2){
                result=result+2*min;
                continue;
            }
            if(list.get(i)==2){
                if(list.get(len-1-i)==1){
                    result=result+b;
                }else {
                    result=result+a;
                }
            }
            if(list.get(len-1-i)==2){
                if(list.get(i)==1){
                    result=result+b;
                }else {
                    result=result+a;
                }
            }

        }
        if(result==-1){
            System.out.println(-1);
        }else {
            if(mid==1){
                if(list.get(helflen)==2){
                    result=result+min;
                }
            }
            System.out.println(result);
        }
    }
}

def go():
    n, a, b = [int(i) for i in input().split(' ')]
    x = [int(i) for i in input().split(' ')]
    total = 0
    for i in range(n // 2):
        if (x[i] == 1 and x[n - 1 - i] == 0) or (x[i] == 0 and x[n - 1 - i] == 1):
            return -1
        elif x[i] == 2 and x[i] == x[n - 1 - i]:
            total += 2 * min(a, b)
        elif x[i] == 2:
            if x[n - i - 1] == 1:
                total += b
            else:
                total += a
        elif x[n - i - 1] == 2:
            if x[i] == 1:
                total += b
            else:
                total += a
    if n % 2 == 1 and x[n // 2] == 2:
        total += min(a, b)
    return total

print(go())


import sys
import math

ini = lambda: int(sys.stdin.readline())
inl = lambda: [int(x) for x in sys.stdin.readline().split()]

def solve():
    p, q, b = inl()
    if p == 0:
        return True
    g = math.gcd(p, q)
    p //= g
    q //= g
    if q == 1:
        return True
    return pow(b, 64, q) == 0

n = ini()
for i in range(n):
    print(["Infinite", "Finite"][solve()])

Finite
Infinite
Infinite
Finite
Infinite
Infinite
Finite
Finite
Finite
Finite

Infinite
Finite
Finite
Infinite
Infinite
Finite
Finite
Finite
Infinite
Finite

Finite
Infinite
Finite
Finite
Finite
Finite
Finite
Infinite
Finite
Finite
Infinite

#include <bits/stdc++.h>
using namespace std;
long long gcd(long long x, long long y) { return y == 0 ? x : gcd(y, x % y); }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long p, q, b;
  int n;
  cin >> n;
  while (n--) {
    cin >> p >> q >> b;
    long long x = p / gcd(p, q);
    long long y = q / gcd(p, q);
    long long cheek = gcd(y, b);
    while (y != 1 && cheek != 1) {
      while (y % cheek == 0) y /= cheek;
      cheek = gcd(b, y);
    }
    if (y == 1)
      cout << "Finite\n";
    else
      cout << "Infinite\n";
  }
}


import java.util.Scanner;

public class Chips {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		int m=scan.nextInt();
		int temp=0;
		while(m>0) {
			for(int i=1;i<=n;i++) {
				if(m>=i) {
					m=m-i;
				}
				else {
					System.out.println(m);temp=1;
					break;
				}
			}
			if(temp==1)break;
		}
		if(temp==0)System.out.println(0);
	}

}

n, m = [int(x) for x in input().split()]

m %= int(n*(n+1)/2)
for i in range(1,n):
	if m<i: break
	m -= i
print(m)


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

public class goodbye {
    static int n,m,x,y;
    static char [][] c;
    static char[] v;
    static char[] b;
    static HashSet<Integer> set;
    static boolean is(){
        int w1=x, w2=y;
        for (int i = 0; i <v.length; i++) {
            int num=Integer.parseInt(v[i]+"");
            if(b[num]=='u')
            {w1--;}
            if(b[num]=='d')
            {w1++;}
            if(b[num]=='r')
            {w2++;}
            if(b[num]=='l')
            {w2--;}
            if(w1>=n||w2>=m||w1<0||w2<0||c[w1][w2]=='#'){return false;}
            if(c[w1][w2]=='E')return true;
        }
        return false ;

    }
    public static void main(String[] args) throws IOException {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
         StringTokenizer sk = new StringTokenizer(in.readLine());
        n=Integer.parseInt(sk.nextToken());
         m=Integer.parseInt(sk.nextToken());
         c=new char[n][m];
         set = new HashSet<>();

         for (int i = 0; i <n; i++) {
             String st=in.readLine();
             for (int j = 0; j <m; j++) {
                 c[i][j]=st.charAt(j);
                 if(c[i][j]=='S'){x=i;y=j;
                 }
             }

        }
         v=in.readLine().toCharArray();
         int ll = 0;
         b=new char[4];

         for (int i = 0; i < 4; i++) {
             for (int j = 0; j < 4; j++) {
                 for (int k = 0; k < 4; k++) {
                     for (int l = 0; l <4; l++) {
                         set.add(i);
                         set.add(j);
                         set.add(k);
                         set.add(l);
                         if(set.size() == 4){
                             b[i] = 'u';
                             b[j] = 'd';
                             b[k] = 'l';
                             b[l] = 'r';
                             if(is())
                                 ll++;
                         }
                         set.clear();

                     }
                 }
             }
        }
         System.out.println(ll);

    }
}

#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> p;
string maze[55];
string path;
int n, m;
bool simulate(int x, int y) {
  int cx = x, cy = y;
  for (int i = 0; i < path.size(); i++) {
    cx += p[path[i] - '0'].first;
    cy += p[path[i] - '0'].second;
    if (cx < 0 || cx >= n || cy < 0 || cy >= m) return 0;
    if (maze[cx][cy] == 'E') return 1;
    if (maze[cx][cy] == '#') return 0;
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  p.push_back({0, 1});
  p.push_back({0, -1});
  p.push_back({1, 0});
  p.push_back({-1, 0});
  sort(p.begin(), p.end());
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> maze[i];
  cin >> path;
  int sx, sy;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++)
      if (maze[i][j] == 'S') sx = i, sy = j;
  }
  int res = 0;
  do {
    res += simulate(sx, sy);
  } while (next_permutation(p.begin(), p.end()));
  cout << res << endl;
  return 0;
}


x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())

if x1 != x2 and y1 != y2:
    ans = abs(x1 - x2) + abs(y1 - y2) + 2
    print(ans * 2)

else:
    ans = abs(x1 - x2) + abs(y1 - y2) + 3
    print(ans * 2)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int q, w;
  cin >> q >> w;
  int qq, ww;
  cin >> qq >> ww;
  vector<pair<int, int>> vpp;
  vpp.push_back(make_pair(qq - 1, ww + 1));
  vpp.push_back(make_pair(qq, ww + 1));
  vpp.push_back(make_pair(qq + 1, ww + 1));
  vpp.push_back(make_pair(qq - 1, ww));
  vpp.push_back(make_pair(qq + 1, ww));
  vpp.push_back(make_pair(qq - 1, ww - 1));
  vpp.push_back(make_pair(qq, ww - 1));
  vpp.push_back(make_pair(qq + 1, ww + 1));
  vpp.push_back(make_pair(qq, ww));
  pair<int, int> target = make_pair(q, w);
  if (find(vpp.begin(), vpp.end(), target) != vpp.end()) {
    cout << vpp.size() - 1 << endl;
  } else {
    int total1, total2, total3, total4;
    (abs(q - qq) > 1) ? total1 = abs(q - qq) : total1 = 1;
    (abs(w - ww) > 1) ? total2 = abs(w - ww) : total2 = 1;
    int total = (2 + total1 + total2) * 2;
    cout << total << endl;
  }
}


#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
long long qpow(long long a, long long b) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = ans * a % mod;
    a = a * a % mod;
    b >>= 1;
  }
  return ans;
}
int main() {
  long long n, m;
  scanf("%lld%lld", &n, &m);
  long long ans = qpow(2, m) * qpow(n + 1, m - 1) % mod * (n - m + 1) % mod;
  printf("%lld", ans % mod);
  return 0;
}

MOD = 10 ** 9 + 7
n, m = input().split(' ')
n = int(n)
m = int(m)
ans = pow(2 * (n + 1), m, MOD)
ans = (ans * (n + 1 - m)) % MOD
ans = (ans * pow(n + 1, MOD - 2, MOD)) % MOD
print(ans)


import java.util.Scanner;
import java.util.ArrayList;
public class CodeF

{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int k=sc.nextInt();
		int a[]=new int[k];
		for(int i=0;i<k;i++)
		{
			a[i]=sc.nextInt();
		}
		ArrayList<Integer> list=new ArrayList<Integer>();
		for(int i=1;i<=n;i++)
		{
			list.add(i);
		}
		int current=0;
		for(int i=0;i<k;i++)
		{
			current=(current+a[i])%(list.size());
			if(current==(list.size()-1))
			{
				System.out.print(list.get(current)+" ");
				list.remove(current);
				current=0;
			}
			else
			{
				System.out.print(list.get(current)+" ");
				list.remove(current);
			}
		}
	}
}

n,y=input().split()
n=int(n)
y=int(y)
liste=list(range(1,n+1))
x=0
z=0
liste2=list(map(int,input().split()))
while x<y:
  z=((z+liste2[x])%len(liste))
  print(liste[z])
  liste.pop(z)
  x+=1


import java.util.HashMap;
import java.util.Scanner;

public class Stone {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        sc.close();
        int l = s.length();
        HashMap<String, Boolean> hm = new HashMap<String, Boolean>();
        int count = 1;
        hm.put(s, true);
        for(int i = 1; i<l; i++)
        {
        	s = s.charAt(l-1) + s.substring(0, l-1);
        	if(!hm.containsKey(s))
        	{
        		hm.put(s, true);
        		count++;
        	}
        }
        System.out.println(count);

    }

}

from collections import Counter
s = input()
counter = Counter()
for i in range(len(s)):
    counter[s[i:len(s)] + s[0:i]] = 1
print(sum(counter.values()))


#include <bits/stdc++.h>
int main() {
  int n, i, number, count_out, counter;
  scanf("%d", &n);
  char s[n];
  int flag = 0, max = 0, waiter = 0, cautious = 0;
  number = count_out = 0;
  for (i = 0; i < n; i++) {
    scanf(" %c", &s[i]);
    if (s[i] == '(') {
      flag = 1;
      counter = 0;
      waiter = 1;
      max = (count_out > max) ? count_out : max;
      count_out = 0;
    } else if (s[i] == ')') {
      if (counter > 0) number++;
      flag = 0;
    } else if (s[i] == '_') {
      if (flag) {
        if (counter > 0) {
          number++;
        }
        counter = 0;
      } else {
        max = (count_out > max) ? count_out : max;
        count_out = 0;
      }
    } else if (flag) {
      counter++;
    } else if (flag == 0)
      count_out++, max = (count_out > max) ? count_out : max;
  }
  printf("%d %d", max, number);
  return 0;
}

length = int(input())
string = input()
outer = ""
inner = ""

i = 0
while i < length:
    if string[i] == '(':
        i += 1
        inner += " "
        while string[i] != ')':
            if string[i] != '_' and string[i] != '&':
                inner += string[i]
            else:
                inner += " "
            i += 1
        if string[i] == ')':
            outer += " "
    else:
        if string[i] != '_' and string[i] != '&':
            outer += string[i]
        else:
            outer += " "
    i += 1

outer = outer.split()
inner = inner.split()

if outer == []:
    print(0, end=" ")
else:
    len_o = []
    for i in outer:
        len_o.append(len(i))
    print(max(len_o), end=" ")

print(len(inner))


n = int(input())
s = list(map(int, input().split()))
dif = 2 * sum(s) // n
t = []
for i in range(n):
    for j in range(n):
        if s[i] + s[j] == dif and i not in t and j not in t and i != j:
            print(i + 1, j + 1)
            t.append(i)
            t.append(j)

#include <bits/stdc++.h>
using namespace std;
void print(vector<int> v) {
  cout << "|";
  for (int i = 0; i < (int)v.size(); i++) {
    cout << v[i] << " ";
  }
  cout << "|\n";
}
int main() {
  int n;
  cin >> n;
  vector<int> a[101];
  vector<int> v(n);
  for (int i = 0; i < n; i++) {
    cin >> v[i];
    a[v[i]].push_back(i + 1);
  }
  sort(v.begin(), v.end());
  int x, y;
  for (int i = 0; i < n / 2; i++) {
    x = a[v[i]][a[v[i]].size() - 1];
    a[v[i]].pop_back();
    y = a[v[n - i - 1]][a[v[n - i - 1]].size() - 1];
    a[v[n - i - 1]].pop_back();
    cout << x << " " << y << endl;
  }
  getchar();
  getchar();
  return 0;
}


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

public class Bearcompress {

	static int count=0;
	static String ar[];
	static char a[];
	static int q;
	static int n;
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		MyScannerbrc sc=new MyScannerbrc();
		 n=sc.nextInt();
		 q=sc.nextInt();
		 ar=new String[q];
		 a=new char[q];
		int i;
		for(i=0;i<q;i++)
		{
			ar[i]=sc.next();
			a[i]=sc.next().charAt(0);
		}
		find(1,'a');
		System.out.println(count);
	}
	static void find(int h,char fc)
	{
		int i;
		if(h!=n)
		for(i=0;i<q;i++)
		{
			if(fc==a[i])
			{
				find(h+1,ar[i].charAt(0));
			}
		}
		else

					count+=1;

	}
}
class MyScannerbrc
{
	BufferedReader br;
	StringTokenizer st;
	MyScannerbrc()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}
	String next()
	{

		while(st==null || !st.hasMoreTokens())
		{
			try
			{
				st=new StringTokenizer(br.readLine());
			}
			catch(Exception 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(Exception e)
		{
			e.printStackTrace();
		}
		return str;

	}
}

6 36
ac a
af a
db a
ab a
cb a
ef a
ad a
bd a
fe a
de a
be a
bb a
aa a
ae a
df a
bc a
bf a
ce a
ba a
fd a
dc a
eb a
cd a
ca a
ee a
cc a
cf a
dd a
da a
ec a
fc a
fa a
ea a
ed a
ff a
fb a

2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c

6 11
ab a
cc c
ca a
ee c
ff d
bc b
da b
eb a
bb b
af e
dc d

5 9
ab a
cc c
ca a
ee c
ff d
bc b
da b
eb a
bb b

4 35
ae f
ad d
aa a
eb d
fb a
ce b
af c
fe c
ca a
ab a
bd d
bc a
be a
bb f
ba c
cb a
cd a
ac c
cc b
bf b
db a
fa a
ed b
ea a
ee d
ec a
cf d
dd a
fc a
df a
ff a
dc b
ef d
de e
da b

6 15
ab b
bd b
ae b
cd b
ac b
ba b
dc b
bc b
bb b
bf b
ef b
aa b
dd b
cf b
fc b

#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
const long long mod = 1000000007;
const int maxn = 200010;
const double PI = acos(-1.0);
int n, q, ans;
int dp[150][100];
char chan[50][10], x[50][10];
int dfs(char a, int len) {
  if (dp[a][n - len] != -1) {
    return dp[a][n - len];
  }
  if (len == n) {
    return 1;
  }
  int i, j, k;
  long long res = 0;
  for (i = 0; i < q; i++) {
    if (x[i][0] == a) {
      char xx = chan[i][0];
      res += dfs(chan[i][0], len + 1);
    }
  }
  dp[a][n - len] = res;
  return dp[a][n - len];
}
void solve() {
  int i, j, k;
  scanf("%d%d", &n, &q);
  memset(dp, -1, sizeof(dp));
  for (i = 0; i < q; i++) {
    cin >> chan[i] >> x[i];
  }
  ans = 0;
  cout << dfs('a', 1);
}
int main() {
  solve();
  return 0;
}


//package HackerEarthA;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;

/**
 *
 * @author prabhat
 */
public class  easy18{
   public  static long[] BIT;
   public  static long[] tree;

   public  static long[] sum;
   public  static int mod=1000000007;
   public  static int[][] dp;
   public  static boolean[][] isPalin;
   public  static int max1=1000005;
   public  static int[][] g;
   public  static LinkedList<Pair> l[];
   public  static int n,m,q,k,t,arr[],b[],cnt[],chosen[],pos[],ans;
   public  static ArrayList<Integer> adj[],al;
   public  static TreeSet<Integer> ts;
   public  static   char[][] s;
   public  static int depth,mini,maxi;
   public  static long V[],low,high,min=Long.MAX_VALUE;
   public  static boolean visit[][],isPrime[],used[];
   public  static int[][] dist;
   public  static ArrayList<Integer>prime;
   public static int[] x={0,1};
   public static int[] y={-1,0};
   public  static ArrayList<Integer> divisor[]=new ArrayList[1500005];
   public  static  int[][] subtree,parent,mat;
   public  static  TreeMap<Integer,Integer> tm;
   public  static LongPoint[] p;
   public  static int[][] grid;
   public  static ArrayList<Pair> list;
   public static TrieNode root;
  static  LinkedHashMap<String,Integer> map;
   public static BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
   public  static void main(String[] args) throws Exception
   {
   	   InputReader in = new InputReader(System.in);
	   PrintWriter pw=new PrintWriter(System.out);
	   n=in.ii();
	   s=new char[n][n];
	   for(int i=0;i<n;i++)
	   {
		   s[i]=in.is().trim().toCharArray();
	   }
	   long ans=0;
	   for(int i=0;i<n;i++)
	   {
		   int r=0;
		   for(char c:s[i])
			 if(c=='C')r++;
		 ans+=nCr(r,2);
	   }
	for(int j=0;j<n;j++)
	{
		int c=0;
		for(int i=0;i<n;i++)
		{
          if(s[i][j]=='C')c++;
		}
		ans+=nCr(c,2);
	}

	   pw.println(ans);

	pw.close();

}

public static void dfs1(int cur)
{
	used[cur]=true;
	cnt[cur]=1;
	for(int ver:adj[cur])
	{
		if(used[ver])continue;
		dfs1(ver);
        cnt[cur]+=cnt[ver];
	}
}
static ArrayList<String> dfs(String s,String[] sarr,HashMap<String, ArrayList<String>> map)
{
   if(map.containsKey(s))return map.get(s);
   ArrayList<String> res=new ArrayList<>();
   if(s.length()==0)
   {
	   res.add("");
	   return res;
   }

   for(String word:sarr)
   {
	   if(s.startsWith(word))
	   {
		   ArrayList<String > sub=dfs(s.substring(word.length()),sarr,map);
		   for(String s2:sub)
		   {
			   res.add(word+ (s2.isEmpty() ? "" : " ")+s2);
		   }
	   }
   }
   map.put(s,res);
   return res;
}
static class SegmentTree{

  int n;
  int max_bound;

  public SegmentTree(int n)
  {

	  this.n=n;
	  tree=new long[4*n+1];
	  build(1,0,n-1);
  }
void build(int c,int s,int e)
{
   if(s==e)
   {
	   tree[c]=arr[s];
	   return ;
   }

   int mid=(s+e)>>1;
   build(2*c,s,mid);
   build(2*c+1,mid+1,e);
   tree[c]=(tree[2*c]+tree[2*c+1]);
}
void put(int c,int s, int e,int l,int r,int  v) {
	if(l>e||r<s||s>e)return ;
	if (s == e)
	{
		tree[c] = arr[s]^v;
		return;
	}
	int mid = (s + e) >> 1;
	if (l>mid) put(2*c+1,m+1, e , l,r, v);
	else if(r<=mid)put(2*c,s,m,l,r , v);
	else{

	}

}
long query(int c,int s,int e,int l,int r)
{
   if(e<l||s>r)return 0L;

   if(s>=l&&e<=r)
   {
	return tree[c];
   }

	int mid=(s+e)>>1;

	return (query(2*c,s,mid,l,r)+query(2*c+1,mid+1,e,l,r));
 }
}

static void update(int indx,long val)
   {
	   while(indx<max1)
	   {
		   BIT[indx]+=val;
		   indx+=(indx&(-indx));
	   }

   }
static long query1(int indx)
   {
	   long sum=0;
	   while(indx>0)
	   {
		   sum+=BIT[indx];
		 //  System.out.println(indx);
		   indx-=(indx&(-indx));
	   }
	   return sum;
	}

   public static ListNode removeNthFromEnd(ListNode a, int b) {

    int cnt=0;
	ListNode ra1=a;
	ListNode ra2=a;
	while(ra1!=null){ra1=ra1.next; cnt++;}

	if(b>cnt)return a.next;
	else if(b==1&&cnt==1)return null;
	else{
		int y=cnt-b+1;
		int u=0;
		ListNode prev=null;
		while(a!=null)
		{
			u++;
		   if(u==y)
		   {
			   if(a.next==null)prev.next=null;
			   else
			   {
				   if(prev==null)return ra2.next;
				   prev.next=a.next;
				   a.next=null;
			   }
			   break;
		   }
		   prev=a;
		   a=a.next;
		}
	}
	return ra2;
}
   static ListNode rev(ListNode a)
   {
       ListNode prev=null;
       ListNode cur=a;
       ListNode next=null;
       while(cur!=null)
       {
           next=cur.next;
           cur.next=prev;
           prev=cur;
           cur=next;
       }
       return prev;
   }

  static class ListNode {
	     public int val;
	     public ListNode next;
	     ListNode(int x) { val = x; next = null; }
	 }
   static class TrieNode
   {
	   int value;  // Only used in leaf nodes
	   TrieNode[] arr =  new TrieNode[2];
	   public TrieNode() {
		   value = 0;
		   arr[0] = null;
		   arr[1] = null;
	   }
   }
   static void insert(int pre_xor)
   {
	   TrieNode temp = root;

	   // Start from the msb, insert all bits of
	   // pre_xor into Trie
	   for (int i=31; i>=0; i--)
	   {
		   // Find current bit in given prefix
		   int val = (pre_xor & (1<<i)) >=1 ? 1 : 0;

		   // Create a new node if needed
		   if (temp.arr[val] == null)
			   temp.arr[val] = new TrieNode();

		   temp = temp.arr[val];
	   }

	   // Store value at leaf node
	   temp.value = pre_xor;
   }

   static int query(int pre_xor)
   {
	   TrieNode temp = root;
	   for (int i=31; i>=0; i--)
	   {
		   // Find current bit in given prefix
		   int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0;

		   // Traverse Trie, first look for a
		   // prefix that has opposite bit
		   if (temp.arr[val] != null)
			   temp = temp.arr[val];

		   // If there is no prefix with opposite
		   // bit, then look for same bit.
		   else if (temp.arr[1-val] != null)
			   temp = temp.arr[1-val];
	   }
	   return pre_xor^(temp.value);
   }

   public static String add(String s1,String s2)
   {
	   int n=s1.length()-1;
	   int m=s2.length()-1;
	   int rem=0;
	   int carry=0;
	   int i=n;
	   int j=m;
	   String ans="";
	   while(i>=0&&j>=0)
	   {
		 int c1=(int)(s1.charAt(i)-'0');
		 int c2=(int)(s2.charAt(j)-'0');
		 int sum=c1+c2;
		 sum+=carry;
		 rem=sum%10;
		 carry=sum/10;
         ans=rem+ans;
		  i--; j--;

	   }
	   while(i>=0)
	   {
		int c1=(int)(s1.charAt(i)-'0');

		int sum=c1;
		sum+=carry;
		rem=sum%10;
		carry=sum/10;
		ans=rem+ans;
		i--;
	   }
	   while(j>=0)
	   {

		int c2=(int)(s2.charAt(j)-'0');
		int sum=c2;
		sum+=carry;
		rem=sum%10;
		carry=sum/10;
		ans=rem+ans;
		j--;
	   }

	   if(carry>0)ans=carry+ans;
	   return ans;
   }
   public static String[] multiply(String A, String B) {
	int lb=B.length();
	char[] a=A.toCharArray();
	char[] b=B.toCharArray();
	String[] s=new String[lb];
	int cnt=0;
	int y=0;
	String s1="";
q=0;
	for(int i=b.length-1;i>=0;i--)
	{
		int rem=0;
		int carry=0;

		for(int j=a.length-1;j>=0;j--)
		{
			int mul=(int)(b[i]-'0')*(int)(a[j]-'0');
			mul+=carry;
			rem=mul%10;
			carry=mul/10;
			s1=rem+s1;
		}
		s1=carry+s1;
		s[y++]=s1;
		q=Math.max(q,s1.length());
		s1="";
		for(int i1=0;i1<y;i1++)s1+='0';

	}
	return s;
}
   public static long nCr(long total, long choose)
   {
	   if(total < choose)
		   return 0;
	   if(choose == 0 || choose == total)
		   return 1;
	   return nCr(total-1,choose-1)+nCr(total-1,choose);
   }

   static int get(long s)
   {
	  int ans=0;
	  for(int i=0;i<n;i++)
	  {
		  if(p[i].x<=s&&s<=p[i].y)ans++;
	  }
	  return ans;
   }
   static class LongPoint {
	public long x;
	public long y;

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

	public LongPoint subtract(LongPoint o) {
		return new LongPoint(x - o.x, y - o.y);
	}

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

}
    static int CountPs(String s,int n)
       {
    	boolean b=false;
    	     char[] S=s.toCharArray();
	       int[][] dp=new int[n][n];
	       boolean[][] p=new boolean[n][n];
	       for(int i=0;i<n;i++)p[i][i]=true;

	       for(int i=0;i<n-1;i++)
	       {
	    	   if(S[i]==S[i+1])
	    	   {
	    		p[i][i+1]=true;
	    		dp[i][i+1]=0;
	    		b=true;
	    	   }
	       }

	       for(int gap=2;gap<n;gap++)
	       {
	    	   for(int i=0;i<n-gap;i++)
	    	   {
	    		   int j=gap+i;
	    		   if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;}

	    		  if(p[i][j])
	    			   dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1];

	    		   else if(!p[i][j]) dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];

	    		   //if(dp[i][j]>=1)
                             //  return true;
	    	   }
	       }

	   // return b;
    return dp[0][n-1];

    }

  static void Seive()
  {
      isPrime=new boolean[1500005];
      Arrays.fill(isPrime,true);
	 for(int i=0;i<1500005;i++){divisor[i]=new ArrayList<>();}
	 int u=0;
	 prime=new ArrayList<>();
      for(int i=2;i<=(1500000);i++)
      {

          if(isPrime[i])
          {
			prime.add(i);
              for(int j=i;j<1500000;j+=i)
              {

                  divisor[j].add(i);

                  isPrime[j]=false;
              }
         /*    for(long x=(divCeil(low,i))*i;x<=high;x+=i)
             {
                 divisor[(int)(x-low)].add(i*1L);
             }*/

          }
      }

  }
  static long divCeil(long a,long b)
  {
      return (a+b-1)/b;
  }
  static long root(int pow, long x) {
        long candidate = (long)Math.exp(Math.log(x)/pow);
        candidate = Math.max(1, candidate);
        while (pow(candidate, pow) <= x) {
            candidate++;
        }
        return candidate-1;
    }

    static long pow(long x, int pow)
    {
        long result = 1;
        long p = x;
        while (pow > 0) {
            if ((pow&1) == 1) {
                if (result > Long.MAX_VALUE/p) return Long.MAX_VALUE;
                result *= p;
            }
            pow >>>= 1;
            if (pow > 0 && p >= 4294967296L) return Long.MAX_VALUE;
            p *= p;
        }
        return result;
    }

  static boolean valid(int i,int j)
  {
	  if(i>=0&&i<n&&j>=0&&j<m)return true;
	  return false;
  }
  private static class DSU{
		int[] parent;
		int[] rank;
		int cnt;
		public DSU(int n){
			parent=new int[n];
			rank=new int[n];
			for(int i=0;i<n;i++){
				parent[i]=i;
				rank[i]=1;
			}
			cnt=n;
		}
		int find(int i){
	        while(parent[i] !=i){
	        	parent[i]=parent[parent[i]];
	        	i=parent[i];
	        }
	        return i;
	    }
		int Union(int x, int y){
	        int xset = find(x);
	        int yset = find(y);
	        if(xset!=yset)
	        	cnt--;
	        if(rank[xset]<rank[yset]){
	        	parent[xset] = yset;
		        rank[yset]+=rank[xset];
		        rank[xset]=0;
		        return yset;
	        }else{
	        	parent[yset]=xset;
	        	rank[xset]+=rank[yset];
	        	rank[yset]=0;
	        	return xset;
	        }
	    }
	}
  public static int[][] packU(int n, int[] from, int[] to, int max) {

	    int[][] g = new int[n][];
	    int[] p = new int[n];
	    for (int i = 0; i < max; i++) p[from[i]]++;
	    for (int i = 0; i < max; i++) p[to[i]]++;
	    for (int i = 0; i < n; i++) g[i] = new int[p[i]];
	    for (int i = 0; i < max; i++) {
	        g[from[i]][--p[from[i]]] = to[i];
	        g[to[i]][--p[to[i]]] = from[i];
	    }
	    return g;
	}
	public static int[][] parents3(int[][] g, int root) {
	    int n = g.length;
	    int[] par = new int[n];
	    Arrays.fill(par, -1);

	    int[] depth = new int[n];
	    depth[0] = 0;

	    int[] q = new int[n];
	    q[0] = root;
	    for (int p = 0, r = 1; p < r; p++) {
	        int cur = q[p];
	        for (int nex : g[cur]) {
	            if (par[cur] != nex) {
	                q[r++] = nex;
	                par[nex] = cur;
	                depth[nex] = depth[cur] + 1;
	            }
	        }
	    }
	    return new int[][]{par, q, depth};
	}
	public static int lower_bound(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] < target)
                low = mid + 1;
            else
                high = mid;
        }
        return nums[low] == target ? low : -1;
    }

    public static int upper_bound(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while (low < high) {
            int mid = low + (high + 1 - low) / 2;
            if (nums[mid] > target)
                high = mid - 1;
            else
                low = mid;
        }
        return nums[low] == target ? low : -1;
    }
  public static boolean palin(String s)
	{
	   int i=0;
	   int j=s.length()-1;
	   while(i<j)
	   {
		   if(s.charAt(i)==s.charAt(j))
		   {
			   i++;
			   j--;
		   }
		   else return false;
	   }
	   return true;
	}

public static int gcd(int a,int b)
{
	int res=1;
	while(a>0)
	{
		res=a;
		a=b%a;
		b=res;
	}
	return res;
}
static int lcm(int a,int b)
{
	return (a*b)/(gcd(a,b));
}

public static long pow(long n,long p,long m)
{
	 long  result = 1;
	  if(p==0)
	    return 1;

	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    if(result>=m)
	    result%=m;
	    p >>=1;
	    n*=n;
	    if(n>=m)
	    n%=m;
	}
	return result;
}

    /**
     *
     * @param n
     * @param p
     * @return
     */
    public static long pow(long n,long p)
     {
	long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    p >>=1;
	    n*=n;
	}
	return result;

     }

static class Edge implements Comparator<Edge> {
	private int u;
	private int v;
	private long w;
	public Edge() {
	}
	public Edge(int u, int v, long w) {
		this.u=u;
		this.v=v;
		this.w=w;
	}
	public int getU() {
		return u;
	}
	public void setU(int u) {
		this.u = u;
	}
	public int getV() {
		return v;
	}
	public void setV(int v) {
		this.v = v;
	}
	public long getW() {
		return w;
	}
	public void setW(int w) {
		this.w = w;
	      }
	public long compareTo(Edge e)
	  {
		return (this.getW() - e.getW());
	}

        @Override
        public int compare(Edge o1, Edge o2) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

}

static class Pair implements Comparable<Pair>
{
	int x,y;
	Pair (int a,int b)
	{
		this.x=a;
		this.y=b;
	}

	public int compareTo(Pair o) {
		// TODO Auto-generated method stub
		if(this.x!=o.x)
		return -Integer.compare(this.x,o.x);
		else
			return -Integer.compare(this.y, o.y);
		//return 0;
	}
	public boolean equals(Object o) {
       if (o instanceof Pair) {
           Pair p = (Pair)o;
           return p.x == x && p.y == y;
       }
       return false;
   }
   public int hashCode() {
       return new Integer(x).hashCode() * 31 + new Integer(y).hashCode();
   }
}

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

   private SpaceCharFilter filter;
    byte inbuffer[] = new byte[1024];
   int lenbuffer = 0, ptrbuffer = 0;
    final int M = (int) 1e9 + 7;
   int md=(int)(1e7+1);
    int[] SMP=new int[md];
   final double eps = 1e-6;
   final double pi = Math.PI;

	PrintWriter out;
   String check = "";
 InputStream   obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
   public InputReader(InputStream stream)
   {
       this.stream = stream;
   }

    int readByte() {
	        if (lenbuffer == -1) throw new InputMismatchException();
	        if (ptrbuffer >= lenbuffer) {
	            ptrbuffer = 0;
	            try {
	                lenbuffer = obj.read(inbuffer);
	            } catch (IOException e) {
	                throw new InputMismatchException();
	            }
	        }
	        if (lenbuffer <= 0) return -1;
	        return inbuffer[ptrbuffer++];
   }

   public  int read()
   {
       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;
   }

   String is() {
	        int b = skip();
	        StringBuilder sb = new StringBuilder();
	        while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
	        {
	            sb.appendCodePoint(b);
	            b = readByte();
	        }
	        return sb.toString();
   }
   public   int ii() {
	        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();
	        }
   }
 public   long il() {
	        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();
	        }
   }

	    boolean isSpaceChar(int c) {
	        return (!(c >= 33 && c <= 126));
	       }

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

	    float nf() {
	        return Float.parseFloat(is());
	    }

	    double id() {
	        return Double.parseDouble(is());
	    }

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

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

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

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

		 long mul(long a, long b) { return a * b % M; }

			long div(long a, long b)
				 {
					return mul(a, pow(b, M - 2));

		           }

	    double[][] idm(int n, int m) {
	        double a[][] = new double[n][m];
	        for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id();
	        return a;
	        }

	    int[][] iim(int n, int m) {
	        int a[][] = new int[n][m];
	        for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii();
	        return a;
          }

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

   public interface SpaceCharFilter
   {
       public boolean isSpaceChar(int ch);
   }
   public boolean isEndOfLine(int c) {
       return c == '\n' || c == '\r' || c == -1;
   }
}

}

20
C.C.CCC.C....C.CCCCC
C.CC.C..CCC....CCCC.
.CCC.CC...CC.CCCCCC.
.C...CCCC..C....CCC.
.C..CCCCCCC.C.C.....
C....C.C..CCC.C..CCC
...C.C.CC..CC..CC...
C...CC.C.CCCCC....CC
.CC.C.CCC....C.CCC.C
CC...CC...CC..CC...C
C.C..CC.C.CCCC.C.CC.
..CCCCC.C.CCC..CCCC.
....C..C..C.CC...C.C
C..CCC..CC..C.CC..CC
...CC......C.C..C.C.
CC.CCCCC.CC.CC...C.C
.C.CC..CC..CCC.C.CCC
C..C.CC....C....C...
..CCC..CCC...CC..C.C
.C.CCC.CCCCCCCCC..CC

7
.CC..CC
CC.C..C
C.C..C.
C...C.C
CCC.CCC
.CC...C
.C.CCC.

6
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC
CCCCCC

19
CC.C..CC...CCC.C...
....C...C..C.C..C.C
CC.CC.CCCC..C.CC..C
........CC...CC..C.
CCCCC.C...C..C..CC.
...CC..C...C.C.CC..
CC....C.CC.C..CC.CC
.C.C.CC..CCC...CCCC
.....C..CC..C..C.C.
C.CCC.CCC.C..C.C...
CCCC...CC.......CCC
C.C....CC.CC....CC.
C..CC...CCCC..C.CCC
CCC..C..CC.C.C.CC..
CCCCC.CCCC.CCCCCCC.
.C..C.CCC..C..CCCCC
.CCC.C.CC.CCCC..CC.
..CCCC...C.C.CCCCCC
CCCCCCCC..CC.CCC...

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  string a;
  int str[n], stl[n], s = 0;
  char c;
  for (int i = 0; i < n; i++) {
    str[i] = 0;
    stl[i] = 0;
  }
  getline(cin, a);
  for (int i = 0; i < n; i++) {
    getline(cin, a);
    for (int j = 0; j < n; j++) {
      if (a[j] == 'C') {
        str[j]++;
        stl[i]++;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    if (str[i] == 2)
      s++;
    else
      s += str[i] * (str[i] - 1) / 2;
    if (stl[i] == 2)
      s++;
    else
      s += stl[i] * (stl[i] - 1) / 2;
  }
  printf("%d", s);
  return 0;
}


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

/**
 * _607B
 * θ(n^3) time
 * θ(n^2) space
 *
 * @author artyom
 */
public class _607B implements Runnable {
    private BufferedReader in;
    private PrintStream out;
    private StringTokenizer tok;

    private void solve() throws IOException {
        int n = nextInt();
        int[] c = readIntArray(n);
        int[][] dp = new int[n + 1][n];
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }
        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                dp[i][j] = 1 + dp[i + 1][j];
                if (c[i] == c[i + 1]) {
                    dp[i][j] = Math.min(dp[i][j], 1 + dp[i + 2][j]);
                }
                for (int k = i + 2; k <= j; k++) {
                    if (c[i] == c[k] && dp[i + 1][k - 1] + dp[k + 1][j] < dp[i][j]) {
                        dp[i][j] = dp[i + 1][k - 1] + dp[k + 1][j];
                    }
                }
            }
        }
        out.print(dp[0][n - 1]);
    }

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

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = System.out;
            tok = null;
            solve();
            in.close();
        } catch (IOException e) {
            System.exit(0);
        }
    }

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

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

    private int[] readIntArray(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = nextInt();
        }
        return arr;
    }
}

invalid literal for int() with base 10: '5 1 2 3 3 1'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 6 2'

invalid literal for int() with base 10: '7 1 2 3 4 5 4 1'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 5 4'

invalid literal for int() with base 10: '10 1 2 3 4 5 6 7 8 7 6'

invalid literal for int() with base 10: '7 1 2 3 4 5 4 3'

invalid literal for int() with base 10: '7 1 2 3 4 5 5 2'

invalid literal for int() with base 10: '6 1 2 3 4 4 4'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 6 2'

invalid literal for int() with base 10: '5 1 2 2 1 1'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 6 3'

invalid literal for int() with base 10: '5 1 2 3 4 1'

invalid literal for int() with base 10: '7 1 2 3 4 5 5 4'

invalid literal for int() with base 10: '7 1 2 3 4 5 5 1'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 7 4'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 5 1'

invalid literal for int() with base 10: '6 1 2 3 4 2 1'

invalid literal for int() with base 10: '6 1 2 3 4 4 2'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 6 3'

invalid literal for int() with base 10: '5 1 2 2 2 1'

invalid literal for int() with base 10: '5 1 2 3 3 2'

invalid literal for int() with base 10: '7 1 2 3 4 5 4 2'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 6 4'

invalid literal for int() with base 10: '6 1 2 2 1 3 3'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 6 5'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 5 3'

invalid literal for int() with base 10: '4 1 2 3 2 1'

invalid literal for int() with base 10: '6 1 2 3 4 4 3'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 6 1'

invalid literal for int() with base 10: '5 1 2 3 2 1'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 7 3'

invalid literal for int() with base 10: '6 1 2 3 4 3 2'

invalid literal for int() with base 10: '6 1 2 3 4 3 1'

invalid literal for int() with base 10: '6 1 2 3 4 3 2 1'

invalid literal for int() with base 10: '5 1 2 3 1 2 3 4'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 7 1'

invalid literal for int() with base 10: '6 1 2 3 4 4 1'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 6 1'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 6 4'

invalid literal for int() with base 10: '7 1 2 3 4 5 5 3'

invalid literal for int() with base 10: '9 1 2 3 4 5 6 7 7 2'

invalid literal for int() with base 10: '8 1 2 3 4 5 6 5 2'

dp=[]
def calculate(i,j,colors):
    if i>j: return 0
    if dp[i][j]==-1:
        if i==j:
            return 1
        dp[i][j] = 10000
        dp[i][j] = min(dp[i][j],1+calculate(i+1,j,colors))
        # print(i,j)
        if colors[i]==colors[i+1]:
            dp[i][j] = min(dp[i][j],1+calculate(i+2,j,colors))
        for k in range(i+2,j+1):
            if colors[k]==colors[i]:
                dp[i][j] = min(dp[i][j],calculate(i+1,k-1,colors)+calculate(k+1,j,colors))
    return dp[i][j]

def solve():
    t = int(input())
    colors = list(map(int, input().split()))
    [dp.append([-1]*len(colors)) for x in range(len(colors))]
    print (calculate(0,len(colors)-1,colors))

try:
    solve()
except Exception as e:
    print (e)


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Main {
	//YOU CAN DO IT ....
	//Do what you love to do and give it your very best. Whether it's business or baseball, or the theater, or any field.
	//If you don't love what you're doing and you can't give it your best, get out of it. Life is too short. You'll be an old man before you know it.
	//Don't aim for success if you want it; just do what you love and believe in, and it will come naturally.
static int n; static int m; static int ans;static long count; static int flag=1;
static int arr[];static int arr2[];static boolean visited[];
static ArrayList<Integer> s[];static ArrayList<Integer>list;
static class pair{int first,second;public pair(int x,int y){x=first;y=second;}}
    public static void main(String[] args) throws FileNotFoundException {
    	Scanner sc = new Scanner(System.in);
    	//Scanner sc=new Scanner(new File("tabs.in"));
    	String s=sc.next();int[] arr=new int[265];
    	for(int i=0;i<s.length();i++)
    	{
    		arr[s.charAt(i)]++;
    	}

    	for(int i=0;i<265;i++)
    	{
    		long x=arr[i];
    		count+=x*x;
    	}

    	System.out.print(count);

    } }

#include <bits/stdc++.h>
using namespace std;
int main() {
  map<char, long long> m;
  string s;
  cin >> s;
  long long sum = 0;
  for (long long i = 0; i < s.length(); i++) {
    char c = s[i];
    m[c]++;
  }
  map<char, long long>::iterator i;
  for (i = m.begin(); i != m.end(); i++) {
    long long temp = i->second;
    temp = temp * temp;
    sum += temp;
  }
  cout << sum << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int MAXN = 100010;
int N, c[MAXN], f[MAXN][2];
vector<int> graph[MAXN];
void dfs(int u, int p) {
  f[u][0] = 1;
  f[u][1] = 0;
  for (int i = 0; i < graph[u].size(); ++i) {
    int v = graph[u][i];
    if (v != p) {
      dfs(v, u);
      f[u][1] = (long long)f[u][1] * f[v][0] % MOD;
      f[u][1] = (f[u][1] + (long long)f[u][0] * f[v][1]) % MOD;
      f[u][0] = (long long)f[u][0] * f[v][0] % MOD;
    }
  }
  if (c[u] == 1)
    f[u][1] = f[u][0];
  else
    f[u][0] = (f[u][0] + f[u][1]) % MOD;
}
int main() {
  int v;
  cin >> N;
  for (int u = 0; u < N - 1; ++u) {
    cin >> v;
    graph[u + 1].push_back(v);
    graph[v].push_back(u + 1);
  }
  for (int i = 0; i < N; ++i) cin >> c[i];
  dfs(0, -1);
  cout << f[0][1] << endl;
  return 0;
}

n = int(input())
edges = [int(x) for x in input().split()]
color = [int(x) for x in input().split()]
graph = [[] for _ in range(n)]

for a,b in enumerate(edges):
    graph[a+1].append(b)
    graph[b].append(a+1)
dp = [[0]*2 for _ in range(n)]
visited = [0]*n

stack = [0]
while stack:
    v = stack[-1]
    visited[v] = -1
    cn = 0
    for u in graph[v]:
        if visited[u] is not 0:
            continue
        else:
            cn += 1
            stack.append(u)
    if not cn:
        dp[v][0] = 1
        dp[v][1] = 0
        for u in graph[v]:
            if visited[u] is -1:
                continue
            dp[v][1] *= dp[u][0]
            dp[v][1] += dp[v][0] * dp[u][1]
            dp[v][0] *= dp[u][0]
            dp[v][1] %= 1000000007
            dp[v][0] %= 1000000007

        if color[v] is 1:
            dp[v][1] = dp[v][0]
        else:
            dp[v][0] += dp[v][1]
            dp[v][0] %= 1000000007
        visited[v] = 1
        stack.pop()

# def dfs(v):
    # dp[v][0] = 1
    # dp[v][1] = 0
#     visited[v] = True
#     for u in graph[v]:
        # if visited[u] is True:
        #     continue
#         dfs(u)
#         dp[v][1] *= dp[u][0]
#         dp[v][1] += dp[v][0] * dp[u][1]
#         dp[v][0] *= dp[u][0]
#         dp[v][1] %= 1000000007
#         dp[v][0] %= 1000000007

#     if color[v] is 1:
#         dp[v][1] = dp[v][0]
#     else:
#         dp[v][0] += dp[v][1]
#         dp[v][0] %= 1000000007

# dfs(0)
ans = dp[0][1]
print(ans)


#include <bits/stdc++.h>
int vx[50007], vy[50007], vl[50007];
int hx[50007], hy[50007], hl[50007];
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%d %d %d", vx + i, vy + i, vl + i);
  }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    scanf("%d %d %d", hx + i, hy + i, hl + i);
    for (int j = 0; j < n; j++) {
      if (vx[j] >= hx[i] && vx[j] <= hx[i] + hl[i] && hy[i] >= vy[j] &&
          hy[i] <= vy[j] + vl[j]) {
        const int r =
            std::min(std::min(std::min(hy[i] - vy[j], vy[j] + vl[j] - hy[i]),
                              vx[j] - hx[i]),
                     hx[i] + hl[i] - vx[j]);
        if (r > ans) {
          ans = r;
        }
      }
    }
  }
  printf("%d", ans);
  return 0;
}

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

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

class TaskD1 {
	public void solve(int testNumber, InputReader in, PrintWriter out) {
		int n = in.nextInt();
		int m = in.nextInt();

		int[] x1 = new int[n];
		int[] y1 = new int[n];
		int[] l1 = new int[n];
		for (int i = 0; i < n; i++) {
			x1[i] = in.nextInt();
			y1[i] = in.nextInt();
			l1[i] = in.nextInt();
		}

		int[] x2 = new int[m];
		int[] y2 = new int[m];
		int[] l2 = new int[m];
		for (int i = 0; i < m; i++) {
			x2[i] = in.nextInt();
			y2[i] = in.nextInt();
			l2[i] = in.nextInt();
		}

		int res = 0;

		for (int i = 0; i < n; i++) {
			int X1 = x1[i];
			int Y1 = y1[i];
			int X2 = x1[i];
			int Y2 = y1[i] + l1[i];
			for (int j = 0; j < m; j++) {
				int X3 = x2[j];
				int Y3 = y2[j];
				int X4 = x2[j] + l2[j];
				int Y4 = y2[j];

				int x = X1;
				int y = Y3;

				if (X3 <= x && x <= X4 && Y1 <= y && y <= Y2) {
					int len = Math.abs(x - X3);
					len = Math.min(len, Math.abs(x - X4));
					len = Math.min(len, Math.abs(y - Y1));
					len = Math.min(len, Math.abs(y - Y2));
					res = Math.max(res, len);
				}
			}
		}

		out.println(res);
	}
}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

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

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

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


from sys import stdin,stdout
from math import gcd
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
    n=nmbr()
    a=lst()
    g=a[0]
    for v in a[1:]:
        g=gcd(g,v)
    mx=max(a)
    terms=abs(n-mx//g)
    print('Alice' if terms&1 else 'Bob')

Alice Alice Bob Bob Alice Bob Bob Alice Bob Alice Alice Bob Bob Bob Alice Bob Bob Bob Alice Alice Bob Bob Alice Alice Alice Bob Bob Alice Alice Bob Bob Bob Alice Alice Alice Bob Bob Alice Alice Alice Bob Bob Alice Bob Alice Alice Alice Alice

#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (b == 0)
    return a;
  else
    return gcd(b, a % b);
}
int main() {
  int n;
  cin >> n;
  vector<long long> a(n);
  long long g = 0;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    g = gcd(g, a[i]);
  }
  sort(a.begin(), a.end());
  int res = (a[a.size() - 1] / g - a.size()) % 2;
  cout << (res ? "Alice\n" : "Bob\n");
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * @Author  Roman Dzhadan
 * @Team    VNTU [Noobs v3.0]
 * @E-Mail  dflash36@gmail.com
 * @Skype   ronex36
 */
public class Main {

    public static final String     TYPE              =   IOSystem.STANDART;
    public static final long       TIME_LIMIT        =   2;
    public static final long       MEMORY_LIMIT      =   256 * (1L << 20);
    public static final String     INPUT_FILE_NAME   =   "input.txt";
    public static final String     OUTPUT_FILE_NAME  =   "output.txt";
    public static final boolean    ONLINE_JUDGE      =   System.getProperty("ONLINE_JUDGE") != null;

    public static void main(String[] args) throws FileNotFoundException {
        IOSystem IO = (TYPE.equals(IOSystem.STANDART) ? new IOSystem() : new IOSystem(INPUT_FILE_NAME, OUTPUT_FILE_NAME));
        new Thread(null, new Task(IO), "", MEMORY_LIMIT).start();
    }
}

class Task implements Runnable {
//------------------------------------------------------  SOLUTION  -----------------------------------------------------------//

    public void solve() throws IOException {
        int n = in.readInt();
        int k = in.readInt();
        List<Long>data = new ArrayList<Long>();
        for (int i = 0; i < n; i++)
            data.add(in.readLong());
        Collections.sort(data);
        for (int i = 0; i < data.size(); i++) {
            int result = Collections.binarySearch(data, data.get(i) * k);
            if (result >= 0) data.remove(result);
        }
        out.println(k == 1 ? n : data.size());
    }

//-----------------------------------------------------------------------------------------------------------------------------//
    public void run() {
        try {
            long startTime = System.currentTimeMillis();
            solve();
            close();
            long endTime = System.currentTimeMillis();
            long totalMemory = Runtime.getRuntime().totalMemory();
            long freeMemory = Runtime.getRuntime().freeMemory();
            System.err.printf("Time = %.3f ms\n", (endTime - startTime) / 1000.0);
            System.err.printf("Memory = %.3f MB\n", (totalMemory - freeMemory) / (double)(1L << 20));
        }
        catch (Throwable e) {e.printStackTrace(System.err);System.exit(-1);}
    }
    public PrintWriter out;
    public IOSystem in;
    public Task(IOSystem io) {out = io.out; this.in = io;}
    public void close() throws IOException {in.in.close(); out.close();}
}

class IOSystem {
    public static final String FILE = "file";
    public static final String STANDART = "stdin";

    BufferedReader in;
    StringTokenizer tok;
    PrintWriter out;

    public IOSystem() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        tok = new StringTokenizer("");
    }

    public IOSystem(String inputFileName, String outputFileName) throws FileNotFoundException {
        in = new BufferedReader(new FileReader(inputFileName));
        out = new PrintWriter(outputFileName);
        tok = new StringTokenizer("");
    }

    String readString() throws IOException {while (!tok.hasMoreTokens()) {String line = in.readLine();if (line == null) return null;tok = new StringTokenizer(line);}return tok.nextToken();}
    int readInt() throws IOException {return Integer.parseInt(readString());}
    long readLong() throws IOException {return Long.parseLong(readString());}
    double readDouble() throws IOException {return Double.parseDouble(readString());}
    void debug(Object... o) {if (!Main.ONLINE_JUDGE) {System.err.println(Arrays.deepToString(o));}}
}

#include <bits/stdc++.h>
using namespace std;
map<unsigned long long, unsigned long long> num;
const int m = 1e5 + 5;
unsigned long long n, k, v[m], mx, cont;
int main() {
  cin >> n >> k;
  for (int i = 0; i < n; ++i) cin >> v[i];
  sort(v, v + n);
  for (int i = n - 1; i >= 0; --i)
    if (num.find(v[i] * k) == num.end()) num[v[i]] = 1;
  cout << num.size() << endl;
  return 0;
}