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

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        AC solver = new AC();
        solver.solve(in, out);
        out.close();
    }
}
class AC {
    final int maxn = 1000010;
    int low[] = new int[maxn];
    int high[] = new int[maxn];
    int a[] = new int[maxn];
    int sum[]  = new int[maxn];
    public void solve(InputReader in, PrintWriter out) {
        String s,t;
        s = in.next();
        t = in.next();
        int pt = 0;
        for(int i = 0; i < s.length(); i++) {
            low[i] = pt;
            if(pt < t.length() && s.charAt(i) == t.charAt(pt)) pt++;
        }
        pt = 0;
        Arrays.fill(high, t.length());
        for(int i = 0; i < t.length(); i++) {
            if(pt > 0) high[pt-1] = Math.min(high[pt-1], i);
            if(pt < s.length() && s.charAt(pt) == t.charAt(i)) pt++;
        }
        long ans = 0;
        //for(int i = 0; i < s.length(); i++) out.print(low[i] + " "); out.println();
        //for(int i = 0; i < s.length(); i++) out.print(high[i] + " "); out.println();
        for(int i = 0; i < s.length(); i++) ans += high[i] - low[i];
        //out.println(ans);
        String rgb = "RGB";
        for(int j = 0; j < 3; j++) for(int k = 0; k < 3; k++) if(j!=k){
            char c1 = rgb.charAt(j) , c2 = rgb.charAt(k);
            sum[0] = 0;
            for(int i = 1; i < t.length(); i++) if(t.charAt(i) == c1 && t.charAt(i-1) == c2) sum[i+1] = sum[i] + 1;
            else sum[i+1] = sum[i];
            for(int i = 1; i < s.length(); i++) if(s.charAt(i) == c2 && s.charAt(i-1) == c1) ans -= sum[high[i]] - sum[low[i]];
        }
        out.println(ans);
    }
}
class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        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 double nextDouble() {
        return Double.parseDouble(next());
    }
    public long nextLong() {
        return Long.parseLong(next());
    }
}
class ArrayUtils {
    public static void fill(long[][] array, long value) {
        for (long[] row : array)
            Arrays.fill(row, value);
    }
    public static void fill(long[][][] array, long value) {
        for (long[][] row : array)
            fill(row, value);
    }
    public static void fill(long[][][][] array, long value) {
        for (long[][][] row : array)
            fill(row, value);
    }
}


s = input()
k = []
for i in range(len(s)):
    for j in range(i+1,len(s)+2):
        x = s[i:j]
        for t in range(i+1,len(s)):
            if x == s[t:t+j-i]:
                k += [j-i]
print(max(k) if k != [] else 0)

import java.util.Scanner;

public class GiveString23A {
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String stroke = in.next();
        char[] s = new char [stroke.length()];
        for (int i=0;i<stroke.length();i++)
            s[i]=stroke.charAt(i);
        int dlina = 0;
        for (int i=0;i<s.length-1;i++)
            for (int j=i+1;j<s.length;j++)
                for (int k=0;k<(s.length-j);k++)
                    if (s[i]==s[j])
                    {
                        int ik=i+k;
                        int jk = j+k;
                        if (s[ik]==s[jk])
                        {
                            if (dlina<k+1)
                                dlina=k+1;
                        }
                        else
                        break;
                    }
        System.out.println(dlina);
    }
}


#!/usr/bin/python3

def readln(): return tuple(map(int, input().split()))

abc = sorted(readln())
print((abc[1] + abc[0] - 1) * (abc[2] + abc[0] - 1) - (abc[0] - 1) * abc[0])

import java.util.Scanner;

public class ProblemA {

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int n = Math.min(b, c);
        int sum = (2*a+n-1)*n;
        int rest = b+c-1-2*n;
        System.out.println(sum+rest*(a+n-1));
    }

}


import java.io.*;
import java.util.*;
public class Main{
    static long atol(String n){return Long.parseLong(n);}
    public static void main(String jfkd[])throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        HashSet<Long> t = new HashSet<Long>();
        long a=0,b=1, max = 1000000000;
        while(a<=max){
            a+=b++;
            t.add(a);
        }
        long n = atol(br.readLine());
        boolean hay =false;
        for(long c:t)
            if(t.contains(n-c)){
                hay = true;
                break;
            }
        if(hay)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

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

n = int( input() )

def f( n ):
    return ( n*( n+1 )//2 )

memo = {}
i=1
limit = 10**9
while True:
    tmp = f(i)
    if tmp > limit:
        break
    memo[tmp] = 1
    i += 1

for i in memo:
    if i > n:
        break
    if n-i in memo:
        print( "YES" )
        exit(0)

print( "NO" )


#include <bits/stdc++.h>
using namespace std;
int main() {
  char s[100007];
  scanf("%s", &s);
  int l = strlen(s), one = 0, zero = 0, x = 0;
  for (int i = 0; i < l; i++)
    if (s[i] == '0')
      zero++;
    else if (s[i] == '1')
      one++;
    else
      x++;
  int n = l;
  if (l & 1) zero++, n = l + 1;
  if (zero + x > one) printf("00\n");
  if (min(one, zero) + x >= n / 2) {
    if (s[l - 1] == '1' || s[l - 1] == '?' && zero + x - 1 >= n / 2)
      printf("01\n");
    if (s[l - 1] == '0' || s[l - 1] == '?' && one + x - 1 >= n / 2)
      printf("10\n");
  }
  if (one + x > zero) printf("11\n");
  return 0;
}

import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class C {

    public C() throws Exception {
        String s = in.next();
        int n = s.length();
        int zero = 0;
        int one = 0;
        int qm = 0;
        for (int i=0;i<n;i++) {
            char c = s.charAt(i);
            if (c=='0') zero++;
            else if (c=='1') one++;
            else qm++;
        }

        one -= ((n>>1)-1) + (n&1);
        zero -= ((n>>1)-1);

        if (zero+qm>=one+2)
            System.out.println("00");

        if (abs(zero-one)<=qm) {
            if (s.charAt(n-1)=='1'||s.charAt(n-1)=='?'&&one!=zero+qm)
                System.out.println("01");
            if (s.charAt(n-1)=='0'||s.charAt(n-1)=='?'&&zero!=one+qm)
                System.out.println("10");
        }

        if (one+qm>=zero+2)
            System.out.println("11");

    }

    Scanner in = new Scanner(System.in);
    StringBuilder buf = new StringBuilder();
    public static void main(String[] args) throws Exception { // {{{
        new C();
    } // }}}
    public static void debug(Object... arr) { // {{{
        System.err.println(Arrays.deepToString(arr));
    } // }}}
}


#include <bits/stdc++.h>
long long int i, j;
using namespace std;
int main() {
  int a, b, c, n, n1, n2, n3, x;
  cin >> a >> b >> c >> n;
  n1 = a - c;
  n2 = b - c;
  n3 = c;
  x = n - n1 - n2 - n3;
  if (n1 >= 0 && n2 >= 0 && n3 >= 0 && x > 0) {
    cout << x << endl;
  } else
    cout << -1;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int r = 0;
  string s;
  cin >> s;
  for (int i = 0; i < s.length(); i++) {
    if (s[i] == 'Q') {
      for (int j = i + 1; j < s.length(); j++) {
        if (s[j] == 'A') {
          for (int k = j + 1; k < s.length(); k++)
            if (s[k] == 'Q') r++;
        }
      }
    }
  }
  cout << r;
}

import java.util.Scanner;

public class Temp1
{
	public static void main(String[] args)
	{
		Scanner obj = new Scanner(System.in);
		String s = obj.nextLine();
		int n = s.length();

		boolean visited[] = new boolean[n];
		int counter = 0;

		for(int i=0 ; i<n-2 ; i++)
		{
			if(s.charAt(i) == 'Q')
			{
				for(int j = i+1 ; j<n ; j++)
				{
					if(s.charAt(j) == 'A')
					{
						for(int k=j+1 ; k<n ; k++)
						{
							if(s.charAt(k)=='Q')
							{
								counter++;
							}
						}
					}
				}
			}
		}

		System.out.println(counter);
	}
}


#include <bits/stdc++.h>
using namespace std;
long long qq(long long x, long long y) {
  long long a1 = y * (y + 1) / 2;
  a1 = a1 * (x + 1);
  long long a2 = (y + 1) * (x + 1) * x / 2;
  return a1 + a2;
}
int main() {
  long long a, b;
  scanf("%lld%lld", &a, &b);
  long long ans = 0;
  for (long long i = 0; i <= b * a; i++) {
    long long ans1 = qq(i, -(i / a) + b - (i % a == 0 ? 0 : 1));
    ans = (ans > ans1) ? ans : ans1;
  }
  printf("%lld\n", ans);
  return 0;
}

m,b=map(int,input().split())
f=lambda n: n*(n+1)//2
def g(y):
    x=m*(b-y)
    return f(x)*(y+1)+f(y)*(x+1)
print(max(g(y) for y in range(b+1)))


import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String s= sc.next();
        int start=0;
        int moves=0;
        for (int i = 0; i < s.length(); i++) {
            int index= s.charAt(i)-97;
            int walk= Math.abs(index-start);
            if(walk<13) {
                moves+=walk;
            }
            else {
                moves+=26-walk;
            }
            start=index;
        }
        System.out.println(moves);
    }
}

import sys
from math import ceil,log

RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('Yes')
def NO(): print('No')
INF = 10 ** 18
MOD = 10 ** 9 + 7

s = ri()
s = 'a'+s
cnt = 0
for i in range(1,len(s)):
    cnt+=(min(abs(ord(s[i])-ord(s[i-1])), 26-abs(ord(s[i])-ord(s[i-1]))  ))

print(cnt)


import sys
from collections import Counter
from math import factorial

input = sys.stdin
output = sys.stdout

# input = open('input.txt')

def read_int():
    return [int(x) for x in input.readline().rstrip().split()]

