def max_of_min_count(s):
    p = ''
    for i in range(len(s)):
        if s[i] == '?':
            p += 'Y'
        else:
            p += s[i]
    max_min_count = 0
    count = 0
    for j in range(len(p)):
        if p[j] == 'N':
            count += 1
            if count > max_min_count:
                max_min_count = count
        else:
            count = 0
    return max_min_count

def get_res(k, s):
    n_count = 0
    M = len(s)
    for i in range(M):
        if s[i] == 'N':
            n_count += 1
        elif s[i] == 'Y':
            if n_count == k:
                if max_of_min_count(s) <= k:
                    return True
            n_count = 0
            continue
        else:
            if n_count == k:
                if max_of_min_count(s) <= k:
                    return True
            elif n_count < k:
                n_count += 1
                continue
            else:
                n_count = 0
    if n_count == k and max_of_min_count(s) <=k:
        return True
    else:
        return False

M, k = [int(s) for s in raw_input().split(" ")]
s = str(raw_input())
res = get_res(k, s)
for q in range(1, M):
    if s[q] == 'Y' or s[q] == '?':
        res = res or get_res(k, s[q:])

if res and max_of_min_count(s) <= k:
    result = 'YES'
else:
    result = 'NO'

print "{}".format(result)


def max_of_min_count(s):
    p = ''
    for i in range(len(s)):
        if s[i] == '?':
            p += 'Y'
        else:
            p += s[i]
    max_min_count = 0
    count = 0
    for j in range(len(p)):
        if p[j] == 'N':
            count += 1
            if count > max_min_count:
                max_min_count = count
        else:
            count = 0
    return max_min_count

def get_res(M, k, s):
    n_count = 0
    for i in range(M):
        if s[i] == 'N':
            n_count += 1
        elif s[i] == 'Y':
            if n_count == k:
                if max_of_min_count(s) <= k:
                    return 'YES'
            n_count = 0
            continue
        else:
            if n_count == k:
                if max_of_min_count(s) <= k:
                    return 'YES'
            elif n_count < k:
                n_count += 1
                continue
            else:
                n_count = 0
    if n_count == k and max_of_min_count(s) <=k:
        return 'YES'
    else:
        return 'NO'

M, k = [int(s) for s in raw_input().split(" ")]
s = str(raw_input())
result = get_res(M, k, s)
print "{}".format(result)


n, k = map(int, input().split())
s = input()
cur = s[0] == 'N'
mx = cur
for i in range(1, n):
    if (s[i] == 'N'):
        cur += 1
    else:
        cur = 0
    mx = max(mx, cur)
if (cur > k):
    print("NO")
    exit(0)
for i in range(k - 1, n):
    ch = 1
    for j in range (i - k + 1, i + 1):
        if (s[j] == 'Y'):
            ch = 0
    if (i > k - 1 and s[i - k] == 'N'):
        ch = 0
    if (i < n - 1 and s[i + 1] == 'N'):
        ch = 0
    if (ch):
        print("YES")
        exit(0)
print("NO")


n, k = map(int, input().split())
k = int(k)
s = input()
s = "Y" + s + "Y"
res = "NO"
cnt = 0
can = True
for ch in s:
    if(ch == 'N'):
        cnt += 1
        if(cnt > k):
            can = False
    else:
        cnt = 0
for i in range(1,n):
    i = int(i)
    if(i + k - 2 < n):
        subs = s[i:i+k]
        flag = True
        for ch in subs:
            if(not ch in "N?"):
                flag = False
        if((s[i-1] in "Y?" or s[i+k] in "Y?") and flag):
            res = "YES"
            # print(s[i-1], subs, s[i+k])
if can:
    print(res)
else:
    print("NO")


n, need = map(int, raw_input().split())
a = raw_input()

f = [[[False for i in xrange(2)] for j in xrange(111)] for k in xrange(111)]

f[0][0][0] = True

for i in xrange(n):
    for j in xrange(i+1):
        for k in xrange(2):
            if f[i][j][k]:
                i2 = i + 1
                if a[i] == 'Y' or a[i] == '?':
                    j2 = 0
                    k2 = k
                    f[i2][j2][k2] = True
                if a[i] == 'N' or a[i] == '?':
                    j2 = j + 1
                    if j2 <= need:
                        k2 = k
                        if j2 == need:
                            k2 = 1
                        f[i2][j2][k2] = True

res = False
for j in xrange(need + 1):
    if f[n][j][1]:
        res = True

if res:
    print 'YES'
else:
    print 'NO'


a1=input().split()
a=int(a1[0])
b=int(a1[1])
n=0
for i in range(a,b+1):
	if bin(i).count('0')==2:
		n+=1
print(n)


input_ = input().split(" ")
input_numbers = list(map(int, input_))

shifted_ = []

a = input_numbers[0]
b = input_numbers[1]
a_ = len(bin(a)[2:])
b_ = len(bin(b)[2:])

all_ = []
answers = []

def generate_answers(mask):
    binaries = []

    for i in range(2, len(mask)):
        aux = '0b'
        aux += mask[2:]
        aux = list(aux)
        aux[i] = '0'
        aux = "".join(aux)
        binaries.append(aux)

    return binaries

for i in range(a_, b_+1):
    shifted = ((1 << i) - 1)
    shifted_.append(bin(mask))

for i in shifted_:
   all_ += generate_answers(i)

for i in all_:
    number = int(i,2)
    if !(number < input_numbers[0] or number > input_numbers[1] or i[2] == '0'):
        answers.append(i)

print(len(answers))


x = input().split()
ans = 0
for i in range(61):
    for j in range(i - 1):
        y = 2 ** i - 1 - 2 ** j
        if y >= x[0] and y <= x[1]:
            ans++
print(ans)


#include <bits/stdc++.h>
#define debug(x) cout << #x << " " << x << endl
#define pb push_back
#define LL long long
using namespace std;

const int MAXN = 1e5+7;
const int INF = 2e9+7;
vector <string> vec;

string to_bin(LL a)
{
    string st;
    while(a){
        st += a % 2 + '0';
        a /= 2;
    }
    string t;
    int len = st.length();
    for(int i = len - 1; i >= 0; --i)
        t += st[i];
    return t;
}

LL to_num(string st)
{
    LL a = 0;
    int len = st.length();
    for(int i = 0; i < len; ++i)
        a = a * 2 + st[i] - '0';
    return a;
}

void init()
{
    string st = "10", R = "1011111111111111111111111111111111111111111111111111111111111";
    while(st != R)
    {
        string s = st;
        vec.pb(s);
        int pos = 1, len = s.length();//0的位置
        while(pos < len - 1)
        {
            swap(s[pos], s[pos + 1]);
            vec.pb(s);
            pos++;
        }
        st += '1';
    }
}
bool cmp(string a, string b)
{
    int len1 = a.length(), len2 = b.length();
    if(len1 > len2) return false;
    else if(len1 < len2) return true;
    else return a <= b;
}
int main(){
    //cout << to_bin((LL)1000000000000000000).length();
    LL a, b;
    cin >> a >> b;
    init();
    sort(vec.begin(), vec.end(), cmp);
    string st1 = to_bin(a), st2 = to_bin(b);
    int len = vec.size();
    int ans = 0;
    cout << st1 << " " << st2 << endl;
    for(int i = 0; i < len; ++i)
    {
        //cout << vec[i] << " ";
        if(cmp(st1, vec[i]) && cmp(vec[i], st2))
            ans++;
    }
    cout << ans << endl;
    return 0;
}


x = map(int,raw_input().split())
a = x[0]
b = x[1]

def zeros(n):
	if n == 1:
		return 0
    l = len(bin(n)) - 3
    x = l * (l-1) / 2
    if len(bin(n)[2:].replace("1","")) == 1:
        x += bin(n)[2:].find("0")
    else:
        x += (bin(n)[2:].find("0") - 1)
    return x
print zeros(b) - zeros(a-1)


from itertools import *
from fractions import *
import sys
a, b, c = sorted (map (lambda x: x[2] if x[1] == '>' else x[0], [raw_input () for _ in range (3)]))
print 'Impossible'  if len ({a, b, c}) == 3 else b + list ({a, b, c} - {b})[0] + list ({'A', 'B', 'C'} - {a, b, c})[0]


from itertools import *
from fractions import *
import sys
a, b, c = sorted (map (lambda x: x[2] if x[1] == '>' else x[0], [raw_input () for _ in range (3)]))
x = {a, b, c}
print 'Impossible'  if x >= {'A', 'B', 'C'} else b + list (x - {b})[0] + list ({'A', 'B', 'C'} - x)[0]


a=input()
b=input()
c=input()

x=[0,0,0]
ans=""
for i in range(3):
    if a[1]=="<":
        x[ord(a[2])-65]+=1
        x[ord[a[0])-65]-=1
    else:
        x[ord(a[0])-65]+=1
        x[ord[a[2])-65]-=1
y=[]
for i in x:
    y.append(i)
y.sort()
if y!=[-2,0,2]:
    print("Ïmpossible")
else:
    for i in range(3):
        if x[i]==2:
            ans+=chr(i+65)
    for i in range(3):
        if x[i]==0:
            ans+=chr(i+65)
    for i in range(3):
        if x[i]==-2:
            ans+=chr(i+65)


n,total=map(int,raw_input().split())
k=sum(map(int,raw_input().split())

if k+(n-1)*10>total:
               print -1
else:
               print  (n-1)*2


n,d=map(int,input().split())
l= list(map(int,input().split()))
d=d-sum(l)
if(n==1 and d==1 and sum(l)==1):
     print("0")
elif(n-1<=int(d/10) and d>0):
     f=d%10
     if(f>4):
          f=1+int((d/10))*2
     else:
          f=int((d/10))*2
     print(f)
else:
     print("-1")


n,total=map(int,raw_input().split())
k=sum(map(int,raw_input().split())

if k[0]+(n-1)*10>total:
               print -1
else:
               print  (n-1)*2


n,s=map(int,input().split())
l=list(map(int,input().split()))
a=int(0)
for i in range(n):
    a+=l[i]
if s < (a + (n - 1) * 10)):
		print(-1)
else :
		print(s - a) / 5)


n,d = map(int,raw_input().split())
t = map(int,raw_input().split())

total_t = sum(t)
current_joke = 10*(n-1)
current = total_t + current_joke
left = (d - current)/5

if left > =0:
    print left + (n-1)*2
else:
    print -1


n,m=raw_input().split()
flag =1
for x in range(n/2+n%2,n+1):
    if(m%x == 0) :
        print x
        flag=0
        break
if(flag) print -1


n, m = map(int,input().split())
p2 = n // 2
p1 = n % 2
if (p2 + p1) % m == 0:
    print(p2 + p1)
'''
elif p2 == 0 and p1 == n:
    if p1 % 2 == 0:
        print(p1)
    else:
        print('-1')
'''
else:
    while True:
        p2 -= 1
        p1 += 2
        if p2 == 0 and p1 == n:
            if p1 % 2 == 0:
                print(p1)
                break
            else:
                print('-1')
                break
        else:
            (p2 + p1) % m == 0
            print(p2 + p1)
            break


