import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class E109_2 {

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

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

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

    public static void main(String[] args) throws Exception {
        int n = nextInt(), m = nextInt();
        int[] cnt = new int[n];
        int[][] e = new int[m][2];
        for (int i = 0; i < m; i++) {
            cnt[e[i][0] = nextInt()-1]++;
            cnt[e[i][1] = nextInt()-1]++;
        }
        int[][] v = new int[n][];
        for (int i = 0; i < n; i++) {
            v[i] = new int[cnt[i]+1];
            cnt[i] = 0;
        }
        for (int i = 0; i < m; i++) {
            v[e[i][0]][cnt[e[i][0]]++] = e[i][1];
            v[e[i][1]][cnt[e[i][1]]++] = e[i][0];
        }

        //---------------------------
        for (int i = 0; i < n; i++) {
            v[i][cnt[i]++] = n;
        }
        final long[] hash = new long[n];
        for (int i = 0; i < n; i++) {
            Arrays.sort(v[i]);
            for (int j = 0; j < cnt[i]; j++) {
                hash[i] = hash[i]*1000003 + (v[i][j]+1);
            }
        }
        Arrays.sort(hash);
        long ans = 0;
        int p = 0;
        while (p < n) {
            long c = 1;
            long cur = hash[p++];
            while (p < n && cur == hash[p]) {
                c++;
                p++;
            }
            ans += c*(c-1)/2;
        }

        //---------------------------
        for (int i = 0; i < n; i++) {
            v[i][cnt[i]-1] = i;
        }
        Arrays.fill(hash, 0);
        for (int i = 0; i < n; i++) {
            Arrays.sort(v[i]);
            for (int j = 0; j < cnt[i]; j++) {
                hash[i] = hash[i]*1000003 + (v[i][j]+1);
            }
        }
        Arrays.sort(hash);
        p = 0;
        while (p < n) {
            long c = 1;
            long cur = hash[p++];
            while (p < n && cur == hash[p]) {
                c++;
                p++;
            }
            ans += c*(c-1)/2;
        }
        out.println(ans);
        out.flush();
    }

}

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int MOD = 1e9 + 7;
const int SEED = 29;
long long int p[N];
long long int h[N];
std::vector<pair<int, int> > v;
map<long long int, long long int> mp;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, m;
  cin >> n >> m;
  p[0] = 1;
  for (int i = 1; i <= n; i++) {
    p[i] = p[i - 1] * SEED;
  }
  for (int i = 0; i < m; i++) {
    int x, y;
    cin >> x >> y;
    v.push_back({x, y});
    h[x] += p[y];
    h[y] += p[x];
  }
  for (int i = 1; i <= n; i++) {
    mp[h[i]]++;
  }
  long long int ans = 0;
  for (auto i : mp) {
    ans += (i.second - 1) * i.second / 2;
  }
  for (auto i : v) {
    if (h[i.first] + p[i.first] == h[i.second] + p[i.second]) ans++;
  }
  cout << ans;
  return 0;
}


n,m = map(int, input().split())
data = []

for i in range(n):
    data.append(list(input()))

boundary = [-1,-1,-1,-1]
for i in range(n):
    for j in range(m):
        if data[i][j] == '*':
            if boundary[0]>j or boundary[0]==-1:
                boundary[0] = j
            if boundary[1]<j or boundary[1]==-1:
                boundary[1] = j
            if boundary[2]>i or boundary[2]==-1:
                boundary[2] = i
            if boundary[3]<i or boundary[3]==-1:
                boundary[3] = i

for i in range(boundary[2], boundary[3]+1):
    for j in range(boundary[0], boundary[1]+1):
        print(data[i][j], end='')
    print()


import math
if __name__ == "__main__":
    n =  int(input())

    for i in range(n):
        m = int(input())

        res = 1
        test = 0
        while(m > 2**res -1):
            res += 1
            if m% (2**res -1) == 0:
                test = m//(2**res -1)
                break

        x = test
        print(x)

#include <bits/stdc++.h>
using namespace std;
const int N = (int)1e5 + 9;
long long power(long long x, long long y) {
  if (y == 0) return 1;
  long long temp = power(x, y / 2);
  if (y % 2 == 1)
    return temp * temp * x;
  else
    return temp * temp;
}
void solve() {
  long long n;
  cin >> n;
  long long s = 1;
  for (long long i = 2;;) {
    s += i;
    if (n % s == 0) {
      cout << n / s << "\n";
      return;
    }
    i = i << 1;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}


#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
int m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int f = 0;
    map<int, int> m;
    int a[n];
    for (int i = 0; i < n; ++i) {
      cin >> a[i];
      if (i) {
        if (m[a[i]] >= 2 || (m[a[i]] && a[i] != a[i - 1])) f = 1;
      }
      m[a[i]]++;
    }
    if (f)
      cout << "YES";
    else
      cout << "NO";
    cout << '\n';
  }
  return 0;
}

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

#!/usr/bin/env python

import sys

def main():
    t = int(input())
    for _ in range(t):
        n = int(input())
        a = list(map(int, input().strip().split()))
        d = dict()
        didbreak = False
        for i in range(n):
            if a[i] not in d:
                d[a[i]] = [1, i]
            else:
                if i - d[a[i]][1] > 1:
                    didbreak = True
                    break
                d[a[i]][0] += 1
        if didbreak:
            print("YES")
        else:
            print("NO")

if __name__ == "__main__":
    main()


#include <bits/stdc++.h>
using namespace std;
int n, s1, s2, c1, c2;
string s;
int main() {
  cin >> n;
  cin >> s;
  for (int i = 0; i < n / 2; i++) {
    if (s[i] == '?')
      c1++;
    else
      s1 += s[i] - '0';
  }
  for (int i = n / 2; i < n; i++) {
    if (s[i] == '?')
      c2++;
    else
      s2 += s[i] - '0';
  }
  s1 += c1 / 2 * 9;
  s2 += c2 / 2 * 9;
  puts(s1 == s2 ? "Bicarp" : "Monocarp");
  return 0;
}

Monocarp Bicarp Monocarp Bicarp Bicarp Bicarp Bicarp Monocarp

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

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

    static class TaskD {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int N = in.nextInt();
            char a[] = in.next().toCharArray();
            int left = 0, right = 0;
            int leftQ = 0, rightQ = 0;
            for (int i = 0; i < N; i++) {
                if (i < N / 2) {
                    if (a[i] == '?') {
                        leftQ++;
                    } else {
                        left += a[i] - '0';
                    }
                } else {
                    if (a[i] == '?') {
                        rightQ++;
                    } else {
                        right += a[i] - '0';
                    }
                }
            }
            left += leftQ / 2 * 9;
            right += rightQ / 2 * 9;
            if (left == right) {
                out.printLine("Bicarp");
            } else {
                out.printLine("Monocarp");
            }
        }

    }

    static class OutputWriter {
        PrintWriter writer;

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

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

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

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

    }

    static class InputReader {
        BufferedReader in;
        StringTokenizer tokenizer = null;

        public InputReader(InputStream inputStream) {
            in = new BufferedReader(new InputStreamReader(inputStream));
        }

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

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

    }
}


y,b,r=map(int,input().split())
l,m,n=(1,2,3)
while(l!=y and m!=b and n!=r):
    l+=1
    m+=1
    n+=1
s=l+m+n
print(s)

#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2 * 1e5 + 5;
const long long INF = 1e8 + 5;
const long long MOD = 1e9 + 7;
long long N;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long Y, B, R;
  cin >> Y >> B >> R;
  long long ans = 0;
  if (B >= R - 1 and Y >= R - 2) {
    ans = max(ans, R + R - 1 + R - 2);
  }
  if (Y >= B - 1 and B + 1 <= R) {
    ans = max(ans, B - 1 + B + B + 1);
  }
  if (B >= Y + 1 and R >= Y + 2) {
    ans = max(ans, Y + Y + 1 + Y + 2);
  }
  cout << ans << endl;
  return 0;
}


import static java.util.Arrays.deepToString;

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

public class B {