line = input.readline().rstrip()
x = ord(line[0]) - ord('a')
y = ord(line[1]) - ord('1')
answer = 0
for _x in range(x - 1, x + 2):
    for _y in range(y - 1, y + 2):
        if _x != x or _y != y:
            if 0 <= _x < 8 and 0 <= _y < 8:
                answer += 1

output.write('%d\n' % answer)

g5 (right and up and down)

Hence, in the example, the king has 8 possible moves.

Right and down

These eight moves apply to any position on the chessboard where the king is located.


#include <bits/stdc++.h>
using namespace std;
const int N = 111111;
int n;
char str[N];
void dfs(int Now, int n) {
  if (Now >= n) return;
  printf("%c", str[Now]);
  dfs(Now + 1, n);
  printf("%c", str[Now]);
}
int main() {
  int ii;
  scanf("%s", str);
  dfs(0, strlen(str));
  return 0;
}

import java.util.Scanner;

public class ugh {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String in = sc.nextLine();
		StringBuilder s = new StringBuilder(in);
		System.out.println(s.toString()+s.reverse().toString());
	}

}


#include <bits/stdc++.h>
using namespace std;
int n, i, ans, a[500100];
int main() {
  cin >> n;
  for (i = 1; i <= n; i++) cin >> a[i];
  sort(a + 1, a + n + 1);
  ans = 1000000000;
  for (i = 1; i + n / 2 <= n; i++) ans = min(ans, a[i + n / 2] - a[i]);
  cout << ans;
  return 0;
}

n = int(input())
x = sorted(list(map(int, input().split())))
print(min([x[i + n // 2] - x[i] for i in range(n // 2)]))


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

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

class TaskC {

    void solve(InputReader in, OutputWriter out) {
        long a = in.nextLong();
        long b = in.nextLong();
        long c = in.nextLong();
        long l = in.nextLong();

        long all = (l+1)*(l+2)*(l+3) / 6;

        all -= bad(a,b,c,l);
        all -= bad(b,c,a,l);
        all -= bad(c,a,b,l);

        out.printLine(all);
    }

    private long bad(long a, long b, long c, long l) {
        long val = 0;
        for(int i=0;i<=l;i++) {
            long fixedSide = a + i;
            long rest = l - i;
            long twoSides = b + c;
            if(fixedSide < twoSides) continue;
            long diff = fixedSide - twoSides;
            rest = Math.min(rest, diff);
            val += ((rest+1) * (rest+2) / 2);
        }
        return val;
    }

}
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 boolean hasNext() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                String line = reader.readLine();
                if ( line == null ) {
                    return false;
                }
                tokenizer = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
    public int nextInt() {
        return Integer.parseInt(next());
    }
    public long nextLong() {
        return Long.parseLong(next());
    }
    public double nextDouble() { return Double.parseDouble(next());}
}
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;
long long ans = 0;
const int mod = 1e9 + 7;
long long rec(int a, int b, int c, int s) {
  if (a < b + c) return (long long)0;
  long long cur = min(s, a - b - c);
  return (cur + 1) * (cur + 2) / 2;
}
int main() {
  long long a[6], l;
  cin >> a[0] >> a[1] >> a[2] >> l;
  for (long long i = 0; i <= l; i++) {
    ans += (l - i + 1) * (l - i + 2) / 2;
  }
  for (long long j = 0; j <= l; j++) {
    ans -= rec(a[0] + j, a[1], a[2], l - j);
    ans -= rec(a[1] + j, a[0], a[2], l - j);
    ans -= rec(a[2] + j, a[0], a[1], l - j);
  }
  cout << ans;
  return 0;
}


import java.util.*;
public class Main{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int k=sc.nextInt();
        int n=sc.nextInt();
        int w=sc.nextInt();
        int sum=0;
        for(int i=1;i<=w;i++)
        {
            sum+=i*k;
        }
        if(sum<=n)
        System.out.println("0");
        else
        System.out.println(sum-n);
    }
}

price = 0
iter = 1
k,n,w = list(map(int,input().split()))
for i in range (w):
    price += k*iter
    iter += 1

if price <= n:
    print(0)
else:
    output = price - n
    print(output)


a, b = map(int, input().split())

if a == b:
  print ('infinity')
elif b > a:
  print (0)
else:
  a -= b
  i = 1
  cont = 0

  while (i*i) <= a:
    if (a % i) == 0:
      if i > b:
        cont += 1
      if (a/i) > b and (i*i) != a:
        cont += 1
    i += 1
  print (cont)

#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
const int MOD = 1e9 + 7;
const int N = 100100;
int a, b;
int main() {
  cin >> a >> b;
  if (a == b) {
    cout << "infinity";
    return 0;
  }
  if (a < b) {
    cout << 0;
    return 0;
  }
  int x = a - b;
  int k = 0;
  for (int i = 1; i * i <= x; i++)
    if (x % i == 0) {
      if (a % i == b) k++;
      if (i != x / i && a % (x / i) == b) k++;
    }
  cout << k;
  return 0;
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Solution{

	public static void main(String args[]) throws Exception {
		FastScanner sc = new FastScanner();
		int[] sticks_lengths = new int[6];
		Map<Integer,Integer> sticks = new HashMap<Integer,Integer>();
		for(int i=0;i<6;i++){
			int lenth = sc.nextInt();
			sticks_lengths[i] = lenth;
			if(!sticks.containsKey(lenth))
				sticks.put(lenth,1);
			else
				sticks.put(lenth, sticks.get(lenth)+1);
		}
		int legs = areLegsEqual(sticks_lengths,sticks);
		if(legs==-1){
			System.out.println("Alien");
		}
		else{
			if(sticks.get(legs)==4)
				sticks.remove(legs);
			else
				sticks.put(legs, sticks.get(legs)-4);
			if(sticks.size()<=1)
				System.out.println("Elephant");
			else
				System.out.println("Bear");
		}

	}

	public static int areLegsEqual(int[] sticks,Map<Integer,Integer> map){
		for(int i=0;i<6;i++){
			if(map.get(sticks[i])>=4)
				return sticks[i];
		}
		return -1;
	}

	public static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(String s) {
			try {
				br = new BufferedReader(new FileReader(s));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

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

		String nextToken() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

}

Alien Bear Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Elephant Alien Alien Alien Alien Elephant Alien Alien Elephant Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Bear Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien Alien

#include <bits/stdc++.h>
using namespace std;
int main() {
  int arr[9] = {0};
  for (int i = 0; i < 6; i++) {
    int help;
    cin >> help;
    arr[--help]++;
  }
  bool flag = false;
  int help = 0;
  for (int i = 0; i < 9; i++) {
    if (arr[i] >= 4) {
      flag = true;
      arr[i] -= 4;
    }
  }
  if (flag) {
    for (int i = 0; i < 9; i++)
      if (arr[i] == 2) {
        cout << "Elephant";
        return 0;
      }
    cout << "Bear";
  } else
    cout << "Alien";
  return 0;
}


string_input = input().split(" ")
n, m = int(string_input[0]), int(string_input[1])
matrix = []
row = n
for i in range(0, n):
    matrix.append(input())
while True:
    if n % 2 == 1:
        break
    else:
        row_flag = 1
        n = n//2
        for i in range(0, n):
            if matrix[i] != matrix[2*n-1-i]:
                row_flag = 0
                break
        if row_flag:
            row = n
        else:
            break
print(row)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, a[105][105];
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> a[i][j];
  if (n % 2 != 0)
    cout << n << endl;
  else {
    int i, j, k, l;
    while (n % 2 == 0) {
      i = 1;
      k = n;
      for (; i <= n / 2; i++, k--) {
        for (j = 1, l = 1; j <= m; j++, l++) {
          if (a[i][j] != a[k][l]) {
            cout << n << endl;
            return 0;
          }
        }
      }
      n /= 2;
    }
    cout << n << endl;
  }
  return 0;
}


a,b,c=map(int,input().split())
M=1073741824
n=a*b*c
d=[1]*(n+1)
for i in range(2,n+1):
	for j in range(i,n+1,i):
	    d[j]+=1
r=0
for i in range(1,a+1):
	for j in range(1,b+1):
		for k in range(1,c+1):
			r+=(d[i*j*k])%M
print(r%M)

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

public class Cf {
	public static void main(String[] args) throws IOException {
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		int c = sc.nextInt();
		int t[] = new int[1000001];
		for(int i=1;i<=1000000;i++)
			for(int j=i;j<=1000000;j=j+i)
				t[j]++;
		long sum = 0;
		long mod = 1073741824;
		for(int i=1;i<=a;i++){
			for(int j=1;j<=b;j++){
				for(int k =1;k<=c;k++){
					int num = i*j*k;
					sum=sum+t[num];
					sum=sum%mod;
				}
			}
		}
		System.out.println(sum);
		// end of main
	}
}


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

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

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            String S = in.next();
            int n = S.length();

            int[] order = new int[26];
            int[] pos = new int[26];

            for (int i = 0; i < 26; ++i) {
                order[i] = i;
                pos[i] = 0;
            }

            int[] all = new int[26 * n];
            int cnt = 0;

            int tconf = 0;
            for (int i = 1; i <= n + 1; ++i) {
                int x = i <= n ? S.charAt(i - 1) - 'a' : 26;
                int conf = 0;
                for (int j = 0; j < 26; ++j) {
                    all[cnt++] = conf;
                    conf |= 1 << order[j];
                    if (order[j] == x || pos[order[j]] == 0) break;
                }
                if (x < 26) {
                    tconf |= 1 << x;
                    int p = 0;
                    while (order[p] != x) ++p;
                    while (p > 0) {
                        order[p] = order[p - 1];
                        --p;
                    }
                    order[0] = x;
                    pos[x] = i;
                }
            }
            Arrays.sort(all, 0, cnt);

            int q = in.nextInt();
            while (q-- > 0) {
                String P = in.next();
                int conf = 0;
                for (int i = 0; i < P.length(); ++i) {
                    conf |= 1 << P.charAt(i) - 'a';
                }
                int p1 = -1, p2 = -1, step;
                for (step = 1; step < cnt; step *= 2) ;
                for (; step > 0; step /= 2) {
                    if (p1 + step < cnt && all[p1 + step] < conf)
                        p1 += step;
                    if (p2 + step < cnt && all[p2 + step] <= conf)
                        p2 += step;
                }

                out.println(conf == tconf ? 1 : p2 - p1);
            }
        }

    }

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

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

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

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

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

            return res.toString();
        }

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

    }
}

