n = int(input())

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

lis = [0] * 31

for i in a:

    for j in range(31):

        if i & (2**j) > 0:
            lis[j] += 1

nmax = 0
maxind = 0
for ind,i in enumerate(a):

    for j in range(31):

        if lis[j] >= 2:

            i |= 2**j
            i -= 2**j

    if nmax < i:
        nmax = i
        maxind = ind

ans = [a[maxind]]

for i in range(n):

    if i != maxind:
        ans.append(a[i])

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


n=int(input())
l=list(map(int,input().split()))
d={}
for i in l:
    b=bin(i)[:1:-1]
    for j in range(len(b)):
        if int(b[j]):
            d[j]=d.get(j,[])
            d[j].append(i)
for i in range(31,-1,-1):
    if len(d.get(i,[]))==1:
        v=d[i].pop()
        print(v,end=' ')
        k=0
        for j in l:
            if j==v and k<1:k+=1
            else:print(j,end=' ')
        quit()
print(' '.join(map(str,l)))


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

for d in range(29, -1, -1):
    bit = 1 << d
    count, j = 0, 0
    for i, x in enumerate(a):
        if bit & x:
            count += 1
            if count == 2:
                break
            else:
                j = i
    if count == 1:
        print(a[j], *(a[:j] + a[j+1:]))
        break
else:
    print(*a)


n=int(input())
l=list(map(int,input().split()))
cnt=[0]*30
for i in range(n):
	for j in range(30):
		if l[i]&(1<<j):
			cnt[j]+=1
options=[i for i in range(n)]
for i in range(29,-1,-1):
	newoptions=[]
	if cnt[i]==1:
		for idx in options:
			if l[idx]&(1<<i):
				newoptions.append(idx)
	if len(newoptions)>0:
		options=newoptions
print(l[options[0]],end=" ")
for i in range(n):
	if i!=options[0]:
		print(l[i],end=" ")


from collections import defaultdict

def solve(A, N):
    assert len(A) == N
    bitCover = defaultdict(int)
    for x in A:
        for i in range(32):
            if (1 << i) & x:
                bitCover[i] += 1
    # Everything that is covered will be deleted in the final result
    best = (0,)
    for j, x in enumerate(A):
        result = 0
        for i in range(32):
            if (1 << i) & x:
                if bitCover[i] == 1:
                    result += 1 << i
        best = max(best, (result, j))

    j = best[1]
    A = [A[j]] + A[:j] + A[j + 1 :]
    return ' '.join(map(str, A))

def __starting_point():
    N, = list(map(int, input().split()))
    A = list(map(int, input().split()))
    ans = solve(A, N)
    print(ans)

__starting_point()


from collections import defaultdict
n = int(input())
xs = list(map(int, input().split()))
count = defaultdict(int)
for x in xs:
    for i, b in enumerate(reversed(bin(x)[2:])):
        if b != '0':
            count[i] += 1
rm = 0
for k, v in list(count.items()):
    if v > 1:
        rm += 2 ** k

m = -1, 0
for i, x in enumerate(xs):
    if (x | rm) - rm > m[0]:
        m = ((x | rm) - rm), i

i = m[1]
xs = [xs[i]] + xs[:i] + xs[i + 1:]
print(' '.join(map(str, xs)))


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

B = [[0] * 33 for i in range(n)]
C = [0] * 33
for i in range(n):
    t = A[i]
    j = 0
    while t > 0:
        B[i][j] += t%2
        C[j] += B[i][j]
        t//=2
        j += 1

M2 = [1]
for i in range(40):
    M2.append(M2[-1]*2)

S = [0] * n
for i in range(n):
    for j in range(33):
        if B[i][j] == 1:
            if C[j] == 1:
                S[i] += M2[j]

ind = S.index(max(S))
ANS = [A[ind]]
for i in range(n):
    if i != ind:
        ANS.append(A[i])
print(" ".join([str(i) for i in ANS]))


import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1/0
def write(*args, sep="\n"):
  for i in args:
    sys.stdout.write("{}{}".format(i, sep))
INF = float('inf')
MOD = int(1e9 + 7)
YES = "YES"
NO = "NO"

def f(x):
  return bin(x)[2:][::-1]

n = int(input())
cnt = [0] * 100
arr = read()

for i in arr:
  s = f(i)

  for j in range(len(s)):
    if s[j] == "1":
      cnt[j] += 1

ans = [-INF, -INF]
for i in arr:
  s = f(i)

  for j in range(len(s)):
    if s[j] == "1":
      cnt[j] -= 1

  x = []
  for j in range(len(s)):
    if cnt[j] == 0:
      x.append(s[j])
    else:
      x.append("0")

  ans = max(ans, [int("".join(x)[::-1], 2), i])

  for j in range(len(s)):
    if s[j] == "1":
      cnt[j] += 1

arr.remove(ans[1])

print(ans[1], *arr)


"""Cowboy Beblop at his computer, problem 717I from https://codeforces.com/problemset/problem/717/I"""
# from fractions import Fraction

# def convert_to_fractions(poly):
#     """convert polygon vertex to fractional type"""
#     poly_frac = []
#     for x, y, z in poly:
#         vertex = (Fraction(x),
#                   Fraction(y),
#                   Fraction(z))
#         poly_frac.append(vertex)
#     return poly_frac

def convert_to_float(poly):
    """convert polygon vertex to float type"""
    poly_float = []
    for x, y, z in poly:
        vertex = (float(x),
                  float(y),
                  float(z))
        poly_float.append(vertex)
    return poly_float

def cross_product(a, b):
    """3-vector product"""
    return (a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0])

def dot_product(a, b):
    """scalar product of 3-vectors"""
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def vect_diff(a, b):
    """vector difference"""
    return a[0] - b[0], a[1] - b[1], a[2] - b[2]

def poly_normal(poly):
    """return normal vector for first three vertex"""
    assert len(poly) >= 3
    x, y, z = poly[:3]
    u = vect_diff(y, x)
    v = vect_diff(z, y)
    return cross_product(u, v)

def intersect_list(poly, plain_norm, plain_point, proj_dir):
    """list of intersection points

    find points where the edges enter or leave upper half-space over the plain
    :return list of points projection on proj_dir
    """
    # vertex projection
    u = [dot_product(vert, proj_dir) for vert in poly]

    # plain anchor
    vr = dot_product(plain_point, plain_norm)

    # polygon vertex
    v = [dot_product(vert, plain_norm) for vert in poly]

    u_list = []
    for i in range(len(poly)):
        if (v[i-1] > vr) != (v[i] > vr):
            ur = ((vr - v[i-1]) * u[i] + (v[i] - vr) * u[i-1]) / (v[i] - v[i-1])
            u_list.append(ur)

    return u_list

def points_to_str(a_points, b_points):
    """string representing the order of points 'a' and 'b'"""
    a_pairs = [('a', val) for val in a_points]
    b_pairs = [('b', val) for val in b_points]
    pairs = sorted(a_pairs + b_pairs, key=lambda pair: pair[1])
    letters = [ch for ch, _ in pairs]
    return ''.join(letters)

def recognize_str(s):
    """return True if string s belong to the grammar

    The context-free grammar is given
    S -> SS
    S -> a S a
    S -> b S b
    S -> e

    The recognising automaton is implemented
    """
    toggle = {'a':'b', 'b':'a'}
    cross_num = 0
    top = None
    for ch in s:
        if not cross_num:
            cross_num = 1
            top = ch
            continue

        if ch == top:
            cross_num -= 1
        else:
            cross_num += 1

        if cross_num:
            top = toggle[top]
        else:
            top = None
    return not cross_num

def is_well_connected(a, b):
    """Two planar polygons are bind together in 3D

    Arguments:
        a_poly,
        b_poly -- lists of vertex triples
    """
    a = convert_to_float(a)
    b = convert_to_float(b)

    a_norm = poly_normal(a)
    b_norm = poly_normal(b)

    common_dir = cross_product(a_norm, b_norm)
    if not any(common_dir):
        return False

    a_list = intersect_list(a, b_norm, b[0], common_dir)
    b_list = intersect_list(b, a_norm, a[0], common_dir)

    char_str = points_to_str(a_list, b_list)
    return not recognize_str(char_str)

def run_from_console():
    a_len, = [int(num) for num in input().split()]

    a = []
    for _ in range(a_len):
        vertex = tuple(int(num) for num in input().split())
        a.append(vertex)

    b_len, = [int(num) for num in input().split()]

    b = []
    for _ in range(b_len):
        vertex = tuple(int(num) for num in input().split())
        b.append(vertex)

    if is_well_connected(a, b):
        print('YES')
    else:
        print('NO')

def __starting_point():
    run_from_console()
__starting_point()


def convert_to_float(poly):
    """convert polygon vertex to float type"""
    poly_float = []
    for x, y, z in poly:
        vertex = (float(x),
                  float(y),
                  float(z))
        poly_float.append(vertex)
    return poly_float

def cross_product(a, b):
    """3-vector product"""
    return (a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0])

def dot_product(a, b):
    """scalar product of 3-vectors"""
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def vect_diff(a, b):
    """vector difference"""
    return a[0] - b[0], a[1] - b[1], a[2] - b[2]

def poly_normal(poly):
    """return normal vector for first three vertex"""
    assert len(poly) >= 3
    x, y, z = poly[:3]
    u = vect_diff(y, x)
    v = vect_diff(z, y)
    return cross_product(u, v)

def intersect_list(poly, plain_norm, plain_point, proj_dir):
    """list of intersection points

    find points where the edges enter or leave upper half-space over the plain
    :return list of points projection on proj_dir
    """
    # vertex projection
    u = [dot_product(vert, proj_dir) for vert in poly]

    # plain anchor
    vr = dot_product(plain_point, plain_norm)

    # polygon vertex
    v = [dot_product(vert, plain_norm) for vert in poly]

    u_list = []
    for i in range(len(poly)):
        if (v[i-1] > vr) != (v[i] > vr):
            ur = ((vr - v[i-1]) * u[i] + (v[i] - vr) * u[i-1]) / (v[i] - v[i-1])
            u_list.append(ur)

    return u_list

def points_to_str(a_points, b_points):
    """string representing the order of points 'a' and 'b'"""
    a_pairs = [('a', val) for val in a_points]
    b_pairs = [('b', val) for val in b_points]
    pairs = sorted(a_pairs + b_pairs, key=lambda pair: pair[1])
    letters = [ch for ch, _ in pairs]
    return ''.join(letters)

def recognize_str(s):
    """return True if string s belong to the grammar

    The context-free grammar is given
    S -> SS
    S -> a S a
    S -> b S b
    S -> e

    The recognising automaton is implemented
    """
    toggle = {'a':'b', 'b':'a'}
    cross_num = 0
    top = None
    for ch in s:
        if not cross_num:
            cross_num = 1
            top = ch
            continue

        if ch == top:
            cross_num -= 1
        else:
            cross_num += 1

        if cross_num:
            top = toggle[top]
        else:
            top = None
    return not cross_num

def is_well_connected(a, b):
    """Two planar polygons are bind together in 3D

    Arguments:
        a_poly,
        b_poly -- lists of vertex triples
    """
    a = convert_to_float(a)
    b = convert_to_float(b)

    a_norm = poly_normal(a)
    b_norm = poly_normal(b)

    common_dir = cross_product(a_norm, b_norm)
    if not any(common_dir):
        return False

    a_list = intersect_list(a, b_norm, b[0], common_dir)
    b_list = intersect_list(b, a_norm, a[0], common_dir)

    char_str = points_to_str(a_list, b_list)
    return not recognize_str(char_str)

def run_from_console():
    a_len, = [int(num) for num in input().split()]

    a = []
    for _ in range(a_len):
        vertex = tuple(int(num) for num in input().split())
        a.append(vertex)

    b_len, = [int(num) for num in input().split()]

    b = []
    for _ in range(b_len):
        vertex = tuple(int(num) for num in input().split())
        b.append(vertex)

    if is_well_connected(a, b):
        print('YES')
    else:
        print('NO')

def __starting_point():
    run_from_console()
__starting_point()


from math import gcd, sqrt
from functools import reduce
import sys

input = sys.stdin.readline

EPS = 0.0000000001

def inp():
    return(int(input()))

def inlt():
    return(list(map(int,input().split())))

def GCD(args):
    return reduce(gcd, args)

def plane_value(plane, point):
    A, B, C, D = plane
    x, y, z = point
    return A*x + B*y + C*z + D

def plane(p1, p2, p3):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    x3, y3, z3 = p3
    a1, b1, c1 = x2 - x1, y2 - y1, z2 - z1
    a2, b2, c2 = x3 - x1, y3 - y1, z3 - z1
    a, b, c = b1 * c2 - b2 * c1, a2 * c1 - a1 * c2, a1 * b2 - b1 * a2
    d = (- a * x1 - b * y1 - c * z1)
    g = GCD([a,b,c,d])
    return a//g, b//g, c//g, d//g

def cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])