    static void solve() throws Exception {
        int n = nextInt();
        int[][] a = new int[n][5];
        for(int i = 0; i < n; i++){
            a[i][0] = nextInt();
            a[i][1] = nextInt();
            a[i][2] = nextInt();
            a[i][3] = nextInt();
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(i != j){
                    if(a[i][0] < a[j][0] &&
                       a[i][1] < a[j][1] &&
                       a[i][2] < a[j][2]){
                        a[i][4] = -1;
                        break;
                    }
                }
            }
        }
        int j = 0;
        int micC = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++){
            if(a[i][4] != -1 && a[i][3] < micC){
                micC = a[i][3];
                j = i;
            }
        }
        System.out.print(j + 1);
    }

    static BufferedReader br;
    static StringTokenizer st;
    static PrintWriter out;

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

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

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

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

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

    public static void main(String[] args) {
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            solve();
            br.close();
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

from sys import stdin,stdout
from heapq import heapify,heappush,heappop,heappushpop
from collections import defaultdict as dd, deque as dq,Counter as C
from bisect import bisect_left as bl ,bisect_right as br
from itertools import combinations as cmb,permutations as pmb
from math import factorial as f ,ceil,gcd,sqrt,log,inf
mi = lambda : map(int,input().split())
ii = lambda: int(input())
li = lambda : list(map(int,input().split()))
mati = lambda  r : [ li() for _ in range(r)]
lcm = lambda a,b : (a*b)//gcd(a,b)
MOD=10**9+7
def soe(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return(prime)
def ncr(n,r):
    p,k=1,1
    if (n - r < r):
        r = n - r
    if r!=0:
        while(r):
            p,k=p*n,k*r
            m=gcd(p,k)
            p,k=p//m,k//m
            n,r=n-1,r-1
    else:
            p=1
    return(p)

def solve():
    n=ii()
    arr=[]
    for x in range(n):
        arr.append(li())
    a=[]
    for x in range(n):
        p=arr[x]
        valid=True
        for y in range(n):
            if x!=y:
                q=arr[y]
                if p[0]<q[0] and p[1]<q[1] and p[2]<q[2]:
                    valid=False
        if valid:
            a.append(p)
    a.sort(key= lambda x:x[3])
    # for x in a:
    #     print(x)
    print(arr.index(a[0])+1)
for _ in range(1):
    solve()


#include <bits/stdc++.h>
using namespace std;
int main() {
  int N, M;
  cin >> N >> M;
  vector<string> vv(N);
  for (int i = 0; i < N; i++) cin >> vv[i];
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      if (vv[i][j] == '#') {
        for (int k = 0; k < N; k++) {
          if (vv[k][j] == '#' && vv[k] != vv[i]) {
            cout << "No";
            return 0;
          }
        }
      }
    }
  }
  cout << "Yes";
}

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

import java.util.Scanner;

public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        long pow[] = new long[60];
        pow[0] = 1;
        for (int i = 1; i < 60; i++) {
            pow[i] = pow[i - 1] * 2;
        }
        long x[] = new long[n];
        for (int i = 0; i < n; i++) {
            long buf = 0;
            char c[] = in.next().toCharArray();
            for (int j = m - 1; j >= 0; j--) {
                if (c[j] == '#') {
                    buf += pow[j];
                }
            }
            x[i] = buf;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if((x[i] & x[j]) != 0 && (x[i] & x[j]) != x[i]){
                    System.out.println("No");
                    return;
                }
            }
        }
        System.out.println("Yes");
    }
}


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

public class B {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens()) {
				String cad = br.readLine();
				if (cad == null)
					return null;
				tk=new StringTokenizer(cad);
			}
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public long nextLong() throws NumberFormatException, IOException{
			return Long.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static class DisjointSet {
		int[] parent;
		public DisjointSet(int n) {
			parent = new int[n];
			for(int i = 0; i < n; i++)
				parent[i] = i;
		}
		int find(int a) {
			if (parent[a] != a)
				parent[a] = find(parent[a]);
			return parent[a];
		}
		void join(int a, int b) {
			parent[find(a)] = find(b);
		}
		boolean check(int a, int b) {
			return find(a) == find(b);
		}
	}

	static int N, M;

	public static void main(String args[]) throws NumberFormatException, IOException {
		Scanner sc = new Scanner();
		N = sc.nextInt();
		M = sc.nextInt();
		DisjointSet ds = new DisjointSet(N);
		for(int i = 0; i < M; i++) {
			int a = sc.nextInt() - 1;
			int b = sc.nextInt() - 1;
			ds.join(a, b);
		}
		int[] map = new int[N];
		for(int i = 0; i < N; i++) {
			int c = ds.find(i);
			map[c]++;
		}
		long should_have = 0;
		for(int i = 0; i < N; i++) {
			int n = map[i];
			long tmp = n * (n - 1L);
			tmp /= 2;
			should_have += tmp;
		}
		if (should_have == M)
			System.out.println("YES");
		else
			System.out.println("NO");
	}

}

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

#include <bits/stdc++.h>
using namespace std;
vector<int> a[150001];
bool visited[150002];
long long cnt;
void dfs(int start) {
  cnt++;
  visited[start] = true;
  for (int i = 0; i < a[start].size(); i++) {
    int next = a[start][i];
    if (!visited[next]) dfs(next);
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    a[u].push_back(v);
    a[v].push_back(u);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    cnt = 0;
    if (!visited[i]) {
      dfs(i);
      ans += cnt * (cnt - 1) / 2;
    }
  }
  if (ans == m)
    printf("YES");
  else
    printf("NO");
  return 0;
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
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 << 29);
        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);
            AAsFastAsPossible solver = new AAsFastAsPossible();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class AAsFastAsPossible {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            long n = in.readInt();
            long l = in.readInt();
            long v1 = in.readInt();
            long v2 = in.readInt();
            long k = in.readInt();

            double ans = (double) l / v1;
            double t = (double) l / (2d * v1 * v2 / (v1 + v2) * (DigitUtils.ceilDiv(n, k) - 1) + v2);
            double cand = t * (2d * v2 / (v1 + v2) * (DigitUtils.ceilDiv(n, k) - 1)) + t;
            out.println(Math.min(ans, cand));
        }

    }

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

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

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

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

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(double c) {
            cache.append(new BigDecimal(c).toPlainString());
            return this;
        }

        public FastOutput println(double c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            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 DigitUtils {
        private DigitUtils() {
        }

        public static long floorDiv(long a, long b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static long ceilDiv(long a, long b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            long c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

    }

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

    }
}

import sys
import math

data = sys.stdin.read()
data = data.split(' ')

n = int(data[0])
l = int(data[1])
w = int(data[2])
v = int(data[3])
k = int(data[4])

z = math.ceil(n/k)
top = l/w - l/(2*w*z) + l/(2*v*z)
bot = 1 + v/(2*w*z) - 1/(2*z)
print(top/bot)


#include <bits/stdc++.h>
using namespace std;
const int MAX = 300009;
int n, m;
int P[MAX];
vector<int> v[MAX];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    int a;
    scanf("%d", &a);
    P[a] = i;
  }
  for (int i = 0; i < m; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    a = P[a];
    b = P[b];
    if (a > b) swap(a, b);
    v[b].push_back(a);
  }
  int mm = -1;
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < (int)v[i].size(); j++) mm = max(mm, v[i][j]);
    ans += mm + 1;
  }
  cout << (long long)n * (n + 1) / 2 - ans << endl;
  return 0;
}

import sys # TLE without
n, m = map(int, input().split())

pos = [None] * (n + 1)
for i, a in enumerate(map(int, input().split())):
    pos[a] = i

z = [300005] * (n + 1)
for pr in sys.stdin.read().splitlines():
    x, y = map(int, pr.split())
    if pos[x] > pos[y]:
        x, y = y, x
    z[pos[x]] = min(z[pos[x]], pos[y])
    '''
    if z[pos[x]] is None:
        z[pos[x]] = pos[y]
    else:
        z[pos[x]] = min(z[pos[x]], pos[y])
    '''

lf, rg = n - 1, n - 1
ans = 0
while lf >= 0:
    if z[lf] is not None:
        rg = min(rg, z[lf] - 1)
    ans += rg - lf + 1
    lf -= 1

print(ans)


#include <bits/stdc++.h>
using namespace std;
long long cnt = 0;
string str = "";
int change(string a) {
  stringstream ss;
  int number;
  ss << a;
  ss >> number;
  ss.clear();
  return number;
}
void dp(long long i) {
  string temp;
  temp = str[i];
  if (change(temp) % 4 == 0) cnt++;
  if (i > 0) {
    temp = "";
    temp = str[i] + temp;
    temp = str[i - 1] + temp;
    if (change(temp) % 4 == 0) {
      for (int j = i; j > 0; j--) cnt++;
    }
  }
}
int main() {
  cin >> str;
  for (long long i = 0; i < str.size(); i++) {
    dp(i);
  }
  cout << cnt;
}

from sys import stdin, stdout

def main():
    s = stdin.readline().rstrip()

    count = 0
    for i, e in enumerate(s):
        if int(e) % 4 == 0:
            count += 1
        if i >= 1:
            if int(s[i - 1: i + 1]) % 4 == 0:
                count += i
    stdout.write(f'{count}\n')

if __name__ == '__main__':
    main()


#include <bits/stdc++.h>
using namespace std;
char ins[123456];
int n = 0;
bool vis[501][501];
int h, w, y, x;
void step(int i) {
  if (ins[i] == 'L') x = max(x - 1, 0);
  if (ins[i] == 'R') x = min(x + 1, w - 1);
  if (ins[i] == 'U') y = max(y - 1, 0);
  if (ins[i] == 'D') y = min(y + 1, h - 1);
}
int main() {
  scanf("%d%d%d%d ", &h, &w, &y, &x);
  x--;
  y--;
  scanf(" %s ", ins);
  while (ins[n] > 0) n++;
  for (int i = 0; i < w; i++)
    for (int j = 0; j < h; j++) vis[i][j] = false;
  vector<int> ret;
  int i = 0;
  do {
    ret.push_back(vis[x][y] ? 0 : 1);
    vis[x][y] = true;
    if (i < n) step(i);
  } while (++i <= n);
  int sm = 0;
  for (int i = 0; i < n; i++) {
    sm += ret[i];
    printf("%d ", ret[i]);
  }
  printf("%d\n", w * h - sm);
  return 0;
}