ygkpypcmqcdyobghazieayxxaoiukrmqrbjepkhswwqhrybvdwwysisnaxjqcuqbqdnmbimwsvgactidnhogjfpfbgsawmynbjgw
10
pf
swy
pcy
ws
awm
cyp
ydo
imw
rhy
wqh

qtxskctsxpdhlgqsoqfbltffjjbfjcvxnnekabynugjjpwtpcpsbywrgjwofhcdmdqhstzabziajnkekeymyankekeiaqboeugij
10
nxv
ltb
dhp
bza
kct
vcx
bzi
fqb
lhd
ke

gyxyugstnzijarvqqclfibtvvhxpwktahsqrvduwcdllfyjbumziassaoohwktgawqcphsmaknjtuqzulxwwblfjrdppeuwtvevcasxghdzibsbxhtezkahmwkdlklojnslewwbutyqfqmawumrfhjjdnqjlkrxswgymnyrulgkvmiebgtejhiuaylraxpwbmoihganwstpmdnqgxsrloztxkntpsoubyfqtssyayxcnewhcnzfakmudrfnjqzoajqwirrxddiqzsaqrhagttlcwjbxqbubzrxlvdjjvljbt
10
dj
ao
tmp
jbl
rdf
kwt
tkn
bs
fq
wpx

aaaaaaaaaabaaaaaabaabbbaacaabbbaaaabbbaabbbcccc
8
a
b
c
ab
bc
ab
bca
z

#include <bits/stdc++.h>
using namespace std;
short fst[1 << 26];
char S[1001000], s[30];
int n, len, a[30], p[30], cnt[10100], y[10100], nxt[10100];
bool cmp(int x, int y) { return a[x] > a[y]; }
void add(int t, int i) {
  y[i] = t;
  nxt[i] = fst[t];
  fst[t] = i;
}
int main() {
  scanf("%s%d", S, &n);
  len = strlen(S);
  for (int i = 0; i < n; i++) {
    scanf("%s", s);
    int t = 0, q = strlen(s);
    for (int j = 0; j < q; j++) t |= (1 << (s[j] - 'a'));
    add(t, i + 1);
  }
  S[len] = 'a' + 26;
  for (int i = 0; i < 27; i++) a[i] = -1;
  for (int i = 0; i < len; i++) {
    if (S[i] == S[i + 1]) continue;
    int q = S[i + 1] - 'a', t = 0;
    a[S[i] - 'a'] = i;
    for (int i = 0; i < 27; i++) p[i] = i;
    sort(p, p + 27, cmp);
    for (int j = 0; j < 27; j++) {
      cnt[fst[t]]++;
      if (p[j] == q || a[p[j]] < 0) break;
      t |= (1 << p[j]);
    }
  }
  for (int i = n; i; i--) cnt[nxt[i]] = cnt[i];
  for (int i = 1; i <= n; i++) printf("%d\n", cnt[i]);
}


w,h=map(int,input().split())
ans=0
for i in range(2,w+1,2):
    for j in range(2,h+1,2):
        ans+=(w+1-i)*(h+1-j)
print(ans)

#include <bits/stdc++.h>
using namespace std;
void FastInputOutput() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
}
inline int D() {
  int t;
  scanf("%d", &t);
  return t;
}
inline long long LLD() {
  long long t;
  scanf("%lld", &t);
  return t;
}
long long power(long long x, long long p, long long m) {
  long long res = 1;
  while (p) {
    if (p & 1) res = (res * x) % m;
    x = (x * x) % m;
    p >>= 1;
  }
  return res;
}
long double ModLog(long double base, long double x) {
  return (logl(x) / logl(base));
}
const int N = 2e6 + 5, MX = 1e9;
int mod(int a, int m) { return (((a % m) + m) % m); }
int main() {
  int n = D(), m = D();
  long long sum = 0;
  for (long long i = 1; i <= n / 2; ++i)
    for (long long j = 1; j <= m / 2; ++j)
      sum += (n - i * 2 + 1) * (m - j * 2 + 1);
  printf("%lld", sum);
  return 0;
}


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

public class D102 {

    static StringTokenizer st;
    static BufferedReader in;
    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int m = nextInt();
        if (n > m) {
            int t = n;
            n = m;
            m = t;
        }
        int ans = 0;
        if (n==1)
            ans = m;
        else if (n==2) {
            ans = 2*(m/2+m/2 % 2);
            if (m % 4==1)
                ans += 2;
        }
        else
            ans = (n*m+1) / 2;
        System.out.println(ans);
        pw.close();
    }
    private static int nextInt() throws IOException{
        return Integer.parseInt(next());
    }

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

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

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

n, m = map(int, input().split())

if n > m:

    n, m = m, n