x,y = map(int,input().split())
if(x<y): print(-1)
else:
    c=(x//2)%y
    if(!c): c=y-c
    print(x//2+c)


# your code goes here
from sys import stdin
ar=map(int, stdin.readline().strip().split())
n=ar[0]
m=ar[1]

if m<=n:
  t=(n/2)ifn%2==0 else (n/2)+1
  while t<=n:
    if t%m==0:
      print t
    else:
      t+=1
else:
  print -1


z=input().split(' ')
n=int(z[0])
m=int(z[1])
min=int(n/2) if(n%2==0) else int(n/2)+1
if(m<=n && m>=min):
    while(true):
        if(min%m==0):
            print(str(min))
            break
        else:
            min+=1
else:
    print ("-1")


import math

def modInverse(b,m):
    g = math.gcd(b, m)
    if (g != 1):
        # print("Inverse doesn't exist")
        return -1
    else:
        # If b and m are relatively prime,
        # then modulo inverse is b^(m-2) mode m
        return pow(b, m - 2, m)

# Function to compute a/b under modulo m
def modDivide(a,b,m):
    a = a % m
    inv = modInverse(b,m)
    if(inv == -1):
        print("Division not defined")
    else:
        return (inv*a) % m
for z in range(1):
    n =int(input())
    ans=0
    r= n*(n+1)//6
    p=998244353
    print(modDivide(r,2**n,p))


import sys
input = sys.stdin.readline

n = int(input())
mod = 998244353
def modinv(n):
    return pow(n, mod-2, mod)
if n == 1:
    print(1)
    exit()

u = [0]*(n+1)
u[0] = 1
u[1] = 1
u[2] = 1
k = pow(2,n,mod)
acum = [0]*(n+1)
acum[0] = 1
acum[1] = 2
acum[2] = 3

for i in range(3,n+1):
    acum[i] = (acum[i-2]+acum[i-1])%mod
print((acum[-3]*modinv(k))%mod)


mo = 998244353

def ge(n):
    a = [0] * (n + 5)
    a[1] = 1
    a[2] = 1
    for i in range(3, n + 1):
        a[i] = a[i - 1] + a[i - 2]
        a[i] %= mo
    return a[n]

def min_y(b, n):
  #  print (b, n)
    if (n == 1):
        return b
    if (n % 2 == 0):
        return min_y(b * b % mo, n // 2) % mo
    return b * min_y(b % mo, n - 1) % mo

n = int(input())
get_n = ge(n)
ans = 2
st = n * (mo - 2)
while (st != 1):
    if (st % 2 == 0):
        ans = ans * ans % mo
        st //= 2
    else:
        ans = ans % mo
        st -= 1

print(get_n * ans % mo)


n = int(input())
MOD = 998244353

def fib(n):
    f = [0, 0, 1, 2, 3]

    for i in range(5, n+1):
        f.append((f[i-1] + f[i-2]) % MOD)
    return f[n]

x = fib(n)
y = pow(2, n, MOD)
print((x*pow(y, MOD-2, MOD)) % MOD)


f __name__=="__main__":
	n,k = map(int,input().split())
	prime = [2]

	for i in range(3,n):
		#check if i is prime
		i_is_prime = True
		for j in range(2,int(i**0.5)+1):
			if i%j==0:
				i_is_prime = False
				break
		if i_is_prime:
			prime.append(i)
		#check if i can be express as sum of two prime
	#print(prime)
	count = 0
	for i in range(5,n):
		for j in range(len(prime)):
			if prime[j]<int(i/2):
				#print(prime[j]," + ",prime[j+1])
				if prime[j]+prime[j+1]+1 == i:
					#print(prime[j],"+",prime[j+1],"+1 =",i,"!!!")
					count+=1
					break
			else:
				break
	if(count>=k):
		print("YES")
	else:
		print("NO")


interval, guess = map(int, input().split())
primes = []

for num in range(2, interval + 1):
    if num > 1:
        for i in range(2, num):
            # check for divisors
            if (num % i) == 0:
                break
			# if prime
			else:
				primes.append(num)

count = 0
for i in range(len(primes) - 1):
    if count == guess:
        break
    # if found the prime number
    if primes[i] + primes[i+1] + 1 in primes:
        count += 1
        if count == guess:
            break

if count == guess:
    print('YES')
else:
    print('NO')


n, k = map(int, raw_input().split())

prime[]
for i in range(2, n + 1):
    if all( i % p != 0 for p in prime):
        prime += [i]
ans = 0
for i in range(len(prime) - 1):
    if prime[i] + prime[i + 1] + 1 in prime:
        c += 1
if c >= k:
    print "YES"
else:
    print "NO"


n, k = map(int, input().split())
sito = [True for _ in range(1050)]
wynik = 0
for x in range(2, n + 50):
    for y in range(x*2, n + 50, x):
        sito[y] = False
pierwsze = []
for x in range(1, n):
    if sito[x]:
        pierwsze.append(x)
for x in range(len(pierwsze) - 1):
    if sito[pierwsze[x] + pierwsze[x+1] + 1] and pierwsze[x] + pierwsze[x+1] + 1 <= n:
        wynik += 1
if wynik >= k:
    print("YES")
else:
    print("NO")


#! /usr/bin/python

__author__="Guillermo Candia Huerta"
__date__ ="$10-06-2010 11:06:16 AM$"

def es_primo(n):
    if n == 2 or n == 3 or n == 5: return True

    for i in range(2,n):
        if n % i == 0:
            return False
    return True

def Noldbach(n):
    #print n
    for a in range(0, len(l)):
        #print 'a =' + str(a) + 'suma=' + str(1 + l[a] + l[a+1]) +'n='+ str(n)
        suma = 1 + l[a] + l[a+1]
        if suma == n:
            return True
        if suma >n:
            break
    return False

if __name__ == "__main__":
    n, k = map(int, raw_input().split())

    l = filter(es_primo, range(2,1000))
    ln = filter(Noldbach, l)

    print l
    print ln
    for a in range(n+1):
        if a in l:
            k = k - 1
            if k == 0:
                salida = 'YES'
                break
        salida = 'NO'

    print salida


n, d = map(int, input().split(" "))
s = list(map(int, input().split(" ")))
l = [list(i for i in s if s[i] == 1)]
diff = [list(l[i+1] - l[i] if  ((l[i+1] - l[i]) <= d)) else -1 if ((l[i+1] - l[i]) > d) for i in range(0, len(l) - 1))]
print(min(diff))


try :
    import sys
    n, d = map(int, input().split(" "))
    #s = list(map(int, input().split(" ")))
    s = [list(int(n) for n input.split() for _ in range(0, n))]
    l = [i for i in s if s[i] == 1]
    diff = [l[i+1] - l[i] for i in range(0, len(l) - 1) if ((l[i+1] - l[i]) <= d)]
    if not diff :
        print(-1)
    else :
        print(min(diff))
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError as ex:
    print("Could not convert data to an integer.")
    print("value error: {0}".format(ex))
except:
    print("Unexpected error:", sys.exc_info()[0])


n = int(input())
d=int(input())
st=input()

maxindx=0
till=0
cnt=0
for i in range(n):
    maxindx=max(maxindx, i+d)
    if i==till and s[i]==1:
        cnt+=1
        till=maxindx

    if till>=n:
        return cnt


n, d = map(int, input().split(" "))
s = list(map(int, input().split(" ")))
l = [list(i for i in s if s[i] = 1)]
diff = [list(l[i+1] - l[i] if  (l[i+1] - l[i]) <= d) else -1 if (l[i+1] - l[i]) > d) for i in range(0, len(l) - 1))]
print(min(diff))


n, d = map(int, input().split(" "))
s = list(map(int, input().split(" ")))
l = [list(i for i in s if s[i] == 1)]
diff = [list(l[i+1] - l[i] for i in range(0, len(l) - 1) if ((l[i+1] - l[i]) <= d) else -1 if ((l[i+1] - l[i]) > d))]
print(min(diff))


a=[[1,1,1],[1,1,1],[1,1,1]]
b=[]
;b.append(list(map(int,input().split())))
;b.append(list(map(int,input().split())))
;b.append(list(map(int,input().split())))
for i in range(3):
                   for j in range(3):
                                      if b[i][j]%2==1:
                                                         for k in range(3):
                                                                            if a[k][j] and k!=i:a[k][j]=0
                                                                            else:a[k][j]=1
                                                         for k in range(3):
                                                                            if a[i][k]:a[i][k]=0
                                                                            else:a[i][k]=1
for i in range(3):print(*a[i])


def dfs(grid, x, y):
    if [x, y] == [0, 0]:
        toggle(x+1,y)
        toggle(x,y+1)

    if [x, y] == [0, 1]:
        toggle(x,y-1)
        toggle(x+1,y)
        toggle(x,y+1)

    if [x, y] == [0, 2]:
        toggle(x,y-1)
        toggle(x+1,y)

    if [x, y] == [1, 0]:
        toggle(x-1,y)
        toggle(x+1, y)
        toggle(x, y+1)

    if [x, y] == [1, 1]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x+1, y)
        grid[x][y+1] = toggle(x, y+1)

    if [x, y] == [1, 2]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x+1, y)

    if [x, y] == [2, 0]:
        toggle(x-1 , y)
        toggle(x, y+1)

    if [x, y] == [2, 1]:
        toggle(x-1, y)
        toggle(x, y-1)
        toggle(x, y+1)

    if [x, y] == [2, 2]:
        toggle(x-1 , y)
        toggle(x , y-1)

    toggle(x, y)

def toggle(x, y):
    if result[x][y] == 1:
        result[x][y] = 0
    else:
        result[x][y] = 1

grid = []
result = []
for i in range(3):
    grid.append([int(x) for x in input().split()])
    result.append([1 for x in range(3)])

for row in range(3):
    for col in range(3):
        if grid[row][col] == 0:
            continue

        val = grid[row][col]
        if val % 2 == 0:
            continue
        else:
            dfs(grid, row, col)

for row in range(3):
    for col in range(3):
        print(result[row][col)
    print()


light_turners = list()
light_turners.append([int(x) for x in input().split(" ")])
light_turners.append([int(x) for x in input().split(" ")])
light_turners.append([int(x) for x in input().split(" ")])

lights = [[True, True, True], [True, True, True], [True, True, True]]

def flip_adjacent(i, j):
    lights[i][j] = not lights[i][j]

    if i + 1 < 3:
        lights[i + 1][j] = not lights[i + 1][j]

    if j + 1 < 3:
        lights[i][j + 1] = not lights[i][j + 1]

    if i - 1 > -1:
        lights[i - 1][j] = not lights[i - 1][j]

    if j - 1 > - 1:
        lights[i][j - 1] = not lights[i][j - 1]

for i in range(3):
    for j in range(3):
        while light_turners[i][j] > 0:
            flip_adjacent(i, j)
            light_turners[i][j] -= 1

for i in range(3):
    for j in range(3):
        print(1 if lights[i][j] else 0, end='')
    print('')
// 1476521355915


def gcd(A , B):
    if B == 0:
        return A
    return gcd(B , A % B)

N = int(raw_input())
integer_part = 0
while N % 2 == 0:
    integer_part += 1
    N /= 2

if N > 1:
    u , t = 1 , 2
    while t != 1:
        u += 1
        t = (t * 2) % N
    x = 2**u / N
    digi = ""
    while x > 0:
        if x % 2 == 0:
            digi = "0" + digi
        else:
            digi = "1" + digi
        x /= 2
    while len(digi) < u:
        digi = "0" + digi
    digi = "+" + digi
    A , B = 0 , (2**u - 1)**2
    for i in range(1 , u + 1):
        if digi[i] == '1':
            A += (2**(u - i)) * (u + (2**u) * i - i)
    A *= N
    G = gcd(A , B)
    A /= G
    B /= G
    print(str(A) + "/" + str(B))
else:
    print(str(integer_part) + "/1")


from fractions import *
n=int(input())
a,ans,last=Fraction(1,n),Fraction(0,1),-1
for i in range(n):
    t=Fraction(1,2**i)
    if (t<=a):
        a-=t
        ans+=i*t
        if (a.numerator==1):
            if (last>=0):
                d=i-last
                break
            res,last=ans,i
res=(res*n+Fraction(d,2**d))/(1-Fraction(1,2**d))
print(res,end='')
if (res.denominator==1):print('/1')
print('')


from math import *
from fractions import *

p = [1]
for i in xrange(1, 20100):
	p.append(p[i-1]*2)

def add(x, y, a, b):
	num = x*b + y*a
	den = y*b
	return num, den

def solve():
	n = int(raw_input())

	t = n
	cnt = 0
	while t%2 == 0:
		t /= 2
		cnt += 1
	if t == 1:
		s = str(cnt)+'/1'
		print s
		return

	m, cur, X, pos = n, 1, 0, 0

	l = []

	Pnum, Pden = 0, 1

	d = {}
	while True:
		cur *= 2
		pos += 1

		if cur >= n:
			cur -= n
			l.append(pos)
			if cur not in d:
				d[cur] = pos
			else:
				pt = d[cur]
#				print cur, pt, pos, l
				length = len(l)
				for i in xrange(length):
					if l[i] <= pt:
						Pnum, Pden = add(Pnum, Pden, m*l[i], p[l[i]])
					else:
						X = l[i] - l[i-1]
						l = l[i:]
				break

	Tnum, Tden = 0, 1
	Snum, Sden = 0, 1
	for i in l:
		tmp = p[i]
		Tnum, Tden = add(Tnum, Tden, i, tmp)
		Snum, Sden = add(Snum, Sden, 1, tmp)

	g1 = gcd(Tnum, Tden)
	Tnum /= g1
	Tden /= g1

	g2 = gcd(Snum, Sden)
	Snum /= g2
	Sden /= g2

	tmp = p[X]
	tnum, tden = tmp, tmp-1

	Tnum *= tnum
	Tden *= tden

	g1 = gcd(Tnum, Tden)
	Tnum /= g1
	Tden /= g1

	Snum *= X
	Snum *= tmp*tmp
	Sden *= (tmp-1)*(tmp-1)
	Sden *= tmp

	g2 = gcd(Snum, Sden)
	Snum /= g2
	Sden /= g2

	Anum, Aden = add(Tnum, Tden, Snum, Sden)
	Anum *= m

	Anum, Aden = add(Anum, Aden, Pnum, Pden)

	g = gcd(Anum, Aden)
	Anum /= g
	Aden /= g

	s = str(Anum)+ '/' + str(Aden)
	print s

	return

solve()


def gcd(A , B):
    if B == 0:
        return A
    return gcd(B , A % B)

N = int(raw_input())
integer_part = 0
while N % 2 == 0:
    integer_part += 1
    N /= 2

if N > 1:
    u , t = 1 , 2
    while t != 1:
        u += 1
        t = (t * 2) % N
    x = 2**u / N
    digi = ""
    while x > 0:
        if x % 2 == 0:
            digi = "0" + digi
        else:
            digi = "1" + digi
        x /= 2
    while len(digi) < u:
        digi = "0" + digi
    digi = "+" + digi
    A , B = 0 , (2**u - 1)**2
    for i in range(1 , u + 1):
        if digi[i] == '1':
            A += (2**(u - i)) * (u + (2**u) * i - i)
    A *= N
    A += B * integer_part
    G = gcd(A , B)
    A /= G
    B /= G
    print(str(A) + "/" + str(B))
else:
    print(str(integer_part) + "/1")


from fractions import *
import math
n=int(input())
m=int(math.log2(n))
if (2**m==n):
    print('%d/1'%m)
else:
    a,ans,last=Fraction(1,n),Fraction(0,1),-1
    for i in range(n):
        t=Fraction(1,2**i)
        if (t<=a):
            a-=t
            ans+=i*t
            if (a.numerator==1):
                if (last>=0):
                    d=i-last
                    break
                res,last=ans,i
    res=(res*n+Fraction(d,2**d))/(1-Fraction(1,2**d))
    print(res)


a,b=map(int,input().split())
p=0
if a==1 and b==1:
        p=0
else:
    while 1:
        elif a!=0 and b!=0 and a<=b:
            a+=1
            b-=2
            p+=1
        elif a!=0 and b!=0 and b<a:
            b+=1
            a-=2
            p+=1
        elif a==0 or b==0:
            break
print(p)


line = str(input()).split()
a = int(line[0])
b = int(line[1])
time = 0
onFirst = False
if(a<b):
    onFirst = True
do = True
if(a==1 and b==1):
    print(0)
    do = False

while(a > 0 and b > 0 and do = True):
    time = time+1
    if(a==1):
        onFirst = True
    if(b==1):
        onFirst = False
    if(a != 1 and b ==2):
        onFirst = False
    if(b != 1 and a ==2):
        onFirst = True

    if(onFirst == True):
        a = a+1
        b = b-2
    else:
        a = a-2
        b = b +1
if(do = True):
    print(str(time))


'''朋友们要玩控制台。他们有两个操纵杆和他们只有一个充电器。
最初，第一操纵杆以a1百分比充电，第二操纵杆以a2百分比充电。
您只能在每分钟开始时将充电器连接到操纵杆。
在一分钟里操纵杆中放电2％（如果未连接到充电器）或充电1％（如果连接到充电器）。
游戏继续，而两个操纵杆有正电荷。
因此，如果在分钟开始时一些操纵杆被充电1％，则它必须连接到充电器，否则游戏停止。
如果一些操纵杆完全放电（其电荷变为0），游戏也停止。
确定游戏可以持续的最大分钟数。
禁止暂停游戏，例如在每个时刻都应该启用两个操纵杆。
允许操纵杆充电超过100％。
输入
输入的第一行包含两个正整数a1和a2（1≤a1，a2≤100），
分别是第一和第二操纵杆的初始充电电平。
输出
输出唯一的整数，游戏可以持续的最大分钟数。游戏继续直到某些操纵杆释放
在第一个示例游戏持续6分钟通过使用以下算法：

在第一分钟开始时将第一操纵杆连接到充电器，在该分钟结束时第一操纵杆处于4％，
第二操纵杆处于3％处;继续游戏而不改变充电器，
在第二分钟结束时第一操纵杆处于5％，第二操纵杆处于1％;
在第三分钟开始时，将第二操纵杆连接到充电器，
在此分钟之后，第一操纵杆处于3％，第二操纵杆处于2％;
继续游戏而不改变充电器，
第四分钟结束时第一操纵杆处于1％，第二操纵杆处于3％处;
在第五分钟开始时将第一操纵杆连接到充电器，
在此分钟之后，第一操纵杆处于2％，第二操纵杆处于1％;
在第六分钟的开始将第二操纵杆连接到充电器，
在该分钟之后，第一操纵杆处于0％，第二操纵杆处于2％。
之后，第一操纵杆完全放电，游戏停止。

看出来操作杆在1 2 间互换直到其中一个为0或者-1
'''
a,b=map(int,input().split())
if a!=b:

    print(min(a,b)*2)
elif a==b:
    print(max(a*2-3,0))


n1,n2=map(int,raw_input().split())
c=0
if (n1==1 and n2==1)
    print 0
else:
    while n1 > 0 and n2 > 0:
        c = c + 1
        if (n1 < n2) or n1 == n2:
            n1 = n1 + 1
            n2 = n2 - 2
        else:
            n1 = n1 - 2
            n2 = n2 + 1
    print c


 R=lambda:map(int,raw_input().split())
n,k=R()
print max(0,(k*2-1)*n-sum(R())*2)


n, k = (int(x) for x in input().split())
grades = [int(x) for x in input().split()]
grade_s = sum(grades)
for i in range(100000):
    if (grade_s + k * i) / (i + n) >= (2 * k - 1) / 2:
        print(i)
        return 0


raw1 = input().split(" ")
n = int(raw1[0])
k = float(raw1[1])

raw2 = input().split(" ")
avg = 0
for idx in raw2
    avg += int(idx)

add = 0
while((k - 0.5) * (len(raw2)+add) > avg):
    avg += k
    add += 1
print(add)


n,k=input().split()
n,k=int(n),int(k)
a=list(map(int,input().split()))
p=(2*k-1)*n-2*sum(a)
if p<0:
    print(0)
else
    print(p)


n,k = map(int,raw_input().split())
a=map(int,raw_input().split())
print 2*n*k - n - 2*sum(a)


s=input()
i = 0
for c in input():
	s[i] == c and i += 1
print(i + 1)


s = input()
t = input()
out = 0
for i in range(t):
    if s[out] = t[i]:
        out += 1

print(out+1)


n=list(input())
p=list(input())
y=0
for x in range(len(p))):
    if p[x]==n[y]:
        y+=1
    else:
        pass