q,b,c,d = map(int,input().split())
s = input()
x,y =c,d
l = 1
print(1,end = ' ')
a = set()
a.add((c,d))
for i in range(len(s)-1):
    item = s[i]
    if (item == 'U'):
        if(x == 1 or (x-1,y) in a):
            print(0,end = ' ')
            if(x-1,y) in a:
                x-=1
        else:
            print(1,end = ' ')
            x-=1
            l+=1
    elif item == 'R':
        if(y == b or (x,y+1) in a):
            print(0,end =' ')
            if(x,y+1) in a:
                y+=1
        else:
            print(1,end = ' ')
            y+=1
            l+=1
    elif item == 'L':
        if(y == 1 or (x,y-1) in a):
            print(0,end = ' ')
            if(x,y-1) in a:
                y-=1
        else:
            print(1,end = ' ')
            y-=1
            l+=1
    else:
        if(x == q or (x+1,y) in a):
            print(0,end = ' ')
            if(x+1,y) in a:
                x+=1
        else:
            print(1,end = ' ')
            x+=1
            l+=1
    a.add((x,y))
print(q*b-l)


import java.util.Scanner;
public class gnome
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        long ans=1;
        for(int a=1;a<=3*n;a++)ans=(ans*3)%1000000007;
        long e=1;
        for(int a=1;a<=n;a++)
        {
            e=(e*7)%1000000007;
        }
        ans-=e;
        System.out.println((ans+1000000007)%1000000007);
    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int N;
  cin >> N;
  string S, T;
  cin >> S >> T;
  int i = 0;
  while (S[i] == T[i]) i++;
  int j = N - 1;
  while (S[j] == T[j]) j--;
  int ret = 0;
  if (S.substr(i, j - i) == T.substr(i + 1, j - i)) ret++;
  if (T.substr(i, j - i) == S.substr(i + 1, j - i)) ret++;
  cout << ret << endl;
  return 0;
}

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

public class E {

	public static void main(String[] args) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		String s = sc.next(), t = sc.next();
		int i = -1, j = -1;
		for(int k = 0; k < n; ++k)
			if(s.charAt(k) != t.charAt(k))
			{
				j = k;
				if(i == -1)
					i = k;
			}
		String c1 = s.substring(i, j + 1), c2 = t.substring(i, j + 1);
		int ans = 0, m = c1.length();
		if((c2.charAt(0) + c1).equals(c2 + c1.charAt(m - 1)))
			++ans;
		if((c1.charAt(0) + c2).equals(c1 + c2.charAt(m - 1)))
			++ans;
		out.println(ans);
		out.flush();
		out.close();
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(FileReader r){	br = new BufferedReader(r);}

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

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

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

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

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

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

	}
}


s1 = ''.join(input().split())
s2 = ''.join(input().split())
for i in s2:
    if s2.count(i) > s1.count(i):
        print("NO")
        exit(0)
print("YES")

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is at the trainer

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the river

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the cove

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the tunnel

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the bay

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the kitchen

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is upstairs

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is on a walk

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is downstears

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is missing

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the attic

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is at the groomer

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the lake

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is at home

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the park

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the car

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the harbor

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the bedroom

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the kennel

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the bathroom

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the garage

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the shed

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the living room

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the cave

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the inlet

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the house

KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw
XZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is on the couch

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the marina

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is downstairs

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is with the sitter

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the yard

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the pond

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the ocean

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is lost

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the lagoon

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the pool

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the grotto

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is at the vet

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the basement

Instead of dogging Your footsteps it disappears but you dont notice anything Your dog is in the closet

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

#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1E9 + 7;
long long h1[26], h2[26];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  if (fopen("inp.txt", "r")) {
    freopen("inp.txt", "r", stdin);
    freopen("outp.txt", "w", stdout);
  }
  string s, t;
  getline(cin, s);
  getline(cin, t);
  long long i;
  for (i = 0; i < s.length(); i++) {
    if (s[i] >= 'A' && s[i] <= 'Z')
      h2[s[i] - 'A']++;
    else if (s[i] >= 'a' && s[i] <= 'z')
      h1[s[i] - 'a']++;
  }
  bool poss = true;
  for (i = 0; i < t.length() && poss; i++) {
    if (t[i] >= 'A' && t[i] <= 'Z') {
      if (h2[t[i] - 'A'])
        h2[t[i] - 'A']--;
      else
        poss = false;
    } else if (t[i] >= 'a' && t[i] <= 'z') {
      if (h1[t[i] - 'a'])
        h1[t[i] - 'a']--;
      else
        poss = false;
    }
  }
  if (poss)
    cout << "YES";
  else
    cout << "NO";
  return 0;
}


class CodeforcesTask391ASolution:
    def __init__(self):
        self.result = ''
        self.dna = ''

    def read_input(self):
        self.dna = input()

    def process_task(self):
        currc = ''
        count = 0
        inserts = 0
        for c in self.dna:
            if currc != c:
                currc = c
                if count:
                    if not count % 2:
                        inserts += 1
                count = 1
            else:
                count += 1
        if not count % 2:
            inserts += 1
        self.result = str(inserts)

    def get_result(self):
        return self.result

if __name__ == "__main__":
    Solution = CodeforcesTask391ASolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())

#include <bits/stdc++.h>
using namespace std;
int main() {
  string s;
  int a, c = 0, x;
  cin >> s;
  a = s.size();
  x = 0;
  for (int i = 0; i < a; i++) {
    if (s[i] == s[i + 1]) {
      x++;
    } else {
      if (x % 2 == 1) {
        c++;
      }
      x = 0;
    }
  }
  cout << c;
  return 0;
}


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

/**
 * @author Don Li
 */
public class SerejaArrangementNumbers {

    int N = (int) 1e5 + 10;

    void solve() {
        int n = in.nextInt(), m = in.nextInt();
        int[] q = new int[m], w = new int[m];
        for (int i = 0; i < m; i++) {
            q[i] = in.nextInt();
            w[i] = in.nextInt();
        }

        int lb = 0, ub = m + 1;
        while (ub - lb > 1) {
            int mid = (lb + ub) >> 1;
            long min;
            if (mid % 2 == 1) {
                min = (long) mid * (mid - 1) / 2;
            } else {
                min = (long) mid * (mid - 1) / 2 + (mid / 2 - 1);
            }
            if (min <= n - 1) lb = mid;
            else ub = mid;
        }

        Integer[] ids = new Integer[m];
        Arrays.setAll(ids, i -> i);
        Arrays.sort(ids, (i, j) -> -Integer.compare(w[i], w[j]));

        long ans = 0;
        for (int i = 0; i < Math.min(lb, n); i++) ans += w[ids[i]];
        out.println(ans);
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new SerejaArrangementNumbers().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

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

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

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

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

#include <bits/stdc++.h>
using namespace std;
long long n, m;
long long a[2000007];
void input();
void solve();
int main() {
  input();
  solve();
  return 0;
}
void input() {
  scanf("%I64d%I64d", &n, &m);
  int i;
  int x;
  for (i = 1; i <= m; i++) {
    scanf("%d%I64d", &x, &a[i]);
  }
  sort(a + 1, a + m + 1);
  reverse(a + 1, a + m + 1);
}
void solve() {
  long long i, c;
  long long ans = 0;
  for (i = 1; i <= m; i++) {
    c = i * (i - 1) / 2;
    if (i % 2 == 0)
      c += i / 2;
    else
      c++;
    if (c <= n) ans += a[i];
  }
  printf("%I64d\n", ans);
}


import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class C {

	void run() throws IOException {
		long ans = 0;
		long mod = 1000000007;
		char[] q = nl().toCharArray();
		int n = q.length;

		long[] p = new long[200];
		p[0] = 1;
		for (int i = 1; i < 200; i++) {
			p[i] = (p[i - 1] * 2) % mod;
		}

		for (int i = n - 1; i >= 0; i--) {
			if (q[i] == '1') {
				ans = (ans + p[n - i + n - 2]) % mod;
			}
		}

		// int m = 1 << n;
		// int x = 0;
		// for (int i = 0; i < n; i++) {
		// if (q[n - i - 1] == '1') {
		// x += 1 << i;
		// }
		// }
		// int[] a = new int[m];
		// int[] b = new int[m];
		//
		// for (int i = 0; i < m; i++) {
		// a[i] = i;
		// b[i] = i ^ x;
		//
		// // tr(a[i] + " " + b[i]);
		// }
		//
		// for (int i = 0; i < m; i++) {
		// for (int j = 0; j < m; j++) {
		// if (a[i] < a[j] && b[j] < b[i]) {
		// ans++;
		// }
		// }
		// }

		pw.println(ans);
	}

	int[] na(int a_len) throws IOException {
		int[] _a = new int[a_len];
		for (int i = 0; i < a_len; i++)
			_a[i] = ni();
		return _a;
	}

	int[][] nm(int a_len, int a_hei) throws IOException {
		int[][] _a = new int[a_len][a_hei];
		for (int i = 0; i < a_len; i++)
			for (int j = 0; j < a_hei; j++)
				_a[i][j] = ni();
		return _a;
	}

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

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

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

	void tr(String debug) {
		if (!OJ)
			pw.println(" " + debug);
	}

	static PrintWriter pw;
	static BufferedReader br;
	static StringTokenizer st;
	static boolean OJ;

	public static void main(String[] args) throws IOException {
		long timeout = System.currentTimeMillis();
		OJ = System.getProperty("ONLINE_JUDGE") != null;
		pw = new PrintWriter(System.out);
		br = new BufferedReader(OJ ? new InputStreamReader(System.in) : new FileReader(new File("C.txt")));

		while (br.ready())
			new C().run();
		if (!OJ) {
			pw.println();
			pw.println(System.currentTimeMillis() - timeout);
		}
		br.close();
		pw.close();
	}

}

#!/usr/local/bin/python3.3 -tt

import sys

if __name__ == '__main__':
    for l in sys.stdin:
        s = l.strip()
        break

    n = len(s)

    d = 2 ** (n - 1)

    print(d * int(s, 2) % 1000000007)


#include <bits/stdc++.h>
using namespace std;
const int maxn = 60;
int n;
long long ai[maxn];
long long sum[maxn];
int l1[maxn], r1[maxn];
int l2[maxn], r2[maxn];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &ai[i]);
  for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + ai[i];
  int res = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = i; j <= n; j++) {
      long long q = sum[j] - sum[i - 1];
      int s = 1;
      int cnt = 0;
      for (int k = 1; k <= n; k++) {
        for (int l = s; l <= k; l++) {
          if (sum[k] - sum[l - 1] == q) {
            cnt++;
            l1[cnt] = l;
            r1[cnt] = k;
            s = k + 1;
            break;
          }
        }
      }
      if (cnt > res) {
        res = cnt;
        for (int k = 1; k <= cnt; k++) l2[k] = l1[k], r2[k] = r1[k];
      }
    }
  }
  printf("%d\n", res);
  for (int i = 1; i <= res; i++) printf("%d %d\n", l2[i], r2[i]);
  return 0;
}