def intersection_of_two_planes(p1, p2):
    A1, B1, C1, D1 = p1
    A2, B2, C2, D2 = p2
#
    crossprod = cross([A1,B1,C1],[A2,B2,C2])

    if (A1*B2-A2*B1) != 0:
        x = ((B1*D2-B2*D1)/(A1*B2-A2*B1), crossprod[0])
        y = ((A2*D1-A1*D2)/(A1*B2-A2*B1), crossprod[1])
        z = (0,crossprod[2])
    elif (B1*C2-B2*C1) != 0:
        x = (0,crossprod[0])
        y = ((C1*D2-C2*D1)/(B1*C2-B2*C1), crossprod[1])
        z = ((B2*D1-B1*D2)/(B1*C2-B2*C1), crossprod[2])
    elif (A1*C2-A2*C1) != 0:
        x = ((C1*D2-C2*D1)/(A1*C2-A2*C1), crossprod[0])
        y = (0,crossprod[1])
        z = ((A2*D1-A1*D2)/(A1*C2-A2*C1), crossprod[2])
    else:
        return None

    return x, y, z

def line_parametric(p1, p2):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    return (x2,x1-x2), (y2,y1-y2), (z2,z1-z2)

def solve_2_by_2(row1, row2):
    a1, b1, c1 = row1
    a2, b2, c2 = row2
    if a1*b2-b1*a2:
        return (c1*b2-b1*c2)/(a1*b2-b1*a2), (a1*c2-c1*a2)/(a1*b2-b1*a2)
    else:
        return None

def sgn(x):
    return 1 if x>0 else 0 if x==0 else -1

def lines_intersection_point(i1, i2):
    x1, y1, z1 = i1
    x2, y2, z2 = i2

    try:
        t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [y1[1], -y2[1], y2[0]-y1[0]])
        if abs(t1*z1[1] - t2*z2[1] - z2[0] + z1[0]) < EPS:
            return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
        else:
            return None
    except:
        try:
            t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
            if abs(t1*y1[1] - t2*y2[1] - y2[0] + y1[0]) < EPS:
                return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
            else:
                return None
        except:
            try:
                t1, t2 = solve_2_by_2([y1[1], -y2[1], y2[0]-y1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
                if abs(t1*x1[1] - t2*x2[1] - x2[0] + x1[0]) < EPS:
                    return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
                else:
                    return None
            except:
                return None

def foo(points):
    down_cnt, up_cnt = 0, 0
    first = points[0]
    other = 1-first
    down = True
    intrusion = True
    for p in points[1:]:
        if p==first:
            intrusion = not intrusion
        else:
            if intrusion:
                if down:
                    down_cnt+=1
                else:
                    up_cnt+=1
            down = not down
    return down_cnt==up_cnt

def populate(plane, poly, tag):
    res = []
    prev = plane_value(plane,poly[-1])
    prev_serious = plane_value(plane,poly[-2]) if not prev else prev
    p_prev = poly[-1]
    for i in range(len(poly)+1):
        p = poly[i%len(poly)]
        curr = plane_value(plane,p)
        if sgn(curr) == -sgn(prev_serious):
            intersector = line_parametric(p_prev,p)
            point, t = lines_intersection_point(intersector,intersectee)
            res.append((t,tag))
            prev_serious = curr
        if sgn(curr):
            prev_serious = curr
        prev, p_prev = curr, p
    return res

x_poly, y_poly = [], []

for _ in range(inp()):
    x_poly.append(inlt())
for _ in range(inp()):
    y_poly.append(inlt())

x_plane = plane(*x_poly[:3])
y_plane = plane(*y_poly[:3])

intersectee = intersection_of_two_planes(x_plane,y_plane)

if intersectee:
    points = sorted(set(populate(y_plane,x_poly,0) + populate(x_plane,y_poly,1)))
    points = [i[1] for i in points]

    print('NO' if foo(points) else 'YES')
else:
    print('NO')


from math import gcd, sqrt
from functools import reduce
import sys

input = sys.stdin.readline

EPS = 0.000000001

def inp():
    return(int(input()))

def inlt():
    return(list(map(int,input().split())))

def GCD(args):
    return reduce(gcd, args)

def plane_value(plane, point):
    A, B, C, D = plane
    x, y, z = point
    return A*x + B*y + C*z + D

def plane(p1, p2, p3):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    x3, y3, z3 = p3
    a1, b1, c1 = x2 - x1, y2 - y1, z2 - z1
    a2, b2, c2 = x3 - x1, y3 - y1, z3 - z1
    a, b, c = b1 * c2 - b2 * c1, a2 * c1 - a1 * c2, a1 * b2 - b1 * a2
    d = (- a * x1 - b * y1 - c * z1)
    g = GCD([a,b,c,d])
    return a//g, b//g, c//g, d//g

def cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])

def intersection_of_two_planes(p1, p2):
    A1, B1, C1, D1 = p1
    A2, B2, C2, D2 = p2

    crossprod = cross([A1,B1,C1],[A2,B2,C2])

    if (A1*B2-A2*B1) != 0:
        x = ((B1*D2-B2*D1)/(A1*B2-A2*B1), crossprod[0])
        y = ((A2*D1-A1*D2)/(A1*B2-A2*B1), crossprod[1])
        z = (0,crossprod[2])
    elif (B1*C2-B2*C1) != 0:
        x = (0,crossprod[0])
        y = ((C1*D2-C2*D1)/(B1*C2-B2*C1), crossprod[1])
        z = ((B2*D1-B1*D2)/(B1*C2-B2*C1), crossprod[2])
    elif (A1*C2-A2*C1) != 0:
        x = ((C1*D2-C2*D1)/(A1*C2-A2*C1), crossprod[0])
        y = (0,crossprod[1])
        z = ((A2*D1-A1*D2)/(A1*C2-A2*C1), crossprod[2])
    else:
        return None

    return x, y, z

def line_parametric(p1, p2):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    return (x2,x1-x2), (y2,y1-y2), (z2,z1-z2)

def solve_2_by_2(row1, row2):
    a1, b1, c1 = row1
    a2, b2, c2 = row2
    if a1*b2-b1*a2:
        return (c1*b2-b1*c2)/(a1*b2-b1*a2), (a1*c2-c1*a2)/(a1*b2-b1*a2)
    else:
        return None

def sgn(x):
    return 1 if x>0 else 0 if x==0 else -1

def lines_intersection_point(i1, i2):
    x1, y1, z1 = i1
    x2, y2, z2 = i2

    try:
        t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [y1[1], -y2[1], y2[0]-y1[0]])
        if abs(t1*z1[1] - t2*z2[1] - z2[0] + z1[0]) < EPS:
            return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
        else:
            return None
    except:
        try:
            t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
            if abs(t1*y1[1] - t2*y2[1] - y2[0] + y1[0]) < EPS:
                return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
            else:
                return None
        except:
            try:
                t1, t2 = solve_2_by_2([y1[1], -y2[1], y2[0]-y1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
                if abs(t1*x1[1] - t2*x2[1] - x2[0] + x1[0]) < EPS:
                    return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
                else:
                    return None
            except:
                return None

def foo(points):
    down_cnt, up_cnt = 0, 0
    first = points[0]
    other = 1-first
    down = True
    intrusion = True
    for p in points[1:]:
        if p==first:
            intrusion = not intrusion
        else:
            if intrusion:
                if down:
                    down_cnt+=1
                else:
                    up_cnt+=1
            down = not down
    return down_cnt==up_cnt

def populate(plane, poly, tag):
    res = []
    prev = plane_value(plane,poly[-1])
    prev_serious = plane_value(plane,poly[-2]) if not prev else prev
    p_prev = poly[-1]
    for i in range(len(poly)+1):
        p = poly[i%len(poly)]
        curr = plane_value(plane,p)
        if sgn(curr) == -sgn(prev_serious):
            intersector = line_parametric(p_prev,p)
            point, t = lines_intersection_point(intersector,intersectee)
            res.append((t,tag))
            prev_serious = curr
        if sgn(curr):
            prev_serious = curr
        prev, p_prev = curr, p
    return res

x_poly, y_poly = [], []

for _ in range(inp()):
    x_poly.append(inlt())
for _ in range(inp()):
    y_poly.append(inlt())

x_plane = plane(*x_poly[:3])
y_plane = plane(*y_poly[:3])

intersectee = intersection_of_two_planes(x_plane,y_plane)

if intersectee:
    points = sorted(set(populate(y_plane,x_poly,0) + populate(x_plane,y_poly,1)))
    points = [i[1] for i in points]

    print('NO' if foo(points) else 'YES')
else:
    print('NO')


def convert_to_float(poly):
    """convert polygon vertex to float type"""
    poly_float = []
    for x, y, z in poly:
        vertex = (float(x),
                  float(y),
                  float(z))
        poly_float.append(vertex)
    return poly_float

def cross_product(a, b):
    """3-vector product"""
    return (a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0])

def dot_product(a, b):
    """scalar product of 3-vectors"""
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def vect_diff(a, b):
    """vector difference"""
    return a[0] - b[0], a[1] - b[1], a[2] - b[2]

def poly_normal(poly):
    """return normal vector for first three vertex"""
    assert len(poly) >= 3
    x, y, z = poly[:3]
    u = vect_diff(y, x)
    v = vect_diff(z, y)
    return cross_product(u, v)

def intersect_list(poly, plain_norm, plain_point, proj_dir):
    """list of intersection points

    find points where the edges enter or leave upper half-space over the plain
    :return list of points projection on proj_dir
    """
    u = [dot_product(vert, proj_dir) for vert in poly]

    vr = dot_product(plain_point, plain_norm)

    v = [dot_product(vert, plain_norm) for vert in poly]

    u_list = []
    for i in range(len(poly)):
        if (v[i-1] > vr) != (v[i] > vr):
            ur = ((vr - v[i-1]) * u[i] + (v[i] - vr) * u[i-1]) / (v[i] - v[i-1])
            u_list.append(ur)

    return u_list

def points_to_str(a_points, b_points):
    """string representing the order of points 'a' and 'b'"""
    a_pairs = [('a', val) for val in a_points]
    b_pairs = [('b', val) for val in b_points]
    pairs = sorted(a_pairs + b_pairs, key=lambda pair: pair[1])
    letters = [ch for ch, _ in pairs]
    return ''.join(letters)

def recognize_str(s):
    """return True if string s belong to the grammar

    The context-free grammar is given
    S -> SS
    S -> a S a
    S -> b S b
    S -> e

    The recognising automaton is implemented
    """
    toggle = {'a':'b', 'b':'a'}
    cross_num = 0
    top = None
    for ch in s:
        if not cross_num:
            cross_num = 1
            top = ch
            continue

        if ch == top:
            cross_num -= 1
        else:
            cross_num += 1

        if cross_num:
            top = toggle[top]
        else:
            top = None
    return not cross_num

def is_well_connected(a, b):
    """Two planar polygons are bind together in 3D

    Arguments:
        a_poly,
        b_poly -- lists of vertex triples
    """
    a = convert_to_float(a)
    b = convert_to_float(b)

    a_norm = poly_normal(a)
    b_norm = poly_normal(b)

    common_dir = cross_product(a_norm, b_norm)
    if not any(common_dir):
        return False

    a_list = intersect_list(a, b_norm, b[0], common_dir)
    b_list = intersect_list(b, a_norm, a[0], common_dir)

    char_str = points_to_str(a_list, b_list)
    return not recognize_str(char_str)

def run_from_console():
    a_len, = [int(num) for num in input().split()]

    a = []
    for _ in range(a_len):
        vertex = tuple(int(num) for num in input().split())
        a.append(vertex)

    b_len, = [int(num) for num in input().split()]

    b = []
    for _ in range(b_len):
        vertex = tuple(int(num) for num in input().split())
        b.append(vertex)

    if is_well_connected(a, b):
        print('YES')
    else:
        print('NO')

def __starting_point():
    run_from_console()
__starting_point()


def convert_to_float(poly):
    """convert polygon vertex to float type"""
    poly_float = []
    for x, y, z in poly:
        vertex = (float(x),
                  float(y),
                  float(z))
        poly_float.append(vertex)
    return poly_float

def cross_product(a, b):
    """3-vector product"""
    return (a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0])

def dot_product(a, b):
    """scalar product of 3-vectors"""
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]

def vect_diff(a, b):
    """vector difference"""
    return a[0] - b[0], a[1] - b[1], a[2] - b[2]

def poly_normal(poly):
    """return normal vector for first three vertex"""
    assert len(poly) >= 3
    x, y, z = poly[:3]
    u = vect_diff(y, x)
    v = vect_diff(z, y)
    return cross_product(u, v)