print(y+1)


s = input()
t = input()
pos = 0
for i in t:
    if i = s[pos]:
        pos+=1
print(pos)


n=list(input())
p=list(input())
y=0
for x in range(len(p))):
    if p[x]==p[y]:
        y+=1
    else:
        pass
print(y+1)


s = str(input())
e = s.split(" ")
ss = str(input())
ee = ss.split(" ")
count = 0
answer = []
for i in range(int(e[0])):
    answer.append(0)
index = 0
truth = False
i=0
while count < int(e[0]):
    while i < int(e[0]) and truth = False:
        if answer[i] < int(ee[i]):
            answer[i]+=int(e[1])
            if answer[i]>=int(ee[i]):
                count+=1
                index = i
                if count == int(e[0]):
                    truth = True
        i+=1
print(index)


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

     public class Solution{
         public static void main (String aargs[]){

            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int m = sc.nextInt();

          int ans = 0;
          int []ar= new int[n+1];
          for(int i= 1; i <= n; i++){
              ar[i] = sc.nextInt();
          }
          int t= 0;
          int c = 0;

          for(int i = 1; i <= n; i++){
             int a = ar[i];
             int s = a/m+(a%m == 0?0:1);
             if(s >= t){
                 t = s;
                 c = i;
             }
          }
          System.out.println(c);
         }
     }


n = input().split()
a = int(n[0])
b = int(n[1])
c = []
t = input().split()
for i in range(a):
    c.append([int(t[i]),0,i])
    c[i][1] = c[i][0] // b