/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;

   public class x1141F
   {
      public static void main(String omkar[]) throws Exception
      {
         BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
         StringTokenizer st = new StringTokenizer(infile.readLine());
         int N = Integer.parseInt(st.nextToken());
         int[] arr = new int[N];
         st = new StringTokenizer(infile.readLine());
         for(int i=0; i < N; i++)
            arr[i] = Integer.parseInt(st.nextToken());
         HashMap<Long, ArrayList<Integer>> map = new HashMap<Long, ArrayList<Integer>>();
         for(int r=0; r < N; r++)
         {
            long sum = 0L;
            for(int i=r; i >= 0; i--)
            {
               sum += arr[i];
               if(!map.containsKey(sum))
                  map.put(sum, new ArrayList<Integer>());
               map.get(sum).add(i);
               map.get(sum).add(r);
            }
         }
         ArrayList<Integer> res = new ArrayList<Integer>();
         for(long key: map.keySet())
         {
            ArrayList<Integer> ls = map.get(key);
            ArrayList<Integer> temp = new ArrayList<Integer>();
            temp.add(ls.get(0));
            temp.add(ls.get(1));
            int r = ls.get(1);
            for(int i=2; i < ls.size(); i+=2)
               if(r < ls.get(i))
               {
                  r = ls.get(i+1);
                  temp.add(ls.get(i));
                  temp.add(ls.get(i+1));
               }
            if(res.size() < temp.size())
               res = temp;
         }
         System.out.println(res.size()/2);
         StringBuilder sb = new StringBuilder();
         for(int i=0; i < res.size(); i+=2)
         {
            sb.append((1+res.get(i))+" "+(1+res.get(i+1)));
            sb.append("\n");
         }
         System.out.print(sb);
      }
   }


import java.util.Scanner;

public class HaveTimeAll {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextInt();
        long b = scanner.nextInt();

        long sum = a + b;

        long countOfBook = (long) (0.5 * (-1 + Math.sqrt(1 + 8 * sum)));

        StringBuilder firstDay = new StringBuilder();
        StringBuilder secondDay = new StringBuilder();

        long firstCount = 0;
        long secondCount = 0;

        for (long i = countOfBook; i > 0; i--) {
            if (i <= a) {
                a -= i;
                firstDay.append(i).append(" ");
                firstCount++;
            } else {
                secondDay.append(i).append(" ");
                secondCount++;
            }
        }

        System.out.println(firstCount);
        System.out.println(firstDay);
        System.out.println(secondCount);
        System.out.println(secondDay);
    }
}

def get_out(list):
    print(len(list))
    out=' '.join(list)
    print(out)

arr = input().split()
a = int(arr[0])
b = int(arr[1])

s=a+b

temp=0
i=0
while(temp<=s):
    i+=1
    temp+=i

i-=1

list_a=[]
list_b=[]
for x in range(i,0,-1):

    if(a-x>=0):
        a-=x
        list_a.append(str(x))
    elif (b-x>=0):
        b-=x
        list_b.append(str(x))

get_out(list_a)
get_out(list_b)


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int n, k;
  char str[51];
  string s;
  cin >> n >> k >> str;
  s = str;
  int l = 0;
  for (int i = 1; i < n; i++) {
    if (s.substr(0, i) == s.substr(n - i, i)) {
      l = i;
    }
  }
  if (k) {
    cout << str;
  }
  for (int i = 1; i < k; i++) cout << (str + l);
  cout << endl;
  return 0;
}

n, k = map(int, input().split())
s = input()
ans = None
for i in range(1, n):
    prefix = s[0:n-i]
    suffix = s[i:n]
    if prefix == suffix:
        ans = prefix
        ans += s[n-i:n] * k
        break
if ans is None:
    ans = s * k
print (ans)


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

public class Main {

	private static int[] input = new int[130000];

	private static boolean check(int value , Map<Integer , Integer> map) {

		long current = 1;
		while (current <= (long) (1 << 30)) {
			if (current >= value) {
				int temp = (int) (current - value);
				if (map.containsKey(temp)) {
					if (temp == value) {
						if (map.get(value) >= 2) {
							return true;
						}
					} else {
						if (map.containsKey(temp)) {
							return true;
						}
					}
				}
			}
			current *= 2;
		}
		return false;

	}

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

		Scanner scan = new Scanner(System.in);

		Map<Integer , Integer> map = new HashMap<>();
		int i , n = scan.nextInt() , ans = 0;
		for (i = 0;i < n;i ++) {
			input[i] = scan.nextInt();
			if (!map.containsKey(input[i])) {
				map.put(input[i] , 1);
			} else {
				map.put(input[i] , map.get(input[i]) + 1);
			}
		}
		for (i = 0;i < n;i ++) {
			int current = input[i];
			if (!check(current , map)) {
				ans ++;
			}
		}
		System.out.println(ans);

	}

}

from collections import*
input()
arr = Counter(map(int,input().split()))
binpow = [2**i for i in range(31)]
deleted = 0
for item in list(arr.elements()):
    flag = True
    for bp in binpow:
        if (arr.get(bp - item) != None):
            if (bp - item == item):
                if (arr.get(bp - item) > 1):
                    flag = False
                    break
            else:
                flag = False
                break
    if (flag):
        deleted += 1
print(deleted)


#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios::sync_with_stdio(0);
  string seq;
  cin >> seq;
  vector<string> f(10);
  for (int i = 0; i < 10; ++i) {
    cin >> f[i];
  }
  for (int i = 0; i + 8 <= 80; i += 10) {
    for (int j = 0; j < 10; ++j) {
      if (f[j] == seq.substr(i, 10)) {
        cout << j;
      }
    }
  }
  cout << endl;
  return 0;
}

import java.util.Scanner;

public class Restoringpassword {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner input = new Scanner(System.in);
		String z = input.next();
		String[] s = new String[10];
		String p = "";
		for(int i=0; i<10;i++)s[i] = input.next();
		int j=0;
		while(j+10<=80){
		for(int i=0; i<10;i++){
			if(z.substring(j,j+10).equals(s[i]))p+=Integer.toString(i);
		}
		j+=10;
	}
		System.out.println(p);
	}

}


# 876A

def main():
	n, a, b, c = int(input()), int(input()), int(input()), int(input())
	if n == 1:
		return 0
	n -= 1
	count = 0
	state = 0
	while n:
		if state == 0:
			if a > b:
				count += b
				state = 2
			else:
				count += a
				state = 1
		elif state == 1:
			if a > c:
				count += c
				state = 2
			else:
				count += a
				state = 0
		else:
			if b > c:
				count += c
				state = 1
			else:
				count += b
				state = 0
		n -= 1

	return count

if __name__ == "__main__":
	print(main())
	# input()

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int a, b, c;
  cin >> a >> b >> c;
  if (n == 1) {
    cout << 0;
    return 0;
  }
  cout << min(a, b) + min(min(a, b), c) * (n - 2);
}


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