def intersect_list(poly, plain_norm, plain_point, proj_dir):
    """list of intersection points

    find points where the edges enter or leave upper half-space over the plain
    :return list of points projection on proj_dir
    """
    # vertex projection
    u = [dot_product(vert, proj_dir) for vert in poly]

    # plain anchor
    vr = dot_product(plain_point, plain_norm)

    # polygon vertex
    v = [dot_product(vert, plain_norm) for vert in poly]

    u_list = []
    for i in range(len(poly)):
        if (v[i-1] > vr) != (v[i] > vr):
            ur = ((vr - v[i-1]) * u[i] + (v[i] - vr) * u[i-1]) / (v[i] - v[i-1])
            u_list.append(ur)

    return u_list

def points_to_str(a_points, b_points):
    """string representing the order of points 'a' and 'b'"""
    a_pairs = [('a', val) for val in a_points]
    b_pairs = [('b', val) for val in b_points]
    pairs = sorted(a_pairs + b_pairs, key=lambda pair: pair[1])
    letters = [ch for ch, _ in pairs]
    return ''.join(letters)

def recognize_str(s):
    """return True if string s belong to the grammar

    The context-free grammar is given
    S -> SS
    S -> a S a
    S -> b S b
    S -> e

    The recognising automaton is implemented
    """
    toggle = {'a':'b', 'b':'a'}
    cross_num = 0
    top = None
    for ch in s:
        if not cross_num:
            cross_num = 1
            top = ch
            continue

        if ch == top:
            cross_num -= 1
        else:
            cross_num += 1

        if cross_num:
            top = toggle[top]
        else:
            top = None
    return not cross_num

def is_well_connected(a, b):
    """Two planar polygons are bind together in 3D

    Arguments:
        a_poly,
        b_poly -- lists of vertex triples
    """
    a = convert_to_float(a)
    b = convert_to_float(b)

    a_norm = poly_normal(a)
    b_norm = poly_normal(b)

    common_dir = cross_product(a_norm, b_norm)
    if not any(common_dir):
        return False

    a_list = intersect_list(a, b_norm, b[0], common_dir)
    b_list = intersect_list(b, a_norm, a[0], common_dir)

    char_str = points_to_str(a_list, b_list)
    return not recognize_str(char_str)

def run_from_console():
    a_len, = [int(num) for num in input().split()]

    a = []
    for _ in range(a_len):
        vertex = tuple(int(num) for num in input().split())
        a.append(vertex)

    b_len, = [int(num) for num in input().split()]

    b = []
    for _ in range(b_len):
        vertex = tuple(int(num) for num in input().split())
        b.append(vertex)

    if is_well_connected(a, b):
        print('YES')
    else:
        print('NO')

def __starting_point():
    run_from_console()

__starting_point()


n = int(input())
first = {}
second = set()
s1 = [0] * n
ans = [0] * n
for i in range(n):
    a, b = input().split()
    a = a[:3]
    b = b[0]
    s1[i] = b
    if a in first.keys():
        first[a].append(i)
    else:
        first[a] = [i]
        ans[i] = a
F = True
for name in first.keys():
    if not F:
        break
    if len(first[name]) > 1:
        for i in first[name]:
            c = name[:2] + s1[i]
            if c in second:
                F = False
                break
            else:
                second.add(c)
                ans[i] = c
        first[name] = 0

def process(name):
    nonlocal F
    if F == False:
        return
    if first[name] != 0 and name in second:
        t = first[name][0]
        c = name[:2] + s1[t]
        if c in second:
            F = False
            return
        else:
            second.add(c)
            ans[t] = c
            first[name] = 0
            if c in first.keys() and first[c] != 0:
                process(c)

for name in first.keys():
    process(name)

if F:
    print('YES')
    for i in range(n):
        print(ans[i])
else:
    print('NO')


def sol():
    n=int(input())
    club=['']*n
    city=['']*n
    mp={}
    for i in range(n):
        s=input().split()
        club[i]=s[0][:3]
        city[i]=s[1][:1]
        if club[i] in mp:
            mp[club[i]].add(i)
        else:
            mp[club[i]]=set()
            mp[club[i]].add(i)

    def rename(abc ,i):
        if abc in name:
            return False
        name[abc]=i
        if abc in mp and len(mp[abc])==1:
            for j in mp[abc] :
                if club[j][:2]+city[j] in name:
                    return False

                mp[abc].clear()
                #name[club[j][:2]+city[j]]=j
                return rename(club[j][:2]+city[j],j)
        return True

    for clubname in mp:
        if len(mp[clubname])>1:
            for i in mp[clubname]:
                abc=club[i][:2]+city[i]
                if abc in name:
                    return False
                if not rename(abc,i):
                    return False

    for clubname in mp:
        if len(mp[clubname])==1:
            for i in mp[clubname]:
                name[clubname]=i
    return True
name={}
if sol() :
    print('YES')
    l=['']*len(name)
    for s in name:
        l[name[s]]=s
    for i in range(len(l)):
        print(l[i])
else:
    print('NO')


def sol():
    n=int(input())
    club=['']*n
    city=['']*n
    mp={}
    for i in range(n):
        s=input().split()
        club[i]=s[0][:3]
        city[i]=s[1][:1]
        if club[i] in mp:
            mp[club[i]].add(i)
        else:
            mp[club[i]]=set()
            mp[club[i]].add(i)

    def rename(abc ,i):
        if abc in name:
            return False
        name[abc]=i
        if abc in mp and len(mp[abc])==1:
            for j in mp[abc] :
                if club[j][:2]+city[j] in name:
                    return False

                mp[abc].clear()
                #name[club[j][:2]+city[j]]=j
                return rename(club[j][:2]+city[j],j)
        return True

    for clubname in mp:
        if len(mp[clubname])>1:
            for i in mp[clubname]:
                abc=club[i][:2]+city[i]
                if abc in name:
                    return False
                if not rename(abc,i):
                    return False

    for clubname in mp:
        if len(mp[clubname])==1:
            for i in mp[clubname]:
                name[clubname]=i
    return True
name={}

if sol() :
    print('YES')
    l=['']*len(name)
    for s in name:
        l[name[s]]=s
    for i in range(len(l)):
        print(l[i])
else:
    print('NO')


from collections import defaultdict
names = int(input())
inp = [input().split() for x in range(names)]
choice = []
res = defaultdict(lambda: [])
for x, word in enumerate(inp):
    choice.append(False)
    res[word[0][:3]].append(x)

while True:
    changes = []
    for key in list(res.keys()):
        if len(res[key]) > 1:
            # All choice = False options must be changed
            remove = []
            for i, index in enumerate(res[key]):
                if choice[index]: continue
                remove.append(i)
                choice[index] = True
                changes.append((inp[index][0][:2] + inp[index][1][0], index))
            for i in remove[::-1]:
                del res[key][i]
    if len(changes) == 0: break
    for word, i in changes:
        res[word].append(i)

bad = False
for key in list(res.keys()):
    if len(res[key]) > 1: bad = True

if bad:
    print("NO")
else:
    print("YES")
    for i in range(names):
        if choice[i]:
            print(inp[i][0][:2] + inp[i][1][0])
        else:
            print(inp[i][0][:3])


from sys import stdin

n = int(stdin.readline().strip())
T,A = [],[]
N,M = {},{}
for _ in range(n):
    t,h = stdin.readline().split()
    n1,n2 = t[:3],t[:2]+h[0]
    N[n1] = N.get(n1,0)+1
    T.append((n1,n2))
    A.append(n1)

def solve():
    for i in range(n):
        n1,n2 = T[i]
        if n1 not in M and N[n1]==1:
            M[n1] = i
            continue
        while n2 in M:
            j = M[n2]
            if n2==T[j][1]:
                return False
            M[n2],A[i]=i,n2
            i,n2 = j,T[j][1]
        else:
            M[n2],A[i] = i,n2
    return True

if solve():
    print("YES")
    print('\n'.join(A))
else:
    print("NO")


#return if sa contains a real prefix: sb
def isPrefix( sa , sb ):
    if len(sa) <= len(sb):
        return False
    return sa[0:len(sb)] == sb

def getOrder( sa , sb ):
    for i in range( 0 , min( len(sa) , len(sb) ) ):
        if sa[i] != sb[i]:
            return sa[i],sb[i]

test = False
if test:
    fp = open("C-4.in","r")
    n = int(fp.readline().strip())
    names = [ fp.readline().strip() for i in range(0,n)]
    fp.close()
else:
    n = int(input().strip())
    names = [ input().strip() for i in range(0,n)]

g = [[False]*26 for i in range(0,26)]

res = True
for i in range(1,n):
    if names[i-1] == names[i] or isPrefix( names[i] , names[i-1] ):
        continue
    elif isPrefix( names[i-1] , names[i] ):
        res = False
        break
    else:
        ca,cb = getOrder( names[i-1] , names[i] )
        #print(ca,"<",cb)
        if g[ord(cb)-ord('a')][ord(ca)-ord('a')]:
            res = False
            break
        else:
            g[ord(ca)-ord('a')][ord(cb)-ord('a')] = True

def printG():
    print("  abcdefghijklmnopqrstuvwxyz")
    for i in range(0,26):
        print( chr( ord("a") + i ) , "".join( [ "1" if x else "0" for x in g[i]] ) , sep = "")
#printG()

if not res:
    print("Impossible")
else:

    def getZeroIndegreeNode():
        for i in range(0,26):
            if not used[i] and indegree[i] == 0:
                return i
        return -1
    #topo sort
    theOrder = []
    indegree = [0] * 26
    used = [False] * 26

    #calc indegree
    for i in range(0,26):
        ithIndegree = 0
        for j in range(0,26):
            if g[j][i]: ithIndegree += 1
        indegree[i] = ithIndegree

    for i in range(0,26):
        zeroIndegreeNode = getZeroIndegreeNode()
        if zeroIndegreeNode == -1:
            res = False
            break
        else:
            used[zeroIndegreeNode] = True
            theOrder.append( chr( ord('a') + zeroIndegreeNode ) )
            for j in range(0,26):
                if g[zeroIndegreeNode][j]:
                    indegree[j] -= 1

    if not res:
        print("Impossible")
    else:
        print( "".join( theOrder ) )


#import sys
#sys.stdin = open('in.txt')
#sys.setrecursionlimit(10000)
def isPrefix(sa, sb):
    if len(sa) <= len(sb):
        return False
    return sa[0:len(sb)] == sb

def getOrder(sa, sb):
    for i in range(0, min(len(sa), len(sb))):
        if sa[i] != sb[i]:
            return sa[i], sb[i]

test = False
if test:
    fp = open("in.txt", 'r')
    n = int(fp.readline().strip())
    names = [fp.readline().strip() for i in range(0, n)]
    fp.close()
else:
    n = int(input().strip())
    names = [input().strip() for i in range(0, n)]

g = [[False] * 26 for i in range(0, 26)]

res = True
for i in range(1, n):
    if names[i - 1] == names[i] or isPrefix(names[i], names[i - 1]):
        continue
    elif isPrefix(names[i - 1], names[i]):
        res = False
        break
    else:
        ca, cb = getOrder(names[i - 1], names[i])
        #print(ca, '<', cb)
        if g[ord(cb) - ord('a')][ord(ca) - ord('a')]:
            res = False
            break
        else:
            g[ord(ca) - ord('a')][ord(cb) - ord('a')] = True

def printG():
    print("   abcdefghijklmnopqrstuvwxyz")
    for i in range(0, 26):
        print(chr(ord('a') + i), "".join(["1" if x else "0" for x in g[i]]), sep =

"")
#printG()

if not res:
    print("Impossible")
else:

    def getZeroIndegreeNode():
        for i in range(0, 26):
            if not used[i] and indegree[i] == 0:
                return i
        return -1
    #topo sort
    theOrder = []
    indegree = [0] * 26
    used = [False] * 26

    #calc indegree
    for i in range(0, 26):
        ithIndegree = 0
        for j in range(0, 26):
           if g[j][i]: ithIndegree += 1
        indegree[i] = ithIndegree
    for i in range(0, 26):
        zeroIndegreeNode = getZeroIndegreeNode()
        if zeroIndegreeNode == -1:
            res = False
            break
        else:
            used[zeroIndegreeNode] = True
            theOrder.append(chr(ord('a') + zeroIndegreeNode))
            for j in range(0, 26):
                if g[zeroIndegreeNode][j]:
                    indegree[j] -= 1
    if not res:
        print("Impossible")
    else:
        print("".join(theOrder))


#import sys
#sys.stdin = open('in.txt')
#sys.setrecursionlimit(10000)
def isPrefix(sa, sb):
    if len(sa) >= len(sb):
        return False
    return sa == sb[0:len(sa)]

def getOrder(sa, sb):
    for i in range(min(len(sa), len(sb))):
        if sa[i] != sb[i]:
            return sa[i], sb[i]

test = False
if test:
    fp = open('in.txt', 'r')
    n = int(fp.readline().strip())
    names = [fp.readline().strip() for _ in range(n)]
    fp.close()
else:
    n = int(input().strip())
    names = [input().strip() for _ in range(n)]