if n > 2 and m > 2:

    print(((n * m) + 1) // 2)

elif n == 1:

    print(m)

else:

    print(2 * (((m // 4) * 2) + min(m % 4, 2)))

# Made By Mostafa_Khaled


//package round676;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

public class E {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int[] a = na(n);
		if(n == 1){
			out.println(a[0]);
			return;
		}
		// 3:1
		// 4:0,3
		// 5:2:5
		// 6:1,4
		long sp = 0;
		for(int i = 0;i < n;i++){
			sp += a[i] * (i % 2 == 0 ? 1 : -1);
		}

		long[] cum = new long[n+1];
		radixSort2(a);
		for(int i = 0;i < n;i++){
			cum[i+1] = cum[i] + a[i];
		}
		long ans = Long.MIN_VALUE;
		int u = (4 - n % 3) % 3;
		for(int i = u;i <= n;i+=3){
			long v = -cum[i] + (cum[n] - cum[i]);
			if(n/2 == i && v == sp) {
				v = -cum[i] + (cum[n] - cum[i]) + a[i] * -2 + a[i-1] * 2;
			}
			ans = Math.max(ans, v);
		}
		out.println(ans);
	}

	public static int[] radixSort2(int[] a)
	{
		int n = a.length;
		int[] c0 = new int[0x101];
		int[] c1 = new int[0x101];
		int[] c2 = new int[0x101];
		int[] c3 = new int[0x101];
		for(int v : a) {
			c0[(v&0xff)+1]++;
			c1[(v>>>8&0xff)+1]++;
			c2[(v>>>16&0xff)+1]++;
			c3[(v>>>24^0x80)+1]++;
		}
		for(int i = 0;i < 0xff;i++) {
			c0[i+1] += c0[i];
			c1[i+1] += c1[i];
			c2[i+1] += c2[i];
			c3[i+1] += c3[i];
		}
		int[] t = new int[n];
		for(int v : a)t[c0[v&0xff]++] = v;
		for(int v : t)a[c1[v>>>8&0xff]++] = v;
		for(int v : a)t[c2[v>>>16&0xff]++] = v;
		for(int v : t)a[c3[v>>>24^0x80]++] = v;
		return a;
	}

	void dfs(List<Deque<Integer>> a)
	{
		if(a.size() == 1){
//			t.add(a.get(0));
			int ptn = 0;
			char[] s = new char[a.get(0).size()];
			for(int v : a.get(0)){
				if(v < 0){
					s[-v-1] = '1';
				}else{
					s[v-1] = '0';
				}
			}
			return;
		}
		int n = a.size();
		for(int i = 0;i < a.size()-1;i++){
			List<Deque<Integer>> b = new ArrayList<>();
			for(int j = 0;j < i;j++){
				b.add(a.get(j));
			}
			Deque<Integer> y = new ArrayDeque<>();
			for(int u : a.get(i)){
				y.add(-u);
			}
			for(int u : a.get(i+1)){
				y.add(-u);
			}
			b.add(y);
			for(int j = i+2;j < n;j++){
				b.add(a.get(j));
			}
			dfs(b);
		}
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

n = int(input())
a = list(map(int,input().split()))
INF = 10 ** 20
DP = [-INF] * 12
DP[1] = a[0]
DP[5] = -a[0]
for elem in a[1:]:
    newDP = []
    newDP.append(DP[5] + elem)
    newDP.append(DP[3] + elem)
    newDP.append(DP[4] + elem)
    newDP.append(DP[1] - elem)
    newDP.append(DP[2] - elem)
    newDP.append(DP[0] - elem)
    newDP.append(max(DP[2] + elem, DP[8] + elem, DP[11] + elem))
    newDP.append(max(DP[0] + elem, DP[6] + elem, DP[9] + elem))
    newDP.append(max(DP[1] + elem, DP[7] + elem, DP[10] + elem))
    newDP.append(max(DP[4] - elem, DP[7] - elem, DP[10] - elem))
    newDP.append(max(DP[5] - elem, DP[8] - elem, DP[11] - elem))
    newDP.append(max(DP[3] - elem, DP[6] - elem, DP[9] - elem))
    DP = newDP
if n == 1:
    print(a[0])
else:
    print(max(DP[7],DP[10]))


n,x,y=map(int,input().split())
a=[(n//2),(n//2)+1]
print(['YES','NO'][x in a and y in a])

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class C85P2 {

    private static BufferedReader in;
    private static PrintWriter out;
    private static StringTokenizer input;

    public static void main(String[] args) throws IOException {
        //-------------------------------------------------------------------------
        //Initializing...
        new C85P2();
        //-------------------------------------------------------------------------
        //put your code here... :)
        int n2 = nextInt(),x = nextInt(),y=nextInt();
        int n = n2/2;
        if(x == n && y==n)
            writeln("NO");
        else if (x==n && y==n+1)
            writeln("NO");
        else if (x==n+1 && y==n )
            writeln("NO");
        else if (x==n+1 && y==n+1)
            writeln("NO");
        else writeln("YES");
        //-------------------------------------------------------------------------
        //closing up
        end();
        //--------------------------------------------------------------------------

    }
    public C85P2() throws IOException {
        //Input Output for Console to be used for trying the test samples of the problem
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        //-------------------------------------------------------------------------
        //Initalize Stringtokenizer input
        input = new StringTokenizer(in.readLine());
    }

    private static int nextInt() throws IOException {
        if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine());
        return Integer.parseInt(input.nextToken());
    }
    private static long nextLong() throws IOException {
        if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine());
        return Long.parseLong(input.nextToken());
    }
    private static double nextDouble() throws IOException {
        if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine());
        return Double.parseDouble(input.nextToken());
    }
    private static String nextString() throws IOException {
        if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine());
        return input.nextToken();
    }
    private static void write(String output){
        out.write(output);
        out.flush();
    }
    private static void writeln(String output){
        out.write(output+"\n");
        out.flush();
    }
    private static void end() throws IOException{
        in.close();
        out.close();
        System.exit(0);
    }

}


import java.util.*;

import java.io.*;
public class D {
  public static void main(String[] args)throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

    int  n= Integer.parseInt(br.readLine());

    long[] ls = new long[n];
    long[] rs = new long[n];
    for(int i=0;i<n;++i){
      StringTokenizer st = new StringTokenizer(br.readLine());
      ls[i] = Integer.parseInt(st.nextToken());
      rs[i] = Integer.parseInt(st.nextToken());
    }
    Arrays.sort(ls);
    Arrays.sort(rs);
    long tot=0;
    for(int i=0;i<n;++i){
      tot+=1+Math.max(ls[i], rs[i]);
    }
    bw.write(tot+"");
    bw.flush();
  }
}

#include <bits/stdc++.h>
using namespace std;
int r[100005], l[100005];
int n;
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d%d", &l[i], &r[i]);
  sort(l, l + n);
  sort(r, r + n);
  long long ans = 0;
  for (int i = n - 1; i >= 0; i--) {
    ans += max(l[i], r[i]);
  }
  cout << ans + n << endl;
  return 0;
}


#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
signed main() {
  long long int n, x;
  cin >> n >> x;
  vector<long long int> a(n);
  unordered_map<long long int, long long int> cnt;
  for (long long int i = 0; i < n; i++) {
    cin >> a[i];
    cnt[a[i]]++;
    if (cnt[a[i]] >= 2) {
      cout << 0 << "\n";
      return 0;
    }
  }
  unordered_map<long long int, long long int> pcnt;
  long long int ans = 1e15;
  for (long long int i = 0; i < n; i++) {
    long long int now = a[i], next = a[i] & x;
    pcnt[next]++;
    if (now != next && cnt.count(next)) ans = 1;
  }
  if (ans > 1e13) {
    for (auto i : pcnt) {
      if (i.second >= 2) ans = 2;
    }
  }
  if (ans > 1e13)
    cout << -1 << "\n";
  else
    cout << ans << "\n";
  return 0;
}

import java.util.*;
public class And {

	public static void main(String[] args) {
		int[] count = new int[1000000];
		int[] count2 = new int[1000000];
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int x = in.nextInt();
		int[] arr = new int[n];
		boolean flag = false;
		for(int i = 0; i < n; i++)
		{
			arr[i] = in.nextInt();
			count[arr[i]]++;
			if(count[arr[i]] >= 2)
			{
				flag = true;
			}
		}
		if(flag)
		{
			System.out.println(0);
			return;
		}
		for(int i = 0; i < n; i++)
		{
			if((arr[i]&x) !=  arr[i] && count[arr[i]&x] > 0)
			{
				System.out.println(1);
				return;
			}
			if((arr[i]&x) !=  arr[i]) count2[arr[i]&x]++;
		}
		for(int i = 0; i < n; i++)
		{
			if((arr[i]&x) !=  arr[i] && count2[arr[i]&x] > 1)
			{
				System.out.println(2);
				return;
			}
		}
		System.out.println(-1);
	}

}


#include <bits/stdc++.h>
using namespace std;
int n, cnt, p[100001], b[100001];
vector<int> v;
void dfs(int x) {
  if (!b[x]) {
    b[x] = 1;
    ++cnt;
    dfs(p[x]);
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  ;
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    cin >> p[i];
  }
  for (long long i = 1; i <= n; ++i) {
    if (!b[i]) {
      cnt = 0;
      dfs(i);
      v.push_back(cnt);
    }
  }
  sort(v.rbegin(), v.rend());
  long long ans = 0;
  if (v.size() > 1) {
    ans += 1LL * (v[0] + v[1]) * (v[0] + v[1]);
  } else
    ans = 1LL * v[0] * v[0];
  for (int i = 2; i < v.size(); ++i) {
    ans += 1LL * v[i] * v[i];
  }
  cout << ans;
}

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

public class Main {
    static class Max {
        long val;
        long key;
        public Max(long value,long Key){
            val=value;
            key=Key;
        }

        public long getKey() {
            return key;
        }

        public long getVal() {
            return val;
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long [] conect=new long[n+1];
        long [] cCon=new long[n+1];
        Max max1=new Max(0,0);
        Max max2=new Max(-1,0);
        boolean  [] vis=new boolean[n+1];
        for (int i = 1; i <=n ; i++) {
            long a =in.nextLong();
            conect[i]=a;
        }
        for (int i = 1; i <=n ; i++) {
            if(vis[i])continue;
            long pass=0;
            long j=i;
            long count=0;
            while(pass!=i)
            {
                vis[(int)j]=true;
                pass=conect[(int)j];
                count++;
                j=pass;
            }
            //System.out.println("estacion "+i+" Esta conectada a "+ count+" Estaciones");

            if(count>=max1.val) {
                max2 = max1;
                max1 = new Max(count,i);
            } else if (count > max2.val) {
                max2 =new Max(count,i);
            }
            //System.out.println("max1 "+max1.key+" : "+max1.val+" max2 "+max2.key+" : "+max2.val);
            cCon[i]=count;
        }
        cCon[(int)max2.key]=0;
        cCon[(int)max1.key]=(max1.val +max2.val);
        long oh=0;
        for (long i:cCon ) {
            if(oh>=Long.MAX_VALUE)System.out.println("overflow Carajo");
            else oh+=i*i;
        }
        System.out.println(oh);
    }
}


#include <bits/stdc++.h>
long long mod = 1e9 + 7;
template <typename T>
inline long long pwr(T base, T n) {
  long long ans = 1;
  while (n > 0) {
    if (n % 2 == 1) ans = ans * base;
    base = base * base;
    n /= 2;
  }
  return ans;
}
struct range {
  int l, h;
};
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, k;
  cin >> n >> k;
  int a[10000] = {0};
  for (int i = 0; i < n; i++) cin >> a[i];
  int flag = 0;
  int sum = 0;
  int i = 0;
  while (i < n) {
    if (a[i] <= 8)
      sum += a[i];
    else {
      sum += 8;
      a[i + 1] += (a[i] - 8);
    }
    if (sum >= k) {
      flag = 1;
      break;
    }
    i++;
  }
  if (flag == 1)
    cout << i + 1 << "\n";
  else
    cout << "-1\n";
  return 0;
}

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

public class A {

	public static void main(String[] args) {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt(), k = scan.nextInt(), c = 0, p = 0;
		for(int i = 0; i < n; i++) {
			p += scan.nextInt();
			int take = Math.min(p, 8);
			c += take;
			p -= take;
			if(c >= k) {
				out.println(i+1);
				out.close();
				return;
			}
		}
		out.println(-1);
		out.close();
	}

	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

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

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

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

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

		public String nextLine() {
			String line = "";
			if(st.hasMoreTokens()) line = st.nextToken();
			else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
			while(st.hasMoreTokens()) line += " "+st.nextToken();
			return line;
		}

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

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

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

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

}


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

public class ColoredBalls {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String[] temp = br.readLine().split(" ");
		br.close();
		int[] colorCount = new int[n];
		for (int i = 0; i < colorCount.length; i++) {
			colorCount[i] = Integer.parseInt(temp[i]);
		}
		System.out.println(getSets(colorCount));
	}

	private static long getSets(int[] colorCount) {
		Arrays.sort(colorCount);
		// all sets must be of size setSize or setSize+1
		int setSize = colorCount[0];
		int[] pointers = new int[colorCount.length];
		for (int i = 0; i < pointers.length; i++) {
			pointers[i] = 1;
		}
		boolean done = false;
		while (!done) {
			for (int i = 0; i < colorCount.length; i++) {
				int minSetSizeNeeded = colorCount[i] / pointers[i];
				// too small to fit in set
				if (setSize > minSetSizeNeeded) {
					setSize = minSetSizeNeeded;
					break;
					// too large to fit in set
				} else if (setSize + 1 < minSetSizeNeeded || (
						setSize + 1 == minSetSizeNeeded && colorCount[i] % pointers[i] != 0)) {
					// try again with larger pointer
					pointers[i] = Math.max(colorCount[i]/(setSize+1),pointers[i]+1);
					i--;
					// all sets have been checked
				}else if(i == colorCount.length - 1){
					done = true;
				}
			}
		}
		long totalSets = 0;
		for (int i = 0; i < pointers.length; i++) {
			totalSets += pointers[i];
		}
		return totalSets;
	}
}

import time
import sys
from math import sqrt

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

sq = int(sqrt(a[0]))+2
s = set()

for box in range(1, sq):
    if a[0] % box == 0:
        s.add(a[0] // box)
        s.add(a[0] // box - 1)
    else:
        s.add(a[0] // box)

for balls in range(1, sq):
    if a[0] % balls <= a[0] // balls:
        s.add(balls)

for size in sorted(s, reverse=True):
    ans = 0
    for x in a:
        if x / size >= x % size:
            ans += (x+size) // (size+1)
        else:
            break
    else:
        print(ans)
        exit()


#include <bits/stdc++.h>
using namespace std;
int n, k;
double l, v1, v2;
double binser(double target) { return target / (v1 + v2); }
double msafa;
double solve(double start, double End, int students) {
  if (start >= End) {
    msafa = End;
    return 0;
  }
  if (students == 0) {
    msafa = min(start + 0.0001, End);
    return min(0.0001, End - start) / v2;
  }
  double t = binser(min(0.0002, 2.0 * (End - start)));
  double r = solve(start + v1 * t, End, max(0, students - k));
  if (start == 0) return l / (msafa / (r + t));
  return r + t;
}
int main() {
  cin >> n >> l >> v1 >> v2 >> k;
  if (k == n) {
    cout << fixed << setprecision(7) << l / v2 << endl;
    return 0;
  }
  cout << fixed << setprecision(10) << solve(0, l, n - k) << endl;
  return 0;
}


//package round47;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class E {
	Scanner in;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int m = ni();
		long all = 0;
		for(long b = 1;b <= n;b++){
			all += Math.min(2L * b * b - 1, 2L * m);
		}
		for(int t = 1;t <= 2*n+1;t++){
			int max = Math.min((int)(((double)m / t + t) / 2), n);
			int min = (int)(Math.ceil((1.0 / t + t) / 2));
			int ct = max - min + 1;
			if(ct >= 2){
				all -= ct - 1;
			}
		}
		out.println(all);
	}

	void run() throws Exception
	{
		in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
		out = new PrintWriter(System.out);

		solve();
		out.flush();
	}

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

	int ni() { return Integer.parseInt(in.next()); }
	void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
}

#include <bits/stdc++.h>
int main() {
  static int kk[5000000 * 2 + 1];
  long long ans;
  int n, m, b, r;
  scanf("%d%d", &n, &m);
  ans = 0;
  r = 0;
  for (b = 1; b <= n; b++) {
    long long b2 = (long long)b * b;
    ans += b2 < m ? b2 : m;
    while ((long long)r * r + m < b2) r++;
    if (r < b) {
      ans -= b - r;
      kk[b + r]++, kk[b + b]--;
      kk[1]++, kk[b - r + 1]--;
    }
  }
  ans *= 2;
  for (b = 1; b <= n * 2; b++)
    if ((kk[b] += kk[b - 1]) != 0) ans++;
  printf("%lld\n", ans);
  return 0;
}


r = lambda: list(map(int, input().split()))[1:]
n,c = map(int, input().split())

d = []
for _ in range(n):
    for i in r():
        if i<c:
            d.append(str(_+1))
            break
print (len(d))
print (' '.join(d))

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

public class A43 {
    public static void main(String [] args) {
        InputStream inputReader = System.in;
        OutputStream outputReader = System.out;
        InputReader in = new InputReader(inputReader);
        PrintWriter out = new PrintWriter(outputReader);
        Algorithm solver = new Algorithm();
        solver.solve(in, out);
        out.close();
    }
}

class Algorithm {
    void solve(InputReader ir, PrintWriter pw) {
        int n = ir.nextInt();
        int v = ir.nextInt();
        TreeSet<Integer> index = new TreeSet<>();
        for (int i = 0; i < n; i++) {
            int k = ir.nextInt();
            for (int j = 0; j < k;j++) {
                if (v > ir.nextInt()) index.add(i + 1);
            }
        }
        pw.println(index.size());
        for (Integer i : index) pw.print(i + " ");
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

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

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

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

}


//package cf36;

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

public class A {
	public static void main(String[] args) throws Exception {
		PrintStream out = new PrintStream("output.txt");
		Scanner sc = new Scanner(new File("input.txt"));
		int t = sc.nextInt();
		int k = sc.nextInt();
		for (int i=0; i<t; i++) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			if (k!=1) {
				int min = Math.min(n, m);
				if (min % (k + 1) == 0) {
					out.println('+');
				} else {
					boolean tmp = (min / (k + 1)) % 2 == 0 ? false : true;
					int max = Math.max(n, m);
					if ((max - min) % 2 == 1)
						tmp = !tmp;
					if (tmp)
						out.println('+');
					else
						out.println('-');
				}
			}
			else {
				if (m%2==1 && n%2==1)
					out.println('-');
				else
					out.println('+');
			}
		}
		out.close();
	}
}

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int N = 1e5 + 5;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie();
  if (fopen("input.txt", "r")) {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
  }
  int T, k;
  cin >> T >> k;
  ++k;
  while (T--) {
    int m, n;
    cin >> m >> n;
    if (m > n) swap(m, n);
    if (m % k == 0) {
      cout << "+";
    } else {
      int group = min(m / k, n / k);
      int del = m / k;
      int x = m - del * k;
      int y = n - del * k;
      bool win = group % 2;
      bool ans;
      if (k == 2) win = 0;
      if ((x + y) % 2 == 0)
        ans = win;
      else
        ans = !win;
      cout << (ans ? "+" : "-");
    }
    cout << '\n';
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  cout << n + (m - 1) << endl;
  for (int i = 1; i <= 1; ++i) {
    for (int j = 1; j <= m; ++j) {
      cout << i << ' ' << j << endl;
    }
  }
  for (int i = 2; i <= n; ++i) cout << i << ' ' << 1 << endl;
  return 0;
}

n, m = map(int, input().split())
print(n + m - 1)
for i in range (1, n + 1): print(i, 1)
for i in range (1, m): print(1, i + 1)


import java.util.*;

public class JavaApplication145 {
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int size = sc.nextInt();
    int[] data = new int[size];
    HashMap<Integer, Integer> map = new HashMap<>();
    for(int i = 0; i<size; i++)
    {
        data[i] = sc.nextInt();
        map.put(data[i], i);
    }
    int m = sc.nextInt();
    long ves = 0, pet = 0;
    for(int i = 0; i<m; i++)
    {
        int q = sc.nextInt();
        int index = map.get(q);
        ves += index+1;
        pet += size - index;
    }
    System.out.println(ves + " " + pet);
}
}

#include <bits/stdc++.h>
using namespace std;
long long astd[100010], aend[100010], bstd[100010], bend[100010];
int main() {
  int n, m;
  while (cin >> n) {
    memset(astd, 0, sizeof(astd));
    memset(bstd, 0, sizeof(bstd));
    memset(aend, 0, sizeof(aend));
    memset(bend, 0, sizeof(bend));
    int x, y;
    for (int i = 1; i <= n; i++) {
      cin >> x;
      if (astd[x] == 0)
        astd[x] = i;
      else
        aend[x] = i;
    }
    cin >> m;
    long long v = 0, p = 0;
    for (int i = 1; i <= m; i++) {
      cin >> y;
      if (astd[y] != 0) {
        if (aend[y] != 0) {
          v += astd[y];
          p += n - aend[y] + 1;
        } else {
          v += astd[y];
          p += n - astd[y] + 1;
        }
      }
    }
    cout << v << " " << p << endl;
  }
  return 0;
}


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

public class Main {
    final static String fileName = "";
    final static boolean useFiles = false;

    public static void main(String[] args) throws FileNotFoundException {
        InputStream inputStream;
        OutputStream outputStream;
        if (useFiles) {
            inputStream = new FileInputStream(fileName + ".in");
            outputStream = new FileOutputStream(fileName + ".out");
        } else {
            inputStream = System.in;
            outputStream = System.out;
        }
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task(in, out);
        Debug.out = out;
        solver.solve();
        out.close();
    }
}
class Task {
    public void solve() {
        int x = in.nextInt();
        if (x == 3) {
            out.print(5);
            return;
        }
        for (int i = 1; i <= Math.max(3 * x, 10); i += 2){
            int sum = 0;
            for (int j = 1; j < i; j += 2)
                sum += 2 * j;
            sum += i;
            if (sum >= x) {
                out.println(i);
                return;
            }
        }
    }

    private InputReader in;
    private PrintWriter out;

    Task(InputReader in, PrintWriter out) {
        this.in = in;
        this.out = out;
    }
}

class Debug {
    public static PrintWriter out;

    public static void printObjects(Object... objects) {
        out.println(Arrays.deepToString(objects));
        out.flush();
    }
}

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 double nextDouble(){
        return Double.parseDouble(next());
    }

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

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

'''input
3
'''
from sys import stdin
import math

def make_dp():
	dp = [0] * 1001
	dp[1] = 1
	dp[3] = 5
	for i in range(5, 100, 2):
		dp[i] = dp[i - 2] + i + i - 2

	return dp

# main starts
x = int(stdin.readline().strip())

if x == 3:
	print(5)
	exit()
dp = make_dp()
for i in range(1, len(dp)):
	if x <= dp[i]:
		print(i)
		break


#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000009;
long long n, f[1000100], g[1000100], times = 1;
long long t(long long x) {
  if (x % 2) return x / 2;
  return 0;
}
signed main() {
  scanf("%lld", &n);
  f[0] = 0;
  f[1] = 2;
  g[1] = 4;
  for (long long i = 2; i <= n; i++) g[i] = (1LL * g[i - 1] * 2 + 4) % MOD;
  for (long long i = 2; i <= n - 2; i++) {
    f[i] =
        1LL * (2 * times % MOD + f[i - 1] + 2LL * g[t(i)] * times % MOD) % MOD;
    if (i % 2) times = 1LL * times * (g[t(i)] + 1) % MOD;
  }
  printf("%lld\n",
         (1LL * 2 * f[n - 2] * f[n - 2] % MOD + 1LL * 8 * f[n - 2] % MOD + 10) %
             MOD);
  return 0;
}


n=int(input())
a=list(map(int, input().split()))
if(sum(a)<2*max(a) or sum(a)%2==1):
    print("NO")
else:
    print("YES")

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

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int a[maxn];
map<int, int> m;
bool cmp(int a, int b) { return a > b; }
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long sum = 0;
  int n;
  cin >> n;
  int maxm = 0;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    sum += a[i];
    maxm = max(maxm, a[i]);
  }
  if (sum % 2 == 0 && (sum - maxm) >= maxm) {
    cout << "YES";
  } else
    cout << "NO";
  return 0;
}