public class CF411D {
	public static void main(String args[]) {
		InputReader in = new InputReader(System.in);
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		/*------------------------------My Code starts here------------------------------*/
		String s=in.next();
		int n=s.length(),i;
		long ans=0,b=0;
		for(i=n-1;i>=0;i--)
		{
			if(s.charAt(i)=='a')
			{
				ans+=b;
				ans%=l;
				b=b<<1;
				b%=l;
			}
			else
				b++;
		}
		out.println(ans%l);
		out.close();
		/*------------------------------The End------------------------------------------*/
	}

	public static final long l = (int) (1e9 + 7);

	private static int[] nextIntArray(InputReader in, int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = in.nextInt();
		return a;
	}

	private static long[] nextLongArray(InputReader in, int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = in.nextLong();
		return a;
	}

	private static int[][] nextIntMatrix(InputReader in, 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] = in.nextInt();
		}
		return a;
	}

	private static void show(int[] a) {
		for (int i = 0; i < a.length; i++)
			System.out.print(a[i] + " ");
		System.out.println();
	}

	private static void show2DArray(char[][] a) {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[0].length; j++)
				System.out.print(a[i][j]);
			System.out.println();
		}
	}

	static class Pair {
		private int first;
		private int second;

		public Pair(int i, int j) {
			this.first = i;
			this.second = j;
		}

		public int getFirst() {
			return first;
		}

		public int getSecond() {
			return second;
		}

		public void setFirst(int k) {
			this.first = k;
		}

		public void setSecond(int k) {
			this.second = k;
		}
	}

	static int modPow(int a, int b, int p) {
		int result = 1;
		a %= p;
		while (b > 0) {
			if ((b & 1) != 0)
				result = (result * a) % p;
			b = b >> 1;
			a = (a * a) % p;
		}
		return result;
	}

	public static void SieveOfEratosthenes(int n) {
		boolean[] prime = new boolean[n + 1];
		Arrays.fill(prime, true);
		prime[1] = false;
		int i, j;
		for (i = 2; i * i <= n; i++) {
			if (prime[i]) {
				for (j = i; j <= n; j += i) {
					if (j != i)
						prime[i] = false;
				}
			}
		}
	}

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

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

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

		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 long nextLong() {
			return Long.parseLong(next());
		}

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

}

def mess():
    String=input()
    count_it=0
    Counter=0

    for i in String:
        if i=='a':
            count_it = (count_it * 2) % Modulo
            count_it+=1

        elif i=='b':
            Counter+=count_it
            #count_it =(count_it* 2)%Modulo
    return Counter

if __name__ == "__main__":
    Modulo = 1000000007
    print(mess()%Modulo)


//  package CF;

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

public class B{

	public static void main(String[] args) throws Exception
	{
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int [] x = new int[4];
		for (int i = 0; i < x.length; i++) {
			x[i] = sc.nextInt();
		}
		int a1 = x[0] ^ x[1];
		int a2 = x[2] | x[3];
		int a3 = x[1] & x[2];
		int a4 = x[0] ^ x[3];
		int b1 = a1 & a2;
		int b2 = a3 | a4;
		out.println(b1 ^ b2);
		out.flush();
		out.close();
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(FileReader fileReader)
		{
			br = new BufferedReader(fileReader);
		}

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

		public int nextInt() throws IOException
		{
			return Integer.parseInt(next());
		}
		public double nextDouble() throws IOException
		{
			return Double.parseDouble(next());
		}

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

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

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

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 50 + 10;
const int MAXM = 1000 + 10;
const int INF = 1000000001;
const int MOD = 1000000007;
int c[300];
bool A(bool a, bool b) { return a ^ b; }
bool B(bool a, bool b) { return a | b; }
bool C(bool a, bool b) { return a & b; }
int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  int a, b, c, d;
  cin >> a >> b >> c >> d;
  int e = A(a, b);
  int f = B(c, d);
  int g = C(b, c);
  int h = A(a, d);
  int i = C(e, f);
  int j = B(g, h);
  cout << A(i, j) << endl;
  return 0;
}


n,m=map(int,input().split())
m1,m2,m3=[m+1]*n,[m+1]*n,[m+1]*n
for i in range(n):
    s=input()
    for j, c in enumerate(s):
        z=min(j, m-j)
        if c>='0' and c<='9':
            m1[i]=min(m1[i],z)
        else:
            if c>='a' and c<='z':
                m2[i]=min(m2[i],z)
            else:
                m3[i]=min(m3[i],z)
ans=m*3
for i in range(n):
    for j in range(n):
        if i!=j:
            for p in range(n):
                if i!=p and j!=p:
                    ans=min(ans,m1[i]+m2[j]+m3[p])
print(ans)

#include <bits/stdc++.h>
using namespace std;
char s[105][105];
int n, m;
long long d[105][3];
int fun(int a) { return a > m - a ? m - a : a; }
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) scanf("%s", s[i]);
  for (int i = 1; i <= n; i++) {
    int min0, min1, min2;
    min0 = min1 = min2 = 0x3f3f3f3f;
    for (int j = 0; j < m; j++)
      if (s[i][j] == '&' || s[i][j] == '#' || s[i][j] == '*')
        min2 = min(min2, fun(j));
      else if (s[i][j] >= '0' && s[i][j] <= '9')
        min1 = min(min1, fun(j));
      else if (s[i][j] >= 'a' && s[i][j] <= 'z')
        min0 = min(min0, fun(j));
    d[i][0] = min0;
    d[i][1] = min1;
    d[i][2] = min2;
  }
  long long ans = 0x3f3f3f3f;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      for (int k = 1; k <= n; k++)
        if (i != j && i != k && j != k)
          ans = min(ans, d[i][0] + d[j][1] + d[k][2]);
  printf("%I64d", ans);
}


def find_path(x,y):
	p1,p2 = [],[]
	while x!=0:
		p1.append(x)
		x = x//2
	while y!=0:
		p2.append(y)
		y = y//2
	p1 = p1[::-1]
	p2 = p2[::-1]
	# print (p1,p2)
	for i in range(min(len(p1),len(p2))):
		if p1[i]==p2[i]:
			ind = i
		else:
			break
	path = []
	for i in range(ind,len(p1)):
		path.append(p1[i])
	path = path[::-1]
	for i in range(ind+1,len(p2)):
		path.append(p2[i])

	return path

q = int(input())
cost = {}
for i in range(q):
	a = list(map(int,input().split()))
	b = find_path(a[1],a[2])
	# print (b)
	if a[0] == 1:
		w = a[-1]
		for j in range(1,len(b)):
			if (b[j],b[j-1]) not in cost:
				cost[(b[j],b[j-1])] = w
				cost[(b[j-1],b[j])] = w
			else:
				cost[(b[j],b[j-1])] += w
				cost[(b[j-1],b[j])] += w
	else:
		ans = 0
		for j in range(1,len(b)):
			if (b[j],b[j-1]) in cost:
				ans += cost[(b[j],b[j-1])]
		print (ans)

#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long INF = 1000000000;
template <class T>
inline void read(T &x) {
  char c;
  int flag = 1;
  while ((c = getchar()) < '0' || c > '9')
    if (c == '-') flag *= -1;
  x = c - '0';
  while ((c = getchar()) >= '0' && c <= '9') x = x * 10 + c - '0';
  x *= flag;
  return;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, q;
  cin >> q;
  map<long long, long long> dp;
  while (q--) {
    long long op, u, v;
    cin >> op >> u >> v;
    if (op == 1) {
      long long w;
      cin >> w;
      while (u ^ v) {
        if (u < v) swap(u, v);
        dp[u] += w, u /= 2;
      }
    } else {
      long long ans = 0;
      while (u ^ v) {
        if (u < v) swap(u, v);
        ans += dp[u], u /= 2;
      }
      cout << ans << endl;
    }
  }
}


import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintWriter;
import java.io.OutputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
    static class TaskB {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            String[] input = in.next().split(":");
            int h = Integer.parseInt(input[0]);
            int m = Integer.parseInt(input[1]);
            int a = in.readInt();
            Time t = new Time(m, h);
            t.add(a);
            out.printLine(t.toStr());
//        out.printLine(h, m, a);

        }

        class Time {
            int hours;
            int minutes;

            public Time(int minutes, int hours) {
                this.minutes = minutes;
                this.hours = hours;
            }

            void add(int moar) {
                int moarhours = moar / 60;
                int newhours = (hours + moarhours) % 24;
                int newminutes = (minutes + moar - moarhours * 60);
                if(newminutes >= 60) newhours = (newhours + 1) % 24;
                newminutes %= 60;
                hours = newhours;
                minutes = newminutes;
            }

            String toStr() {
                String hrs = Integer.toString(hours);
                if(hrs.length() < 2) hrs = "0" + hrs;
                String mins = Integer.toString(minutes);
                if(mins.length() < 2) mins = "0" + mins;
                return hrs + ":" + mins;
            }

        }

    }

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

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

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

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

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

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

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

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

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

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

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

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

        public void print(Object... objects) {
            for(int i = 0; i < objects.length; i++) {
                if(i != 0)
                    writer.print(' ');
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

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

    }
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, c, d, e;
  scanf("%d", &a);
  getchar();
  scanf("%d%d", &b, &c);
  d = b + c;
  e = a + (d / 60);
  e = e % 24;
  d = d % 60;
  printf("%02d:%02d\n", e, d);
}