res = True
g = [[False] * 26 for _ in range(26)]
"""
for i in range(26):
    for j in range(26):
        g[i][j] = False
"""
def printG():
    print(" abcdefghijklmnopqrstuvwxyz")
    for i in range(0, 26):
        print(chr(ord('a') + i), "".join(["1" if x else "0" for x in g[i]]), sep =

"")
#get a table
for i in range(n - 1):
    if names[i] == names[i + 1] or isPrefix(names[i], names[i + 1]):
        continue
    elif isPrefix(names[i + 1], names[i]):
        res = False
        break
    else:
        ca, cb = getOrder(names[i], names[i + 1])
        #print(ca, '<', cb)
        if g[ord(cb) - ord('a')][ord(ca) - ord('a')]:
            res = False
            break
        else:
            #pass
            #printG()
            a = ord(ca) - ord('a')
            b = ord(cb) - ord('a')
            g[a][b] = True
            #printG()

if not res:
    print("Impossible")
else:
    def getZeroIndegreeNode():
       for i in range(26):
          if not vis[i] and Indegree[i] == 0:
              return i
       return -1

    #cacl Indegree
    strOrder = []
    vis = [False] * 26
    Indegree = [0] * 26
    for i in range(26):
        ithIndegree = 0
        for j in range(26):
            if g[j][i]: ithIndegree += 1
        Indegree[i] = ithIndegree

    #get the order string
    for i in range(26):
        ZeroIndegreeNode = getZeroIndegreeNode()
        if ZeroIndegreeNode == -1:
            res = False
            break
        else:
            strOrder.append(chr(ord('a') + ZeroIndegreeNode))
            vis[ZeroIndegreeNode] = True
            for i in range(26):
                if g[ZeroIndegreeNode][i]:
                    Indegree[i] -= 1
    if not res:
        print("Impossible")
    else:
        print("".join(strOrder))


import string

def make_link(G, char1, char2):
    if char1 in G:
        if char2 in G[char1]:
            return
        else:
            G[char1].append(char2)
    else:
        G[char1] = [char2]

def make_order(G, str1, str2):
    for i in range(min(len(str1), len(str2))):
        if str1[i] != str2[i]:
            make_link(G, str1[i], str2[i])
            return True

    if len(str2) > len(str1):
        return True
    else:
        return False

def topological_sort(G, ans, k = '', visited = {}):
    if visited.get(k, True) == False:
        return True
    if k not in visited:
        visited[k] = False
        for next in G.get(k, []):
            if topological_sort(G, ans, next, visited):
                return True
        visited[k] = True
        ans.insert(0, k)
    return False

def main():
    N = int(input())

    strs = [input() for i in range(N)]

    G = {}

    for i in range(N-1):
        if not make_order(G, strs[i], strs[i + 1]):
            print("Impossible")
            return

    G[''] = reversed(string.ascii_lowercase)

    ans = []
    if topological_sort(G, ans):
        print("Impossible")
    else:
        print(''.join(ans))

main()


n=int(input())
x=input()
a=len(x)
lex=dict()
ALPHA=list('abcdefghijklmnopqrstuvwxyz')

for i in ALPHA:
    for j in ALPHA:
        lex[(i,j)]=0

for i in range(n-1):
    y=input()
    b=len(y)
    for j in range(min([a,b])):
        if x[j]!=y[j]:
            if lex[(x[j],y[j])]==-1:
                print('Impossible')
                raise SystemExit
            else:
                lex[(x[j],y[j])]=1
                lex[(y[j],x[j])]=-1
                x=y
                a=b
            break
        if j==(min([a,b])-1):
            if a>b:
                print('Impossible')
                raise SystemExit
            x=y
            a=b

def biggest(alphabet):
    for i in alphabet:
        t=0
        for j in alphabet:
            if lex[(i,j)]<0:
                t=1
                break
        if t==0:
            return i
    return -1
newalpha=['']*26
i=0
while ALPHA!=[]:
    BIG=biggest(ALPHA)
    if biggest(ALPHA)==-1:
        print('Impossible')
        raise SystemExit
    newalpha[i]=BIG
    i=i+1
    ALPHA.remove(BIG)

print(''.join(newalpha))


NN = 18
MI = [1<<100] * ((1<<NN+1)-1)

def update(x):
    i = (1<<NN) - 1 + x
    MI[i] = x
    while True:
        i = (i-1) // 2
        MI[i] = min(MI[2*i+1], MI[2*i+2])
        if i == 0:
            break

def rangemin(a, b):
    l = a + (1<<NN)
    r = b + (1<<NN)
    mi = 1<<100
    while l < r:
        if l%2:
            mi = min(mi, MI[l-1])
            l += 1
        if r%2:
            r -= 1
            mi = min(mi, MI[r-1])
        l >>= 1
        r >>= 1
    return mi

N = int(input())
A = [int(a) for a in input().split()]
B = sorted([(A[i], i) for i in range(N)])
i = 0 # large
j = 0 # small
X = [1<<20] * (2*N)
while i < N:
    while 2 * B[j][0] < B[i][0]:
        update(B[j][1])
        update(B[j][1]+N)
        j += 1
    X[B[i][1]] = rangemin(B[i][1], B[i][1]+N)
    X[B[i][1]+N] = X[B[i][1]] + N
    i += 1
for i in range(2*N-1)[::-1]:
    X[i] = min(X[i], X[i+1])
for i in range(N):
    X[i] -= i
X = [a if a < (1<<20) else -1 for a in X[:N]]
print(*X)


import sys
input = sys.stdin.readline

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

B=[(-a,i) for i,a in enumerate(A)]

from collections import deque

LIST=deque()
LIST.append(B[0])

for b,i in B[1:]:
    if b>LIST[-1][0]:
        LIST.append((b,i))

import bisect

DIS=[-1]*n