//https://codeforces.com/problemset/problem/1143/A
//package codeforces;

import java.util.Scanner;

public class TheDoors {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		int[] doors = new int[N];
		for (int i = 0; i < N; i++) {
			doors[i] = scanner.nextInt();
		}
		int leftDoor = 0;
		int rightDoor = 0;
		for (int i = 0; i < N; i++) {
			if (doors[i] == 0) {
				leftDoor = i+1;
			}
			else
				rightDoor = i+1;

		}
		if (leftDoor > rightDoor) {
			System.out.println(rightDoor);
		}
		else
			System.out.println(leftDoor);

		scanner.close();
	}

}

def the_doors(arr,n):
    count_1 = 0
    count_0 = 0
    for i in arr:
        if i == 0:count_0 += 1
        else:count_1 += 1
    check_1 = 0
    check_0 = 0
    for i in range(n):
        if arr[i] == 0:
            check_0 += 1
        else:
            check_1 += 1
        if count_0 == check_0:
            return i+1
        elif check_1 == count_1:
            return i+1
n = int(input())
arr = list(map(int,input().split()))
print(the_doors(arr, n))


import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] array = new int[n][2];
        for (int i = 0; i < n; i++){
            for(int j = 0; j < 2; j++)
                array[i][j] = scan.nextInt();
        }
        int[] order = new int[n];
        int second = array[0][0], third = array[0][1];
        if (array[third - 1][0] == second || array[third - 1][1] == second){
            int temp = second;
            second = third;
            third = temp;
        }
        order[0] = 1; order[1] = second; order[2] = third;
        for (int i = 3; i < n; i++){
            int neighborOne = array[order[i - 2] - 1][0], neighborTwo = array[order[i - 2] - 1][1];
            order[i] = neighborTwo;
            if (neighborOne != order[i - 1])
                order[i] = neighborOne;
        }
        for (int x: order)
            System.out.print(x + " ");
    }
}