"""
Codeforces
5D - Follow Traffic Rules
http://codeforces.com/contest/5/problem/D

Héctor González Belver
../07/2018
"""
import sys

def time_distance(v0, a, d):
  #quadratic equation. Time is positive ==> root with (+discriminant) in quadratic formula
  #d = v0*t + (a/2)*t^2
  return (-v0 + (v0**2 + 2*a*d)**0.5)/a

def time_accelerating(v0, v1, a):
  return (v1 - v0)/a

def time_speed(v, d):
  return d/v

def distance_travelled(v0, t, a):
  return v0*t + (a/2)*t**2

def main():
  a, v = map(int,sys.stdin.readline().strip().split())
  l, d, w = map(int,sys.stdin.readline().strip().split())

  time = 0

  time_to_d = time_distance(0, a, d)
  time_to_v = time_accelerating(0, v, a)

  if (v if time_to_v <= time_to_d else time_to_d * a) <= w:
    #Accelerating 0-v
    acceleration_time = time_to_v
    acceleration_distance = distance_travelled(0, acceleration_time, a)

    if acceleration_distance >= l:
      #Accelerating 0-?
      time = time_distance(0, a, l)
    else:
      #Accelerating 0-v
      time = acceleration_time
      #Max speed v
      time += time_speed(v, l - acceleration_distance)

  else:
    if time_to_v <= time_to_d:
      #Accelerating 0-v
      acceleration_time = time_to_v
      acceleration_distance = distance_travelled(0, acceleration_time, a)

      #Decelerating v-w
      deceleration_time = time_accelerating(v, w, -a)
      deceleration_distance = distance_travelled(v, deceleration_time, -a)

    if time_to_v > time_to_d or acceleration_distance + deceleration_distance > d:
      #Accelerating 0-w
      acceleration_time = time_accelerating(0, w, a)
      acceleration_distance = distance_travelled(0, acceleration_time, a)

      remaining_distance = d - acceleration_distance
      #Remaining distance --> Acceleration = -Deceleration ==> half remaining distance each action
      delta_time = time_distance(w, a, remaining_distance/2)
      #Accelerating 0-? and Decelerating ?-w
      time = acceleration_time + 2*delta_time
    else:
      #Accelerating 0-v
      time = time_to_v
      #Max speed v
      time += time_speed(v, d - deceleration_distance - acceleration_distance)
      #Decelerating v-w
      time += deceleration_time

    #Accelerating w-v
    acceleration_time = time_accelerating(w, v, a)
    acceleration_distance = distance_travelled(w, acceleration_time, a)
    if acceleration_distance >= l - d:
      #Accelerating w-?
      time += time_distance(w, a, l - d)
    else:
      #Accelerating w-v
      time += acceleration_time
      #Max speed v
      time += time_speed(v, l - (d + acceleration_distance))

  sys.stdout.write('{0:.5f}'.format(time) + '\n')

if __name__ == '__main__':
  main()

#include <bits/stdc++.h>
using namespace std;
double a, v, l, d, w;
double Move(double v1, double v2, double a, double d) {
  double ret = 0;
  double s_2 = (v2 * v2 - v1 * v1) / (2 * a);
  if (d > s_2) {
    ret += (v2 - v1) / a;
    ret += (d - s_2) / v2;
  } else {
    double v_tmp = sqrt(v1 * v1 + 2 * a * d);
    ret += (v_tmp - v1) / a;
  }
  return ret;
}
int main() {
  scanf("%lf%lf", &a, &v);
  scanf("%lf%lf%lf", &l, &d, &w);
  double ans = 0;
  if (w < v) {
    double s_2 = w * w / (2 * a);
    if (s_2 >= d)
      ans = Move(0, v, a, l);
    else {
      double s_3 = (2 * v * v - w * w) / (2 * a);
      if (d > s_3) {
        ans += (2 * v - w) / a;
        ans += (d - s_3) / v;
      } else {
        double v_2 = sqrt((w * w + 2 * a * d) / 2);
        ans += (2 * v_2 - w) / a;
      }
      ans += Move(w, v, a, l - d);
    }
  } else
    ans = Move(0, v, a, l);
  printf("%.12lf\n", ans);
  return 0;
}


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

public class Main {

    public void solve() throws IOException{

        int r = in.nextInt();
        int g = in.nextInt();

        int[] dp = new int[r + 1];
        int MOD = 1000000007;

        dp[r] = 1;

        for(int i = 1; i <= 999; i++){

            //out.println("Trying to create the ith level: " + i);
            //printArr(dp);

            int total = i * (i - 1) / 2; // previous stage total cubes used
            //out.println("previous total cubes needed: " + total);
            int[] newDp = new int[r + 1];
            boolean found = false;

            for(int j = 0; j <= r; j++){

                if(j + i <= r){
                    newDp[j] = (newDp[j] + dp[j + i]) % MOD; // getting to new state with dp[j + i]
                    found |= (dp[j + i] != 0);
                }

                if(total - (r - j) + i <= g){ // if we have enough green for this stage
                    newDp[j] = (newDp[j] + dp[j]) % MOD;
                    found |= (dp[j] != 0);
                }

            }

            //out.println("Updated: ");
            //printArr(newDp);

            if(!found){
                long res = 0;
                for(int j = 0; j <= r; j++){
                    res = (res + dp[j]) % MOD;
                }
                //out.println("level" + i);
                out.println(res);
                return;
            }

            dp = newDp;

        }

    }

    public BigInteger gcdBigInt(BigInteger a, BigInteger b){

        if(a.compareTo(BigInteger.valueOf(0L)) == 0){
            return b;
        }else{
            return gcdBigInt(b.mod(a), a);
        }

    }

    FastScanner in;
    PrintWriter out;

    static class FastScanner {

        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
            st = null;
        }

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

        String nextLine() throws IOException {
            if (st == null || !st.hasMoreTokens())
                return br.readLine();
            StringBuilder result = new StringBuilder(st.nextToken());
            while (st.hasMoreTokens()) {
                result.append(" ");
                result.append(st.nextToken());
            }
            return result.toString();
        }

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

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

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

    }

    void run() throws IOException {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out, false);
        solve();
        out.close();
    }

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

    public void printArr(int[] arr){
        for(int i = 0; i < arr.length; i++){
            out.print(arr[i] + " ");
        }
        out.println();
    }

    public long gcd(long a, long b){
        if(a == 0) return b;
        return gcd(b % a, a);
    }

    public boolean isPrime(long num){

        if(num == 0 || num == 1){
            return false;
        }

        for(int i = 2; i * i <= num; i++){
            if(num % i == 0){
                return false;
            }
        }

        return true;
    }

    public class Pair<A, B>{
        public A x;
        public B y;

        Pair(A x, B y){
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            if (!x.equals(pair.x)) return false;
            return y.equals(pair.y);
        }

        @Override
        public int hashCode() {
            int result = x.hashCode();
            result = 31 * result + y.hashCode();
            return result;
        }

    }

    class Tuple{
        int x; int y; int z;
        Tuple(int ix, int iy, int iz){
            x = ix;
            y = iy;
            z = iz;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 123;
vector<int> v[maxn];
int n, m, High[maxn];
bool mark[maxn];
int Dfs(int Vert, int Dad) {
  mark[Vert] = true;
  vector<int> now;
  now.clear();
  for (__typeof(v[Vert].begin()) i = v[Vert].begin(); i != v[Vert].end(); ++i)
    if (!mark[*i]) {
      High[*i] = High[Vert] + 1;
      if (Dfs(*i, Vert) == 1) now.push_back(*i);
    } else if (*i != Dad and High[*i] < High[Vert])
      now.push_back(*i);
  while (now.size() >= 2) {
    int x = now.back();
    now.pop_back();
    int y = now.back();
    now.pop_back();
    printf("%d %d %d\n", x, Vert, y);
  }
  if (now.empty())
    return 1;
  else {
    printf("%d %d %d\n", now[0], Vert, Dad);
    return 0;
  }
}
int main() {
  int fi, se;
  cin >> n >> m;
  if (m % 2) {
    puts("No solution");
    return 0;
  }
  while (m--) {
    cin >> fi >> se;
    v[fi].push_back(se);
    v[se].push_back(fi);
  }
  Dfs(1, 0);
  return 0;
}

import sys

input = sys.stdin.readline
print = sys.stdout.write

def get_input():
    n, m = [int(x) for x in input().split(' ')]

    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        c1, c2 = [int(x) for x in input().split(' ')]
        graph[c1].append(c2)
        graph[c2].append(c1)

    if m % 2 != 0:
        print("No solution")
        exit(0)

    return graph

def dfs(graph):
    n = len(graph)
    w = [0] * n
    pi = [None] * n
    visited = [False] * n
    finished = [False] * n
    adjacency = [[] for _ in range(n)]

    stack = [1]
    while stack:
        current_node = stack[-1]

        if visited[current_node]:
            stack.pop()
            if finished[current_node]:
                w[current_node] = 0
                continue

            # print(current_node, adjacency[current_node])
            finished[current_node] = True
            unpair = []
            for adj in adjacency[current_node]:
                if w[adj] == 0:
                    # print('unpaired ->', adj, w[adj])
                    unpair.append(adj)
                else:
                    print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))

            while len(unpair) > 1:
                print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
            w[current_node] = unpair.pop() if unpair else 0
            continue

        visited[current_node] = True
        not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
        stack += not_blocked_neighbors
        adjacency[current_node] = not_blocked_neighbors
        # print('stack:', stack, current_node)