for i in range(n-1,-1,-1):
    x=bisect.bisect(LIST,(-A[i]//2,1<<20))
    if x<len(LIST):
        DIS[i]=LIST[x][1]

    while len(LIST)>=1 and A[i]<=-LIST[0][0]:
        LIST.popleft()

    LIST.appendleft(B[i])

if max(DIS)==-1:
    print(*[-1]*n)
    return

for i in range(n):
    if DIS[i]!=-1:
        start=i
        break

ANS=[-1]*n

if DIS[start]>start:
    ANS[start]=DIS[start]-start
else:
    ANS[start]=DIS[start]+(n-start)

for i in range(start-1,-1,-1):
    if DIS[i]==-1:
        ANS[i]=ANS[(i+1)%n]+1
    else:
        if DIS[i]>i:
            ANS[i]=min(DIS[i]-i,ANS[(i+1)%n]+1)
        else:
            ANS[i]=min(DIS[i]+(n-i),ANS[(i+1)%n]+1)

for i in range(n-1,-1,-1):
    if DIS[i]==-1:
        ANS[i]=ANS[(i+1)%n]+1
    else:
        if DIS[i]>i:
            ANS[i]=min(DIS[i]-i,ANS[(i+1)%n]+1)
        else:
            ANS[i]=min(DIS[i]+(n-i),ANS[(i+1)%n]+1)

for i in range(n-1,-1,-1):
    if DIS[i]==-1:
        ANS[i]=ANS[(i+1)%n]+1
    else:
        if DIS[i]>i:
            ANS[i]=min(DIS[i]-i,ANS[(i+1)%n]+1)
        else:
            ANS[i]=min(DIS[i]+(n-i),ANS[(i+1)%n]+1)

print(*ANS)


import sys
readline = sys.stdin.readline

class Segtree:
    def __init__(self, A, intv, initialize = True, segf = max):
        self.N = len(A)
        self.N0 = 2**(self.N-1).bit_length()
        self.intv = intv
        self.segf = segf
        if initialize:
            self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N)
            for i in range(self.N0-1, 0, -1):
                self.data[i] = self.segf(self.data[2*i], self.data[2*i+1])
        else:
            self.data = [intv]*(2*self.N0)

    def update(self, k, x):
        k += self.N0
        self.data[k] = x
        while k > 0 :
            k = k >> 1
            self.data[k] = self.segf(self.data[2*k], self.data[2*k+1])

    def query(self, l, r):
        L, R = l+self.N0, r+self.N0
        s = self.intv
        while L < R:
            if R & 1:
                R -= 1
                s = self.segf(s, self.data[R])
            if L & 1:
                s = self.segf(s, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def binsearch(self, l, r, check, reverse = False):
        L, R = l+self.N0, r+self.N0
        SL, SR = [], []
        while L < R:
            if R & 1:
                R -= 1
                SR.append(R)
            if L & 1:
                SL.append(L)
                L += 1
            L >>= 1
            R >>= 1

        if reverse:
            for idx in (SR + SL[::-1]):
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                if check(self.data[2*idx+1]):
                    idx = 2*idx + 1
                else:
                    idx = 2*idx
            return idx
        else:
            for idx in (SL + SR[::-1]):
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                if check(self.data[2*idx]):
                    idx = 2*idx
                else:
                    idx = 2*idx + 1
            return idx - self.N0

N = int(readline())
A = list(map(int, readline().split()))
B = [2*a for a in A]
B *= 3
inf = 2*10**9
B.append(-2)
T = Segtree(B, inf, True, min)

NN = T.N0

J = [0]*(NN+1)
J[3*N] = inf
KK = [None]*(NN+1)
for i in range(3*N-1, -1, -1):
    a = A[i%N]
    k = T.binsearch(i, NN, lambda x: x < a ,reverse = False)
    KK[i] = k
    J[i] = min(J[i+1], k)

Ans = [-1]*N
for i in range(N):
    j = J[i]
    if j == 3*N:
        continue
    Ans[i] = j - i
print(*Ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

class Binary_Indexed_Tree():
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)

    def add(self, i, x):
        while i <= self.n:
            self.data[i] += x
            i += i & -i

    def get(self, i):
        return self.sum_range(i, i)

    def sum(self, i):
        ret = 0
        while i:
            ret += self.data[i]
            i &= i-1
        return ret

    def sum_range(self, l, r):
        return self.sum(r)-self.sum(l-1)

    def lower_bound(self, w):
        if w<=0:
            return 0
        i = 0
        k = 1<<(self.n.bit_length())
        while k:
            if i+k <= self.n and self.data[i+k] < w:
                w -= self.data[i+k]
                i += k
            k >>= 1
        return i+1

class RangeMinimumQuery:
    def __init__(self, n, func=min, inf=float("inf")):
        self.n0 = 2**(n-1).bit_length()
        self.op = func
        self.inf = inf
        self.data = [self.inf]*(2*self.n0)

    def construct(self, lis):
        for i, x in enumerate(lis):
            self.data[i+self.n0-1] = x
        for i in range(self.n0-2, -1, -1):
            self.data[i] = self.op(self.data[2*i+1], self.data[2*i+2])

    def query(self, l,r):
        l += self.n0
        r += self.n0
        res = self.inf
        while l < r:
            if r&1:
                r -= 1
                res = self.op(res, self.data[r-1])
            if l&1:
                res = self.op(res, self.data[l-1])
                l += 1
            l >>=1
            r >>=1
        return res

n = int(input())
a = list(map(int, input().split()))
a = [i*2 for i in a]
BIT = Binary_Indexed_Tree(2*n)
RMQ = RangeMinimumQuery(2*n)
RMQ.construct(a+a)

b = [[j,i] for i,j in enumerate(a)]
b.sort(reverse=True)
ans = [0]*n
for j, i in b:
    cnt = BIT.sum(2*n-i)
    tmp = float("inf")
    if cnt:
        p = 2*n-BIT.lower_bound(cnt)
        tmp = p-i + ans[p%n]
    BIT.add(2*n-i, 1)
    BIT.add(n-i, 1)
    left = i
    right = 2*n
    if RMQ.query(i, right) < j//2:
        while right-left>1:
            mid = (right+left)//2
            if RMQ.query(i, mid) < j//2:
                right = mid
            else:
                left = mid
        tmp = min(tmp, right-i-1)
    ans[i] = tmp
ans = [i if i!=float("inf") else -1 for i in ans]
print(*ans)


import sys
input = sys.stdin.readline

class SegTree(object):
	"""docstring for SegTree"""
	def __init__(self, n, arr):
		self.n = n
		self.arr = arr
		self.tree = [0 for i in range(2*n)]

	def construct(self): # Construction
		for i in range(self.n):
			self.tree[n+i] = self.arr[i]
		for i in range(n-1,0,-1):
			self.tree[i] = self.function(self.tree[2*i],self.tree[2*i+1])

	def update(self,index,change):
		start = index+self.n
		self.tree[start] = value
		while start>0:
			self.tree[start] = self.function(self.tree[2*start],self.tree[2*start+1])
			start = start//2

	def calc(self,low,high): # 0-indexed
		low+=self.n
		high+=self.n
		ans = 0 # Needs to initialised
		while low<high:
			if low%2:
				ans = self.function(ans, self.tree[low])
				low += 1
			if high%2:
				high -= 1
				ans = self.function(ans, self.tree[high])
			low = low//2
			high = high//2
		return ans

	def function(self,a,b): # Function used to construct Segment Tree
		return max(a,b)

n = int(input())*3
a = list(map(int,input().split()))
a = a + a + a
st = SegTree(n,a)
st.construct()
ans = [-1]*n
m = a[0]
flag = 0
for i in range(1,n):
	if a[i]<=(m-1)//2:
		ans[0] = i
		flag = 1
		prev = i
		break
	else:
		m = max(m,a[i])
if not flag:
	print(*ans[0:n//3])
	return
for i in range(1,n//3):
	if a[i]>=a[i-1]:
		ans[i] = ans[i-1]-1
	else:
		maxx = st.calc(i,prev+1)
		while a[prev]>(maxx-1)//2:
			# print (prev,i,maxx)
			maxx = max(maxx,a[prev])
			prev += 1
		ans[i] = prev - i
print(*ans[0:n//3])


def f():
    n, m, k = map(int, input().split())
    p = [[] for i in range(n + 1)]
    for i in range(m):
        a, b = map(int, input().split())
        p[a].append(b)
        p[b].append(a)
    t, r = [0] * (n + 1), [1]
    x = t[1] = 1
    i = 0 - k
    while True:
        for y in p[x]:
            if t[y] == 2: return r[r.index(y): ]
            if t[y]: continue
            t[y], x = 1, y
            r.append(x)
            i += 1
            if i >= 0: t[r[i]] = 2
            break
t = f()
print(len(t))
print(' '.join(map(str, t)))


n,l,k=map(int,input().split())
c=list([] for i in range(n+1))
for i in range(l):
    x,y=map(int,input().split())
    c[x].append(y)
    c[y].append(x)
d=list(0 for i in range(n+1))
d[1]=1
now=1
time=1
f=True
while f:
    time+=1
    v=0
    while v>=0:
        if d[c[now][v]]==0:
            now=c[now][v]
            d[now]=time
            v=-1
        elif d[c[now][v]]+k<time:
            f=False
            mintime=d[c[now][v]]
            v=-1
        else:
            v+=1
g=list(0 for i in range(time-mintime))
for i in range(n+1):
    if d[i]>=mintime:
        g[d[i]-mintime]=i
print(time-mintime)
print(*g)


import sys
import threading

def put():
    return list(map(int, sys.stdin.readline().split()))

def dfs(i, h):
    vis[i] =h
    done[i]=1
    element.append(i)
    for j in graph[i]:
        if vis[j]!=0 and h-vis[j]>=k:
                ind = element.index(j)
                ans.extend(element[ind:])
                raise ValueError
        elif done[j]==0:
            dfs(j,h+1)
    vis[i]=0
    element.pop()

def solve():
    try:
        for i in range(1, n+1):
            if done[i]==0:
                dfs(i,1)
    except:
        print(len(ans))
        print(*ans)

n,m,k = put()
graph = [[] for _ in range(n+1)]
for i in range(m):
    x,y = put()
    graph[x].append(y)
    graph[y].append(x)

done,vis = [0]*(n+1),[0]*(n+1)
element,ans = [],[]

max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()


def find_cycle_optimum(n,m,k,adj):
    path = [1]
    visited = [-1 for _ in range(n+1)]
    visited[1] = 1
    while True:
        v = path[-1]
        visited[v] = len(path) - 1
        for w in adj[v]:
            if visited[w] == -1:
                path.append(w)
                break
            elif len(path) - visited[w] > k:
                return path[visited[w]::]

def main ():
    n,m,k =[int(i) for i in input().split()]
    adj = [[] for i in range(n+1)]
    for _ in range(m):
        u,v = [int(i) for i in input().split()]
        adj[u].append(v)
        adj[v].append(u)
    c = find_cycle_optimum(n,m,k,adj)
    l = len(c)
    print(l)
    print(' '.join(str(v) for v in c))

main()


import sys
from sys import stdin

import bisect

def LIS(lis , end):

    seq = []

    for c in lis:
        ind = bisect.bisect_right(seq,c)

        if ind == len(seq):
            seq.append(c)
        else:
            if ind != 0:
                seq[ind] = c

    return bisect.bisect_right(seq,end)

tt = 1

for loop in range(tt):

    n,k = list(map(int,stdin.readline().split()))
    a = list(map(int,stdin.readline().split()))
    b = list(map(int,stdin.readline().split()))

    a = [float("-inf")] + a + [float("inf")]
    b = [0] + b + [n+1]
    for i in range(n+2):
        a[i] -= i

    for i in range(len(b)-1):
        if a[b[i]] > a[b[i+1]]:
            print(-1)
            return

    ans = n+1
    for i in range(len(b)-1):
        now = LIS(a[ b[i]:b[i+1] ] , a[b[i+1]])
        ans -= now

    print (ans)


import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,k = inpl()
a = inpl()
if k != 0:
    b = inpl()
pre = 0
bad = False
for i in range(k-1):
    lind = b[i]-1; rind = b[i+1]-1
    l = a[lind]; r = a[rind]
    if r-l < rind-lind: bad = True
if bad: print(-1); quit()
l = []; r = []; dv = []
if k == 0:
    l = [-INF]; r = [INF]; dv = [a]
else:
    for _,i in enumerate(b):
        dv.append(a[pre:i-1])
        if pre == 0: l.append(-INF)
        else: l.append(a[pre-1])
        r.append(a[i-1])
        pre = i
    dv.append(a[pre:])
    l.append(a[pre-1]); r.append(INF)
# print(dv,l,r)
res = 0
for i in range(k+1):
    li = []
    L = l[i]+1; R = r[i]-1
    ln = len(dv[i])
    for j,x in enumerate(dv[i]):
        if L+j <= x <= R-ln+j+1:
            li.append(x-j)
    dp = [INF] * (len(li))
    for i,x in enumerate(li):
        ind = bisect_right(dp,x)
        dp[ind] = x
    ans = len(li)
    for i,x in enumerate(dp):
        if x == INF:
            ans = i
            break
    res += ln-ans
print(res)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key, lru_cache

import sys
input = sys.stdin.readline
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]

def give(i, j, mi, ma):
    # print(i, j, mi, ma)
    l1 = []
    for k in range(i, j + 1):
        if mi <= l[k] <= ma:
            ind = br(l1, l[k])
            if ind == len(l1):l1.append(l[k])
            else:l1[ind] = l[k]
    # print(j - i + 1, len(l1))
    return j - i - len(l1) + 1

n, k = li()
l = [0] + li()

if k:
    b = li()
else:b = []

for i in range(1, k):
    if l[b[i]] - l[b[i - 1]] < b[i] - b[i - 1] or l[b[i]] < l[b[i - 1]]:
        print(-1)
        return

for i in range(n + 1):l[i] -= i

if k:
    ans = give(1, b[0] - 1, -float('inf'), l[b[0]])
    ans += give(b[-1] + 1, n, l[b[-1]], float('inf'))

    for i in range(1, k):
        ans += give(b[i-1], b[i], l[b[i - 1]], l[b[i]])

else:
    ans = give(1, n, -float('inf'), float('inf'))

print(ans)


import sys
input=sys.stdin.readline
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = []
if k:
    b = list(map(int,input().split()))
for i in range(n):
    a[i] -= i
prev = -1
ans = 0
for j in range(k + 1):
    if j < k:
        val = b[j] - 1
        if j and a[prev] > a[val]:
            print(-1)
            quit()
    else:
        val = n
    if val - prev > 1:
        path = [0] * (val - prev - 1)
        arr = [0] * (val - prev)
        found = 0
        for i in range(val - prev - 1):
            if val < n and a[i + prev + 1] > a[val]:
                continue
            elif prev + 1 and a[prev] > a[i + prev + 1]:
                continue
            l = 1
            h = found
            while h >= l:
                m = (l + h + 1) // 2
                if a[arr[m] + prev + 1] <= a[i + prev + 1]:
                    l = m + 1
                else:
                    h = m - 1
            path[i] = arr[l - 1]
            arr[l] = i
            if l > found:
                found = l
        ans += found
    prev = val
print(n - k - ans)


import sys,os,io
input = sys.stdin.readline
from bisect import bisect_right
N, K = map(int, input().split())
A = [-float('inf')]+list(map(int, input().split()))+[float('inf')]
if K:
  B = [0]+list(map(int, input().split()))+[N+1]
else:
  B = [0,N+1]
ans = N-K
for k in range(K+1):
  left, right = B[k], B[k+1]
  if A[left]-left>A[right]-right:
    print(-1)
    break
  lis = []
  for i in range(left+1,right):
    if not A[left]-left<=A[i]-i<=A[right]-right:
      continue
    ind = bisect_right(lis,A[i]-i)
    if ind == len(lis):
      lis.append(A[i]-i)
    else:
      lis[ind] = A[i]-i
  ans -= len(lis)
else:
  print(ans)


import sys
def Z(s):
    return int(s)-1

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

Hotels=[False]*(n)

Rep=[0]*(n+1)
Chains=[]

Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
    if(Type[i]==1):
        Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))

for item in A:
    Rep[item]+=1
for i in range(n):
    if(Hotels[i]):
        Chains.append([i])
        x=A[i]
        if(x==-1):
            continue
        while(A[x]!=-1 and Rep[x]<=1):
            Chains[-1].append(x)
            x=A[x]
        if(Rep[x]<=1):
            Chains[-1].append(x)

if(n==1):
    print(1)
    print(1)
else:

    X=max(Chains,key=len)

    sys.stdout.write(str(len(X))+"\n")
    sys.stdout.write(str(X[-1]+1))

    for i in range(len(X)-2,-1,-1):
        sys.stdout.write(" "+str(X[i]+1))


3

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

n, = readln()
t = (-1,) + readln()
v = (0,) + readln()
cnt = [0] * (n + 1)
for i in range(1, n + 1):
    cnt[v[i]] += 1
ans = []
for i in range(1, n + 1):
    if t[i] == 1:
        j = i
        tmp = [i]
        while(t[v[j]] == 0) and cnt[v[j]] == 1:
            j = v[j]
            tmp.append(j)
        if(len(tmp) > len(ans)):
            ans = tmp
print(len(ans))
print(*tuple(reversed(ans)))


n = int(input())
a, b = [0] + list(map(int, input().split())), [0] + list(map(int, input().split()))
ans, p = [], [0] * (n + 1)
for i in b:
    p[i] += 1
for i in range(1, n + 1):
    if a[i] == 1:
        t = [i]
        x = b[i]
        while p[x] == 1:
            t.append(x)
            x = b[x]
        if len(t) > len(ans): ans = t[:]
ans.reverse()
print(len(ans))
print(' '.join(str(x) for x in ans))


import sys

n = int(input())
type = input().split()
fa = list(map(int, input().split()))

degree = [0] * (n+1)
for i in fa:
    degree[i]+=1

type = [0] + type
fa= [0] + fa
max=0
maxi=0

for i in range(1, n+1):
    if type[i] == '1': # it's hotel
        cnt = 0

        cur=fa[i]
        while not (cur==0 or type[cur] == '1' or degree[cur]>1):
            cnt+=1
            cur=fa[cur]

        if(max <= cnt):
            max=cnt
            maxi=i
print(max+1)
ans = []
cur=maxi
while not(not cur or type[cur] == '1' and cur!=maxi or degree[cur]>1):
    ans.append(cur)
    cur=fa[cur]

print(*ans[::-1])


import sys

def solve():
    n = int(input())
    types = list(map(int, input().split()))
    a = list(map(int, input().split()))
    res = list()
    count = [0] * (n + 1)
    for val in a:
        count[val-1]+=1
    for i in range(n):
        if types[i] == 1:
            temp = list()
            cur = i
            while True:
                if count[cur] > 1 or cur < 0: break
                temp.append(cur + 1)
                cur = a[cur] - 1
            if len(temp) > len(res):
                res = temp
    print(len(res))
    return ' '.join(map(str, res[::-1]))
    # adj = [list() for _ in range(n)]
    # visited = [0] * (n + 1)
    # best = -1
    # start = -1
    # bestlen = 0
    # for i in range(n):
    #     if a[i] > 0: adj[a[i] - 1].append(i)
    # # counter = 0
    # for i in range(n):
    #     if visited[i] == 0:
    #         cur = i
    #         # temp = list()
    #         # temp.append(cur)
    #         temp = 1
    #         visited[cur] += 1
    #         while len(adj[cur]) == 1:
    #             # print(cur)
    #             if len(adj[cur]) > 0 and adj[cur][0] == cur: break
    #             cur = adj[cur][0]
    #             # temp.append(cur)
    #             visited[cur]+=1
    #             temp+=1
    #             # if counter == 10000: return - 1
    #         if types[cur] == 1 and temp > bestlen:
    #             best = cur
    #             bestlen = temp
    #             start = i
    # res = list()
    # while True:
    #     res.append(best)
    #     if best == start: break
    #     next = a[best] - 1
    #     best = next
    # res = res[::-1]
    # for i in range(len(res)): res[i] += 1
    # print(len(res))
    # return ' '.join(map(str, res))

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())


import sys

def solve():
    n = int(input())
    types = list(map(int, input().split()))
    a = list(map(int, input().split()))
    res = list()
    count = [0] * (n + 1)
    for val in a:
        count[val-1]+=1
    for i in range(n):
        if types[i] == 1:
            temp = list()
            cur = i
            while True:
                if count[cur] > 1 or cur < 0: break
                temp.append(cur + 1)
                cur = a[cur] - 1
            if len(temp) > len(res):
                res = temp
    print(len(res))
    return ' '.join(map(str, res[::-1]))

if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())


n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))