n = int(input())
p = [(None, None)]
for _ in range(n):
  p.append(list(map(int, input().split())))

if n==3:
	print("1 2 3")
else:
	for idx, (a, b) in enumerate(p[1:], 1):
	  if a in p[b]:
	    p[idx] = [b]
	  elif b in p[a]:
	    p[idx] = [a]

	return_val = [p[1][0]]
	n-=1
	while n:
	  return_val.append(p[return_val[-1]][0])
	  n-=1

	print(" ".join([str(x) for x in return_val]))


n = int(input())
s = list(map(int, input().split()))
d = {}
mt = False
mti = -1
for i in range(len(s)):
    if s[i] not in d:
        d[s[i]] = 1
    else:
        d[s[i]] += 1
        if d[s[i]] > 2:
            mt = True
            mti = i
good = []
for i in d.keys():
    if d[i] == 1:
        good.append(i)
if len(good) % 2 == 0:
    print("YES")
    good1 = good[:len(good) // 2]
    for i in s:
        if i in good1:
            print('A', end='')
        else:
            print('B', end='')
else:
    if mt:
        print("YES")
        good1 = good[:len(good) // 2]
        u = False
        for i in s:
            if (i in good1) or ((not u) and (i == s[mti])):
                print('A', end='')
                if i == s[mti]:
                    u = True
            else:
                print('B', end='')
    else:
        print("NO")

#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> Sin;
int numm[101], pos[101];
struct Node {
  int num;
  char grp;
  Node() { grp = 'A'; }
} a[101];
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++)
    scanf("%d", &a[i].num), numm[a[i].num]++, pos[a[i].num] = i;
  for (int i = 1; i <= 100; i++) {
    if (numm[i] == 1)
      Sin.push_back(i);
    else if (numm[i] > 2)
      k = i;
  }
  if (Sin.size() % 2 != 0 && k == 0) return cout << "NO", 0;
  cout << "YES\n";
  for (int i = 0; i < Sin.size() / 2; i++) a[pos[Sin[i]]].grp = 'B';
  if (Sin.size() % 2 != 0) a[pos[k]].grp = 'B';
  for (int i = 1; i <= n; i++) cout << a[i].grp;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  char s[101000];
  scanf("%s", s);
  int n = strlen(s), k;
  bool exist[101000];
  scanf("%d", &k);
  int br[250];
  memset(br, 0, sizeof(br));
  memset(exist, 0, sizeof(exist));
  for (int i = 0; i < n; i++) {
    br[(int)s[i]]++;
  }
  while (1) {
    int minn = 9999999, tmp;
    for (int i = (int)'a'; i <= (int)'z'; i++)
      if (br[i] != 0 && br[i] < minn) minn = br[i], tmp = i;
    if (k < minn || minn == 9999999) break;
    br[tmp] = 0;
    k -= minn;
    exist[tmp] = 1;
  }
  int ans = 0;
  for (int i = 0; i < 250; i++)
    if (br[i] > 0) ans++;
  char c[101000];
  int cnt = 0;
  for (int i = 0; i < n; i++)
    if (exist[(int)s[i]] == 0) {
      c[cnt++] = s[i];
    }
  printf("%d\n", ans);
  printf("%s\n", c);
  return 0;
}

import itertools
import math

import time
def timer(f):
    def tmp(*args, **kwargs):
        t = time.time()
        res = f(*args, **kwargs)
        print("Время выполнения функции: %f" % (time.time()-t))
        return res

    return tmp

#n = int(input())

s = input()
n = int(input())

array = [[0, chr(i+ord('a'))] for i in range(26)]
for i in range(len(s)):
    array[ord(s[i])-ord('a')][0]+=1

array = sorted(array, key=lambda i: i[0])

index = 0
q = n
for i in range(len(array)):
    if array[i][0]>0:
        if array[i][0]<=q:
            q-=array[i][0]
            array[i][0] = 0

array = sorted(array, key=lambda i: ord(i[1]))

m = 0
for i in range(len(array)):
    if array[i][0] > 0:
        m+=1

print(m)

newS = ""
for i in range(len(s)):
    if array[ord(s[i])-ord('a')][0] > 0:
        newS+=s[i]

print(newS)


import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class A {

	public A() {
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = sc.nextInt();
		Arrays.sort(a);
		int cur = a[0];
		int cnt = 0;
		for (int i = 0; i < n; i++)
			if (a[i] == cur)
				cnt++;
		cur = a[n - 1];
		if (cur == a[0]) {
			out.println(0);
			out.close();
			System.exit(0);
		}
		for (int i = n - 1; i >= 0; i--)
			if (a[i] == cur)
				cnt++;
		out.println(n - cnt);
		sc.close();
		out.close();
	}

	public static void main(String[] args) {
		new A();
	}
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, r = 0, i, j, p = 0;
  cin >> n;
  int a[n];
  for (i = 0; i < n; i++) {
    cin >> a[i];
  }
  sort(a, a + n);
  for (i = 0; i < n; i++) {
    if (a[0] == a[i] || a[n - 1] == a[i]) p++;
  }
  cout << n - p;
}


#include <bits/stdc++.h>
using namespace std;
const long long P = 1e9 + 7;
long long fpow(long long b, long long p) {
  p %= (P - 1);
  long long r = 1ll;
  while (p) {
    if (p & 1) r *= b, r %= P;
    b = b * b % P;
    p >>= 1;
  }
  return r;
}
int main() {
  long long a, b, x, n;
  scanf("%I64d%I64d%I64d%I64d", &a, &b, &n, &x);
  if (a == 1)
    printf("%I64d\n", (x + n % P * b % P) % P);
  else
    printf("%I64d\n",
           (fpow(a, n) * x % P +
            ((fpow(a, n) - 1) * fpow(a - 1, P - 2)) % P * b % P + P) %
               P);
  return 0;
}

import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Created by omar on 11/11/17.
 */
public class Main {

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

        long A = sc.nextLong(), B = sc.nextLong(), n = sc.nextLong(), x = sc.nextLong();
        long[][] first = {{x, 1}, {0, 0}}, second = {{A, 0}, {B, 1}};
        out.println(multiply(first, exp(second, n), first.length)[0][0]);