# def recursive_dfs(graph):
#     n = len(graph)
#     visited = [False] * n
#     recursive_dfs_visit(graph, 1, visited)

# def recursive_dfs_visit(graph, root, visited):
#     unpair = []
#     visited[root] = True
#     adjacency = [x for x in graph[root] if not visited[x]]
#     for adj in adjacency:
#         w = recursive_dfs_visit(graph, adj, visited)
#         if w == 0:
#             unpair.append(adj)
#         else:
#             print(' '.join([str(root), str(adj), str(w), '\n']))

#     while len(unpair) > 1:
#         print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n']))

#     if unpair:
#         return unpair.pop()
#     return 0

if __name__ == "__main__":
    graph = get_input()
    dfs(graph)


//package abbyycup2013;
import java.io.*;

public class ProblemD12 {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    ProblemD12() throws IOException {
//        reader = new BufferedReader(new FileReader("input.txt"));
//        writer = new PrintWriter(new FileWriter("output.txt"));
    }

    int[] readInts() throws IOException {
        String[] strings = reader.readLine().split(" ");
        int[] ints = new int[strings.length];
        for(int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(strings[i]);
        }
        return ints;
    }

    int[] tt = null;
    int tx = 0;
    int readInt() throws IOException {
        if(tt == null || tx >= tt.length) {
            tt = readInts();
            tx = 0;
        }
        return tt[tx++];
    }

    int mod = 1000 * 1000 * 1000 + 7;
    int sum(int x, int y) {
        x += y;
        return x >= mod ? x - mod : x;
    }

    int mult(int x, int y) {
        return (int)((long)x * y % mod);
    }

    int pow(int x, int k) {
        int ret = 1;
        while(k > 0) {
            if(k % 2 == 1) {
                ret = mult(ret, x);
            }
            x = mult(x, x);
            k /= 2;
        }
        return ret;
    }

    int inv(int x) {
        return pow(x, mod - 2);
    }

    void solve() throws IOException {
        int n = readInt();
        int[] a = readInts();
        n = 0;
        int m = 0;
        for(int x : a) if(x == 1) n++; else m++;
        int[][] dp = new int[n + 1][m + 1];
        dp[0][0] = 1;
        int[] f = new int[n + m + 1];
        f[0] = 1;
        for(int i = 1; i < f.length; i++) {
            f[i] = mult(f[i - 1], i);
        }
        int[] invs = new int[n + m + 1];
        for(int i = 0; i < invs.length; i++) {
            invs[i] = inv(f[i]);
        }
        int[][] C = new int[501][501];
        for(int N = 0; N <= 500; N++) {
            C[N][0] = 1;
            for(int K = 1; K <= N; K++) {
                C[N][K] = sum(C[N - 1][K - 1], C[N - 1][K]);
            }
        }
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= m; j++) {
                if(i + j == 0) continue;
                if(i == 0) {
                    for(int k = 0; k <= j - 1; k++) {
                        int A = mult(f[j - 1], invs[j - 1 - k]);
                        dp[i][j] = sum(dp[i][j], mult(dp[i][j - 1 - k], A));
                    }
                }
                else {
                    for(int k = 0; k <= j; k++) {
                        int A = mult(f[j], invs[j - k]);
                        dp[i][j] = sum(dp[i][j], mult(dp[i - 1][j - k], A));
                        if(i >= 2) {
                            //dp[i][j] = sum(dp[i][j], mult(mult(dp[i - 2][j - k], i - 1), A));
                            //int C = mult(f[j], inv(mult(f[k], f[j - k])));
                            dp[i][j] = sum(dp[i][j], mult(mult(dp[i - 2][j - k], i - 1), mult(C[j][k], f[k + 1])));
                        }
                    }
                }
            }
        }
        writer.println(dp[n][m]);
        writer.flush();
    }

    void multiSolve() throws IOException {
        int n = readInts()[0];
        for(int i = 0; i < n; i++) {
            solve();
        }
        writer.flush();
    }

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


n=int(input())

l=list(map(int,input().split()))

ans=0
repeat={}
for i in l:
    if i in repeat:
        repeat[i]+=1
        if i==0:
            pass
        elif repeat[i]>2:
            ans=-1
            break
        else:
            ans+=1
    else:
        repeat[i]=1
print(ans)

import java.util.*;
import java.io.*;
public class Contests {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(input.readLine());
        int count = 0;
        ArrayList<Integer> list = new ArrayList<Integer>();
        String[] se = input.readLine().split(" ");
        for( int i = 0; i < n; i++ )
        {
            if( Integer.parseInt(se[i]) == 0 ){continue;

            }
            else if( list.contains( Integer.parseInt(se[i]) )  )
            {
                count++;
            }
            else if(!list.contains(Integer.parseInt(se[i])))
            {
                list.add(Integer.parseInt(se[i]));
            }
        }
        int ax;
        for( int i = 0; i < n; i++ )
        {
            ax = 0;
            for( int j = 0; j <se.length; j++ )
            {
                if( i != j)
                {

                    if( se[i].equals(se[j]) && !se[i].equals("0"))
                        ax++;
                }
            }
            if( ax > 1 )
            {
                System.out.println("-1");
                return;
            }
        }
        System.out.println(count);

    }
}


#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
vector<int> digitos(long long n, int dig) {
  vector<int> res;
  while (n > 0) {
    res.push_back(n % 2);
    n /= 2;
  }
  while (res.size() < dig) res.push_back(0);
  reverse(res.begin(), res.end());
  return res;
}
int main() {
  int n;
  while (cin >> n) {
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];
    int actualAnd[21];
    memset(actualAnd, 0, sizeof(actualAnd));
    set<int> res;
    for (int i = 0; i < n; i++) {
      vector<int> dig = digitos(a[i], 21);
      for (int j = 0; j < 21; j++) {
        if (dig[j] == 0) {
          actualAnd[j] |= a[i];
          res.insert(actualAnd[j]);
        } else {
          actualAnd[j] = 0;
        }
      }
    }
    cout << res.size() << endl;
  }
  return 0;
}

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

public class P243A {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		Task solver = new Task();
		solver.solve(in, out);
		out.close();
	}

	static class Task {
		public void solve(InputReader in, PrintWriter out) {
			int n = in.nextInt();
			Set<Integer> set = new HashSet<>();
			int[] a = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = in.nextInt();
			}
			Set<Integer> set2 = new HashSet<>();
			for (int i = 0; i < n; i++) {
				Set<Integer> set3 = new HashSet<>();
				for (int x : set2) {
					set3.add(x | a[i]);
				}
				set3.add(a[i]);
				set.addAll(set3);
				set2 = set3;
			}
			out.println(set.size());
		}

	}

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

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

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

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

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

		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

	}
}