ans, cnt = [], [0 for i in range(n + 1)]

for i in a:
    cnt[i] += 1

for i in range(1, n + 1):
    if t[i] == 1:
        crt = [i]
        x = a[i]
        while cnt[x] == 1:
            crt.append(x)
            x = a[x]
        if len(crt) > len(ans):
            ans = crt[:]
ans.reverse()
print(len(ans))
print(' '.join(map(str, ans)))


n = int(input())

t = [0] + list(map(int, input().split()))

a = [0] + list(map(int, input().split()))

ans, cnt = [], [0 for i in range(n + 1)]

for i in a:

    cnt[i] += 1

for i in range(1, n + 1):

    if t[i] == 1:

        crt = [i]

        x = a[i]

        while cnt[x] == 1:

            crt.append(x)

            x = a[x]

        if len(crt) > len(ans):

            ans = crt[:]

ans.reverse()

print(len(ans))

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

# Made By Mostafa_Khaled


n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))

res, cnt = [], [0] * (n + 1)
for i in a:
    cnt[i] += 1
for i in range(1, n+1):
    if t[i] == 0:
        continue
    curr_res = [i]
    x = a[i]
    while cnt[x] == 1:
        curr_res.append(x)
        x = a[x]
    if len(curr_res) > len(res):
        res = curr_res[:]
res.reverse()
print(len(res))
print(*res)


from math import factorial
n = int(input())
a = n * (n - 1) * (n - 2) * (n - 3) * (n - 4)
ans = a // factorial(5)
a *= (n - 5)
ans += a // factorial(6)
a *= (n - 6)
ans += a // factorial(7)
print(ans)


n = int(input())

ret = 0
ways = 1
for i in range(1, 8):
    ways = ways * (n - i + 1) // i
    if i >= 5:
        ret += ways

print(ret)


import sys
def fact(n):
	ret = 1
	for x in range(1, n + 1):
		ret = ret * x
	return ret

def C(n, k):
	return fact(n) // (fact(k) * (fact(n - k)))
n = int(input())
print(C(n, 7) + C(n, 6) + C(n, 5))


from functools import reduce
from math import factorial
n = int(input())
C_n_k = lambda n, k: reduce(lambda x, y: x*y, list(range(n, n-k, -1))) // factorial(k)
print(C_n_k(n, 7) + C_n_k(n, 6) + C_n_k(n, 5))


from math import factorial as f
n = int(input())
res = 0
for i in range(5, 8):
    res += f(n) // (f(n - i) * f(i))
print(res)


def fact(i):
  ans = 1
  for j in range(1, i + 1):
    ans *= j
  return ans

def c(i, j):
  return fact(i) // (fact(j) * fact(i - j))

n = int(input())
print(c(n, 5) + c(n, 7) + c(n, 6))


def cnk(n, k):
    return f[n] // f[n - k] // f[k]

n = int(input())

f = [0 for i in range(n + 1)]
f[0] = 1
for i in range(1, n + 1):
    f[i] = f[i - 1] * i
ans = 0
for i in range(5, 8):
    if (i <= n):
        ans += cnk(n, i)
print(ans)


from math import factorial as f

x = int(input())
#x, y = map(int, input().split())