        out.flush();
        out.close();
    }

    static int MOD = (int)1e9 + 7;
    static long[][] multiply (long[][] A, long[][] B, int n) {
        long[][] res = new long[n][n];
        for (int row = 0; row < n; row++)
            for (int col = 0; col < n; col++) {
                for (int lop = 0; lop < n; lop++) {
                    res[row][col] += (A[row][lop] * B[lop][col] % MOD);
                    if (res[row][col] >= MOD) res[row][col] -= MOD;
                }
            }
        return res;
    }
    static long[][] identity (int n) {
        long[][] res = new long[n][n];
        for (int i = 0; i < n; i++)
            res[i][i] = 1;
        return res;
    }
    static long[][] exp (long[][] M, long p) {
        if (p == 0) return identity(M.length);
        if (p == 1) return M;
        if (p % 2 == 0) return exp(multiply(M, M, M.length), p >> 1L);
        else return multiply(M, exp(multiply(M, M, M.length), p >> 1L), M.length);
    }
}


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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 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);
            CLevkoAndStrings solver = new CLevkoAndStrings();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class CLevkoAndStrings {
        int mod = (int) 1e9 + 7;
        Debug debug = new Debug(true);

        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.ri();
            int k = in.ri();
            char[] s = new char[n + 1];
            in.rs(s, 1);
            long[] ps = new long[k + 1];
            long[][] dp = new long[n + 1][k + 1];
            dp[0][0] = 1;
            ps[0] = 1;
            for (int i = 1; i <= n; i++) {
                int right = n - i + 1;
                int less = s[i] - 'a';
                int greater = 'z' - s[i];
                for (int j = 0; j <= k; j++) {
                    dp[i][j] = ps[j] * less;
                    int d;
                    for (int t = i - 1; t >= 0 && (d = j - (i - t) * right) >= 0; t--) {
                        dp[i][j] += dp[t][d] * greater;
                    }
                    dp[i][j] %= mod;
                    ps[j] += dp[i][j];
                    if (ps[j] >= mod) {
                        ps[j] -= mod;
                    }
                }
            }

            debug.debug("s", s);
            debug.debug("dp", dp);
            long ans = ps[k];
            out.println(ans);
        }

    }

    static class Debug {
        private boolean offline;
        private PrintStream out = System.err;
        static int[] empty = new int[0];

        public Debug(boolean enable) {
            offline = enable && System.getSecurityManager() == null;
        }

        public Debug debug(String name, Object x) {
            return debug(name, x, empty);
        }

        public Debug debug(String name, Object x, int... indexes) {
            if (offline) {
                if (x == null || !x.getClass().isArray()) {
                    out.append(name);
                    for (int i : indexes) {
                        out.printf("[%d]", i);
                    }
                    out.append("=").append("" + x);
                    out.println();
                } else {
                    indexes = Arrays.copyOf(indexes, indexes.length + 1);
                    if (x instanceof byte[]) {
                        byte[] arr = (byte[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof short[]) {
                        short[] arr = (short[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof boolean[]) {
                        boolean[] arr = (boolean[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof char[]) {
                        char[] arr = (char[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof int[]) {
                        int[] arr = (int[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof float[]) {
                        float[] arr = (float[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof double[]) {
                        double[] arr = (double[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof long[]) {
                        long[] arr = (long[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else {
                        Object[] arr = (Object[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    }
                }
            }
            return this;
        }

    }

    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 ri() {
            return readInt();
        }

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

        public int rs(char[] data, int offset) {
            return readString(data, offset);
        }

        public int readString(char[] data, int offset) {
            skipBlank();

            int originalOffset = offset;
            while (next > 32) {
                data[offset++] = (char) next;
                next = read();
            }

            return offset - originalOffset;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private static final int THRESHOLD = 32 << 10;
        private final Writer os;
        private StringBuilder cache = new StringBuilder(THRESHOLD * 2);

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

        private void afterWrite() {
            if (cache.length() < THRESHOLD) {
                return;
            }
            flush();
        }

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

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

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

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

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

        public FastOutput println() {
            return append('\n');
        }

        public FastOutput flush() {
            try {
//            boolean success = false;
//            if (stringBuilderValueField != null) {
//                try {
//                    char[] value = (char[]) stringBuilderValueField.get(cache);
//                    os.write(value, 0, cache.length());
//                    success = true;
//                } catch (Exception e) {
//                }
//            }
//            if (!success) {
                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();
        }

    }
}

#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') f = -1;
  for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
  return x * f;
}
const int N = 2005, mod = 1e9 + 7;
int dp[N][N], sum[N];
char s[N];
void add(int &x, int y) {
  x += y;
  if (x >= mod) x -= mod;
}
int main() {
  int n = read(), k = read();
  scanf("%s", s + 1);
  sum[0] = dp[0][0] = 1;
  for (int i = 1; i <= n; ++i) {
    for (int j = 0; j <= k; ++j) {
      for (int l = i - 1; l >= 0 && (i - l) * (n - i + 1) <= j; --l)
        add(dp[i][j], dp[l][j - (i - l) * (n - i + 1)]);
      dp[i][j] = 1ll * ('z' - s[i]) * dp[i][j] % mod;
      add(dp[i][j], 1ll * sum[j] * (s[i] - 'a') % mod);
      add(sum[j], dp[i][j]);
    }
  }
  int ans = 0;
  for (int i = 0; i <= n; ++i) add(ans, dp[i][k]);
  cout << ans;
  return 0;
}


__author__ = 'ratnesh.mishra'

weights = map(int, input())

weights = [cnt for cnt, x in enumerate(weights, 1) if x]

m = int(input())

state = [(0, 0, 0, [])]

res = "NO"
while state:
    w, b, k, l = state.pop()

    if k == m:
        res = 'YES\n' + ' '.join(map(str, l))
        break

    for wt in weights:
        if wt != w and wt > b:
            state.append((wt, wt-b, k+1, l+[wt]))

print(res)

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

public class hals {

	public static void main(String[] args)throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s = br.readLine();
		int m = Integer.parseInt(br.readLine());
		long x1=0,x2=0;
		int cnt = 0,last=-1;
		int[] arr = new int[m];
		boolean flag=false;
		for(int w=0;w<10;w++){
			if(s.charAt(w)=='0')continue;
			x1=0;
			x2=0;
			cnt=1;
			arr[0]=w+1;
			last=w+1;
			x1+=w+1;
			flag=true;
			while(cnt<m){
				flag=false;
				for(int i=0;i<10;i++){
					if(s.charAt(i)=='1'){
						if(cnt%2==0){
							if(x1+i+1>x2 && (i+1)!=last){
								x1+=i+1;
								last=i+1;
								flag=true;
								arr[cnt++]=i+1;
								break;
							}
						}
						else{
							if(x2+i+1>x1 && (i+1)!=last){
								x2+=i+1;
								last=i+1;
								flag=true;
								arr[cnt++]=i+1;
								break;
							}
						}
					}
				}
				if(!flag){
					break;
				}
			}
			if(flag)
				break;
		}
		if(!flag)
			System.out.println("NO");
		else{
			System.out.println("YES");
			System.out.print(arr[0]);
			for(int i=1;i<m;i++)
				System.out.print(" "+arr[i]);
			System.out.println();
		}
	}
}


n,k=map(int,input().split())
s=input()
if(k==2):
    #A
    sol1=[s[i] for i in range(n)]
    ans1=0
    for i in range(n):
        if(i%2==0 and sol1[i]=="B"):
            ans1+=1
            sol1[i]="A"
        elif(i%2!=0 and sol1[i]=="A"):
            ans1+=1
            sol1[i]="B"
    #B
    sol2=[s[i] for i in range(n)]
    ans2=0
    for i in range(n):
        if(i%2==0 and sol2[i]=="A"):
            ans2+=1
            sol2[i]="B"
        elif(i%2!=0 and sol2[i]=="B"):
            ans2+=1
            sol2[i]="A"
    if(ans1<=ans2):
        print(ans1)
        print("".join(str(x) for x in sol1))
    else:
        print(ans2)
        print("".join(str(x) for x in sol2))
else:
    s=[s[i] for i in range(n)]
    ans=0
    for i in range(1,n):
        if(s[i]==s[i-1]):
            ans+=1
            x=chr((ord(s[i-1])-65+1)%k+65)
            if(i==n-1 or s[i+1]!=x):s[i]=x
            else:
                y=chr((ord(s[i-1])-65+1+1)%k+65)
                s[i]=y
    print(ans)
    print("".join(str(x) for x in s))


import java.util.*;

public class StrangePartition{
  public static void main(String[] args){
    Scanner gd = new Scanner(System.in);
    int tt = IO.ri();
    int n;
    long x;
    long[] arr;
    long min,max;
    long sum;
    long val;
    while(tt>0){
      n = IO.ri();
      x = IO.rl();
      sum = 0;
      min = 0;
      max = 0;
      for(int i=0;i<n;i++){
        val = IO.rl();
        sum+=val;
        min+=(long)Math.ceil(val/(x*1.0));
      }
      max = (long)Math.ceil(sum/(x*1.0));
      if(min<max){
        IO.pf("%d %d\n",min,max);
      }
      else{
        IO.pf("%d %d\n",max,min);
      }
      tt--;
    }
  }
}

// Template
class IO{
  static Scanner gd = new Scanner(System.in);
  public static long rl(){
    return gd.nextLong();
  }
  public static int ri(){
    return gd.nextInt();
  }
  public static String rs(){
    return gd.next();
  }
  public static int[] rai(int len){
    int[] temp = new int[len];
    for(int i=0;i<len;i++){
      temp[i] = gd.nextInt();
    }
    return temp;
  }
  public static long[] ral(int len){
    long[] temp = new long[len];
    for(int i=0;i<len;i++){
      temp[i] = gd.nextLong();
    }
    return temp;
  }
  public static String[] ras(int len){
    String[] temp = new String[len];
    for(int i=0;i<len;i++){
      temp[i] = gd.next();
    }
    return temp;
  }
  public static void pf(String format,Object... args){
    System.out.printf(format,args);
  }
  public static void pl(Object data){
    System.out.println(data);
  }
  public static void pai(int arr[]){
    for(int i=0;i<arr.length;i++){
      System.out.printf("%d ",arr[i]);
    }
    System.out.println();
  }
  public static void pal(long arr[]){
    for(int i=0;i<arr.length;i++){
      System.out.printf("%d ",arr[i]);
    }
    System.out.println();
  }
  public static void pas(String arr[]){
    for(int i=0;i<arr.length;i++){
      System.out.printf("%s ",arr[i]);
    }
    System.out.println();
  }
}

class UT{
  public static long fact(long k){
    if(k==1){
      return 1;
    }
    else{
      return k*fact(k-1);
    }
  }
  public static HashMap<Integer,Integer> gen_primes(int upper_bound){
    int[] arr = new int[upper_bound];
    int ptr = 0;
    boolean flag;
    int next_ptr=1;
    for(int i=0;i<upper_bound;i++){
      arr[i] = i+2;
    }
    while(next_ptr!=0){
      flag = true;
      next_ptr = 0;
      for(int j=ptr+1;j<arr.length;j++){
        if(((arr[ptr]*arr[ptr])>upper_bound)){
          break;
        }
        if(arr[j]!=0&&flag==true){
          flag = false;
          next_ptr = j;
        }
        if(arr[j]%arr[ptr]==0){
          arr[j] = 0;
        }
      }
      ptr = next_ptr;
    }
    HashMap<Integer,Integer> prime_nums = new HashMap<Integer,Integer>();
    for(int p=0;p<arr.length;p++){
      if(arr[p]!=0){
        prime_nums.put(arr[p],arr[p]);
      }
    }
    return prime_nums;
  }
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long

int main() {
	ios_base :: sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int t;
	cin>>t;
	while(t--){
	    int n;
	    cin>>n;
	    ll x;
	    cin>>x;
	    vector<ll> a(n);
	    ll sum = 0;
	    ll ans =0;
	    for(int i=0;i<n;i++){
	        cin>>a[i];
	        ans += a[i];
	        sum += (a[i]/x);
	        if(a[i]%x != 0){
	            sum += 1;
	        }
	    }
	   ll ans2 = ans/x;
	    if(ans%x != 0){
	            ans2 += 1;
	   }
	   cout<<min(ans2,sum)<<" "<<max(ans2,sum)<<'\n';
	}
	return 0;
}


from sys import stdin, gettrace

if not gettrace():
    def input():
        return next(stdin)[:-1]

def main():
    n = int(input())
    bb = [int(a) for a in input().split()]
    seq = {}
    for i, b in enumerate(bb):
        if b - i in seq:
            seq[b-i] += b
        else:
            seq[b-i] = b
    print(max(seq.values()))

if __name__ == "__main__":
    main()

#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int b[N], n;
long long res = -1;
map<int, long long> mp;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", b + i);
    mp[b[i] - i] += b[i];
  }
  for (auto it = mp.begin(); it != mp.end(); it++) {
    if (res < it->second) res = it->second;
  }
  cout << res << endl;
  return 0;
}


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

public class Rextester{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = new Integer(br.readLine());
        br.close();
        int[][] mat = new int[n][n];
        int p=1;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                mat[i][j]=p++;
            }
        }
        StringBuffer sb = new StringBuffer();
        int done = 0,r=0,c=0;
        for(done=0;done<n;done++){
            if(done%2==0){
                for(int y=0;y<n;y++){
                    if(y<n/2){
                        sb.append(mat[r+y][c]).append(" ");
                    }
                    else if(y>n/2){
                        sb.append(mat[r+y][n-c-1]).append(" ");
                    }
                }
                if(n%2!=0){
                    sb.append(mat[r+(n/2)][c]);
                }
                else{
                    sb.append(mat[r+(n/2)][n-c-1]);
                }
                sb.append("\n");
            }
            else{
                for(int y=0;y<n;y++){
                    if(y<n/2){
                        sb.append(mat[r+y][n-c-1]).append(" ");
                    }
                    else if(y>n/2){
                        sb.append(mat[r+y][c]).append(" ");
                    }
                }
                if(n%2!=0){
                    sb.append(mat[r+(n/2)][n-c-1]).append("\n");
                }
                else{
                    sb.append(mat[r+(n/2)][c]).append("\n");
                }
                c++;
            }
        }
        System.out.println(sb);
    }
}

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 4e2 + 7;
int main() {
  int n;
  int mp[MAXN][MAXN], cnt = 1;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    if (i % 2 == 1)
      for (int j = 1; j <= n; j++) mp[j][i] = cnt++;
    else
      for (int j = n; j >= 1; j--) mp[j][i] = cnt++;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      printf("%d ", mp[i][j]);
    }
    printf("\n");
  }
}


def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)

n, m = map(int, input().split(' '))
x = list(map(int, input().split(' ')))
p = list(map(int, input().split(' ')))
dx = [x[i+1]-x[i] for i in range(n-1)]
d = dx[0]
for i in dx:
    d = gcd(i, d)
for i in range(m):
    if d % p[i] == 0:
        print('YES')
        print(x[0], i+1)
        exit()
print('NO')

#include <bits/stdc++.h>
using namespace std;
long long N, M, a[300005], p[300005], diff, k;
long long gcd(long long x, long long y) {
  if (y == 0) return x;
  return gcd(y, x % y);
}
int main() {
  cin >> N >> M;
  for (long long i = 0; i < N; i++) cin >> a[i];
  for (long long i = 0; i < M; i++) cin >> p[i];
  for (long long i = 1; i < N; i++) {
    diff = a[i] - a[i - 1];
    k = gcd(k, diff);
  }
  for (long long i = 0; i < M; i++) {
    if (gcd(k, p[i]) == p[i]) {
      cout << "YES\n" << a[0] << " " << i + 1 << "\n";
      return 0;
    }
  }
  cout << "NO\n";
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
void in() {
  ifstream cin("input.txt");
  ios_base::sync_with_stdio(false);
  cin.tie(0);
}
void solution() {}
void out() {}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    int F, u, L, R, ans = 0;
    cin >> F >> u >> L >> R;
    ans = F / u - R / u + (L - 1) / u;
    cout << ans << "\n";
  }
  return 0;
}

if __name__ == '__main__':
    t = input()
    t = int(t)
    while t:
        e, v, l, r = input().split()
        e = int(e)
        v = int(v)
        l = int(l)
        r = int(r)
        res = e//v
        if l % v != 0:
            st = l//v + 1
        else:
            st = l//v
        en = r//v
        print(res-(en-st+1))
        t=t-1


#include <bits/stdc++.h>
const long long LINF = 1e18;
const int INF = 1e9;
const int M = 1e9 + 7;
const double EPS = 1.0e-9;
const double PI = acos(-1.0);
using namespace std;
string s;
char ch[10010];
int ans[10100];
int main() {
  std::ios_base::sync_with_stdio(0);
  cin >> s;
  int len = s.length();
  int pos = 0;
  while (pos < len - 1) {
    if (s[pos] != s[pos + 1]) {
      ans[pos] = 1;
    }
    pos++;
  }
  if (s[len - 1] == 'a') ans[len - 1] = 1;
  for (int i = 0; i < len; i++) cout << ans[i] << " ";
  return 0;
}

s = input()
arr_ans = [0] * len(s)
for i in range(1, len(s)):
    if s[i] == 'a':
        arr_ans[i - 1] = (arr_ans[i - 1] + 1) % 2
        arr_ans[i] += 1
print(*arr_ans)


n, m, a, b = list(map(int, input().split()))

k = n%m
print(min(k*b, (m - k)*a))

#include <bits/stdc++.h>
int main() {
  long long int n, m, a, b, ans1, ans2, i, p;
  scanf("%I64d%I64d%I64d%I64d", &n, &m, &a, &b);
  if (n % m == 0) {
    printf("");
  }
  if (n < m) {
    ans1 = ((m - n) * a);
    ans2 = n * b;
  } else {
    ans1 = (n % m) * b;
    ans2 = ((((n / m) + 1) * m) - n) * a;
  }
  if (ans1 < ans2)
    printf("%I64d", ans1);
  else
    printf("%I64d", ans2);
  return 0;
}


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

public class Solution{
    InputStream is;
    static PrintWriter out;
    String INPUT = "";
    static long mod = (long)1e9+7L;

    public void solve(){
        long k = nl(), d = nl(), t = nl();

        long a = ((k+d-1L)/d) * d;   // a minute me k minute stove on rehta h.

        long inc = a - k;   //increase in time for first  k  minute is (a - k)/2;
        //consider
        long ans = 0L;
        t = 2L*t;

        long cookedInAInterval = 2L*k + inc;

        long freq = t/cookedInAInterval;
        ans = (freq * a);
        t = t - (freq * cookedInAInterval);

        boolean offset = false;
        if(2L * k >= t){
            ans = ans + t/2L;
            out.print(ans);
            if(t%2L == 1L){
                out.print(".5");
            }
            return;
        }
        else{
            //out.println("else");
            ans = ans + k;
            t = t - 2L*k;
            ans = ans + t;
            out.print(ans);
            //if(t%2L == 1L){
              //  out.print(".5");
            //}
            return;
        }

    }

    void run(){
        is = new DataInputStream(System.in);
        out = new PrintWriter(System.out);
        int t=1;while(t-->0)solve();
        out.flush();
    }
    public static void main(String[] args)throws Exception{new Solution().run();}
    long mod(long v, long m){if(v<0){long q=(Math.abs(v)+m-1L)/m;v=v+q*m;}return v%m;}
    long mod(long v){if(v<0){long q=(Math.abs(v)+mod-1L)/mod;v=v+q*mod;}return v%mod;}
    //Fast I/O code is copied from uwi code.
    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;
    private int readByte(){
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }
    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }
    private String ns(){
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    private char[] ns(int n){
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }
    private char[][] nm(int n, int m){
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }
    private int[] na(int n){
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }
    private int ni(){
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    private long nl(){
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    static  int i(long x){return (int)Math.round(x);}
    static class Pair implements Comparable<Pair>{
        long fs,sc;
        Pair(long a,long b){
            fs=a;sc=b;
        }
        public int compareTo(Pair p){
            if(this.fs>p.fs)return 1;
            else if(this.fs<p.fs)return -1;
            else{
                return i(this.sc-p.sc);
            }
            //return i(this.sc-p.sc);
        }
        public String toString(){
            return "("+fs+","+sc+")";
        }
    }

}

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long double k, d, t;
  cin >> k >> d >> t;
  if (d < k) {
    d = ceil(k / d) * d;
  }
  unsigned long long num = floor((2 * t) / (d + k));
  long double time = num * d;
  long double left = 1 - num * ((d + k) / (2 * t));
  if (left <= (k / t)) {
    time += left * t;
  } else {
    time += k;
    time += (left - k / t) * (2 * t);
  }
  cout << fixed << setprecision(10) << time;
}


def main():
	n = int(input())
	games = list(map(int, input().split(' ')))

	result = max([games[:i].count(0) + games[i:].count(1) for i in range(n+1)])

	print(result)

if __name__ == "__main__":
	main()

#include <bits/stdc++.h>
using namespace std;
int a[105];
int dp[105];
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    dp[i] = dp[i - 1] + (a[i] == 0);
    cnt += a[i];
  }
  int res = cnt;
  int one = 0;
  for (int i = 1; i <= n; i++) {
    one += a[i];
    res = max(res, dp[i] + (cnt - one));
  }
  cout << res << endl;
  return 0;
}