import java.io.*;
    import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

     public class Main {
    	public static InputReader in;
        public static PrintWriter pw;

    	public static void main(String args[]) {
    		new Thread(null, new Runnable() {
                public void run() {
                    try{
                        solve();
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }, "1", 1 << 26).start();
        }
    	static ArrayList<Integer> g[];
    	static ArrayList<Integer> h[];
    	static boolean visited[];
    	static int[] parent;
    	static int par[];
    	static int degree[];
    	static int edjes=0;
    	static int start=-1;
    	static int end=-1;
    	static int Total=0;
    	static int time1[];
    	static int time2[];
    	static int glob=0;
    	static long ans[]=new long[1000000];
    	static boolean vis2[][];
    	//static long sum1=0;
    	//static long val[];
        static ArrayList<Integer> levels[];
        static int max=0;
        static int lev=1;
        static ArrayList<Integer> nodes[];
        static ArrayList<Integer> values[];
        static int depth[];
        static boolean found=false;
       // static long sm[];
        static int sum1=0;
        static int pre[][];
        static int subtree[];
       static  int cnt=0;
       static  HashMap<String,Integer> hm;
       static int sm[];
       static int size[];
       static long mul[];
       static long d[]=new long[1000000];
       static int tot=0;
       static long highest=(long)1e9;
       static boolean bit=false;
        static Stack<Integer> tt=new Stack();
       static HashSet<String> set=new HashSet<String>();
 	   static long fact[],num[];
 	   static long MOD=1000000007;
 	   static int value[];static int premen[];
 	   static int count=0,index=0;
 	   static double ans11[];
 	   static int price[];
 	   static ArrayList<String> hp[][];
 	   static boolean visit[][];
 	   static int cnu[]=new int[1000001];
 	   static int label=1;
 	   static int his[][];
 	   static int size1=0;
 	   static int up[],down[];
 	   static int TotalUp=0;
 	 public static void solve() throws FileNotFoundException{

    		 in = new InputReader(System.in);
    		 pw = new PrintWriter(System.out);
    		 int n=in.nextInt();
    	     g=new ArrayList[n+1];
    	     for(int i=1;i<=n;i++)g[i]=new ArrayList<Integer>();
    	     h=new ArrayList[n+1];
    	     for(int i=1;i<=n;i++)h[i]=new ArrayList<Integer>();
    	     for(int i=1;i<n;i++)
    	     {
    	    	 int x=in.nextInt();
    	    	 int y=in.nextInt();
    	    	 g[x].add(y);g[y].add(x);
    	    	 h[x].add(y);
    	     }
    	     up=new int[n+1];
    	     down=new int[n+1];
    	     depth=new int[n+1];
    	     depth[1]=0;
    	     visited=new boolean[n+1];
    	     dfs1(1,0);
    	     int ans=Integer.MAX_VALUE;
    	     for(int i=1;i<=n;i++)
    	     {
    	            ans = Math.min(ans, TotalUp + depth[i] - 2*up[i]);
    	            //System.out.println(up[i]);
             }
    	     System.out.println(ans);
    	     for(int i=1;i<=n;i++)
    	     {
    	    	 int x=(TotalUp + depth[i] - 2*up[i]);
    	    	 if(x==ans)
    	    	 {
    	    		 System.out.print(i+" ");
    	    	 }
    	     }
        }
 	  public static void dfs1(int curr,int parent)
 	  {
 		  visited[curr]=true;

 		  for(int x:g[curr])
 		  {

 			  if(x==parent)continue;
 			  depth[x]=depth[curr]+1;
 			  up[x]=up[curr];
 			  if(h[x].contains(curr)){
 				  up[x]++;
 				  TotalUp++;
 			  }
 			  dfs1(x,curr);
 		  }
 	  }

        public static void dfs(int curr,int Parent)
        {
        	visited[curr]=true;
        	size[curr]=1;
        	parent[curr]=Parent;
        	count++;
        	if(value[curr]>0)
        	{
        		index=value[curr];
        	}
        	for(int x:g[curr])
        	{
        		if(!visited[x])
        		{
        			dfs(x,curr);
        			size[curr]+=size[x];
        		}
        	}
        }
        static long ncr(long a, long b){
			if(b>a || b<0) return 0;
			long f = (fact[(int) a]*modInverse(((fact[(int) b]*fact[(int) (a-b)])%MOD), MOD))%MOD;
			return f;
		}
		static long modInverse(long a, long mOD2){
            return  power(a, mOD2-2, mOD2);
}
static long power(long x, long y, long m)
{
    if (y == 0)
        return 1;
    long p = power(x, y/2, m) % m;
    p = (p * p) % m;

    return (y%2 == 0)? p : (x * p) % m;
}

        public static long gcd(long x, long y) {
    		if (x == 0)
    			return y;
    		else
    			return gcd( y % x,x);
    	}
        public static long power(long a,long b)
		{
			long result=1;
			while(b>0)
			{
				if(b%2==1)
					result*=a;
				a=a*a;
				b/=2;
			}
			return result;
		}
        static class Pair implements Comparable<Pair>{
        	//int index;
        		int beauty;
        		int cost;
        		//int index;
        		Pair(int index,int value){
        	     	this.beauty=index;
        			this.cost=value;

        		}
        		@Override
        		public int compareTo(Pair o) {
                      return cost-o.cost;
        		}

        	}
    	static class InputReader {

    		private InputStream stream;
    		private byte[] buf = new byte[8192];
    		private int curChar, snumChars;
    		private SpaceCharFilter filter;

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

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

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

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

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

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

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

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

#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > vec[300005];
long long d[300005], r[300005], cost[300005];
long long val = 300005, temp;
long long rev;
void dfs(int node, int parent, int dist, int inv) {
  d[node] = dist;
  r[node] = inv;
  for (int i = 0; i < vec[node].size(); i++) {
    pair<long long, long long> p = vec[node][i];
    long long u = p.first;
    if (u == parent) continue;
    dfs(u, node, dist + 1, inv + p.second);
    rev += p.second;
  }
}
int main() {
  long long n;
  cin >> n;
  for (int i = 0; i < n - 1; i++) {
    int x, y;
    cin >> x >> y;
    vec[x].push_back(make_pair(y, 0));
    vec[y].push_back(make_pair(x, 1));
  }
  dfs(1, 0, 0, 0);
  for (int i = 1; i <= n; i++) {
    cost[i] = rev - r[i] + (d[i] - r[i]);
    if (cost[i] < val) val = cost[i];
  }
  cout << val << endl;
  for (int i = 1; i <= n; i++)
    if (cost[i] == val) cout << i << " ";
  return 0;
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class d123 {

    public static void debug(Object... obs)
    {
        System.out.println(Arrays.deepToString(obs));
    }

    static long gcd(long a,long b)
    {
        return (b==0)?a:gcd(b,a%b);
    }

    public static void main(String[] args) throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());

        Set<P> pts = new TreeSet<P>();

        for(int i=0;i<n;i++)
        {
            StringTokenizer st=new StringTokenizer(br.readLine());
            long ki = Long.parseLong(st.nextToken());
            long bi = Long.parseLong(st.nextToken());

            if(ki == 0) continue;

            long ak = Math.abs(ki);
            long ab = Math.abs(bi);

            long gd = gcd(ak,ab);

            ki = ki/gd;
            bi = bi/gd;

            P pair = new P(ki,bi);
            pts.add(pair);
        }

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

    private static class P implements Comparable<P>
    {
        long k, b;
        int sgn;

        public P(long k, long b)
        {
            super();
            if(b < 0 && k < 0)
                sgn = 1;
            else if(b > 0 && k > 0)
                sgn = 1;
            else if(b == 0)
                sgn = 1;
            else
                sgn = 2;

            this.k = Math.abs(k);
            this.b = Math.abs(b);
        }

        @Override
        public int compareTo(P arg0)
        {
            if(b == 0 && arg0.b ==0)
                return 0;

            if(k - arg0.k != 0)
                return sgn(k - arg0.k);

            if(b - arg0.b != 0)
                return sgn(b - arg0.b);

            return sgn - arg0.sgn;
        }

        private int sgn(long l)
        {
            if(l < 0) return -1;
            if (l > 0) return 1;
            return 0;
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
int n;
double k, b;
set<long double> a;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lf%lf", &k, &b);
    if (k != 0) a.insert(b / k);
  }
  printf("%d\n", a.size());
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
struct st {
  int x;
  int c;
};
int pr(st a, st b) { return a.c < b.c; }
st a[1005];
long long b[1005];
int i, j, k, n, m, x, y;
long long res, t, z;
int main() {
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a[i].x >> a[i].c;
  }
  sort(a, a + n, pr);
  cin >> m;
  for (i = 0; i < m; i++) {
    cin >> b[i];
  }
  for (i = m - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  j = 0;
  i = 0;
  b[m] = 1000000000;
  b[m] *= b[m];
  while (i < n) {
    if (a[i].x == 0) {
      i++;
      continue;
    }
    if (b[j] == 0) {
      j++;
      continue;
    }
    t = min((long long)a[i].x, b[j]);
    res += t * (j + 1) * a[i].c;
    a[i].x -= t;
    b[j] -= t;
  }
  cout << res << endl;
  return 0;
}

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

public class C {
    public static void main(String[] args) throws Exception {
        FastScannerC fs = new FastScannerC();
        PrintWriter out = new PrintWriter(System.out);

        int n = fs.nextInt();
        Type[] a = new Type[n];
        for(int i = 0; i < n; i++) {
            a[i] = new Type(fs.nextInt(), fs.nextInt());
        }
        Arrays.sort(a);
        int t = fs.nextInt();
        long[] p = new long[t];
        for(int i = 0; i < t; i++)
            p[i] = fs.nextLong();
        int atP = 0;
        int atT = 0;
        long res = 0;
        long factor = 1;
        long dest = 0;
        while(atT < a.length) {
            if(atP == p.length) {
                long gets = a[atT].has;
                res += gets * a[atT].price * factor;
                a[atT].has = 0;
            } else {
                long need = p[atP] - dest;
                long gets = Math.min(need, a[atT].has);
                res += gets * a[atT].price * factor;
                dest += gets;
                a[atT].has -= gets;
                if (dest >= p[atP] && atP != p.length) {
                    atP++;
                    factor++;
                }
            }
            if(a[atT].has == 0) atT++;
        }
//        System.out.printf("%d\n", factor);

        out.println(res);
        out.close();
    }

    static class Type implements Comparable<Type> {
        long has;
        long price;

        public Type(int h, int p) {
            has = h;
            price = p;
        }

        public int compareTo(Type o) {
            if(price == o.price) {
                if(has < o.has) return -1;
                else if(has > o.has) return 1;
                return 0;
            }
            if(price < o.price) return -1;
            if(price > o.price) return 1;
            return 0;
        }
    }

}

class FastScannerC {
    BufferedReader br;
    StringTokenizer st;

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

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

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

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

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

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

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

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

    public char[] nextCharArray() {
        return nextLine().toCharArray();
    }
}