print(f(x)//f(5)//f(x-5) + f(x)//f(6)//f(x-6) + f(x)//f(7)//f(x-7))


def fact(n):
    return 1 if n == 0 else (n * fact(n - 1))

def c(n, k):
    return fact(n) // (fact(k) * (fact(n - k)))

n = int(input())

print(c(n, 5) + c(n, 6) + c(n, 7))


def C(n,m):
    a = 1
    b = 1
    for i in range(1,m+1):
        a *= n+1-i
        b *= i
    return a//b

def __starting_point():

    n = int(input())

    print(C(n,5)+C(n,6)+C(n,7))
__starting_point()


from math import factorial

def C(n, k):
    return factorial(n) // (factorial(k) * factorial(n - k))

n = int(input())
print(C(n, 5) + C(n, 6) + C(n, 7))


from math import factorial

def nCr(n,r):
    f = factorial
    return f(n) // f(r) // f(n-r)

n = int(input())
ans = nCr(n, 7) + nCr(n, 6) + nCr(n, 5)
print(ans)


import math
n = int(input())
a = int(math.factorial(n)/(math.factorial(5)*math.factorial(n - 5)))
b = int(math.factorial(n)/(math.factorial(6)*math.factorial(n - 6)))
c = int(math.factorial(n)/(math.factorial(7)*math.factorial(n - 7)))
print(int(a + b + c))


from math import factorial

n = int(input())
ans = 0
cur = 1
for i in range(7):
    cur *= n - i
ans += cur // factorial(7)
cur = 1
for i in range(6):
    cur *= n - i
ans += cur // factorial(6)
cur = 1
for i in range(5):
    cur *= n - i
ans += cur // factorial(5)
print(ans)


def fact(a):
    ans = 1
    for i in range(2, a + 1):
        ans *= i
    return ans

n = int(input())
ans = 0
for i in range(5, 8):
    ans += fact(n) // fact(i) // fact(n - i)
print(ans)


import math
n = int(input())
s = 0
for i in range(5, 8):
    s += (math.factorial(n)//(math.factorial(n-i)*math.factorial(i)))
print(s)


n = int(input())
ans = 0
t = 7
w = n
temp = 1
while (t>0):
	temp *= w
	w-=1
	t-=1
ans = temp//5040
t = 6
w = n
temp = 1
while (t>0):
	temp *= w
	w-=1
	t-=1
ans += temp//720
t = 5
w = n
temp = 1
while (t>0):
	temp *= w
	w-=1
	t-=1
ans += temp//120
print (ans)


def put():
    return list(map(int, input().split()))
def diff(x,y):
    ans = 0
    for i in range(n*m):
        if s[x][i]!= s[y][i]:
            ans+=1
    return ans
def find(i):
    if i==p[i]:
        return i
    p[i] = find(p[i])
    return p[i]
def union(i,j):
    if rank[i]>rank[j]:
        i,j = j,i
    elif rank[i]==rank[j]:
        rank[j]+=1
    p[i]= j
def dfs(i,p):
    if i!=0:
        print(i,p)
    for j in tree[i]:
        if j!=p:
            dfs(j,i)

n,m,k,w = put()
s = ['']*k
for i in range(k):
    for j in range(n):
        s[i]+=input()
edge = []
k+=1
rank = [0]*(k)
p = list(range(k))
cost = 0
tree = [[] for i in range(k)]

for i in range(k):
    for j in range(i+1,k):
        if i==0:
            z=n*m
        else:
            z = diff(i-1,j-1)*w
        edge.append((z,i,j))

edge.sort()
for z,i,j in edge:
    u = find(i)
    v = find(j)
    if u!=v:
        union(u,v)
        cost+= z
        tree[i].append(j)
        tree[j].append(i)

print(cost)
dfs(0,-1)


from heapq import *

N = int(input())
price = [int(i) for i in input().split()]

total = 0
inf = (10**6) + 1
h = [inf]

#Assume we bought and sold optimally for the first k prices.
#We adjust our answer for the (k+1)th price that comes up.
for p in price:
    if p > h[0]:
        total += (p - heappop(h))
        #We push p onto heap in case we should have bought at this price instead
        #of selling.
        heappush(h, p)
    heappush(h, p)

print(total)


import math
from heapq import *

def maxProfit(prices, days):

    payoff = 0
    maxPrice, minPrice = max(prices), min(prices)
    maxIndex, minIndex = prices.index(maxPrice), prices.index(minPrice)
    iterator = iter(prices)
    h = [] # heap

    if days == 1:
        print(0)
        return

    for i in range(days):
        p = next(iterator)
        if not i:
            heappush(h, p)
            continue
        if h[0] < p:
            payoff += p - h[0]
            heappop(h)
            heappush(h, p)
        heappush(h, p)

    print(payoff)

def __starting_point():
    n = int(input())
    prices = list(map(int, input().split()))
    maxProfit(prices, n)
__starting_point()


from heapq import heappush,heappop
n=int(input())
ar=list(map(int,input().split()))
unsed=[]
selled=[]
sm=0
for x in ar:
    U,S=len(unsed),len(selled)
    u=heappop(unsed) if U else float('inf')
    s=heappop(selled) if S else float('inf')
    y=min(u,s)
    if(y<x):
        if(u==y):
            sm+=x-y
            if(S):heappush(selled,s)
            heappush(selled,x)
        else:
            sm+=x-y
            heappush(unsed,y)
            if(U):heappush(unsed,u)
            heappush(selled,x)
    else:
        if(S):heappush(selled,s)
        if(U):heappush(unsed,u)
        heappush(unsed,x)
print(sm)


X,Y=map(int,input().split())
print('Alice' if abs(X-Y) > 1 else 'Brown')


x, y = map(int, input().split())
if abs(x - y) <= 1:
    print('Brown')
else:
    print('Alice')


a,b = map(int, input().split())
print('Alice' if abs(a-b) > 1 else 'Brown')


x, y = list(map(int, input().split()))
if -1 <= x - y <= 1:
    print('Brown')
else:
    print('Alice')

# abs(x - y) <= 1 → abs(x - y) >= 2
# abs(x - y) >= 2 → abs(x - y) <= 1


x, y = list(map(int, input().split()))
if abs(x - y) > 1:
  print('Alice')
else:
  print('Brown')


x, y = list(map(int, input().split()))

if abs(x - y) <= 1:
    ans = "Brown"
else:
    ans = "Alice"

print(ans)


X, Y = list(map(int, input().split()))
if abs(X - Y) > 1:
    print('Alice')
else:
    print('Brown')


x,y = map(int,input().split())
if abs(x - y) > 1:
  print("Alice")
else:
  print("Brown")


X,Y=list(map(int,input().split()))

if X+Y<=1:
    print("Brown")

else:
    n=X-Y
    if n<0:
        n=(-1)*n

    if n<=1:
        print("Brown")
    else:
        print("Alice")


import sys

def main():
    x,y=list(map(int,input().split()))
    s=2*x+y
    t=2*y+x
    if s//3-(s%3==0)==t//3-(t%3==0):
        print('Brown')
    else:
        print('Alice')

def __starting_point():
    main()

__starting_point()


x, y = list(map(int, input().split()))

print(('Brown' if abs(x - y) <= 1 else 'Alice'))


#!/usr/bin/env python3
import sys

def solve(X: int, Y: int):
    print(("Brown" if -1 <= X - Y <= 1 else "Alice"))

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    solve(X, Y)

def __starting_point():
    main()

__starting_point()


X, Y = map(int, input().split())
if abs(X - Y) <= 1:
  print("Brown")
else:
  print("Alice")


X, Y = map(int, input().split())
if abs(X - Y) <= 1:
  print('Brown')
else:
  print('Alice')


X, Y = map(int, input().split())
if abs(X - Y) > 1:
  print("Alice")
else:
  print("Brown")


X, Y = list(map(int,input().split()))
if abs(X-Y) <= 1:
    print("Brown")
else:
    print("Alice")


x,y=map(int,input().split())
if abs(x-y)>1:
  print('Alice')
else:
  print('Brown')


x, y = map(int, input().split())
if abs(x-y) <= 1:
    print("Brown")
else:
    print("Alice")


x,y = map(int,input().split())
if y > x:
    x,y = y,x

if x - y <= 1:
    print("Brown")
else:
    print("Alice")


x,y=map(int,input().split())
if x>y:
  x,y=y,x

if y-x<=1:
  print("Brown")
else:
  print("Alice")


def solve():
    x, y = list(map(int, input().split()))
    if abs(x - y) <= 1:
        print('Brown')
    else:
        print('Alice')

def __starting_point():
    solve()

__starting_point()


a,b=map(int,input().split())
print("Alice" if abs(a-b)>1 else "Brown")


x,y=map(int, input().split())
print("Brown"if abs(x-y)<2else"Alice")


X, Y = list(map(int, input().split()))
if abs(X - Y) <= 1:
    print('Brown')
else:
    print('Alice')


x,y=map(int,input().split())
if abs(x-y)>=2:
  print("Alice")
else:
  print("Brown")


def main():
    X, Y = list(map(int, input().split(' ')))
    if abs(X - Y) > 1:
        print('Alice')
    else:
        print('Brown')

def __starting_point():
    main()
__starting_point()


X, Y = map(int, input().split())
print("Brown" if abs(X - Y) <= 1 else 'Alice')


X,Y=map(int,input().split())
X,Y=max(X,Y),min(X,Y)
#print(X,Y)

if X<=1:
  print("Brown")
else:
  if X-Y>=2:
    print("Alice")
  else:
    print("Brown")


x,y=map(int,input().split())
print("Brown" if abs(x-y)<=1 else "Alice")


# -*- coding: utf-8 -*-

import sys

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

X, Y = MAP()

memo = list2d(1007, 1007, -1)
def rec(x, y):
    if memo[x][y] != -1:
        return memo[x][y]
    if x < 2 and y < 2:
        memo[x][y] = 0
        return 0
    res = 0
    for i in range(2, x+1):
        if not rec(x - i, y + i//2):
            res = 1
    for i in range(2, y+1):
        if not rec(x + i//2, y - i):
            res = 1
    memo[x][y] = res
    return res

# for i in range(X+1):
#     for j in range(Y+1):
#         rec(i, j)
# for i in range(X+1):
#     print(memo[i][:Y+1])

if abs(X - Y) >= 2:
    print('Alice')
else:
    print('Brown')


x, y = map(int, input().split())
if abs(x - y) < 2:
    print('Brown')
else:
    print('Alice')


import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def main():
    X,Y = list(map(int,input().split()))
    if abs(X - Y) <= 1:
        print('Brown')
    else:
        print('Alice')
def __starting_point():
    main()

__starting_point()


# 解説AC
X,Y = map(int, input().split())
print("Alice" if abs(X - Y) > 1 else "Brown")


x,y= list(map(int,input().split()))
result=abs(x-y)

if result <=1:
    print("Brown")
else:
    print("Alice")


X,Y = map(int, open(0).read().split())
if abs(X-Y) <= 1:
    print('Brown')
else:
    print('Alice')


x, y = map(int, input().split())
print('Alice' if abs(x-y) > 1 else 'Brown')


X,Y=map(int,input().split())
print("Brown" if abs(X-Y)<=1 else "Alice")


a,b=map(int,input().split())
if abs(a-b)>1:print("Alice")
else:print("Brown")


X, Y = map(int, input().split())
print("Brown" if abs(X-Y) <= 1 else "Alice")


x,y=list(map(int,input().split()))
print(("Alice" if abs(x-y)>1 else "Brown"))


n,m = map(int,input().split())
if abs(n-m) < 2:
  print('Brown')
else:
  print('Alice')


#01:25
a,b = map(int,input().split())
if abs(a-b) <= 1:
  print('Brown')
else:
  print('Alice')


X, Y = map(int,input().split())
if abs(X - Y) < 2:
    print("Brown")
else:
    print("Alice")


X,Y=map(int,input().split())
if abs(X-Y)>1:
    print("Alice")
else:
    print("Brown")


x,y=map(int,input().split())
if abs(x-y)<=1:
    print("Brown")
else:
    print("Alice")


import sys

sys.setrecursionlimit(10 ** 6)
def MI(): return map(int, sys.stdin.readline().split())

def main():
    x,y=MI()
    if x>y:x,y=y,x
    if y>x+1:print("Alice")
    else:print("Brown")

main()


x,y=map(int,input().split())
a=abs(x-y)
if a==0 or a==1:
  print("Brown")
else:
  print("Alice")


X,Y = list(map(int,input().split()))

print(("Brown" if abs(X-Y) <= 1 else "Alice"))


X, Y = map(int, input().split())

if X >= Y+2:
  print('Alice')
elif X <= Y-2:
  print('Alice')
else:
  print('Brown')


#一問目
x,y=list(map(int,input().split()))
if abs(x-y)<=1:
    print("Brown")
else:
    print("Alice")


X, Y = map(int,input().split())
print('Brown' if abs(X - Y) <= 1 else 'Alice')


x,y=list(map(int,input().split()))
if abs(x-y)<=1:
  print('Brown')
else:
  print('Alice')


a,b=map(int,input().split())
if -2<a-b<2:print("Brown")
else:print("Alice")


x, y = map(int,input().split())

if abs(x-y) <= 1:
  print("Brown")
else:
  print("Alice")


X,Y=list(map(int,input().split()))
if X+Y<2 or abs(X-Y)<2: print("Brown")
else : print("Alice")


x, y = list(map(int, input().split()))

print(("Alice" if abs(x - y) > 1 else "Brown"))


x,y = map(int, input().split())

if abs(x-y)>1:
    print("Alice")
else:
    print("Brown")


X, Y = map(int,input().split())
if abs(X-Y) <=1:
  print('Brown')
else:
  print('Alice')


X,Y = map(int,input().split())
if abs(X-Y)<=1:
  print("Brown")
else:
  print("Alice")


import sys

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inl = lambda: [int(x) for x in sys.stdin.readline().split()]
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))

def solve():
    x, y = inl()
    if x > y:
        x, y = y, x
    d = y - x
    if d <= 1:
        return False
    return True

print("Alice" if solve() else "Brown")


x,y = list(map(int,input().split()))
if abs(x-y) <= 1:
    print("Brown")
else:
    print("Alice")
# a:x+y >1 , abs(x-y)>1
# b:x+y >1 , abs(x-y) <=1
# c:x+y <=1, (abs(x-y) <=1  )　--> lose
#
#       c <--- a <---> b
#       a <---> a


import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def ZIP(n): return list(zip(*(MAP() for _ in range(n))))
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
mod = 10 ** 9 + 7

X, Y = MAP()
if abs(X-Y) <= 1:
	print("Brown")
else:
	print("Alice")


X, Y = map(int, input().split())

if abs(X - Y) <= 1:
    print ('Brown')
else:
    print ('Alice')


x,y = map(int,input().split())

print("Alice" if abs(x-y)>1 else "Brown")


import sys

def solve():
    input = sys.stdin.readline
    X, Y = map(int, input().split())
    if abs(X - Y) > 1: print("Alice")
    else: print("Brown")

    return 0

def __starting_point():
    solve()
__starting_point()


x,y = map(int,input().split())

if abs(x-y) <= 1:
    print("Brown")
else:
    print("Alice")


x,y=map(int,input().split())
print('Brown' if abs(x-y)<=1 else 'Alice')


x, y = list(map(int, input().split()))
if abs(x-y) <= 1:
    print('Brown')
else:
    print('Alice')


x,y = map(int,input().split())
if abs(x-y)<=1:
    print('Brown')
else:
    print('Alice')


x, y = list(map(int,input().split()))
if abs(x-y) <= 1:
    print('Brown')
else:
    print('Alice')


x,y=map(int,input().split())
if abs(x-y)<=1:print("Brown")
else:print("Alice")


X, Y = list(map(int, input().split()))

print(('Alice' if abs(X - Y) > 1 else 'Brown'))


import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

X, Y = lr()

if abs(Y - X) >= 2:
    print('Alice')
else:
    print('Brown')

# 24


X, Y = map(int, input().split())
if abs(X-Y) <= 1:
    print('Brown')
else:
    print('Alice')


X, Y = list(map(int, input().split()))
ans = 'Brown' if abs(X - Y) <= 1 else 'Alice'
print(ans)


X, Y = map(int, input().split())
print('Alice' if abs(X-Y)>=2 else 'Brown')


# solution
import io

nim,mike = map(int,input().split())
print("Brown" if abs(nim-mike)<2 else "Alice")


a,b=list(map(int,input().split()))
cnt=1
if abs(a-b)<=1:
    print('Brown')
else:
    print('Alice')

# if b>a:
#     a,b=b,a
# a=a-b
# b=0
# mod_a=a%3
# if a==3:
#     print('Alice')
# elif mod_a==2:
#     print('Alice')
# elif mod_a==1:
#     print('Brown')
# elif (mod_a==0)and(a!=3):
#     print('Brown')
# if (mod_a==3)and(mod_b==3):
#     print('Alice')
# elif (mod_a==3)and(mod_b==1):
#     print('Alice')
# elif (mod_a==1)and(mod_b==3):
#     print('Alice')
# elif (mod_a==2)and(mod_b==0):
#     print('Alice')
# elif (mod_a==0)and(mod_b==2):
#     print('Alice')
# else:
#     print('Brown')


x, y = map(int, input().split())
print("Alice" if abs(x - y) > 1 else "Brown")


a,b = map(int, input().split())
if abs(a-b) <= 1:
  print("Brown")
else:
  print("Alice")


x, y = map(int, input().split())
if -1 <= x-y <= 1:
  print("Brown")
else:
  print("Alice")


def main():
    x, y = map(int, input().split())
    if abs(x-y) <= 1:
        print("Brown")
    else:
        print("Alice")

def __starting_point():
    main()
__starting_point()


#!/usr/bin/env python3
import sys

def solve(X: int, Y: int):
    return 'Alice' if abs(X-Y) > 1 else 'Brown'

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    X = int(next(tokens))  # type: int
    Y = int(next(tokens))  # type: int
    print((solve(X, Y)))

def __starting_point():
    main()

__starting_point()


X,Y = map(int,input().split())
diff = abs(X-Y)
if(diff < 2):
    print('Brown')
else:
    print('Alice')


a,b=map(int,input().split())
if abs(a-b)<=1:
  print("Brown")
else:
  print("Alice")


# editorial

def main():
    X, Y = list(map(int, input().split()))

    def solve(x, y):
        """手番が勝つか"""
        return not ((X + Y <= 1) or (abs(X - Y) <= 1))

    cond = solve(X, Y)
    print(('Alice' if cond else 'Brown'))

def __starting_point():
    main()

# e,e
# o,e
# o,o
# o,e遷移は今回は関係なかった

# 負け状態
# 0,0
# 0,1
# 1,1
# まとめると
# X+Y<=1
# abs(X-Y)<=1 <-> >1 と交互

# まとめ方
# 偶奇
# 和と差

__starting_point()


X, Y = list(map(int, input().split()))

if (X == 0 and Y == 0) or (X == 0 and Y == 1) or (
        X == 1 and Y == 0) or (X == 1 and Y == 1):
    print('Brown')
    return

num = abs(X - Y)

if num <= 1:
    print('Brown')
else:
    print('Alice')


X, Y = list(map(int, input().split()))

print(('Brown' if abs(X - Y) < 2 else 'Alice'))


x,y=map(int,input().split())
if abs(x-y)<=1:
  print('Brown')
else:
  print('Alice')


x,y=list(map(int,input().split()))
if abs(x-y)<=1:
  print("Brown")
else:
  print("Alice")


import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy

X, Y = map(int, input().split())

print("Brown" if abs(X - Y) <= 1 else "Alice")


X,Y=map(int,input().split())
if X<Y:
    X,Y=Y,X

print('Brown' if (X-1<=Y and Y<=X+1) else 'Alice')


x,y=map(int,input().split())
if abs(x-y)<=1:
  print("Brown")
else:
  print("Alice")


# 1: starting from there, P1 wins (who starts)
# 0: P0 wins (who doesn't start)
#
# 0 0 1 1 1 1 1
# 0 0 0 1 1
# 1 0 0 0
# 1 1 0
# 1 1
# 1
# 1
# |X-Y| <= 1 : 0
# |X-Y| >  1 : 1
## X-Y: must change by 3
X, Y = list(map(int, input().split()))
if abs(X-Y) > 1:
  print('Alice')
else:
  print('Brown')


T=int(input())

for t in range(T):
    s=input()
    ans=0
    L=[]
    for i in [1,2,3,4,6,12]:
        x=i
        y=12//x
        E=[]
        for j in range(12):
            if(j%y==0):
                E.append("")
            E[-1]+=s[j]
        for j in range(y):
            c=0
            for z in range(i):
                if(E[z][j]=='X'):
                    c+=1
            if(c==i):
                ans+=1
                L.append(i)
                break
    print(ans,end=" ")
    for item in L:
        print(item,end="x")
        print(12//item,end=" ")
    print()


#!/usr/bin/env python3

def read_ints():
	return list(map(int, input().strip().split()))

t, = read_ints()

for _ in range(t):
	x = input()

	correct = []

	for a in [1, 2, 3, 4, 6, 12]:
		cor = False
		for c in range(0, 12//a):
			s = set(x[c::12//a])

			if len(s)==1 and 'X' in s:
				cor = True
				break

		if cor == True:
			correct.append("{}x{}".format(a, 12//a))

	print(len(correct), ' '.join(correct))


# http://codeforces.com/contest/400/problem/0
# Codeforces : A. Inna and choose options

liste_a = (1, 2, 3, 4, 6, 12)
liste_results = []

def process(essai):
    nonlocal liste_results
    liste_av = [0]
    for a in liste_a:
        b = 12 // a
        for r in range(b):
            if essai[r::b] == 'X'*a:
                liste_av[0] += 1
                liste_av.append('{}x{}'.format(a,b))
                break
    liste_av[0] = str(liste_av[0])
    liste_results.append(liste_av)

t = int(input())
for k in range(t):
    essai = input()
    process(essai)

for s in liste_results:
    print(*s)


t = int(input())
for i in range(t):
    s = input().strip()
    cnt = 0
    ans = []
    for b in [1, 2, 3, 4, 6, 12]:
        List = []
        a = 12 // b
        for begin in range(b):
            column = ''
            j = begin
            while j < 12:
                column += s[j]
                j += b
            List.append(column)
        #print(i, b, List)
        if 'X' * a in List:
            cnt += 1
            ans.append((a, b))
    print(cnt, end = ' ')
    for pair in sorted(ans):
        print('x'.join(map(str, pair)), end = ' ')
    print()


def test(s):
    res = []
    for i in [[1, 12], [2, 6], [3, 4], [4, 3], [6, 2], [12, 1]]:
        a = [["O" for i in range(i[1])] for j in range(i[0])]
        for j in range(i[0]):
            for k in range(i[1]):
                a[j][k] = s[j * i[1] + k]
        if check(a):
            res.append(i)
    return res

def check(a):
    for i in range(len(a[0])):
        if not "O" in [a[j][i] for j in range(len(a))]:
            return True
    return False

t = int(input())
for i in range(t):
    s = input().strip()
    x = test(s)
    print(len(x), end=" ")
    for j in x:
        print(j[0], "x", j[1], sep="", end=" ")
    print()


for _ in range(int(input())):
    cards = input()
    count = 0
    output = ''
    if 'X' in cards:
        count += 1
        output += ' 1x12'
    for q, p in zip(cards[:6], cards[6:]):
        if q == p == 'X':
            count += 1
            output += ' 2x6'
            break
    for q, p, r in zip(cards[:4], cards[4:8], cards[8:]):
        if q == p == r == 'X':
            count += 1
            output += ' 3x4'
            break
    for q, p, r, s in zip(cards[:3], cards[3:6], cards[6:9], cards[9:]):
        if q == p == r == s == 'X':
            count += 1
            output += ' 4x3'
            break
    for q, p, r, s, t, u in zip(cards[:2], cards[2:4], cards[4:6], cards[6:8], cards[8:10], cards[10:]):
        if q == p == r == s == t == u == 'X':
            count += 1
            output += ' 6x2'
            break
    if 'O' not in cards:
        count += 1
        output += ' 12x1'
    print(str(count) + output)


n = int(input())
ab = [12, 6, 4, 3, 2, 1]
lst = [list(input()) for i in range(n)]
res = [[0] for i in range(n)]
for pr in range(n):
    for elem in ab:
        for i in range(elem):
            x = 1
            for j in range(0, 12, elem):
                if lst[pr][i + j] == "O":
                    x = 0
            if x == 1 and str(12 // elem) + "x" + str(elem) not in res[pr]:
                res[pr][0] += 1
                res[pr].append(str(12 // elem) + "x" + str(elem))
for i in range(len(res)):
    print(" ".join(map(str, res[i])))


t = int(input())
for i in range(t):
    s = input()
    ans = ""
    count = 0
    for j in range(1, 13):
        flag = False
        if 12 % j == 0:
            for p in range(12 // j):
                q = p
                while q < 12 and s[q] == "X":
                    q += 12 // j
                if q >= 12:
                    flag = True
        if flag:
            ans += str(j) + "x" + str(12 // j) + " "
            count += 1
    print(count, ans[:-1])


n = int(input())
p = 0
f = True
for k in range(n):
    s = input().strip()
    ot = set()
    for i in range(1, 13):
        if i == 5 or i == 7 or i == 9 or i == 10 or i == 11 or i == 8:
            continue
        for t in range(i):
            p = True
            for j in range(t, 12, i):
                if s[j] == 'O':
                    p = False
            if p:
                ot.add(i)
    ot = list(reversed(sorted(list(ot))))
    print(len(ot), end = ' ')
    for i in ot:
        print(str(12//i)+'x'+str(i), end = ' ')
    print()


from functools import reduce

def sol(l):
  if not "X" in l: return "0"
  l = l.replace("O","0").replace("X","1")
  res = [ "%ix%i" % (12//i, i) for i in (12,6,4,3,2,1) if reduce(lambda x, y: x&y, [int(l[i*j:i*j+i],2) for j in range(12//i)], -1)]
  return ("%i %s" % (len(res), " ".join(res)))

n = int(input())
print("\n".join([sol(input()) for i in range(n)]))


from functools import reduce
print("\n".join([(lambda x:("%i %s" % (len(x), " ".join(x))))((lambda h:[ "%ix%i" % (12//i, i) for i in (12,6,4,3,2,1) if reduce(lambda x, y: x&y, [int(h.replace("O","0").replace("X","1")[i*j:i*j+i],2) for j in range(12//i)], -1)])(input())) for i in range(int(input()))]))


t = int(input())
n = 12
while t > 0:
    ans = []
    t = t - 1
    s = input()
    for i in range(n):
        r = i+1
        if n%r != 0:
            continue
        c = n//r
        flag = False
        for j in range(c):
            id = j
            ff = False
            while id < n:
                if s[id] != 'X':
                    ff = True
                    break
                id = id + c
            if ff == False:
                flag = True
                break
        if flag == True:
            ans.append((r, c))

    print(len(ans), end = '')
    for i in range(len(ans)):
        print(' ', ans[i][0], 'x', ans[i][1], sep = '', end = '')
    print('')


q = [12, 6, 4, 3, 2, 1]
p = {12 // i: 'X' * i for i in q}
r = {i: str(12 // i) + 'x' + str(i) for i in q}
for i in range(int(input())):
    s, t = [], input()
    for j in q:
        if any(t[k :: j] == p[j] for k in range(j)): s.append(r[j])
    print(len(s), ' '.join(s))


#!/usr/local/bin/python33
n = int(input())

for i in range(n):
	cnt = 0
	answ = ['1x12', '2x6', '3x4', '4x3', '6x2', '12x1']
	answb = [False, False, False, False, False, False]
	instr = input()

	if 'X' in instr:
		cnt += 1
		answb[0] = True
	for j in range(6):
		if (instr[j] == instr[6 + j] == 'X'):
			cnt += 1
			answb[1] = True
			break
	for j in range(4):
		if (instr[j] == instr[4 + j] == instr[8 + j] == 'X'):
			cnt += 1
			answb[2] = True
			break
	for j in range(3):
		if (instr[j] == instr[3 + j] == instr[6 + j] == instr[9 + j] == 'X'):
			cnt += 1
			answb[3] = True
			break
	for j in range(2):
		if (instr[j] == instr[2 + j] == instr[4 + j] == instr[6 + j] == instr[8 + j] == instr[10 + j] == 'X'):
			cnt += 1
			answb[4] = True
			break
	if not 'O' in instr:
		cnt += 1
		answb[5] = True

	print(cnt, end = ' ')
	for i in range(6):
		if answb[i]:
			print(answ[i], end = ' ')
	print()


t = int(input())
for i in range(0, t):
    str = input()
    answer = []
    p = [1, 2, 3, 4, 6, 12]
    for j in range(0, len(p)):
        d1, d2 = p[j], 12 // p[j]
        cnt = [0 for h in range(0, d2)]
        for i2 in range(0, 12):
            tt = i2 % d2
            cnt[tt] += (str[i2] == 'X')
        ans_cand = False
        for i2 in range(0, d2):
            if cnt[i2] == d1:
                ans_cand = True
        if ans_cand:
            answer.append('%dx%d' % (d1, d2))
    print(len(answer), end = ' ')
    for j in range(0, len(answer)):
        print(answer[j], end = ' ')
    print()


t = int(input().strip())
for i in range(t):
    s = input()
    ans = []
    for h in [x for x in range(1, 13) if 12 % x == 0]:
        good = False
        w = 12 // h
        for k in range(w):
            ok = True
            for l in range(h):
                if s[l * w + k] != 'X':
                    ok = False
            if ok:
                good = True
        if good:
            ans.append(str(h) + "x" + str(w))
    print(str(len(ans)) + " " + " ".join(ans))


T=int(input())

while T>=1:
    T-=1
    a=input()
    list=[]
    for i in range(1,13):
        if 12 % i==0:
            l=12//i
            for j in range(0,l):
                for k in range(0,i):
                    if a[k*l+j]!='X':
                        break
                else:
                    break
            else:
                continue
            list.append(i)
    print(len(list),end=' ')
    for i in range(0,len(list)):
        print(str(list[i])+'x'+str(12//list[i]),end=' ')
    print()


a=int(input())
while a:
    l=[]
    b=input()
    if((b.count("X"))>0):
        l.append("1x12")
    if((b[:6].count("X"))>0):
        p=[i for i in range(6) if b[i]=='X']
        for i in p:
            if(b[i:12:6]=='XX'):
                l.append("2x6")
                break
    if((b[:4].count("X"))>0):
        p=[i for i in range(4) if b[i]=='X']
        for i in p:
            if(b[i:12:4]=="XXX"):
                l.append("3x4")
                break
    if((b[:3].count("X"))>0):
        p=[i for i in range(3) if b[i]=='X']
        for i in p:
            if(b[i:12:3]=="XXXX"):
                l.append("4x3")
                break
    if((b[:2].count("X"))>0):
        p=[i for i in range(2) if b[i]=='X']
        for i in p:
            if(b[i:12:2]=="XXXXXX"):
                l.append("6x2")
                break
    if(b.count("X")==12):
        l.append("12x1")
    print(len(l),end=" ")
    if(len(l)>0):
        for i in l:
            print(i,end=" ")
    print()
    a-=1


def test_col(s, a, b, col):
	res = True
	for i in range(0, a):
		if s[i * b + col] != 'X':
			res = False
	return res

def test_all_cols(s, a):
	b = len(s) // a
	if a * b != len(s):
		return False
	else:
		res = False
		for i in range(0, b):
			res = res or test_col(s, a, b, i)
		return res

n = int(input())
for i in range(0, n):
	s = input()
	slen = len(s)
	cvariants  = 0
	variants = ""
	for a in range(1, slen + 1):
		if (test_all_cols(s, a)):
			cvariants += 1
			variants += str(a) + "x" + str(slen // a) + " "
	print(str(cvariants), variants)


# -*- coding: UTF-8 -*-
def evaluate(origin_str):
    ans = []
    for i in [1,2,3,4,6,12]:
        last_idx = int(12 / i)
        flags = [1 for i in range(0,last_idx)]
        if (i == 1):
            flag = False
            for ch in origin_str:
                if (ch == 'X'):
                    flag = True
            if (flag):
                ans.append([i,last_idx])
        else:
            for j in range(0,last_idx):
                tmp = []
                k = j - last_idx
                for x in range(0,i):
                    k += last_idx
                    tmp.append(k)
                for l in tmp:
                    ch = origin_str[l]
                    if (ch != 'X'):
                        flags[j] = 0
            if (sum(flags) != 0):
                ans.append([i,last_idx])
    s = ""
    for a in ans:
        s += str(a[0])+"x"+str(a[1]) + " "
    print(str(len(ans)) + " " + s)

def main():
    n = int(input())
    for i in range(0,n):
        evaluate(input())

main()


n = int(input())

for _ in range(n):
    mystr = input()
    answer = []

    divisibles = [1,2,3,4,6,12]
    for i in divisibles:
        flag=0

        for j in range(0,12//i):
            columnSet = set(mystr[j::12//i])
            if len(columnSet)==1 and "X" in columnSet:
                flag=1
                break

        if flag==1:
           answer.append("{}x{}".format(i,12//i));
    print(len(answer), " ".join(answer))


t = int(input())
for _ in range(t):
  s = input()
  b = []
  for n in [1, 2, 3, 4, 6, 12]:
    m = 12 // n
    for j in range(m):
      if s[j::m] == "X" * n:
        b += [(n, m)]
        break
  print(len(b), ' '.join(str(x) + "x" + str(y) for x, y in b))


t = int(input())
ans = [[] for i in range(t)]
for i in range(t):

    s = input()
    for a in range(1, 13):

        if 12 % a != 0:
            continue
        b = 12 // a
        c = [[] for h in range(b)]
        for h in range(b):
            for k in range(a):
                c[h].append(s[k * b + h])
        if a == 3:
            a = 3
        T = True
        for h in range(b):
            if T:
                ok = True
                for k in range(a):
                    if c[h][k] == 'O':
                        ok = False
                if ok:
                    ans[i].append([a, b])
                    T = False
                    break
for i in range(t):
    print(len(ans[i]), end = ' ')
    for z in ans[i]:
        print(z[0], end = '')
        print('x', end= '')
        print(z[1], end = ' ')
    print()


def do(string):
    num = 0
    ok = []
    for i in [12, 6, 4, 3, 2, 1]:
        for j in range(0, i):
            if string[j::i] == 'X' * int(12/i):
                ok.append(str(int(12/i))+'x'+str(i))
                num += 1
                break

    ok = [str(num)] + ok
    print(' '.join(ok))

for i in range(int(input())):
    do(input())