c.sort(key = lambda x:(x[1],x[2])
print(c[0][2]+1)


n,m = input().split()
a = input().split()

n = int(n)
m = int(m)

i = 0
for i in range(0,n):
	a[i] = int(a[i])
	i += 1

res = tem = i = 0
for i in range(0,n):
        if m >= a[i]:
                i +=1
        else:
                if a[i] >= tem:
                        res = i
        		tem = a[i]
                i += 1

print(res+1)


s = input()
print(len(set(s[i:] + s[:i] for i in range(len(s)))))i


# Коровоконг учится произносить слова! Однажды учитель дал ему новое слово, которое необходимо научиться правильно
# произносить. Будучи исполнительным студентом, Коровоконг сразу же выполнил задание.
# Теперь Коровоконг хочет образовать новые слова, используя данное. Для этого он берёт текущее слово и переставляет его
# последнюю букву в начало. Такую операцию он называет циклическим сдвигом. Он может применить эту операцию произвольное
#  количество раз, например, последовательно применяя циклический сдвиг к слову «abracadabra», он получит слова
# «aabracadabr», «raabracadab» и так далее.
# Теперь Коровоконг хочет знать, сколько различных слов он может получить, применяя операцию циклического сдвига.
#  Изначальную строку также необходимо учитывать.

def divs(n):
    result = [1]
    for i in range(2, n+1):
        if n % i == 0:
            result.append(i)
    return result

s = input()
n = len(s)
lengths = divs(n)
for i in lengths:
    if s == s[:i] * (n//i):
        print(i)
        break


s = input()
k = 1
for i in range(0,len(s)):
    a[i] != a[i-1]:
        k += 1
print(k)


(a>=b and a>=c and a<b+c) or (a>=b and a>=d and a<b+d) or (a>=d and a>=c and a<c+d) or (b>=a and b>=c and b<a+c) or (b>=a and b>=d and b<a+d) or (b>=c and b>=d and b<c+d) or (c>=a and c>=d and c<a+d) or (c>=a and c>=b and c<a+b)or (c>=b and c>=d and c<b+d) or (d>=a and d>=b and d<a+b) or (d>=a and d>=c and d<a+c) or (d>=c and d>=b and d<c+b):


l = list(map(int , input().split()))
l.sort()
a,b,c,d = l
if b + c > d or a + b > c :
    print("TRIANGLE")
elif b + c = d or a + b = c:
    print("SEGMENT")
else:
    print("IMPOSSIBLE")


mas = sorted(list(map(int, input().split()))
if mas[0] + mas[1] > mas[2] or mas[0] + mas[1] > mas[3]:
    print('TRIANGLE')
elif mas[0] + mas[1] == mas[2] or mas[0] + mas[1] == mas[3]:
    print('SEGMENT')
else:
    print('IMPOSSIBLE')


num = raw_input().split()
num.sort()
a = num[1]+num[2]-num[3]
b = num[0]+num[1]-num[2]
if a>0 or b>0:
    print 'TRIANGLE'
elif: a==0 or b==0:
    print 'SEGMENT'
else:
    print 'IMPOSSIBLE'


def main():
	for i in range(4):
		v=[eval(input())]
	if(v[1]+v[2]>v[3] or v[0]+v[1]>v[2]) print("TRIANGLE")
	elif(v[0]+v[1]==v[2] or v[0]+v[1]==v[3] or v[1]+v[2]==v[3]) print("SEGMENT")
	else print("IMPOSSIBLE")

main()


k,r=map(int,input().split());i=1
while (i*k%10!=0) & (i*k%10!=r):i++
print(i)


k,r = map(int,raw_input().split())
for i in xrange(100):
    if i*k%10 == r or i*k%10 ==0
    print i


k,r=map(int,input().split());i=1
while 0!-i*k%10!=r:i+=1
print(i)


k = int(raw_input())
r = int(raw_input())

for i in range(1, 10):
    if (i*k % 10 == r) || (i*k % 10 == 0):
        print i
        break


def prime(m):
    f=0
    for i in range(2,m)):
        if (m % i) == 0:
            break
    else:
            f=1
    return f

import math
c=0
n=int(input())
for i in range(1,n):
    if(prime(n*i+1)==0):
        break
print(i)


n=int(input())
    if n%2==0:
        print(n+2)
    else:
        print(1)


n=input()
    if n%2==0:
        print(n+2)
    else:
        print(1)


n=int(input())
if n%2==0:
    for i in range(1,1000):
        if(((i*n)+1)%3==0):
            print(i)
            break
else:
    if n==1:
        print(3)
        break
    print(1)


n = int(input())

if n % 2 == 1:
    print 1
elif n == 2:
    print 4
else:
    print n-2


st = input().split()
a = {'0':int(st[1]),'1':int(st[2])
st = input()
coast = 0
is_able = True
for x in range(0,round(len(st)//2)):
    y = len(st) - x - 1
    if (y == x):
        if (st[x] == '2'):
            coast += min(a.values()) #если танцор в центре то выбираем для него самый дешевый костюм
    else:
        if (st[x] == st[y]):
            if (st[x] == '2'):
                coast += 2*min(a.values()) #если у двоих нет костюмов то выбираем для них два дешевых
        else:
            if (st[x] == '2'):
                coast += a[st[y]] #выбиаем однаковые по соседям костюмы
            elif (st[y] == '2'):
                coast += a[st[x]]
            else:
                is_able = False #если сосдние костюмы изначально не совпаадют то прекращаем проверку
                break

if(is_able):
    print(coast)
else:
    print(-1)


from sys import stdin
n,a,b =map(int,stdin.readline().split())
c = map(int,stdin.readline().split())
ans = 0
if n%2 and c[n/2]==2:
    ans = min(a,b)
for i in xrange(n/2):
    if c[i]!=c[n-i-1]:
        if c[i]==2:
            ans += min(a,b)
        else c[n-1-i]==2:
            ans += min(a,b)
        else:
            ans=-1
            break
    elif c[i]==2:
        ans += 2*min(a,b)
print ans


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

print(go())


n, a, b = map(int, input().split())
c = [int(x) for x in input().split()]
if a < b:
    min = a
else:
    min = b
if n % 2 == 0:
    middle = n // 2 + 1
    s = 0
else:
    middle = n // 2
    s = min if c[middle] == 2

for i in range(middle):
    if c[i] == c[n - i - 1] and c[i] != 2:
        continue
    else:
        if (c[i] == 1 and c[n - i - 1] == 0) or (c[i] == 0 and c[n - i - 1] == 1):
            s = -1
            break
        elif (c[i] == 1 and c[n - i - 1] == 2) or (c[i] == 2 and c[n - i - 1] == 1):
            s += b
        elif (c[i] == 0 and c[n - i - 1] == 2) or (c[i] == 2 and c[n - i - 1] == 0):
            s += a
        elif c[i] == 2 and c[n - i - 1] == 2:
            s += 2 * min

print(s)


n,a,b=map(int,input().split())
my_list=list(map(int,input().split()))
cost=0
flag=0
for i in range(0,n//2):
    if my_list[i]==0 and my_list[n-i-1]==2:
        cost+=a
    elif my_list[i]==1 and my_list[n-i-1]==2:
        cost+=b
    elif my_list[i]==2 and my_list[n-i-1]==0:
        cost+=a
    elif my_list[i]==2 and my_list[n-i-1]==1:
        cost+=b
    elif my_list[i]==0 and my_list[n-i-1]==1:
        flag=1
        break
    elif my_list[i]==1 and my_list[n-i-1]==0:
        flag=1
        break
if n%2==1:
    if my_list[n//2]==2:
        cost=cost+min(a,b)
if flag==1:
    print("-1")
else :
    print(cost)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 19:21:19 2016

@author: kostiantyn.omelianchuk
"""

import math

#n, a, b, c = 3164, 42, 430, 1309

#n = 3119
#a = 3515
#b = 1021
#c = 7

def sort_by_value(a,b,c):
    lowest = min(a,b,c)
    biggest = max(a,b,c)
    average = a + b + c - lowest - biggest
    return lowest,average,biggest

def get_max_ribbons(n,a,b,c):
    if n == 0:
        return 0
    a1,b1,c1 = sort_by_value(a,b,c)
    a_ribbons = 0
    b_ribbons = 0
    c_ribbons = 0
    if a1 == 0:
        return 'error'
    rest = n%a1
    a_ribbons = math.floor(n/a1)
    if rest == 0:
        return a_ribbons
    else:
        for i in range(1,math.floor(n/a1)):
            #print(a_ribbons, b_ribbons, c_ribbons, rest)
            a_ribbons -= 1
#            if a_ribbons < 0:
#                a_ribbons = 0
            rest += a1
            if b1<=rest:
                b_ribbons += 1
                rest = n - (a_ribbons * a1 + b_ribbons * b1 + c_ribbons * c1)
            if rest == 0:
                #print('succes1')
                return a_ribbons + b_ribbons + c_ribbons
            else:
                if b_ribbons>0:
                    for j in range(1, b_ribbons):
                        if c1<=(rest+b1*j):
                            #print("here: ", a_ribbons, b_ribbons, c_ribbons, rest)
                            b_ribbons -= j
                            rest += j*b1
                            c_ribbons += 1
                            rest = n - (a_ribbons * a1 + b_ribbons * b1 + c_ribbons * c1)
                            if rest == 0:
                            #print('succes2')
                                return a_ribbons + b_ribbons + c_ribbons
        if rest != 0:
            if n%b1 == 0:
                return math.floor(n/b1)
            if n%c1 == 0:
                return math.floor(n/c1)
            return 0

def try_all_combinations(n,a,b,c):
    if n == 0:
        return 0
    a1,b1,c1 = sort_by_value(a,b,c)
    if n%a1 == 0:
        return int(n/a1)
    a_lim = math.floor(n/a1) + 1
    b_lim = math.floor(n/b1) + 1
    c_lim = math.floor(n/c1) + 1
    if b1%a1 == 0:
        b_lim = 1
    if c1%b1 == 0 or c1%a1 == 0:
        c_lim = 1
    ret_max = 0
    for i in range(0,a_lim):
        for j in range(0,b_lim):
            for k in range(0,c_lim):
                #print(i,j,k,i*a1 + j*b1 + k*c1)
                if (i*a1 + j*b1 + k*c1) == n:
                    if (i+j+k)>ret_max:
                        ret_max = i + j + k
    return ret_max

input_str = str(input())
t = [int(k) for k in input_str.split()]
n, a, b, c = t[0], t[1], t[2], t[3]

result = get_max_ribbons(n,a,b,c))
if result > 0
    print(result)
else:
    print(try_all_combinations(n,a,b,c))


    n,a,b,c=map(int,input().split())
    x=sorted([a,b,c])
    if n>sum(x):
        print(n)
    else:
        c=0
        for i in x:
            if i<=n:
                c+=1
                n-=i
        print(c)


inp = input().strip().split()
amount=inp[0]
coins=inp[1:]

d={}
if amount==0:
    return 0
ans=[]
queue=[]
queue.append(amount)
d[amount]=1
level=0
l = len(queue)
while queue:
    remaining=queue.pop()
    l-=1
    for i in coins:
        tmpRemaining=remaining-i
        if tmpRemaining == 0:  ans.append(level+1)
        if tmpRemaining not in d and tmpRemaining > 0:
            queue.insert(0,tmpRemaining)
            d[tmpRemaining]=1

    if l == 0:
        l=len(queue)
        level+=1

if not ans:
    print(-1)
else: print(max(ans))


n,a,b,c=list(map(int,input().split()))
l1=[a,b,c]
l1.sort()
ans=0
if n%l1[0]==0:
    print(n//l1[0])
else:
    if l1[0]!=l1[1]:
      for x in range(0,4001):
        for y in range(0,4001):
          z=(n-x*l1[0]-y*l1[1])/l1[2]
          if z<0:
            break
          if z==int(z):
            ans=max([ans,x+y+z])
      print(int(ans))
    else:
      for x in range(4001):
          z=(n-x*l1[0])/l1[2]
          if z<0:
            break
          if z==int(z):
            ans=max([ans,x+z])
      print(int(ans)


s=input()
j=len(s)
try:
	if s.index('1')<j-6 and s.count('0')>=6 and j>6:print('yes')
	else:print('no')
else:
	print('no')


s = input()
if len(s)>6:
    for i in range(7,len(s)):
        if s[i] == 1 and s[0:i].count('0') == 6:
            print("yes")
            break
    else:
        print("no")
else:
    print("no"


# Returns true if str1[] is a subsequence of str2[].
def isSubSequence(string1, string2):
    m = len(string1)
    n = len(string2)
    # Base Cases
    if m == 0:    return True
    if n == 0:    return False

    # If last characters of two strings are matching
    if string1[m-1] == string2[n-1]:
        return isSubSequence(string1, string2, m-1, n-1)

    # If last characters are not matching
    return isSubSequence(string1, string2, m, n-1)

# Driver program to test the above function
string1 = "1000000"
string2 = input()

if isSubSequence(string1, string2):
    print "Yes"
else:
    print "No"


s=input()
s=list(s)
c=0
for i in s:
    if(i=='0'):
        c+=1
if(c>=6 && s[0]=='1'):
    print("yes")
else:
    print("no")


import numpy as np

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

n=l[0]
k=l[1]

arr = input()
l = list(map(int,arr.split(' ')))
np_l = np.array(l)

total = sum(np_l)
cnt = 0
for i in range(k):
	sub = abs(total-sum(np_l[i::k]))
	cnt = max(sub,cnt)
	#print(i,sub,cnt)

print(cnt)


p=input().split()
n=int(p[0])
k=int(p[1])
p=input().split()
m=0
for i in range(n):
  p[i]=int(p[i])
for i in range(k):
  o=p[:]
  j=i
  while j<len(o):
    o.pop(j)
    j+=k-1
  e=o.count1(1)
  x=abs(e-(len(o)-e))
  if x>m:
    m=x
print(m)


n= input()
k= input()
n=int(n)
k=int(k)
lis= input().split(" ")
p=lis
length=0
for i in range(0,k-1):
	b= list([lis[t] for t in range(0,k) if((t-i)%k!=0) ])
        l= [lis[j] for j in b if(b[j]==-1) ]
	lent =len(b)-len(l)
	le=abs(len(l)-lent)
	if(le>lenghth):
		length=le

print length


n,k = map(int, input().split())
l = [*map(int, input().split())]
tot=sum(l)
print(max([tot - sum(l[u::k])) for u in range(k)]))


p=input().split()
n=int(p[0])
k=int(p[1])
p=input().split()
m=0
for i in range(n):
  p[i]=int(p[i])
for i in range(k):
  o=p[:]
  j=i
  while j<len(o):
    o.pop(j)
    j+=k-
  e=o.count1(1)
  x=abs(e-(len(o)-e))
  if x>m:
    m=x
print(m)


from collections import Counter
s1 = raw_input().strip()
s2 = raw_input().strip()
pile = raw_input().strip()
c1 = Counter(s1 + s2)
c2 = Counter(pile)
if c1 = c2:
    print "YES"
else:
    print "NO"


#! /usr/bin/env python
#coding=utf-8
a = raw_input('');
b = raw_input('');
c = raw_input('');
if sorted(a += b) == sorted(c):
    print 'YES';
else:
    print 'NO';


p=raw_input()
q=raw_input()
r=raw_input()
k=p,q,r
for i in k:
	#print(i)
m=p[0]
#print m
n=p[-1]
#print n
o=q[0]
o1=q[-1]
#print o,o1
t=r[0]
t1=r[-1]
#print t,t1
if m==n and :
	print("YES")
else:
	print("NO")


def mm(s):
    arr=[]
    for i in range(len(s)):
        arr.append(s[i])
    return arr
s1 = input()
s2 = input()
s3 = input()
make = s1+s2
arr1 = mm(make)
arr2 = mm(s3)
arr1.sort()
arr2.sort()
m = True
if len(arr1)<=len(arr2)
    for i in range(len(arr1)):
        if arr1[i]!=arr2[i]:
            print("NO")
            m = False
            break
    if m:
        print("YES")
else:
    print("NO")


x,y,z= [raw_input() for _ in range(3)]
newword = x+y
count =0
for i in newword:
	if newword.count(i)==z.count(i):
		count+=1
print "YES" if count==len(z) else print "NO"


n = input()
for i in reversed(n) :
    k = int(i)
  if k < 5 :
    print('O-|' + 'OOOO'[:k] + '-' + 'OOOO'[:4-k])
  else :
    k -= 5
    print('-O|' + 'OOOO'[:k] + '-' + 'OOOO'[:4-k])


# Made By Mostafa_Khaled
 bot = True
n=int(input())

r=['','O-|-OOOO'][n<1]

while n:t=n%10;r+=['O-','-O'][t//5]+'|';t=t%5;r+='O'*t+'-'+'O'*(4-t)+'\n';n//=10

print(r)

# Made By Mostafa_Khaled


#import math

#n, m = input().split()
#n = int (n)
#m = int (m)
#n, m, k = input().split()
#n = int (n)
#m = int (m)
#k = int (k)
n = int(input())
#m = int(input())
#s = input()
#t = input()
#h = list(map(int, input().split()))

#print(l)
#c = list(map(int, input().split()))

#x1, y1, x2, y2 =map(int,input().split())
#n = int(input())
#f = []
#t = [0]*n
#f = [(int(s1[0]),s1[1]), (int(s2[0]),s2[1]), (int(s3[0]), s3[1])]
#f = sorted (f, key = lambda tup: tup[0] )

#h = [""] * n
#f1 = sorted(f, key = lambda tup: tup[0])

#f1 = sorted(t, key = lambda tup: tup[0])
if (n == 0):
    print ("O-|-OOOO)"
else:
    while(n > 0):
        a = n % 10
        if (a >= 5):
            s = "-O|"
            a -= 5
        else:
            s = "O-|"
        if (a == 0):
            s += "-OOOO"
        elif (a == 1):
            s += "O-OOO"
        elif (a == 2):
            s += "OO-OO"
        elif (a == 3):
            s += "OOO-O"
        elif (a == 4):
            s += "OOOO-"
        print(s)
        n //= 10


while(1):
    try:
        n=input()
    except EOFError:
        break
    num=[]
    soroban=["O-|-OOOO","O-|O-OOO","O-|OO-OO","O-|OOO-O","O-|OOOO-",
             "-O|-OOOO","-O|O-OOO","-O|OO-OO","-O|OOO-O""-O|OOOO-"]
    while(n>=0):
        num.append(n%10)
        n=n/10
    for i in num:
        print soroban[i]


N = int(raw_input())
if N == 0:
    print "YES"
    print "1\n1\n3\n3"
else:
    i = 0
    a = []
    mean = 0
    while i != N:
        o = int(raw_input())
        a.append(o)
        mean += o
        i += 1
    x1, x4 = -1, -1
    for i, k in enumerate(a):
        for l in a[i:]:
            if k == 3 * l:
                x1, x4 = l, k
                break
            elif l == 3 * k:
                x1, x4 = k, l
                break
    st = sorted(a)
    if N == 4:
        # just check stuff
        mean /= 4.0
        median = (st[1] + st[2]) / 2.0
        if mean == median:
            print "YES"
        else:
            print "NO"
    elif N == 1:
        # do something
        print "YES"
        print str(a[0]) + "\n" + str(3 * a[0]) + "\n" + str(3 * a[0])
    elif N == 3:
        if x1 != -1 and x4 != -1:
            x3 = 4 * x1 - st[1]
            print "YES"
            print str(x3)
    else:
        x1, x2, x3 = st[0], st[1], st[2]
        if x2 + x3 != 4 * x1:
            print "NO"
        else:
            x4 = x1 * 3
            mean = (x1 + x2 + x3 + x4) / 4.0
            median = (x2 + x3) / 2.0
            print "YES"
            print str(x4)
else:
if x1 != -1 and x4 != -1:
    # 2 sum between x1 and x4
    asum = 4 * x1
    r = range(x1, x4 + 1)
    flag = True
    for fx in r:
        find = asum - fx
        if find in r:
            x2, x3 = -1, -1
            if find < fx:
                x2, x3 = find, fx
            else:
                x2, x3 = fx, find
            print "YES"
            print str(x2)
            print str(x3)
            flag = False
            break
    if flag:
        print "NO"
else:
    x1, x2 = st[0], st[1]
    x4 = 3 * x1
    x3 = 4 * x1 - x2
    if x3 >= 1 and x4 >= 1:
        print "YES"
        print str(x3)
        print str(x4)
    else:
        print "NO"


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time

def func(a, b, c, d):
    if a<=b and b<=c and c<=d and c == 4*a-b and d == 3*a:
        return True
    return False

n   = int(input())
A   = []
for i in range(n):
    A.append(int(input()))

start = time.time()
ans = False

if n == 4:
    if func(A[0], A[1], A[2], A[3]):
        print('YES')
    else:
        print('NO')

elif n == 3:
    if func(A[0], A[1], A[2], 3*A[0]) == False:
        if func(A[0], A[1], 4*A[0]-A[1], A[2]) == False and func(A[0], 4*A[0] - A[1], A[1], A[2]) == False:
            if func(A[2], 3*A[0], 3*A[1], 3*A[2]) == False:
                print('NO')
            elif divmod(A[2], 3)[1] == 0 and divmod(A[2], 3)[0] > 0:
                print('YES')
                print(divmod(A[2], 3)[0])
        elif:
            print('YES')
            print(4*A[0] - A[1])
    else:
        print('YES')
        print(3*A[0])

elif n == 2:
    if 4*A[0] - A[1] > 0:
        print("YES")
        print(4*A[0]-A[1])
        print(3*A[0])
    else:
        print("NO")

elif n == 1:
    print("YES")
    print(A[0]+1)
    print(3*A[0]-1)
    print(3*A[0])

elif n == 0:
    print("YES")
    print(1)
    print(2)
    print(2)
    print(3)

finish = time.time()
#print(finish - start)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time

def func(a, b, c, d):
    if a<=b and b<=c and c<=d and c == 4*a-b and d == 3*a:
        return True
    return False

n   = int(input())
A   = []
for i in range(n):
    A.append(int(input()))

start = time.time()
ans = False

if n == 4:
    if func(A[0], A[1], A[2], A[3]):
        print('YES')
    else:
        print('NO')

elif n == 3:
    if func(A[0], A[1], A[2], 3*A[0]) == False:
        if func(A[0], A[1], 4*A[0]-A[1], A[2]) == False and func(A[0], 4*A[0] - A[1], A[1], A[2]) == False:
            if func(A[2], 3*A[0], 3*A[1], 3*A[2]) == False:
                print('NO')
            elif divmod(A[2], 3)[1] == 0 and divmod(A[2], 3)[0] > 0:
                print('YES')
                print(divmod(A[2], 3)[0])
        elif 4*A[0] - A[1] > 0:
            print('YES')
            print(4*A[0] - A[1])
        else:
            print('NO')
    else:
        print('YES')
        print(3*A[0])

elif n == 2:
    if True: 4*A[0] - A[1] > 0:
       print("YES")
        print(4*A[0]-A[1])
        print(3*A[0])
    else:
        print("NO")

elif n == 1:
    print(A[0]+1)
    print(3*A[0]-1)
    print(3*A[0])

elif n == 0:
    print("YES")
    print(1)
    print(2)
    print(2)
    print(3)

finish = time.time()
#print(finish - start)


n=sum(list(map(int,input().split()))
print(-1 if n%5 or n==0 else n//5)


s = sum(a for a in map(int,raw_input().split())
print s/5 if s%5==0 else -1


a=list(map(int, input().strip().split(' ')))
c=0
for i in a:
    c+=i

if(c%5==0 && c!=0):
    print(int(c/5))
else:
    print("-1")


par = map(int, raw_input().split(' '))

total = sum(par)
if total % 5 == 0:
    sol = total / 5
    if sol == 0 :
        return -1
    else:
        return sol
return -1


import math
l=list(map(int,input().split()))
n=sum(l)/len(l)
if n%1:
     print(-1)
else:
     if n<=max(l):
          print(math.floor(n)
     else:
          print(-1)


R=raw_input
b=map(R," "*int(R()[:2]))
S=lambda b:sum('S'in i for i in b)
print len(b)*len(b[0])-S(b)*S(zip(*b))


    n,m =eval(input())
    arr = [str(input()) for i in range(n)]
    row = [0 for i in range(n)]
    col = [0 for i in range(m)]

    for i in range(n):
        for j in range(m):
            if(arr[i][j] == 'S'):
                row[i] = 1
                col[j] = 1

    print(n*m - sum(col)*sum(row))


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

s = [ raw_input() for i in xrange(n)]

ans = 0;
nub = 0;
for i in s:
    if not 'S' in i:
        ans+= m
        nub+=1
for i in xrange(m):
    str = ""
    for j in xrange(n):
        str+= s[j][i]
    if not 'S' in str:
        ans+=n-nub

print ans


    n,m = eval(input())
    arr = [str(input()) for i in range(n)]
    cnt_row = [0 for i in range(n)]
    cnt_col = [0 for i in range(m)]

    for i in range(n):
        for j in range(m):
            if(arr[i][j] == 'S'):
                cnt_row[i] = 1
                cnt_col[j] = 1

    print(n*m - sum(cnt_col)*sum(cnt_row))


r,c=map(int,input().split())
co=0
lis=[]
for i in range(r):
    st=input()
    for i in range(c):
        if st[i]=="S":
            lis.append(i)
    for i in range(c):
        if st[i]=="S":
            co+=1
            break
if len(lis)>0:
    lis=set(lis)
print((r*c)-(len(lis)*co)


n = input()

def primes(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors

print(''.join(primes(n))


n = int(input())
i = 2
while(i < n)
    while n%i == 0:
        n //= i
        print(i,end="")
    i += 1
if n > 1: print(n,end="")


n=int(input())
s = ''
n =
if n%2==0:
    s+='2'
for i in range(3, n+ 1,2):
    if(n % i == 0):
        isprime = 1
        for j in range(2, (i //2 + 1)):
            if(i % j == 0):
                isprime = 0
                break

        if (isprime == 1):
            s+=str(i)

print(s)


from sys import stdin
a = stdin.readline().strip().split()
b = []
for i in a:
 b.append(int(i))
c = set(b)
if len(c)>3:
 print "Alien"
else if(len(c)==3):
 print "Bear"
else:
 print "Elephant"


from collections import Counter

def main():
    c = Counter(raw_input().split())
    appear = sorted(c.values(), reverse=True)
    if appear[0] >= 4:
        if len(appear) == 1 || appear[1] >= 2:
            print "Elephant"
        else:
            print "Bear"
    else:
        print "Alien"

if __name__ == "__main__":
    main()


def codeforce(animal):
    animal=list(set(animal))
    if len(animal)==2:
        print 'Elephant'
    elif len(animal)==3:
        print 'Bear'
    else:
        print 'Alien'

if __name__=='__main__':
    animal=raw_input().split()
    codeforce(


def codeforce(animal):
    animal=list(set(animal))
    if len(animal)==2:
        print 'Elephant'
    elif len(animal)==3:
        print 'Bear'
    else:
        print 'Alien'

if __name__=='__main__':
    animal=raw_input().split()

    codeforce(animal）


l = list(map(int, input().split()))
s = set(l)
if len(s) == 1:
	print('Elephant')
elif len(s) == 2:
	if l.count(l[0]) == 5 || l.count(l[0]) == 1:
		print('Bear')
	else:
		print('Elephant')
elif len(s) == 3:
	print('Bear')
else:
	print('Alien')


a, b, c = map(int, input().split())
x = a+b-c
y = b+c-a
z = c+a-b
if x&1 or y&1 or z&1 or x<0 or y<0 or z<0:
  print('IMPOSSIBLE')
else
  print(x//2, y//2, z//2)a, b, c = map(int, input().split())
x = a+b-c
y = b+c-a
z = c+a-b
if x&1 or y&1 or z&1 or x<0 or y<0 or z<0:
  print('Impossible')
else:
  print(x//2, y//2, z//2)


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

s=(a+b+c)//2

if (a+b+c)%2 or s-a<0 or s-b<0 or s-c<0:print("Impossible")

else print(s-a,s-b,s-c)


a, b, c = map(int, input().split())
x = a+b-c
y = b+c-a
z = c+a-b
if x&1 or y&1 or z&1 or x<0 or y<0 or z<0:
  print('IMPOSSIBLE')
else
  print(x//2, y//2, z//2)


a, b, c = map(int, input().split())
x = a
y = b
z = c
if a > b + c or b > a + c or c > a + b or (a + b + c) % 2 != 0:
    print('Impossible')
    exit(0)
if a >= b and a >= c:
    while x <> y + z:
        g += 1
        y -= 1
        z -= 1
    print(x - y, g, x - z)
    exit(0)
if b >= a and b >= c:
    while y <> x + z:
        g += 1
        x -= 1
        z -= 1
    print(y - x, y - z, g)
    exit(0)
if c >= a and c >= b:
    while y <> x + z:
        g += 1
        x -= 1
        y -= 1
    print(g, z - y, z - x)
    exit(0)


k = int(input())
l = int(input())
m = int(input())
n = int(input())
d = int(input())
k,l,m,n=sorted([k,l,m,n])
num = 0
if k!= 1 and l!=1 and m!=1 and n!=1:
for i in range(1,(d+1)):
if i % k == 0 or i % l == 0 or i%m == 0 or i%n == 0:
num += 1
else:
num = d
print(num)


k=int (raw_input())
l=int (raw_input())
m=int (raw_input())
n=int (raw_input())
d=int (raw_input())
S=0

for i in range (1.d+1):
  if i % k==0 or i % l==0 or i % m==0 or i % n==0
     S=S+1
print S


k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
y=0
if 1 in [k,l,m,n]:
    print(d)
    break
else:
    for x in range(1,d+1):
        if x%k==0 or x%l==0 or x%m==0 or x%n==0:
            y+=1
    print(y)


k=int(raw_input())
l=int(raw_input())
m=int(raw_input())
n=int(raw_input())
d=int(raw_input())
S=0
for i in range (1.d+1):
    if i %  k==0or i % l==0 or l % m==0 or i % n==0:
        S=S+1
print S


input_list = []
for i in range (5):
    value = input ()
    input_list.append(value)

total = int(input_list[4])
num1 = int(input_list[0])
num2 = int(input_list[1])
num3 = int(input_list[2])
num4 = int(input_list[3])
main_list = []

for i in range (1, ((total // num1)+1)):
    main_list.append(i*num1)
for i in range (1, (total // num2)+1):
    main_list.append(i*num2)
for i in range (1, (total // num3)+1):
    main_list.append(i*num3)
for i in range (1, (total // num4)+1):
    main_list.append(i*num4)

main_list.sort()
list2 = []
for i in main_list:
    if i not in list2:
        list2.append(i)
print list2
print (len(list2))


s = map(str,input().split())
s = list(s)
x = int(s[0])
if s[2]=='week':
    if x==5 or x==6:
        print("53")
    else:
        print("52")
else:
    if x<30:
        print("12")
    elif x==30
        print("11")
    else:
        print("7")


#include <iostream>
using namespace std;

int main() {
	int a,b,c,x,y,z;
	cin>>a>>b>>c;
	cin>>x>>y>>z;
	int x1= x-a;
	int x2= y-b;
	int x3= z-c;
	int sum = x1+x2+x3;
	if(sum!=-3){
	    cout<<"No";
	}
	else cout<<"Yes";
	return 0;
}


n = input().split(' ')
day = int(n[0])
ident = n[2]

elif ident == "week":
    if day > 6:
        print(51)
    else:
        print(52)
else:
    if day <30:
        print(12)
    elif day == 30:
        print(11)
    else:
        print(7)


a,b,c=map(str,input().split())

if c=='month' and int(a)<=29:
    print(12)
elif c=='month' and int(a)==30:
    print(11):
elif c=='month' and int(a)==31:
    print(7)
elif c=='week' and a=='4':
    print(53)
elif c=='week' and a=='5':
    print(53)
else:
    print(52)


n=int(input())
people=list(map(int,input().split()))
sum=0
for i in range(n):
    sum+=4*li[i]*i
print(sum)


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

minim = 10000000000000
curr = 0

for opt_etage in len(a):

    curr = 0
    for population in len(a):

        curr +=  a[population]*(abs(opt_etage-population) + abs(opt_etage) + abs(population)) * 2

    curr -= a[0]*(abs(opt_etage) + abs(opt_etage) + abs(0)) * 2

    if(minim>curr):
        minim=curr

print(minim)


f = open("input.txt")
a = 10000
b = -10000
checker = 0
for i in str(f).split()[:len(str(f)) - 3]:
    if checker % 2 == 0:
        if a > int(i):
            a = int(i)
    else:
        if b < int(i):
            b = int(i)
    checker += 1
print(a + b)


n=int(input())
l=input().split()
l=list(map(int,l))
z=0
for i in range(len(l)):
    z=z+i*l[i]
k=(len(l)-1)*(len(l)-2)/2
x=int(z/k)

f=(sum(l)-l[0])
ab=0
for i in range(1,len(l)):
    ab=ab+abs(i-x)

print(2*z+f+ab)


# Author : raj1307 - Raj Singh
# Date   : 11.12.19

from __future__ import division, print_function

import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading
#from itertools import permutations

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    n=ii()
    l=li()

    p=inf

    for j in range(n):
        pos=j
        for i in range(n):
            ans+=l[i]*(2*abs(pos-i)+2*i+2*pos)
        p=min(p,ans)
        #print(l[i]*(2*(pos-i)+2*i+2*pos),2*(pos-i)+2*i+2*pos,pos)
    print(p)

    """
    s=list(si())

    cnt=0
    l=[]
    for i in range(len(s)):

        if s[i]=='b':
            l.append(cnt)
            cnt=0
        else:
            if s[i]=='a':
                cnt+=1

    l.append(cnt)

    ss=sum(l)

    ans=ss

    for i in range(len(l)):

        ans=(ans+((ss-l[i])*l[i])%mod)%mod
        ss-=l[i]

    print(ans)
    """

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    #read()
    main()
    #dmain()

# Comment Read()


y,b,r=[int(i) for i in input().split()]
x=[y,b,r]
if y<b<r:
    print((3*r)+3)
elif y=r=b:
    print((3*r)-3)
elif min(x)==r:
    print((3*r)-3)
elif min(x)==b and b!=r:
    print((3*b))
elif min(x)==y and y!=r and y!=b:
    if b>r:
        if r-y<=2:
            print((3*r)-3)
        else:
            print((3*y)+3)
    elif b==r:
        if r-y==1:
            print((3*r)-3)
        elif (r-y)>1:
            print((3*y)+3)


def(r,b,y):
    if r=>b and r=>y:
        def(r,b,y)=3r-3
    elif b>>r and b=>y:
        def(r,b,y)=3b
    else:
        def(r,b,y)=3y+3


y,b,r=(int,input().split())
    if r=>b and r=>y:
        print(3r-3)
    elif b>r and b=>y:
        print(3b)
    else:
        print(3y+3)


def(r,b,y):
    if r=>b and r=>y:
        def(r,b,y)=3r-3
    elif b>r and b=>y:
        def(r,b,y)=3b
    else:
        def(r,b,y)=3y+3


n = raw_input()
l = 0
u = 0
for i in n:
	if i.islower() == True:
		l+=1
	else:
		u+=1
if l>=u:
	print n.lower()
else:
	print n.upper()


x = input()
s = ""
for i in range(0,len(x)):
    if x == 0:
        s+= x[i].upper()
    else
        s+=x[i]
print(s)


    word = list(input())
    word[0] = word[0].upper()
    result = ''.join(word)
    return result


str =input()
if(len(str)>0 and str[0].islower()):
      print str[0].upper()+str[1:]
else:
      print str


s = input()
print(s.lower()) if (2 * (sum(1 for x in s if x.isupper()) < len(s)) else print(s.upper())


str = input()

lower = 0
for i in range(len(str)):
    if(str[i] >= 'a' && str[i] <= 'z'):
        lower += 1
        if(lower >= len(str)):
            print(str.lower())
            break

print(str.upper())


str = input()
upper=0
lower=0
for i in range(0,len(str)):
	if str[i]>=65 and str[i]<=90:
		upper+=1
	else
		lower+=1

if upper>lower:
	print(str.upper())
else:
	print(str.lower())


a = list(input())
low = 0
high = 0
for i in a:
	if i.islower():
		low += 1
	else :
		high += 1

if high > low :
	for ele in a :
		a[a.index(ele)] = ele.upper()

	print("".join(a))

else :
	for ele in a :
		a[a.index(ele)] 5= ele.lower()

	print("".join(a))


sa=input()
count=0
count1=0
for i in range(len(sa)):
 if sa[i].isupper():
   count+=1
  if sa[i].islower():
   count1+=1
if count > count1:
    print(sa.upper())
else :
    print(sa.lower())


ri=lambda:map(int,input().split(' '))
r,g,b=ri()
x=min(r,g,b)
r-=x; g-=x; b-=x;
x += r//3 + g//3 b//3
print(x)


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

def rep(n,s):
    if len(set(s)) == n:
        return(n)
    else:
        for i in range(n//2,0,-1):
            for j in range(n-i-i+1):
                if s[j:j+i] == s[j+i:j+i+i]:
                    # print(s[j:j+i])
                    return n-i+1
        return n
print(rep(n,s))

# # Length of longest non-repeating substring can be recursively
# # defined as below.
# #
# # LCSRe(i, j) stores length of the matching and
# #             non-overlapping substrings ending
# #             with i'th and j'th characters.
# #
# # If str[i-1] == str[j-1] && (j-i) > LCSRe(i-1, j-1)
# #      LCSRe(i, j) = LCSRe(i-1, j-1) + 1,
# # Else
# #      LCSRe(i, j) = 0
# #
# # Where i varies from 1 to n and
# #       j varies from i+1 to n
#
# if len(set(s))==n:
#     print(n)
# else:
#     lcsr = [[0 for i in range(n)] for j in range(n)]
#     # print(lcsr)
#     for i in range(n):
#         for j in range(i+1,n):
#             if s[i-1]==s[j-1] and (j-i) > lcsr[i-1][j-1]:
#                 lcsr[i][j] = lcsr[i-1][j-1]+1
#
#     max_val=0
#     for i in range(n):
#         max_val=max(max(lcsr[i]), max_val)
#         # print(max_val)
#     if max_val==1:
#         print(n-max_val)
#     else:
#         print(n-max_val+1)


n=int(input())
s=input()
f=[0 for i in range(0,n)]
f[0]=1
for i in range(1,n):
	f[i]=f[i-1]+1
	for j in range(0,i):
		if s[2*j-i-1:j]==s[j:i+1]:f[i]=min(f[i],f[j-1]+1)
print(f[-1])


n = int(input())
s = input()
ans = 0
while s:
    if len(s) % 2 == 1:
        ans += 1
        s = s[:len(s) - 1]
    else:
        if s[:len(s) // 2] == s[len(s) // 2:]:
            ans += 1
            s = s[:len(s) // 2]
        else:
            ans += 1
            s = s[:len(s) - 1]
print(ans)


r = input
ans = n = int(r())
s = r()
len = 1
while len * 2 <= n:
  if s[0:len] == s[len:len*2]:
    ans = min(ans, n - len + 1)
print(ans)


n = int(input())
s= input()
c=0
for i in range(int(n/2),-1,-1):7
abcabca

     if(s[0:i]==s[i:2*i]):
          print(n-i+1)
          c=1
          break
if(c==0): print(n)


class graph:
    # initialize graph
    def __init__(self, gdict=None):
        if gdict is None:
            gdict = dict()
        self.gdict = gdict

    # get edges
    def edges(self):
        return self.find_edges()

    # find edges
    def find_edges(self):
        edges = []
        for node in self.gdict:
            for nxNode in self.gdict[node]:
                if {nxNode, node} not in edges:
                    edges.append({node, nxNode})
        return edges

    # Get verticies
    def get_vertices(self):
        return list(self.gdict.keys())

    # add vertix
    def add_vertix(self, node):
        if node not in self.gdict:
            self.gdict[node] = []

    # add edge
    def add_edge(self, node1, node2):
        # edge = set(edge)
        if node1 in self.gdict:
            self.gdict[node1].append(node2)
        else:
            self.gdict[node1] = [node2]

        if node2 in self.gdict:
            self.gdict[node2].append(node1)
        else:
            self.gdict[node2] = [node1]

    def dfsUtil(self, v, visit):

        visit[v] = True
        print(v)

        for i in self.gdict[v]:
            if visit[i] == False:
                self.dfsUtil(i, visit)
        self.topsort.append(v)

        # dfs for graph

    def dfs(self):
        node_len = len(self.gdict)
        visit = [False] * (node_len)
        self.cnt, self.topsort = 0, []

        for i in range(node_len):
            if visit[i] == False:
                self.dfsUtil(i, visit)
                self.cnt += 1

def inp():
    return map(int, input().split())

from copy import *

n, m = inp()
student = graph()
for i in range(m):
    a, b = inp()
    student.add_edge(a, b)

dic = deepcopy(student.gdict)
for i, j in dic:
    l = len(j)
    if l > :

print(student.gdict)


def comb(n, r):
    if n == 0 or r == 0: return 1
    return comb(n, r - 1) * (n - r + 1) / r
n,m=map(int,raw_input().split())
if n/m==1:
    if n==m:
        print 0,0
    else:
        max=comb(n-m+1,2)
        print n%m,max
a=[n/m]*m
max=comb(n-m+1,2)
else:
    for i in range(0,n%m):
        a[i]+=1
    if a[0]!=a[-1]:
        min=comb(a[0],2)*a.count(a[0])+comb(a[-1],2)*a.count(a[-1])
    elif a[0]==a[-1]:
        min=comb(a[0],2)*m
    print min,max


def get_result(line,remainder,quotient,m):
    result1 = remainder * ((line[0]*(line[0]-1))/2)
    result2 = (m-remainder) * ((quotient*(quotient-1))/2)
    return result1 + result2

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

max_friends = (n-m+1)*(n-m)/2

line = m*[n/m]
remainder = n%m
quotient = n/m

for i in range(remainder):
    line[i] += 1

min_friends = get_result(line,remainder,quotient,m)

print min_friends  max_friends


from math import factorial
    import time
    n, m = map(int, input().split())

    if m == 1:
        kmin = kmax = factorial(n) // (factorial(2) * factorial(n - 2))
    elif m == 2:
        if n == 2:
            kmax = kmin = 0
        elif n == 3:
            kmax = kmin = 1
        else:
            if n % 2 == 0:
                kmin = 2 * factorial(n // 2) // (factorial(2) * factorial((n // 2) - 2))
                kmax = factorial(n - 1 // 2) // (factorial(2) * factorial(n - 3))
            else:
                kmin = factorial(n // 2) // (factorial(2) * factorial((n // 2) - 2)) + factorial(n // 2 + 1) // (factorial(2) * factorial((n // 2) - 1))
                kmax = factorial(n - 1 // 2) // (factorial(2) * factorial(n - 3))

    else:
        x = n - m + 1
        kmax = factorial(x) // (factorial(2) * factorial(x - 2))
        if n % 2 == 1:
            kmin = 3 + (n - 3) // 2
        else:
            kmin = n // 2

    print(kmin, kmax)


use std::io;
use std::io::Read;

fn main() {
    let mut buffer = String::new();
    io::stdin().read_to_string(&mut buffer).unwrap();
    let mut cin = buffer.split_whitespace().map(|x| x.parse::<u64>().unwrap());
    let n = cin.next().unwrap() as usize;
    let mut a = cin.enumerate().collect::<Vec<_>>();
    a.sort_by_key(|x| x.1);
    for i in 0..n / 2 {
        println!("{} {}", a[i].0 + 1, a[n - i - 1].0 + 1);
    }
}


n=int(input())
a=list(map(int,input().split())
s=sum(a)
for i in range(n):
  if a[i]==0.4:
    continue
  for j in range(i+1,n):
    if a[i]+a[j]==2*s//n:
      print(i+1,j+1)
      a[j]=0.4
      break


def get_num (cards,start_index):
    pair =[]
    for i in range(start_index,n):
        if cards[i] + cards[start_index] == (sum(cards)/n) * 2:
            pair.append(start_index)
            pair.append(i)
    return pair

n = int(raw_input())
cards = raw_input()

print sum(cards/n)* 2
for i in range(n):
    print " ".join(map(str,get_num(cards,i))


n = int(input())
a = map(int,input().split())
s = sum(a)
a.sort()
for i in range(n//2):
print(a[i],s*2//n-a[i])


 n = int(raw_input())

ent = map(int,raw_input().split())

media = sum(ent)/(n/2)

indicesAcessados = []

mapa = {}

for i in range(n):
	j = i+1
	if i not in indicesAcessados:
		soma = ent[i]
		while j < n:
			if j in indicesAcessados:
				j += 1
			if soma + ent[j] == media:
				mapa[i+1] = j+1
				indicesAcessados.append(j)
				break
			j += 1

for i in mapa:
	print i, mapa[i]


a=[]
a.append("4")
a.append("7")
p=[]
p.append("4")
p.append("7")
j=0
for i in range(1,200):
	xx=[]
	l=2*(i-1)
	r=2*i
	for j in range(l,r):
		x=a[j]+"4"
		a.append(x)
		x=a[j]+"7"
		a.append(x)
b=[]
for x in a:
	b.append(int(x))

b.sort()
n=int(input())
i=1
for x in b:
	if(x==n):
		print i
		break
	i+=1


n =int(input())
if (n == 4):
print(1)
elif (n==7):
print(2)
else:
temp = n/10
final_count = 0
counter = 1

while(temp != 0):
  final_count = final_count + (2**counter)
  temp = int(temp/10)
  counter += 1

for i in range(counter):
  mod_val = 10
  curr_val = n % mod_val
  n = int(n / 10)
  if(curr_val == 7):
    final_count = final_count + (2**i)

print(final_count+1)


n = input()
ans = 2**len(n) - 2

for i in range(len(n)):
    if n[i] == '7':
        ans+=2**len(n[i+1:])

print(ans+1


n = int(input())
ans = 0
m = 1
while n>0:
    k = n%10
    n = n/10
    if k == 4:
        ans = ans + m * 1
    elif k == 7:
        ans = ans + m * 2
    m = m * 2
print ans


n = int(raw_input())

def f(a, b, c):
    return (a + 1) * (b + 2) * (c + 2) - a * b * c

Smax = f(n, 1, 1)

from math import sqrt
Smin = Smax
for a in range(1, int(sqrt(n)) + 1):
    if n % a != 0:
        continue
    for i in range(1, int(sqrt(n / a)) + 1):
        if (n / a) % i == 0:
            Smin = min(Smin, f(a, i, (n / a) / i))

print Smin, Smax


n = input()
Min, Max = 999999999999999999L, -1

i = 1
while i * i <= n:
    if n % i == 0:
        n1 = n / i
        a = i + 1

        j = 1
        while j * j <= n1:
            if n1 % j == 0:
                b = j + 2
                c = n1 / j + 2
                tmp = a * b * c - n
                Min = min(tmp,Min)
                Max = max(tmp,Max)
            j += 1

        a = n1 + 1
        j = 1
        while j * j <= i:
            if i % j == 0:
                b = j + 2
                c = i / j + 2
                tmp = a * b * c - n
                Min = min(tmp,Min)
                Max = max(tmp,Max)
            j += 1
    i += 1
print Min, Max


import sys
from math import sqrt

n = int(sys.stdin.readline())

def triples(x):
    r = int(sqrt(x)) + 1
    ts = set([])
    ds = [1, x]
    for i in xrange(2, r+1):
        if x % i == 0:
            ds.extend([i, x / i])
    ds = sorted(ds)
    for d in ds:
        r = int(sqrt(d))+1
        i = 0
        while ds[i] <= r:
            if d % ds[i] == 0:
                ts.add(tuple(sorted([x / d, ds[i], d / ds[i]])))
            i += 1
    return list(ts)

rmax = -1
rmin = float('inf')

for t in triples(n):
    a, b, c = t
    i = (a+1)*(b+2)*(c+2)
    j = (b+1)*(a+2)*(c+2)
    k = (c+1)*(a+2)*(b+2)
    keys = [i, j, k]
    for k in keys:
        rmax = max(rmax, k-n)
        rmin = min(rmin, k-n)

print rmin, rmax


import itertools as it
from functools import reduce

PRIME = -1

N = 10**5

primes = [PRIME for x in range(N + 1)]

def factor(n):
    """
    >>> factor(2)
    [(2, 1)]

    >>> factor(6)
    [(3, 1), (2, 1)]

    >>> factor(98)
    [(7, 2), (2, 1)]

    >>> factor(1)
    []
    """
    if n == 1:
        return []
    if primes[n] == PRIME:
        return [(n, 1)]
    result = []
    result += [(primes[n], 1)]
    n //= primes[n]

    while primes[n] != PRIME:
        if result[-1][0] == primes[n]:
            result[-1] = (primes[n], result[-1][1] + 1)
        else:
            result += [(primes[n], 1)]
        n //= primes[n]

    if result[-1][0] == n:
        result[-1] = (n, result[-1][1] + 1)
    else:
        result += [(n, 1)]

    return result

def all_divisors(prime_factorization):
    """
    >>> all_divisors(factor(6))
    [1, 2, 3, 6]

    >>> all_divisors(factor(12))
    [1, 2, 4, 3, 6, 12]

    >>> all_divisors(factor(7))
    [1, 7]

    >>> all_divisors(factor(1))
    [1]
    """
    if len(prime_factorization) == 0:
        return [1]
    result = []
    factor_with_mult = []
    for pfactor in prime_factorization:
        factor_with_mult += [[1]]
        for _ in range(pfactor[1]):
            factor_with_mult[-1] += [factor_with_mult[-1][-1] * pfactor[0]]
    for divisor in it.product(*factor_with_mult):
        result += [reduce(lambda x, y: x * y, divisor)]
    return result

if __name__ == '__main__':
    # sieve
    for i in range(2, N + 1):
        if primes[i] == PRIME:
            j = 2
            while j * i < N + 1:
                primes[j * i] = i
                j += 1
    primes[0] = primes[1] = 0

    n = int(input())

    min_result = 10**9
    max_result = 0

    for divisor in all_divisors(factor(n)):
        for div2 in all_divisors(factor(divisor)):
            if div2 * div2 > divisor:
                break
            a = n // divisor + 1
            b = divisor // div2 + 2
            c = div2 + 2
            min_result = min([min_result,
                              c * b + (a - 1) * 2 *
                              (b + c - 2)])
            max_result = max([max_result,
                              c * b + (a - 1) * 2 *
                              (b + c - 2)])
    print(str(min_result) + " " + str(max_result))


n = int(input())

if (n+1) % 2 ==0 and (n!=0):
    print((n+1)//2)
elif n==0:
    print 0
else:
    print(n+1)


n = int(input());
a = 0;
if (n == 0)
    a = 0
else if (n == 1)
    a = 1
else if (n % 2 == 0)
    a = n + 1
else
    a = n - 1

print(a);


import math
guests = int(input())
if guests == 0:
    print(0)
guests = guests+1
elif guests % 2 == 0:
    print(guests//2)

else:
    print(guests)


n = int(input())
if n == 0:
    print 0
if (n+1) % 2 ==0:
    print((n+1)//2)
else:
    print(n+1)


n = int(input())
a = 0
if (n == 0):
    a = 0
else if (n == 1):
    a = 1
else if (n % 2 == 0):
    a = n + 1
else:
    a = n - 1

print(a)


import math
a = map(int, input().split()))
print(a)


n, m, a = map(int, input().split())
if n and m > a:
    print((n // a + 1) * 2)
elif:
    n > a and m <= a:
        print((n // a) * 2)
elif:
    m > a and n <= a:
        print((m // a) * 2)
else:
    print(m * n // (a * a))


n, m, a = map(int, input().split())
print (n % a == 0 ? n: n % a + 1)*(m % a == 0 ? m: m % a + 1)


k,n,s,p= map(int, input().split())
sp=n/s
spq=round(sp+1)
r=(spq*k/p)
if r%1==0:
    print(int(r))
else:
    print(int(round(r+1))


k,n,s,p = map(int,input().split())
m=int()
kl=int()
vl=int()
if n % s ==0:
	kl = n // s
	else:
		kl = n // s + 1
vl = kl * k
if vl % p == 0:
	m = vl // p
else: m = vl // p + 1
print (m)


n,s,k,l=list(map(int,input().split()))
if s//k==s/k:
    op=int(s//k)
else:
    op=int(s//k)+1
kam=n*op
if kam//l==kam/l:
    print(int(kam/l)
else:
    print(int(kam//l)+1)


include math
ent=input()
a,b,c,d=ent.split()
print(math.ceil((a*math.ceil(b/c))/d))


k,n,s,p=map(int,input().split())
m=int()
kl=int()
if n % s ==0:
	kl = n // s
	else:
		kl = n // s + 1
vl = kl * k
if vl % p == 0:
	m = vl // p
else: m = vl // p + 1
print (m)


#python27

def program():
    s=str(raw_input())

    if(s.isupper() or len(s)==1 s[1:].isupper()):
        s=s.swapcase()
        print s
        return
    else:
        print s
program()


input = raw_input()

input_list = list(input)

"""print str(input_list[0]).upper(), "\b", ''.join(input_list[1:]).lower()"""

hoay = []

hoay.append(input_list[0].upper())

for i in input_list[1:]:
	hoay.append(i.lower())

if for i in input_list[1:]	== i.lower()
	print ''.join(hoay)
else:
	print input


# author : sudoer
# from __future__ import print_function
# from __future__ import division
import math
# from collections import OrderedDict

def prob(n):
  if(n.isupper() == True):
    # print "upper"
    a = str(n[0].upper())
    b =str(n[1:].lower())
    print a+b
  elif n[0].islower() == True and n[1:].isupper()==True:
    print n[0].upper()+n[1:].lower()
   else :
     print n

n = raw_input()
n = str(n)
prob(n)


n=input()
s=""

if n[1:].isupper() or n.isupper() or len(n)=1 :
    for i in n:
        s=s+i.swapcase()

    print(s)

else :
    print(n)


x = raw_input()
y =0
for i in x:
	if i=i.lower():
		y+=1
if y==1:
	print x[0].upper()+x[1:].lower()
else:
	print x


def IsBerlanese():
    s = raw_input()
    vowels = 'aeiou'
    i = 0
    while i < len(s)-1:
        if s[i] not in vowels and s[i] != 'n':
            if s[i+1] not in vowels:
                return 'NO'
        i += 1

    if s[i] == 'n' or s[i] in vowels:
        return 'YES'
    else:
        return 'NO'

print IsBerlanese()


a=input()
b=["a","e","i","o","u"]
temp=True
for i in range(len(a)):
    if a[i] not in b and a[i]!="n":
        if i!=len(a)-1:
            if a[i+1] in b:
                continue
            else:
                temp=False
                print("NO")
                break
        else:
            temp=False
            pprint("NO")
        else:
            continue

if temp==True:
    print("YES")


n=input()
c=0
if (n[len(n)-1]="a" or n[len(n)-1]="e" or n[len(n)-1]="i" or n[len(n)-1]="o" or n[len(n)-1]="u" or n[len(n)-1="n"]):
    for i in range (1,len(n),2):
        if (n[i]="a" or n[i]="e" or n[i]="o" or n[i]="o" or n[i]="u"):
            c=1
    for j in range (0,len(n),2):
        if (n[i]="a" or n[i]="e" or n[i]="o" or n[i]="o" or n[i]="u"):
            c=1
if c=1:
    print("YES")
else:
    print("NO")


w = input()
word = ''.join([i if i != 'n' else "*" for i in w]

vowels = "aeiou"
cons = [word[i-1] + word[i] for i in range(1 , len(word)) if word[i-1] not in vowels]
con_vow = [i for i in cons if i[-1] in vowels]

if len(cons) == len(con_vow) :
    print("YES")
else :
    print("NO")


# coding: utf8
s = input()
k = int(input())
n = s.count('*')
m = s.count('?')
l = len(s) - m - n
if k < l - m - n or (n == 0 and k > l):
    s = 'Impossible'
elif k > l:
    # 需要添加 k-l 个 *前面的数字
    # 用replace('*'，个数，1) 把第一个*替换为k-l个前面的字母即可
    i = s.find('*')
    s = s.replace('*', s[i - 1] * (k - l), 1)
# 下面一行很巧妙，处理删l-k个字符的时候，直接吧*换成?，避免判断?和*个数的情况
s = s.replace('*', '?')
# 类似于 in range(0, l-k)， 如果l-k小于等于0的话是不循环的
for _ in [0] * (l - k):
    i = s.find('?')
    # 删除 ?和前面的字符，拼起来一起replace with ''
    s = s.replace(s[i - 1] + '?', '', 1)
print(s.replace('?', ''))


stroka = input()
k = int(input())
n1 = stroka.count('*')
n2 = stroka.count('?')
t = 0
p = ''
if n1 > 0 and n2 > 0:
    for i in range(len(stroka)):

        if stroka[i+t]=='?'and (len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))>k:
            stroka = stroka[:i+t-1]+'!!'+stroka[i+t+1:]
        elif  stroka[i+t]=='?'and (len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))<=k:
            stroka = stroka[:i+t]+'!'+stroka[i+t+1:]
        elif stroka[i+t] =='*' and (len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))>k:
            stroka = stroka[:i+t - 1] + '!!' + stroka[i+t + 1:]
        elif stroka[i+t] =='*' and (len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))==k:
            stroka = stroka[:i +t] + '!'  + stroka[i +t+ 1:]
        elif stroka[i+t] =='*' and (len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))<k:
            y = abs((len(stroka)-stroka.count('?')-stroka.count('*')-stroka.count('!'))-k)
            stroka = stroka[:i+t] + stroka[i+t-1]*y + stroka[i+t + 1:]
            t+=y-1
elif n1 > 0 and n2 ==0:
    for i in range(len(stroka)):
        print(stroka)        if stroka[i+t] == '*' and (len(stroka) - stroka.count('*')-stroka.count('!')) > k:
            stroka = stroka[:i+t - 1] + '!!' + stroka[i+t + 1:]
        elif stroka[i+t] == '*' and (len(stroka)  - stroka.count('*')-stroka.count('!')) == k:
            stroka = stroka[:i+t] + '!' + stroka[i +t+ 1:]
        elif stroka[i+t] == '*' and (len(stroka)  - stroka.count('*')-stroka.count('!')) < k:
            y = abs((len(stroka)  - stroka.count('*')-stroka.count('!')) - k)
            stroka = stroka[:i + t] + stroka[i + t - 1] * y + stroka[i + t + 1:]
            t += y-1
elif n1==0 and n2 > 0:
    for i in range(len(stroka)):
        if stroka[i] == '?' and (len(stroka) - stroka.count('?') -stroka.count('!')) > k:
            stroka = stroka[:i - 1] + '!!' + stroka[i + 1:]
        elif stroka[i] == '?' and (len(stroka) - stroka.count('?') -stroka.count('!')) <= k:
            stroka = stroka[:i] + '!' + stroka[i + 1:]
for i in range(len(stroka)):
    if stroka[i]!='!':
        p += stroka[i]

if len(p)==k:
    print(p)
else:
    print('Impossible')


import re

def f(cs):
    nonlocal x
    if x > 0:
        x -= 1
        return ''
    elif x > 0:
        return cs[0][0] * x
        x = 0
    else:
        return cs[0][0]

s = input()
x = len(s) - s.count('?') - s.count('*') - int(input())
s = re.sub(r'\w[?*]', f, s)
print('Impossible' if x else s)


s, k = input(), int(input())

inf = 200

min_len = len(s) - 2 * (s.count('?') + s.count('*'))

max_len = inf if '*' in s else len(s) - 2 * s.count('?')

if min_len <= k <= max_len:
	if '*' in s:
		last_snowflake_index = len(s) - 1 - s[::-1].index('*')
		repeats_needed = k - (len(s) - 2 * (s.count('?') + s.count('*')) + 1)

		a = ''
		for i in range(len(s)):
			if s[i] == '?':
				a = a[:-1]
			elif s[i] == '*':
				if i < last_snowflake_index:
					a = a[:-1]
				else:
					a += repeats_needed * s[i - 1]
			else:
				a += s[i]

		print(a)
	else:
		removes_needed = k - (len(s) - (s.count('?') + s.count('*'))

		a = ''
		for i in range(len(s)):
			if s[i] in '?*':
				if removes_needed > 0:
					a = a[:-1]
			else:
				a += s[i]

		print(a)
else:
	print('Impossible')


from collections import Counter

a = input()
target = int(input())
c= Counter(a)
length = len(a) - 2* c["*"] - 2 * c["?"]

if length > target:
    print("Impossible")
else:
    pure = length + c["*"] + c["?"]
    pon = pure - target
    if not pon:
        for aa in a:
            if aa=="*" or aa=="?":
                continue
            else:
                print(aa,end="")
    elif pon < 0:
        if c["*"] == 0:
            print("Impossible")
            return
        for idx, aa in enumerate(a):
            if aa =="?":
                continue
            elif aa =="*":
                while pon != 0:
                    print(a[idx-1],end="")
                    pon+=1
            else:
                print(aa,end="")
    else:
        b = []
        for aa in a:
            if b and pon > 0 and (aa=="*" or aa=="?"):
                b.pop()
                pon-=1
            elif (aa=="*" or aa=="?"):
                continue
            else:
                b.append(aa)
        print("".join(b))


import math
a,b,c,d,e = input().split()
a=int(a)
b=int(b)
c = int(c)
d=int(d)
e=int(e)
if(a!=1):
	g = a
	h = g-1
	f = a*(g-1)
	print(f)
else(print(1))


n, a, b, c, d = map(int, input().split(' '))
sums = [a+b, a+c, b+d, c+d]
sums.sort()
ans = max(0, n - sums[3] + sums[0])
ans *= n
print(ans


#-*-coding:utf-8-*-
import math
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# s , a = s1

# 서로간 이웃한 값 c (si-si-1 = c)
# b가 이 시퀸스에 포함
# si = b
#

n, a, b, c, d=map(int,raw_input().split())

x1=0
x2=0
x3=0
x4=0
x5=0

count = 0

for i in (1, n) :
	x1 = i
	x2 = x1+b-c
	x4 = x1+a-d
	x5 = x2+a-d

	if x1 <=n and x2 <=n and x4 <=n and x5 <=n \
	x1 >0 and x2 >n and x4 >n and x5 >n: count +=1
print count*n


#-*-coding:utf-8-*-
import math
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# s , a = s1

# 서로간 이웃한 값 c (si-si-1 = c)
# b가 이 시퀸스에 포함
# si = b
#

a, b, c=map(int,raw_input().split())

if a == b and c == 0 : print "YES"
elif c!=0 :
	if (b - a) % c == 0 :  print "YES"
	else : print "NO"
else : print "NO


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
// vsInput()

n,a,b,c,d=value()
ans=0

minSum=a+b+2
maxSum=a+b+2*n

for mid in range(1,n+1):
    box1=(a+b+mid+1,a+b+mid+n)
    box2=(a+c+mid+1,a+c+mid+n)
    box3=(c+d+mid+1,c+d+mid+n)
    box4=(d+b+mid+1,d+b+mid+n)

    minSum=max(box1[0],box2[0],box3[0],box4[0])
    maxSum=min(box1[1],box2[1],box3[1],box4[1])

    # print(minSum,maxSum)
    ans+=max(maxSum-minSum+1,0)

print(ans)


n, m = map(int, input().split())
days = 0
i = 1
while n > 0:
n -= 1
days += 1
if days == m * i:
n += 1
i += 1
print(days)


 n , m = map(int , input().split())
    s = n # s refers sum
    while n >= m :
        n = n%m + n//m
        s+=n
    print(s)


n=input()
m=input()
while(1<n<100&&2<m<100):
    if n>m:
        print (n+m+1)
    elif n==m:
        print(n+1)
    else:
        print(n)


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

print(round(n + (n-1)/(m-1))


Иван Иванов

4 месяца назад
вася и носки
n, m = map(int, input().split())
z=0
while n>0
    n-=1
    z+=1
    if z%m==0
        n+=1
print(z)


[n,a,b,c]=[int(x) for x in input().split()]
k=0
minprice=0
for i in range (4):
    if (n+i)%4==0:
        k=i
if k==0:
    print(0)
elif k==1:
    print(min(a,b+c,3*c)
elif k==2:
    print(min(b,2*a,2*c)
elif k==3:
    print(min(c,3*a,b+a))


n, a, b, c = (int(x) for x in input().split())
nd = 4 - n % 4
if nd == 0:
    print 0
elif nd == 1:
    print(a)
    elif nd == 2:
        print(min(2 * a, b))
    else:
        print(min(3 * a, min(a + b, c)))


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

left = n % 4

if left == 4:
	print(0)
elif left == 3:
	print(a, b + c, 3*c)
elif left == 2:
	print(min(2*a, b, 2*c)
else:
	print(min(3*a, a + b, c))


n,a,b,c=input().split(" ")
n=int(n)
a=int(a)
b=int(b)
c=int(c)
if(n%4==0):
    print(0)
else :
    n=n%4
    b=b/2
    c=c/3
    n=4-n
    if(n==3):
        a=min(a,c)
        print(int(a*n))
    elif(n==1)
        print(int(a * n))
    else:
        a = min(a, b)
        print(int(a * n))


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

l = sorted(list(map(int,input().split())))
for i in range(m - n - 1):
    print(min([l[i+n-1]-l[i]))


from collections import deque
q=deque
min_diff=1e5+9
n,m=map(int,input().strip().split())
l=list(map(int,input().strip().split())
for i in range(n):
    q.append(l[i])
for i in range(n,m):
    min_diff = min(min_diff,max(q)-min(q))
    q.popleft()
    q.append(l[i])
min_diff=min(min_diff,max(q)-min(q))
print(min_diff)


n,m = map(int, raw_input().split()))
s = list(map(int, raw_input().split())))
s.sort()
minim = max(s) - min(s)
for i in range(m-n+1):
	if ( s[i+n-1]-s[i] < minim):
		minim = s[i+m-n]-s[i]

print minim


l=[]
p=[]
n=int(input())
m=int(input())
if 2<=n<=m<=50:
   for i in range(m):
       l.append(int(input())
   for i in range(0,m-n+1):
       p.append(l[i+4-1]-l[i])
   print(min(p))
else:
    print("redo")


x,y = map(int,raw_input().split())
l = list(map(int,raw_input().split()))
l =sorted(l)
m =1000
for i in range(y-x+1):
	d = l[i+x-1] - l[i]
	if d <m:
		m =d
print m


a=input()
cc=input()
cc=cc.split(" ")
b=cc[0]
c=cc[1]
l=["6", "7", "8", "9", "T", "J", "Q", "K","A"]

if(a in band a not in c):
    print("YES")
else:
    if(l.index(b[0])>l.index(c[0])):
        print("YES")
    else:
        print("NO")


s=input()
a,b=input().split()
x="6789TJQKA"if a[1]==s: print("YES")
elif b[1]==s or a[1]!=b[1]: print("NO")
elif x.index(a[0])>x.index(b[0]): print("YES")
else: print("NO")


suit = ['S', 'H', 'D', 'C']
rank = ['6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']

trump = str(raw_input())
cards = str(raw_input())

win = False

if cards[1] == cards[4] and rank.index(cards[0]) > rank.index(cards[3]):
    win = True

if cards[1] == trump
    win = True

if win:
    print('YES')
else:
    print('NO')


#include <bits/stdc++.h>

#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL);
#define precision(x); cout<<fixed<<setprecision(x);
#define ll long long int
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define desc greater<int>()
#define mod 1000000007

using namespace std;

ll modExp(ll x,ll y,ll p){
    ll res=1;
    x=x%p;
    while(y>0){
        if(y&1){
            res=((res%p)*(x%p))%p;
        }
        y=y>>1;
        x=((x%p)*(x%p))%p;
    }
    return res;
}

int main()
{
    BOOST
    ll x,k,a,b;
    cin>>x>>k;
    if(x==0){
    	cout<<0;
    }else{
		a=modExp(2,k+1,mod);
		b=modExp(2,k,mod);
    	cout<<((((((x%mod)*(a%mod))%mod)-(b%mod)+1)+mod)%mod);
    }
    return 0;
}


/**
Sometimes you must hurt in order to know,fall in order to grow,lose in order to gain because life’s greatest lessons are learned through pain.
*/
#include <bits/stdc++.h>
#define forn(i, l, r) for(ll i=l;i<=r;i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define nd second
#define st first
#define debug(x) cout<<#x<<" -> "<<x<< endl
#define kakimasu(x) cout << x << '\n'
#define sz(x) (ll)x.size()
#define UNIQUE(v) (v).resize(unique(all(v)) - (v).begin())

using namespace std;
typedef long long ll;

const ll INF = 1 << 30;
/**
Start coding from here
*/
const int MOD=1e9+7;
void add(ll& a, ll b) {
	a+=b;
	if (a >= MOD) a -= MOD;
}

void subtract(ll& a, ll b) {
	if (b>a) a+=MOD;
	a=(a-b)%MOD;
}

ll sum (ll a, ll b) {
	add(a, b);
	return a;
}

ll multiply(ll a, ll b) {
	return (long long) ((a%MOD) * (b%MOD)) % MOD;
}

ll mpow(ll a, ll b) {
	ll ret = 1;
	while (b) {
		if (b & 1) {
			ret = multiply(ret, a);
		}
		a = multiply(a, a);
		b >>= 1;
	}
	return ret;
}

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	#ifdef LOCAL_PROJECT
		freopen("input.txt","r",stdin);
	#endif
	ll x, k;
	cin>>x>>k;
	if(x==0) {
		cout<<"0\n";
		exit(0);
	}
	ll ans = multiply(x, mpow(2LL, k+1));
	ll temp = mpow(2LL, k);
	subtract(temp, 1LL);
	// debug(temp);
	subtract(ans, temp);
	cout<< ans<<'\n';
	return 0;
}


def power(x,y):
	mod=1000000007
	res = 1
	while (y > 0):
	// If y is odd, multiply x with result
		if (y and 1):
			res = (res * x)%mod
		y = y >> 1
		x = (x * x)%mod
	return res;
x,k=map(int,input().split())
mod=1000000007
x%=mod
factor=power(2,k)
factor%=mod
ans=((2*factor*x)%mod- (factor)%mod+1)%mod
if x==0:
	print("0")
else:
	print(ans)


def power(x,y):
	mod=1000000007
	res = 1
	while (y > 0):
	// If y is odd, multiply x with result
		if (y and 1):
			res = (res * x)%mod
		y = y >> 1
		x = (x * x)%mod
	return res
x,k=map(int,input().split())
mod=1000000007
x%=mod
factor=power(2,k)
factor%=mod
ans=((2*factor*x)%mod- (factor)%mod+1)%mod
if x==0:
	print("0")
else:
	print(ans)


 from sys import stdin
import math

line = stdin.readline().rstrip().split()
l = int(line[0])
r = int(line[1])
x = int(line[2])
y = int(line[3])

w = x * y

maxN = min(min(r, y), math.floor(math.sqrt(w)))
count = 0

if y%x != 0:
    print(0)
else:
    for a in range(l, maxN+1):
        if w % a == 0:
            b = int(w/a)
            if a >= l and a <= r and b >=l and b <= r:
                if a % x == 0 and b % x == 0 and y % a == 0 and y % b == 0:
                    gcd = math.gcd(int(a/x), int(b/x))
                    if gcd == 1:
                        if a != b:
                            count += 1
                        count += 1
    print(count)


#include <iostream>

using namespace std;

int main(){
    int n;
    cin>>n;
    int matrix[n][n];
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
            cin>>matrix[i][j];
    for(int k=0;k<n;++k){
        for(int i=0;i<n;++i){
            for(int j=0;j<n;++j){
                matrix[i][j] = min(matrix[i][j], matrix[i][k] + matrix[k][j]);
            }
        }
    }
    for(int i=0;i<n;++i){
        for(int j=0;j<n;++j){
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
}


list1=[]
list2=[]
a,b=input().split()
a=int(a)
b=int(b)
tt=0
t1=0
t2=0
while len(list1)<c:
    t1=t1+1
    list1.append(t1)
    t2=t2+1
    list1.append(t2)
if len(list1)>c:
    list2=list1[0:-1]
else list2=list1:
print(sum(list2))


a=int(input())
b=int(input())
if a>b:
    k=a-b
else
    k=b-a
if k%2==0:
    j=k//2
    x=0
    for v in range(0,j+1):
        x=x+v
    y=0
    for v in range(j,0,-1):
        y=y+v
    print(x+y)
else:
    j=(k//2)
    x=0
    for s in range(0,j+1):
        x=x+s
    y=0
    for s in range(j+1,0,-1):
        y=y+s
    print(x+y)


a=int(input())
b=int(input())
if b==min(a,b)
    a,b=b,a
c=(a+b)//2
d=c-a
e=b-c
s=0
p=0
for i in range (1,d+1):
    s=s+i
for j in range (1,e+1):
    p=p+j
print(s+p)


x,y,z = map(int,input().split())
if z<y:print(z)
elif z>=y and z<=x:print(y)
elif z%y=0 and z>x:print(5-(z%5))
elif z%y==0 and z>x:print(0)


n,k,t = map(int,input().split())
if t<=k:
    print t
elif t<=n:
    print k
else:
    print k-(t-n)


# import sys
# sys.stdin = open("test.in","r")
# sys.stdout = open("test.out","w")
n,k,t=map(int,input().split())
if t<=k:
	print(t)
elif t<n and t>=k:
	print(k)
else:
	print(n+k-t


n, k, t=map(int, input().split())
if(t<k):
    print(t)
elif(t>k and t<=n):
    print(k)
elif(t==n+k):
    print(0)
elif(t>n):
    m=t-n
    print(n-(n+m-k))


n,k,t=map(int,input().split())
s=0
a=[]
for i in range(t):
    if i+1<=k:
        s+=1
        a.append(s)
    elif i+1>n-k and i+1<=n:
        a.append(s)
    else:
        s-=1
        a.append(s)
print(a[t-1])


c=input()
c.replace(' ','')
c.strip('0')
n=1
for i in c.split('1')
    n*=c.len()+1
print(n)


n = int(input())
a=list(map(int,input().split())
ans = 1
k = 1
for i in a:
    if i:
        ans*=k
        k=1
    else:
        k+=1
print(ans)


n = int(input())
f = list(map(int, input().split()))
ans = 1
now = -1
for i in range(n):
    if (f[i]):
        if (now != -1):
            ans = ans * (i - now)
        now = i
if (now == -1)
    ans = 0
print(ans)