"""
What I cannot create, I do not understand.

https://github.com/Cheran-Senthil/PyRival
Copyright (c) 2018 Cheran Senthilkumar
"""
# IMPORTS---------------------------------------------------------------------#
from __future__ import division, print_function

import itertools
import sys
from atexit import register
from io import BytesIO

# import cmath
# import math
# import operator as op
# import random
# from bisect import bisect_left as bl, bisect_right as br
from collections import Counter, defaultdict, deque
# from copy import deepcopy
# from cPickle import dumps
# from decimal import Decimal, getcontext
# from difflib import SequenceMatcher
# from fractions import Fraction, gcd
# from heapq import heappop, heappush
# from Queue import PriorityQueue, Queue

# PYTHON3---------------------------------------------------------------------#
class dict(dict):
    def items(self):
        return dict.iteritems(self)

    def keys(self):
        return dict.iterkeys(self)

    def values(self):
        return dict.itervalues(self)

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

input = raw_input
range = xrange

# FASTIO----------------------------------------------------------------------#
# sys.stdout = BytesIO()
# register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
# sys.stdin = BytesIO(sys.stdin.read())

# input = lambda: sys.stdin.readline().rstrip()
# print = lambda *args: sys.stdout.write(' '.join(str(x) for x in args) + '\n')
# flush = sys.stdout.flush

# SETTINGS--------------------------------------------------------------------#
# getcontext().prec = 100
# sys.setrecursionlimit(32768)

# CONSTANTS-------------------------------------------------------------------#
MOD = 1000000007
INF = float('+inf')

ASCII_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'
ASCII_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# MAIN------------------------------------------------------------------------#
def main():
    n = int(input())
    ops = Counter(input())
    x, y = map(int, input().split(' '))

    if n < abs(x) + abs(y):
        print(-1)
    else:
        diff_x = x - (ops['U'] - ops['D'])
        diff_y = y - (ops['R'] - ops['L'])
        if (abs(diff_x) + abs(diff_y)) % 2 == 1:
            print(-1)
        else:
            print((abs(diff_x) + abs(diff_y)) // 2)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
"""
This file is part of https://github.com/Cheran-Senthil/PyRival.

Copyright 2018 Cheran Senthilkumar all rights reserved,
Cheran Senthilkumar <hello@cheran.io>
Permission to use, modify, and distribute this software is given under the
terms of the MIT License.

"""
from __future__ import division, print_function

import cmath
import itertools
import math
import operator as op
# import random
import sys
from atexit import register
from bisect import bisect_left, bisect_right
# from collections import Counter, MutableSequence, defaultdict, deque
# from copy import deepcopy
# from decimal import Decimal
# from difflib import SequenceMatcher
# from fractions import Fraction
# from heapq import heappop, heappush

if sys.version_info[0] < 3:
    # from cPickle import dumps
    from io import BytesIO as stream
    # from Queue import PriorityQueue, Queue
else:
    # from functools import reduce
    from io import StringIO as stream
    from math import gcd
    # from pickle import dumps
    # from queue import PriorityQueue, Queue

if sys.version_info[0] < 3:
    class dict(dict):
        """dict() -> new empty dictionary"""
        def items(self):
            """D.items() -> a set-like object providing a view on D's items"""
            return dict.iteritems(self)

        def keys(self):
            """D.keys() -> a set-like object providing a view on D's keys"""
            return dict.iterkeys(self)

        def values(self):
            """D.values() -> an object providing a view on D's values"""
            return dict.itervalues(self)

    def gcd(x, y):
        """gcd(x, y) -> int
        greatest common divisor of x and y
        """
        while y:
            x, y = y, x % y
        return x

    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

def sync_with_stdio(sync=True):
    """Set whether the standard Python streams are allowed to buffer their I/O.

    Args:
        sync (bool, optional): The new synchronization setting.

    """
    global input, flush

    if sync:
        flush = sys.stdout.flush
    else:
        sys.stdin = stream(sys.stdin.read())
        input = lambda: sys.stdin.readline().rstrip('\r\n')

        sys.stdout = stream()
        register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

def main():
    n = int(input())
    seq = input()
    x, y = map(int, input().split(' '))

    if n < abs(x) + abs(y):
        print(-1)
        return

    pref_sum = [[0, 0] for _ in range(n + 1)]
    for i in range(n):
        if seq[i] == 'U':
            pref_sum[i + 1] = [pref_sum[i][0], pref_sum[i][1] + 1]
        if seq[i] == 'D':
            pref_sum[i + 1] = [pref_sum[i][0], pref_sum[i][1] - 1]
        if seq[i] == 'L':
            pref_sum[i + 1] = [pref_sum[i][0] - 1, pref_sum[i][1]]
        if seq[i] == 'R':
            pref_sum[i + 1] = [pref_sum[i][0] + 1, pref_sum[i][1]]

    x_cnt, y_cnt = pref_sum[-1]

    if (x == x_cnt) and (y == y_cnt):
        print(0)
        return

    def is_sol(z):
        for i in range(n - z + 1):
            x1, y1 = pref_sum[i]
            x2, y2 = pref_sum[i + z]

            if abs(x1 - x2) + abs(y1 - y2) >= abs(x - x_cnt + x2 - x1) + abs(y - y_cnt + y2 - y1):
                return True

        return False

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

    lo, hi = 0, n + 1
    mid = (hi + lo) // 2

    while True:
        if is_sol(mid):
            if not is_sol(mid - 1):
                print(mid)
                return
            hi = mid
        else:
            lo = mid

        mid = (hi + lo) // 2

if __name__ == '__main__':
    sync_with_stdio(False)
    main()


"""
What I cannot create, I do not understand.

https://github.com/Cheran-Senthil/PyRival
Copyright (c) 2018 Cheran Senthilkumar
"""
# IMPORTS---------------------------------------------------------------------#
from __future__ import division, print_function

import itertools
import sys
from atexit import register
from io import BytesIO

# import cmath
# import math
# import operator as op
# import random
# from bisect import bisect_left as bl, bisect_right as br
from collections import Counter, defaultdict, deque
# from copy import deepcopy
# from cPickle import dumps
# from decimal import Decimal, getcontext
# from difflib import SequenceMatcher
# from fractions import Fraction, gcd
# from heapq import heappop, heappush
# from Queue import PriorityQueue, Queue

# PYTHON3---------------------------------------------------------------------#
class dict(dict):
    def items(self):
        return dict.iteritems(self)

    def keys(self):
        return dict.iterkeys(self)

    def values(self):
        return dict.itervalues(self)

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

input = raw_input
range = xrange

# FASTIO----------------------------------------------------------------------#
# sys.stdout = BytesIO()
# register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
# sys.stdin = BytesIO(sys.stdin.read())

# input = lambda: sys.stdin.readline().rstrip()
# print = lambda *args: sys.stdout.write(' '.join(str(x) for x in args) + '\n')
# flush = sys.stdout.flush

# SETTINGS--------------------------------------------------------------------#
# getcontext().prec = 100
# sys.setrecursionlimit(32768)

# CONSTANTS-------------------------------------------------------------------#
MOD = 1000000007
INF = float('+inf')

ASCII_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'
ASCII_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# MAIN------------------------------------------------------------------------#
def main():
    n = int(input())
    ops = Counter(input())
    x, y = map(int, input().split(' '))

    diff_x = x - (ops['U'] - ops['D'])
    diff_y = y - (ops['R'] - ops['L'])
    if (abs(diff_x) + abs(diff_y)) % 2 == 1:
        print(-1)
    else:
        if (abs(diff_x) + abs(diff_y)) // 2 <= n:
            print((abs(diff_x) + abs(diff_y)) // 2)
        else:
            print(-1)

if __name__ == '__main__':
    main()


from __future__ import division
from sys import stdin, stdout
from collections import deque, defaultdict, Counter

rstr = lambda: stdin.readline().strip()
rints = lambda: [int(x) for x in stdin.readline().split()]
rstr_enu = lambda: [[i, x] for i, x in enumerate(rstr())]

n, s = int(input()), rstr()
x, y = rints()
dist, ans, memall = abs(x) + abs(y), float('inf'), Counter(s)

if dist > n or ((n - dist) & 1):
    print(-1)

elif memall['R'] - memall['L'] == x and memall['U'] - memall['D'] == y:
    print(0)
else:
    be, en = 1, n
    while be <= en:
        md = (be + en) >> 1
        mem, val = Counter(s[:md - 1]), 0

        for i in range(md - 1, n):
            mem[s[i]] += 1
            cur = [(memall['L'] - mem['L']) * -1 + (memall['R'] - mem['R']),
                   (memall['D'] - mem['D']) * -1 + (memall['U'] - mem['U'])]

            rem = abs(cur[0] - x) + abs(cur[1] - y)

            if rem == md:
                val = 1
                break

            mem[s[i + 1 - md]] -= 1

        if val:
            ans = min(ans, md)
            en = md - 1
        else:
            be = md + 1

    print(ans)


from __future__ import division
from sys import stdin, stdout
from collections import deque, defaultdict, Counter

rstr = lambda: stdin.readline().strip()
rints = lambda: [int(x) for x in stdin.readline().split()]
rstr_enu = lambda: [[i, x] for i, x in enumerate(rstr())]

n, s = int(input()), rstr()
x, y = rints()
dist, ans, memall = abs(x) + abs(y), float('inf'), Counter(s)

if dist > n or ((n - dist) & 1):
    print(-1)

elif memall['R'] - memall['L'] == x and memall['U'] - memall['D'] == y:
    print(0)
else:
    be, en = 1, n
    while be <= en:
        md = (be + en) >> 1
        mem, val = Counter(s[:md - 1]), 0

        for i in range(md - 1, n):
            mem[s[i]] += 1
            cur = [(memall['R'] - mem['R']) - (memall['L'] - mem['L']),
                   (memall['U'] - mem['U']) - (memall['D'] - mem['D'])]

            rem = abs(cur[0] - x) + abs(cur[1] - y)

            if rem <= md:
                val = 1
                break

            mem[s[i + 1 - md]] -= 1

        if val:
            ans = min(ans, md)
            en = md - 1
        else:
            be = md + 1

    print(ans)


import sys
range = xrange
input = raw_input

n = int(input())
S = input()

X,Y = [int(x) for x in input().split()]

if (X+Y+n)%2==1:
    print -1
    sys.exit()

counter = [[0]*(n+1) for _ in range(4)]
for i in range(n):
    c = S[i]
    counter[0][i+1] = counter[0][i]
    counter[1][i+1] = counter[1][i]
    counter[2][i+1] = counter[2][i]
    counter[3][i+1] = counter[3][i]
    if c=='R':
        counter[0][i+1] += 1
    elif c=='L':
        counter[1][i+1] += 1
    elif c=='U':
        counter[2][i+1] += 1
    else:
        counter[3][i+1] += 1

best = n+1
for i in range(n):
    a = i
    b = n+1
    while a!=b:
        mid = (a+b)//2

        Rs = counter[0][-1] - (counter[0][mid] - counter[0][i])
        Ls = counter[1][-1] - (counter[1][mid] - counter[1][i])
        Us = counter[2][-1] - (counter[2][mid] - counter[2][i])
        Ds = counter[3][-1] - (counter[3][mid] - counter[3][i])

        interval = mid-i
        mx = Rs-Ls
        my = Us-Ds

        if abs(X-mx)+abs(Y-my)<=interval:
            b = mid
        else:
            a = mid+1
    if b!=n+1:
        best = min(b-i,best)
if best==n+1:
    print -1
else:
    print best


import sys
range = xrange
input = raw_input

n = int(input())
S = input()

mx = 0
my = 0
for c in S:
    if c=='L':
        mx -= 1
    elif c=='R':
        mx += 1
    elif c=='U':
        my += 1
    else:
        my -= 1

X,Y = [int(x) for x in input().split()]

dx = mx-X
dy = my-Y

if dx%2==1 or dy%2==1:
    print -1
    sys.exit()

remove_r = max(0,dx//2)
remove_l = max(0,-dx//2)
remove_u = max(0,dy//2)
remove_d = max(0,-dy//2)

counter = [[0]*(n+1) for _ in range(4)]
for i in range(n):
    c = S[i]
    counter[0][i+1] = counter[0][i]
    counter[1][i+1] = counter[1][i]
    counter[2][i+1] = counter[2][i]
    counter[3][i+1] = counter[3][i]
    if c=='L':
        counter[0][i+1] += 1
    elif c=='R':
        counter[1][i+1] += 1
    elif c=='U':
        counter[2][i+1] += 1
    else:
        counter[3][i+1] += 1

best = n+1
for i in range(n):
    a = i
    b = n+1
    while a!=b:
        mid = (a+b)//2
        if remove_r <= counter[1][mid] - counter[1][i] and \
           remove_l <= counter[0][mid] - counter[0][i] and \
           remove_u <= counter[2][mid] - counter[2][i] and \
           remove_d <= counter[3][mid] - counter[3][i]:

            b = mid
        else:
            a = mid+1
    if b!=n+1:
        best = min(b-i,best)
if best==n+1:
    print -1
else:
    print best


from sys import exit

n = input()
s = raw_input().strip()
x, y = map(int, raw_input().strip().split())

vert = abs(y)
hor = abs(x)

if (n < vert + hor) or ((n - (vert + hor)) % 2 == 1):
    print -1
    exit()

pre = [[0 for i in xrange(n + 1)] for j in xrange(4)]
for i in xrange(1, n + 1):
    c = s[i - 1]
    if c == 'L':
        pre[0][i] = pre[0][i - 1] + 1
    if c == 'R':
        pre[1][i] = pre[1][i - 1] + 1
    if c == 'U':
        pre[2][i] = pre[2][i - 1] + 1
    if c == 'D':
        pre[3][i] = pre[3][i - 1] + 1
    for j in xrange(4):
        if pre[j][i] == 0: pre[j][i] = pre[j][i - 1]

l = pre[0][n ]
r = pre[1][n]
u = pre[2][n]
d = pre[3][n]

if (r - l == x and u - d == y):
    print 0
    exit()

lo = 1
hi = n

mid1 = -1
while lo <= hi:
    mid = (lo + hi) // 2
    if mid == mid1:
        print hi
        break
    mid1 = mid
    poss = 0
    for i in xrange(n - mid + 1):
        j = i + mid - 1
        l = pre[0][i] - pre[0][0] + pre[0][n] - pre[0][j + 1]
        r = pre[1][i] - pre[1][0] + pre[1][n] - pre[1][j + 1]
        u = pre[2][i] - pre[2][0] + pre[2][n] - pre[2][j + 1]
        d = pre[3][i] - pre[3][0] + pre[3][n] - pre[3][j + 1]
        x0 = r - l
        y0 = u - d
        res_x = abs(x - x0)
        res_y = abs(y - y0)
        if res_x + res_y <= mid and ((mid - (res_x + res_y)) % 2 != 1):
            poss = 1
            break

    if poss == 1: hi = mid
    else: lo = mid


def works(state):
    global pos, end
    #state=[U,D,L,R]
    assert(state[0]>=0 and state[1]>=0 and state[2]>=0 and state[3]>=0)
    dx,dy=end[0]-pos[0],end[1]-pos[1]
    if (dx+dy)%2==1:
        return False
    dx-=state[2]
    dx+=state[3]
    dy+=state[0]
    dy-=state[1]

    if abs(dx)+abs(dy) <= state[0] + state[1] + state[2] + state[3]:
        return True
    return False
n=input()
s=raw_input()
end=map(int,raw_input().split())

pos=[0,0]
for ch in s:
    if ch=="U":
        pos[1]+=1
    elif ch=="D":
        pos[1]-=1
    elif ch=="L":
        pos[0]-=1
    elif ch=="R":
        pos[0]+=1
    else:
        assert(False)
best=1000000

j=-1
state=[0,0,0,0]

for i in range(n):
    #seg starts at i and ends at j
    while j<i-1 or not works(state):
        if j==n-1:
            break
        j+=1

        ch=s[j]
        if ch=="U":
            state[0]+=1
        elif ch=="D":
            state[1]+=1
        elif ch=="L":
            state[2]+=1
        elif ch=="R":
            state[3]+=1
    if works(state):
        best=min(best,j-i+1)
    ch=s[i]
    if ch=="U":
        state[0]-=1
    elif ch=="D":
        state[1]-=1
    elif ch=="L":
        state[2]-=1
    elif ch=="R":
        state[3]-=1
assert (best>=0)
if best != 1000000:
    print best
else:
    print -1


def works(state):
    global pos, end
    #state=[U,D,L,R]
    dx,dy=end[0]-pos[0],end[1]-pos[1]
    dx-=state[2]
    dx+=state[3]
    dy+=state[0]
    dy-=state[1]
    if abs(dx)+abs(dy) <= state[0] + state[1] + state[2] + state[3]:
        return True
    return False
n=input()
s=raw_input()
end=map(int,raw_input().split())

pos=[0,0]
for ch in s:
    if ch=="U":
        pos[1]+=1
    elif ch=="D":
        pos[1]-=1
    elif ch=="L":
        pos[0]-=1
    elif ch=="R":
        pos[0]+=1
    else:
        print("FEL")
best=1000000

j=-1
state=[0,0,0,0]
for i in range(n):
    #seg starts at i
    while not works(state):
        if j==n-1:
            break
        j+=1

        ch=s[j]
        if ch=="U":
            state[0]+=1
        elif ch=="D":
            state[1]+=1
        elif ch=="L":
            state[2]+=1
        elif ch=="R":
            state[3]+=1
    if works(state):
        best=min(best,j-i+1)
    ch=s[i]
    if ch=="U":
        state[0]-=1
    elif ch=="D":
        state[1]-=1
    elif ch=="L":
        state[2]-=1
    elif ch=="R":
        state[3]-=1
if best != 1000000:
    print best
else:
    print -1


def works(state):
    global pos, end
    #state=[U,D,L,R]
    dx,dy=end[0]-pos[0],end[1]-pos[1]
    dx-=state[2]
    dx+=state[3]
    dy+=state[0]
    dy-=state[1]
    if abs(dx)+abs(dy) <= state[0] + state[1] + state[2] + state[3]:
        return True
    return False
n=input()
s=raw_input()
end=map(int,raw_input().split())

pos=[0,0]
for ch in s:
    if ch=="U":
        pos[1]+=1
    elif ch=="D":
        pos[1]-=1
    elif ch=="L":
        pos[0]-=1
    elif ch=="R":
        pos[0]+=1
    else:
        assert(False)
best=1000000

j=-1
state=[0,0,0,0]
for i in range(n):
    #seg starts at i and ends at j
    while j<i-1 or not works(state):
        if j==n-1:
            break
        j+=1

        ch=s[j]
        if ch=="U":
            state[0]+=1
        elif ch=="D":
            state[1]+=1
        elif ch=="L":
            state[2]+=1
        elif ch=="R":
            state[3]+=1
    if works(state):
        best=min(best,j-i+1)
    ch=s[i]
    if ch=="U":
        state[0]-=1
    elif ch=="D":
        state[1]-=1
    elif ch=="L":
        state[2]-=1
    elif ch=="R":
        state[3]-=1
if best != 1000000:
    print best
else:
    print -1


def works(state):
    global pos, end
    #state=[U,D,L,R]
    dx,dy=end[0]-pos[0],end[1]-pos[1]
    dx-=state[2]
    dx+=state[3]
    dy+=state[0]
    dy-=state[1]
    if abs(dx)+abs(dy) <= state[0] + state[1] + state[2] + state[3]:
        return True
    return False
n=input()
s=raw_input()
end=map(int,raw_input().split())

pos=[0,0]
for ch in s:
    if ch=="U":
        pos[1]+=1
    elif ch=="D":
        pos[1]-=1
    elif ch=="L":
        pos[0]-=1
    elif ch=="R":
        pos[0]+=1
    else:
        assert(False)
best=1000000

j=-1
state=[0,0,0,0]
for i in range(n):
    #seg starts at i and ends at j
    while j<i or not works(state):
        if j==n-1:
            break
        j+=1

        ch=s[j]
        if ch=="U":
            state[0]+=1
        elif ch=="D":
            state[1]+=1
        elif ch=="L":
            state[2]+=1
        elif ch=="R":
            state[3]+=1
    if works(state):
        best=min(best,j-i+1)
    ch=s[i]
    if ch=="U":
        state[0]-=1
    elif ch=="D":
        state[1]-=1
    elif ch=="L":
        state[2]-=1
    elif ch=="R":
        state[3]-=1
if best != 1000000:
    print best
else:
    print -1


#!/usr/bin/env python3

import itertools

def solve(L, n, px, py, x, y):
    for i in range(n):
        j = i + L
        if j > n:
            break
        dx = px[i] + px[-1] - px[j]
        dy = py[i] - py[-1] - py[j]
        if abs(dx) + abs(dy) <= L:
            return True
    return False

def main(args):
    n = int(input())
    d = input()
    x, y = map(int, input().split())
    py = [0] + [1 if c == 'U' else (-1 if c == 'D' else 0) for c in d]
    px = [0] + [1 if c == 'R' else (-1 if c == 'L' else 0) for c in d]
    if abs(x+ y)%2 != n%2:
        print(-1)
        return 0
    py = list(itertools.accumulate(py))
    px = list(itertools.accumulate(px))
    if px[-1] == x and py[-1] == y:
        print(0)
        return 0
    if abs(x) + abs(y) > n:
        print(-1)
        return 0
    left = 0
    right = n
    while left + 1 < right:
        mid = (left + right) // 2
        if possible(mid, n, px, py, x, y):
            left, right = left, mid
        else:
            left, right = mid, right
    print(right)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


#!/usr/bin/env python3

import itertools

def solve(n, pos, px, py, x, y):
    m = n - pos
    if abs(x) > m or abs(y) > m:
        return n**2
    if px[-1] == x and py[-1] == y:
        return 0
    left = pos
    right = n
    while left + 1 < right:
        mid = (left + right) // 2
        d = mid - pos
        mx, my = px[mid]-px[pos], py[mid]-py[pos]
        dx, dy = px[-1] - mx - x, py[-1] - my - y
        d1 = abs(dx) + abs(dy)
        if abs(dx) + abs(dy) > d or (d1 % 2) != (m % 2):
            left, right = mid, right
        else:
            left, right = left, mid
    res = right - pos
    return right - pos

def main(args):
    n = int(input())
    d = input()
    x, y = map(int, input().split())
    py = [0] + [1 if c == 'U' else (-1 if c == 'D' else 0) for c in d]
    px = [0] + [1 if c == 'R' else (-1 if c == 'L' else 0) for c in d]
    if (abs(x) + abs(y))%2 != n%2:
        print(-1)
        return 0
    py = list(itertools.accumulate(py))
    px = list(itertools.accumulate(px))
    res = n**2
    for i in range(n):
        cur = solve(n, i, px, py, x, y)
        res = min(res, cur)
    res = -1 if res == n**2 else res
    print(res)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


#!/usr/bin/env python3

import itertools

def solve(L, n, px, py, x, y):
    for i in range(n):
        j = i + L
        if j > n:
            break
        dx = px[i] + px[-1] - px[j] - x
        dy = py[i] + py[-1] - py[j] - y
        if abs(dx) + abs(dy) <= L:
            return True
    return False

def main(args):
    n = int(input())
    d = input()
    x, y = map(int, input().split())
    py = [0] + [1 if c == 'U' else (-1 if c == 'D' else 0) for c in d]
    px = [0] + [1 if c == 'R' else (-1 if c == 'L' else 0) for c in d]
    if abs(x+ y)%2 != n%2:
        print(-1)
        return 0
    py = list(itertools.accumulate(py))
    px = list(itertools.accumulate(px))
    if px[-1] == x and py[-1] == y:
        print(0)
        return 0
    if abs(x) + abs(y) > n:
        print(-1)
        return 0
    left = 0
    right = n
    while left + 1 < right:
        mid = (left + right) // 2
        if solve(mid, n, px, py, x, y):
            left, right = left, mid
        else:
            left, right = mid, right
    print(right)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


#!/usr/bin/env python3

import itertools

def solve(L, n, px, py, x, y):
    for i in range(n):
        j = i + L
        if j > n:
            break
        dx = px[i] + px[-1] - px[j]
        dy = py[i] - py[-1] - py[j]
        if abs(dx) + abs(dy) <= L:
            return True
    return False

def main(args):
    n = int(input())
    d = input()
    x, y = map(int, input().split())
    py = [0] + [1 if c == 'U' else (-1 if c == 'D' else 0) for c in d]
    px = [0] + [1 if c == 'R' else (-1 if c == 'L' else 0) for c in d]
    if abs(x+ y)%2 != n%2:
        print(-1)
        return 0
    py = list(itertools.accumulate(py))
    px = list(itertools.accumulate(px))
    if px[-1] == x and py[-1] == y:
        print(0)
        return 0
    if abs(x) + abs(y) > n:
        print(-1)
        return 0
    left = 0
    right = n
    while left + 1 < right:
        mid = (left + right) // 2
        if solve(mid, n, px, py, x, y):
            left, right = left, mid
        else:
            left, right = mid, right
    print(right)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


#!/usr/bin/env python3

import itertools

def solve(n, pos, px, py, x, y):
    m = n - pos
    if abs(x) > m or abs(y) > m:
        return n**2
    if px[-1] == x and py[-1] == y:
        return 0
    left = pos
    right = n
    while left + 1 < right:
        mid = (left + right) // 2
        d = mid - pos
        mx, my = px[mid]-px[pos], py[mid]-py[pos]
        dx, dy = px[-1] - mx - x, py[-1] - my - y
        if abs(dx) + abs(dy) > d:
            left, right = mid, right
        else:
            left, right = left, mid
    res = right - pos
    return right - pos

def main(args):
    n = int(input())
    d = input()
    x, y = map(int, input().split())
    py = [0] + [1 if c == 'U' else (-1 if c == 'D' else 0) for c in d]
    px = [0] + [1 if c == 'R' else (-1 if c == 'L' else 0) for c in d]
    if (abs(x) + abs(y))%2 != n%2:
        print(-1)
        return 0
    py = list(itertools.accumulate(py))
    px = list(itertools.accumulate(px))
    res = n**2
    for i in range(n):
        cur = solve(n, i, px, py, x, y)
        res = min(res, cur)
    res = -1 if res == n**2 else res
    print(res)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


def go(pos,k):
    if 'U'==k:
        pos[1]+=1
    elif 'D'==k:
        pos[1]-=1
    elif 'L'==k:
        pos[0]-=1
    else:
        pos[0]+=1
    return pos

def relapos(a,b):           #返回b的坐标减a的坐标
    c=[b[0]-a[0],b[1]-a[1]]
    return c

def stdis(a,b):
    return abs(b[1]-a[1])+abs(b[0]-a[0])

n=int(input())
s=input()
x,y=[int(i) for i in input().split()]
poss=[[0,0]]             #第n次操作后的位置
pos=[0,0]
for i in range(0,n):
    poss.append(tuple(go(pos,s[i])))
if abs(x)+abs(y)>n:
    print(-1)
else:
    lpos=poss[-1]
    dd=stdis(lpos,[x,y])
    q=(dd+1)//2
    j=True
    lpos1=[0,0]
    while j:
        for k1 in range(n-q):
            r=relapos(poss[k1],poss[k1+q])
            lpos1[0]=lpos[0]-r[0]
            lpos1[1]=lpos[1]-r[1]
            if stdis(lpos1,[x,y])<=q:
                print(q)
                j=False
                break
        else:
            q+=1
            j=True


def go(pos,k):
    if 'U'==k:
        pos[1]+=1
    elif 'D'==k:
        pos[1]-=1
    elif 'L'==k:
        pos[0]-=1
    else:
        pos[0]+=1
    return pos

def relapos(a,b):           #返回b的坐标减a的坐标
    c=[b[0]-a[0],b[1]-a[1]]
    return c

def stdis(a,b):
    return abs(b[1]-a[1])+abs(b[0]-a[0])

n=int(input())
s=input()
x,y=[int(i) for i in input().split()]
poss=[[0,0]]             #第n次操作后的位置
pos=[0,0]
for i in range(0,n):
    poss.append(tuple(go(pos,s[i])))
if abs(x)+abs(y)>n or abs(n-x-y)%2!=0:
    print(-1)
else:
    lpos=poss[-1]
    dd=stdis(lpos,[x,y])
    q=(dd+1)//2
    j=True
    lpos1=[0,0]
    while j:
        for k1 in range(n-q+1):
            r=relapos(poss[k1],poss[k1+q])
            lpos1[0]=lpos[0]-r[0]
            lpos1[1]=lpos[1]-r[1]
            if stdis(lpos1,[x,y])<=q:
                print(q)
                j=False
                break
        else:
            q+=1
            j=True


def go(pos,k):
    if 'U'==k:
        pos[1]+=1
    elif 'D'==k:
        pos[1]-=1
    elif 'L'==k:
        pos[0]-=1
    else:
        pos[0]+=1
    return pos

def relapos(a,b):           #返回b的坐标减a的坐标
    c=[b[0]-a[0],b[1]-a[1]]
    return c

def stdis(a,b):
    return abs(b[1]-a[1])+abs(b[0]-a[0])

n=int(input())
s=input()
x,y=[int(i) for i in input().split()]
poss=[[0,0]]             #第n次操作后的位置
pos=[0,0]
for i in range(0,n):
    poss.append(tuple(go(pos,s[i])))
if abs(x)+abs(y)>n or abs(n-x-y)%2!=0:
    print(-1)
else:
    lpos=poss[-1]
    dd=stdis(lpos,[x,y])
    if dd==0:
        print(0)
    else:
        q1=(dd-1)//2
        q2=n
        j=True
        lpos1=[0,0]
        while q2-q1!=1:
            q=(q2+q1)//2
            for k1 in range(n-q+1):
                r=relapos(poss[k1],poss[k1+q])
                lpos1[0]=lpos[0]-r[0]
                lpos1[1]=lpos[1]-r[1]
                if stdis(lpos1,[x,y])<=q:
                    q2=q
                    break
            else:
                q1=q
        print(q2)


import sys
import bisect
#input=sys.stdin.readline
#t=int(input())
t=1
mod=10**9+7
def opx(c):
    if c=='L':
        return -1
    if c=='R':
        return 1
    return 0

def opy(c):
    if c=='D':
        return -1
    if c=='U':
        return 1
    return 0

def utilch(n1,x1,y1):
    x1=xi-x1
    y1=yi-y1
    diffx=abs(x1-xf)
    diffy=abs(y1-yf)
    if diffy+diffx<=n1 and (diffy+diffx)%2==n1%2:
        return True
    return False

def ch(n1):
    x1,y1=0,0
    for i in range(n1):
        x1+=opx(s[i])
        y1+=opy(s[i])

    if utilch(n1,x1,y1):
        return True

    for i in range(n1,n):
        x1-=opx(s[i-n1])
        x1+=opx(s[i])
        y1-=opy(s[i-n1])
        y1+=opy(s[i])
        if utilch(n1,x1,y1):
            return True
    return False

for _ in range(t):
    n=int(input())
    #n,r=map(int,input().split())
    s=input()
    #l=list(map(int,input().split()))
    #l2=list(map(int,input().split()))
    xf,yf=map(int,input().split())
    xi,yi=0,0
    for i in range(len(s)):
        xi+=opx(s[i])
        yi+=opy(s[i])
    if (abs(xf)+abs(yf))<=n and (abs(xf)+abs(yf))%2==n%2:

        l,r=-1,n
        ans=n
        while r-l>1:
            mid=(l+r)//2
            if ch(mid):
                ans=min(ans,mid)
                r=mid
            else:
                l=mid
        #if ch(0):
        #    ans=0

        print(ans)

    else:
        print(-1)


import sys
import bisect
#input=sys.stdin.readline
#t=int(input())
t=1
mod=10**9+7
def opx(c):
    if c=='L':
        return -1
    if c=='R':
        return 1
    return 0

def opy(c):
    if c=='D':
        return -1
    if c=='U':
        return 1
    return 0

def utilch(n1,x1,y1):
    x1=xi-x1
    y1=yi-y1
    diffx=abs(x1-xf)
    diffy=abs(y1-yf)
    if diffy+diffx<=n1 and (diffy+diffx)%2==n1%2:
        return True

def ch(n1):
    x1,y1=0,0
    for i in range(n1):
        x1+=opx(s[i])
        y1+=opy(s[i])

    if utilch(n1,x1,y1):
        return True

    for i in range(n1+1,n):
        x1-=opx(s[i-n1])
        x1+=opx(s[i])
        y1-=opy(s[i-n1])
        y1+=opy(s[i])
        if utilch(n1,x1,y1):
            return True
    return False

for _ in range(t):
    n=int(input())
    #n,r=map(int,input().split())
    s=input()
    #l=list(map(int,input().split()))
    #l2=list(map(int,input().split()))
    xf,yf=map(int,input().split())
    xi,yi=0,0
    for i in range(len(s)):
        xi+=opx(s[i])
        yi+=opy(s[i])
    if (abs(xf)+abs(yf))<=n and (abs(xf)+abs(yf))%2==n%2:

        l,r=0,n-1
        ans=n
        while l<r:
            mid=(l+r)//2
            if ch(mid):
                ans=min(ans,mid)
                r=mid
            else:
                l=mid+1

        print(ans)

    else:
        print(-1)


import sys
import bisect
#input=sys.stdin.readline
#t=int(input())
t=1
mod=10**9+7
def opx(c):
    if c=='L':
        return -1
    if c=='R':
        return 1
    return 0

def opy(c):
    if c=='D':
        return -1
    if c=='U':
        return 1
    return 0

def utilch(n1,x1,y1):
    x1=xi-x1
    y1=yi-y1
    diffx=abs(x1-xf)
    diffy=abs(y1-yf)
    if diffy+diffx<=n1 and (diffy+diffx)%2==n1%2:
        return True
    return False

def ch(n1):
    x1,y1=0,0
    for i in range(n1):
        x1+=opx(s[i])
        y1+=opy(s[i])

    if utilch(n1,x1,y1):
        return True

    for i in range(n1,n):
        x1-=opx(s[i-n1])
        x1+=opx(s[i])
        y1-=opy(s[i-n1])
        y1+=opy(s[i])
        if utilch(n1,x1,y1):
            return True
    return False

for _ in range(t):
    n=int(input())
    #n,r=map(int,input().split())
    s=input()
    #l=list(map(int,input().split()))
    #l2=list(map(int,input().split()))
    xf,yf=map(int,input().split())
    xi,yi=0,0
    for i in range(len(s)):
        xi+=opx(s[i])
        yi+=opy(s[i])
    if (abs(xf)+abs(yf))<=n and (abs(xf)+abs(yf))%2==n%2:

        l,r=0,n-1
        ans=n
        while l<r:
            mid=(l+r)//2
            if ch(mid):
                ans=min(ans,mid)
                r=mid
            else:
                l=mid+1
        if ch(0):
            ans=0

        print(ans)

    else:
        print(-1)


import sys
import bisect
#input=sys.stdin.readline
#t=int(input())
t=1
mod=10**9+7
def opx(c):
    if c=='L':
        return -1
    if c=='R':
        return 1
    return 0

def opy(c):
    if c=='D':
        return -1
    if c=='U':
        return 1
    return 0

def utilch(n1,x1,y1):
    x1=xi-x1
    y1=yi-y1
    diffx=abs(x1-xf)
    diffy=abs(y1-yf)
    if diffy+diffx<=n1 and (diffy+diffx)%2==n1%2:
        return True
    return False

def ch(n1):
    x1,y1=0,0
    for i in range(n1):
        x1+=opx(s[i])
        y1+=opy(s[i])

    if utilch(n1,x1,y1):
        return True

    for i in range(n1,n):
        x1-=opx(s[i-n1])
        x1+=opx(s[i])
        y1-=opy(s[i-n1])
        y1+=opy(s[i])
        if utilch(n1,x1,y1):
            return True
    return False

for _ in range(t):
    n=int(input())
    #n,r=map(int,input().split())
    s=input()
    #l=list(map(int,input().split()))
    #l2=list(map(int,input().split()))
    xf,yf=map(int,input().split())
    xi,yi=0,0
    for i in range(len(s)):
        xi+=opx(s[i])
        yi+=opy(s[i])
    if (abs(xf)+abs(yf))<=n and (abs(xf)+abs(yf))%2==n%2:

        l,r=0,n-1
        ans=n
        while l<r:
            mid=(l+r)//2
            if ch(mid):
                ans=min(ans,mid)
                r=mid
            else:
                l=mid+1

        print(ans)

    else:
        print(-1)


#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

#-------------------game starts now-----------------------------------------------------
n = int(input())
dx = [0 for i in range(n + 1)]
dy = [0 for i in range(n + 1)]
for i, ch in enumerate(input()):
    dx[i + 1] = dx[i]
    dy[i + 1] = dy[i]
    if ch == 'U':
        dy[i + 1] += 1
    elif ch == 'D':
        dy[i + 1] -= 1
    elif ch == 'R':
        dx[i + 1] += 1
    else:
        assert ch == 'L'
        dx[i + 1] -= 1
x, y = map(int, input().split())
def canChange(left, right):
    dx1 = dx[left]
    dy1 = dy[left]
    dx3 = dx[-1] - dx[right]
    dy3 = dy[-1] - dy[right]
    dx2 = x - dx1 - dx3
    dy2 = y - dy1 - dy3
    length = right - left
    free = length - (abs(dx2) + abs(dy2))
    return free >= 0 and free % 2 == 0
result = n + 1
ptr = n + 1
for i in reversed(range(n)):
    while ptr - 1 >= i and canChange(i, ptr - 1):
        ptr -= 1
        result = min(result, ptr - i)
if ptr == n + 1:
    print(-1)
else:
    print(result)


n = int(input())
a = input()
x, y = map(int, input().split())
if abs(x) + abs(y) > n or (x + y + n) % 2 != 0:
    print(-1)
else:
    dx = [0]*(n)
    dy = [0]*(n)
    for i in range(n):
        if a[i] == 'R':
            dx[i] = 1
        elif a[i] == 'L':
            dx[i] = -1
        elif a[i] == 'U':
            dy[i] = 1
        else:
            dy[i] = -1
    xx = sum(dx)
    yy = sum(dy)
    if xx == x and yy == y:
        print(0)
    else:
        l = 0
        res = n
        for r in range(n):
            xx -= dx[r]
            yy -= dy[r]
            while r-l+1 >= abs(x-xx) + abs(y-yy):
                xx += dx[l]
                yy += dy[l]
                l += 1
            if l > 0:
                res = min(res, r-l+2)
        print(res)


#!/usr/bin/python3
from collections import Counter

def readint():
    return int(input())

def readline():
    return [int(c) for c in input().split()]

def update(pos, mv, d):
    if mv == 'U':
        pos[1] += d
    elif mv == 'D':
        pos[1] -= d
    elif mv == 'L':
        pos[0] -= d
    elif mv == 'R':
        pos[0] += d

def can(u, v, length):
    d = abs(u[0] - v[0]) + abs(u[1] - v[1])
    if d % 2 != length % 2:
        return False
    return length >= d

def ok(length, n, x, y, s):
    pos = [0, 0]
    for i in range(length, n):
        update(pos, s[i], 1)

    l, r = 0, length
    while True:
        if can(pos, [x, y], length):
            return True
        if r == n:
            break
        update(pos, s[l], 1)
        l += 1
        update(pos, s[r], -1)
        r += 1

    return False

def main():
    n = readint()
    s = input()
    x, y = readline()

    if not ok(n, n, x, y, s):
        print(-1)
        return

    l, r = -1, n
    while r - l > 1:
        mid = (l + r) // 2
        if ok(mid, n, x, y, s):
            r = mid
        else:
            l = mid

    print(r)

if __name__ == '__main__':
    main()

"""
#include <bits/stdc++.h>

using namespace std;

const int N = int(1e5) + 9;

string s;
int n;
int x, y;

void upd(pair<int, int> &pos, char mv, int d){
	if(mv == 'U')
		pos.second += d;
	if(mv == 'D')
		pos.second -= d;
	if(mv == 'L')
		pos.first -= d;
	if(mv == 'R')
		pos.first += d;
}

bool can(pair<int, int> u, pair<int, int> v, int len){
	int d = abs(u.first - v.first) + abs(u.second - v.second);
	if(d % 2 != len % 2) return false;
	return len >= d;
}

bool ok(int len){
	pair<int, int> pos = make_pair(0, 0);
	for(int i = len; i < n; ++i)
		upd(pos, s[i], 1);

	int l = 0, r = len;
	while(true){
		if(can(pos, make_pair(x, y), len))
			return true;

		if(r == n) break;
		upd(pos, s[l++], 1);
		upd(pos, s[r++], -1);
	}

	return false;
}

int main() {
	//freopen("input.txt", "r", stdin);

	cin >> n;
	cin >> s;
	cin >> x >> y;

	if(!ok(n)){
		puts("-1");
		return 0;
	}

	int l = -1, r = n;
	while(r - l > 1){
		int mid = (l + r) / 2;
		if(ok(mid)) r = mid;
		else l = mid;
	}

	cout << r << endl;
    return 0;
}
"""


import sys

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

if abs(x)+abs(y)>n or (abs(x)+abs(y))%2!=n%2:
    print(-1)
    sys.exit()

now=[0,0]
LISTL=[(0,0)]
for s in S:
    if s=="R":
        now[0]+=1
    elif s=="L":
        now[0]-=1
    elif s=="U":
        now[1]+=1
    else:
        now[1]-=1

    LISTL.append((now[0],now[1]))

LISTR=[(0,0)]
now=[0,0]
for s in S[::-1]:
    if s=="R":
        now[0]+=1
    elif s=="L":
        now[0]-=1
    elif s=="U":
        now[1]+=1
    else:
        now[1]-=1

    LISTR.append((now[0],now[1]))

def su(a,b,x,y):
    return abs(x-(a[0]+b[0]))+abs(y-(a[1]+b[1]))

ANS=0
for i in range(n+1):
    for j in range(max(0,ANS-i),n+1):
        if su(LISTR[i],LISTL[j],x,y)<=n-i-j:
            #print(i,j)
            if ANS<i+j:
                ANS=i+j

        else:
            break

print(n-ANS)


n = int(input())
subtract = lambda t1, t2: (t1[0] - t2[0], t1[1] - t2[1])
add = lambda t1, t2: (t1[0] + t2[0], t1[1] + t2[1])
def conv(ch):
	if ch == 'L':
		return (-1, 0)
	elif ch == 'R':
		return (1, 0)
	elif ch == 'U':
		return (0, 1)
	elif ch == 'D':
		return (0, -1)

ops = [conv(ch) for ch in input()]
x, y = map(int, input().split())
lsum = [ops[0]] * n
for i in range(1, n):
	lsum[i] = add(lsum[i - 1], ops[i])
rsum = [ops[n - 1]] * n
i = n - 2
while i >= 0:
	rsum[i] = add(rsum[i + 1], ops[i])
	i = i - 1

def check(L):

	for i in range(0, n - L + 1):
		moves = (x, y)
		if i > 0:
			moves = subtract(moves, lsum[i - 1])
		if i + L < n:
			moves = subtract(moves, rsum[i + L])
		turns = abs(moves[0]) + abs(moves[1])
		if (turns <= L and (L - turns) % 2 == 0):
			return True;
	return False;

if abs(x) + abs(y) > n or (abs(x) + abs(y) - n) % 2 != 0:
	print(-1);
else:
	st, en = 0, n
	while st < en:
		md = (st + en) // 2
		if check(md):
			en = md
		else:
			st = md + 1
	print(st)


n = int(input())
subtract = lambda t1, t2: (t1[0] - t2[0], t1[1] - t2[1])
add = lambda t1, t2: (t1[0] + t2[0], t1[1] + t2[1])
def conv(ch):
	if ch == 'L':
		return (-1, 0)
	elif ch == 'R':
		return (1, 0)
	elif ch == 'U':
		return (0, 1)
	elif ch == 'D':
		return (0, -1)

ops = [conv(ch) for ch in input()]
x, y = map(int, input().split())
lsum = [ops[0]] * n
for i in range(1, n):
	lsum[i] = add(lsum[i - 1], ops[i])
rsum = [ops[n - 1]] * n
i = n - 2
while i >= 0:
	rsum[i] = add(rsum[i + 1], ops[i])
	i = i - 1

def check(L):

	for i in range(0, n - L):
		moves = (x, y)
		if i > 0:
			moves = subtract(moves, lsum[i - 1])
		if i + L < n:
			moves = subtract(moves, rsum[i + L])
		turns = abs(moves[0]) + abs(moves[1])
		if (turns <= L and (L - turns) % 2 == 0):
			return True;
	return False;

if abs(x) + abs(y) > n or (abs(x) + abs(y) - n) % 2 != 0:
	print(-1);
else:
	st, en = 0, n
	while st < en:
		md = (st + en) // 2
		if check(md):
			en = md
		else:
			st = md + 1
	print(st)


def check(x, y, fx, fy, num_moves):
	if ((abs(fx - x) +  abs(fy - y))-num_moves) <= 0 and ((abs(fx - x) +  abs(fy - y))-num_moves)%2  == 0:
		return True
	return False

N = int(input())
mm =  {'U':0,'D':1,'L':2,'R':3}

dpmat = [[0] for i in range(4)]

ops =  str(input())

for op in ops:
	dpmat[0].append(dpmat[0][-1])
	dpmat[1].append(dpmat[1][-1])
	dpmat[2].append(dpmat[2][-1])
	dpmat[3].append(dpmat[3][-1])

	dpmat[mm[op]][-1] = dpmat[mm[op]][-1]+1

fpos = list(map(int,input().split()))
if N < fpos[0]+fpos[1]:
	print("-1")
else :
	x,y = 0,0

	ans = 10e10

	while y <= N and x <= y:
		if y == 0 and x == 0:
			num_moves = 0
			xr = dpmat[3][N]
			xl = dpmat[2][N]
			yu = dpmat[0][N]
			yd = dpmat[1][N]
		else:
			num_moves = y-x+1
			xr = dpmat[3][x-1] +  dpmat[3][N] - dpmat[3][y]
			xl = dpmat[2][x-1] +  dpmat[2][N] - dpmat[2][y]
			yu = dpmat[0][x-1] +  dpmat[0][N] - dpmat[0][y]
			yd = dpmat[1][x-1] +  dpmat[1][N] - dpmat[1][y]

		if check(xr-xl, yu-yd, fpos[0], fpos[1], num_moves) == True:
			x += 1
			ans = min(ans, num_moves)
		else:
			if x==0:
				x += 1
			y += 1
	if ans == 10e10:
		print("-1")
	else:
		print(max(0,ans))


def check(length: int):
    global n, x, y, cur, hor, ver
    hor = 0
    ver = 0
    for i in range(length, n):
        upd(i)
    for i in range(n - length + 1):
        if abs(x - hor) + abs(y - ver) <= length:
            return True
        if i + length < n:
            upd(i)
            minus_upd(i + length)
    return False

def upd(pos: int):
    global s, ver, hor
    if s[pos] == 'U':
        ver += 1
    elif s[pos] == 'D':
        ver -= 1
    elif s[pos] == 'R':
        hor += 1
    else:
        hor -= 1

def minus_upd(pos: int):
    global s, ver, hor
    if s[pos] == 'U':
        ver -= 1
    elif s[pos] == 'D':
        ver += 1
    elif s[pos] == 'R':
        hor -= 1
    else:
        hor += 1

n = int(input())
s = list(input())
x, y = map(int, input().split())
if (x + y) % 2 != n % 2 or abs(x) + abs(y) > n:
    print(-1)
    exit()

ver = 0
hor = 0
cur = 0
for i in range(n):
    upd(i)

left = -1
r = n
while r - left > 1:
    length = (r + left) // 2
    if check(length):
        r = length
    else:
        left = length

print(r)


def check(length: int):
    global n, x, y, cur, hor, ver
    hor = 0
    ver = 0
    for i in range(length, n):
        upd(i)
    for i in range(n - length):
        if abs(x - hor) + abs(y - ver) <= length:
            return True
        upd(i)
        minus_upd(i + length)
    return False

def upd(pos: int):
    global s, ver, hor
    if s[pos] == 'U':
        ver += 1
    elif s[pos] == 'D':
        ver -= 1
    elif s[pos] == 'R':
        hor += 1
    else:
        hor -= 1

def minus_upd(pos: int):
    global s, ver, hor
    if s[pos] == 'U':
        ver -= 1
    elif s[pos] == 'D':
        ver += 1
    elif s[pos] == 'R':
        hor -= 1
    else:
        hor += 1

n = int(input())
s = list(input())
x, y = map(int, input().split())
if (x + y) % 2 != n % 2 or abs(x) + abs(y) > n:
    print(-1)
    exit()

ver = 0
hor = 0
cur = 0
for i in range(n):
    upd(i)

left = -1
r = n + 1
while r - left > 1:
    length = (r + left) // 2
    if check(length):
        r = length
    else:
        left = length

print(r)


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], deg[N], vis2[N];
VI slo[N];
int root;
void Exit() {
  cout<<"-1\n";
  exit(0);
}
int Dfs(int v) {
  vis2[v] = 1;
  set<int> hehs;
  for (auto nei : slo[v]) {
    if (vis2[nei]) { continue; }
    hehs.insert(Dfs(nei) + 1);
  }
  if (v == root) {
    if (SZ(hehs) == 1) {
      cout<<2 * *(hehs.begin())<<endl;
      exit(0);
    } else if (SZ(hehs) == 2) {
      cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      exit(0);
    }
  }
  if (SZ(hehs) > 1) {
    Exit();
  }
  if (SZ(hehs)) {
    return *(hehs.begin());
  }
  return 0;
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].PB(b);
    slo[b].PB(a);
    deg[a]++;
    deg[b]++;
  }
  RE (i, n) {
    if (deg[i] == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    cout<<n-1<<endl;
    return 0;
  }
  int shortest = n + 1;
  for (auto leaf : leaves) {
    int cur = leaf;
    int cnt = 0;
    while (deg[cur] <3 /* heart in valentine's day! yay! */) {
      vis1[cur] = 1;
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3) {
          cur = nei;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    if (shortest > cnt) {
      shortest = cnt;
      root = cur;
    }
  }
  debug(root);
  Dfs(root);

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], vis2[N], deg[N];
set<int> slo[N];
int root;
int cut[N];
void Exit() {
  cout<<"-1\n";
  exit(0);
}
//~ int Dfs(int v) {
  //~ vis2[v] = 1;
  //~ set<int> hehs;
  //~ for (auto nei : slo[v]) {
    //~ if (vis2[nei]) { continue; }
    //~ hehs.insert(Dfs(nei) + 1);
  //~ }
  //~ if (v == root) {
    //~ if (SZ(hehs) == 1) {
      //~ cout<<2 * *(hehs.begin())<<endl;
      //~ exit(0);
    //~ } else if (SZ(hehs) == 2) {
      //~ cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      //~ exit(0);
    //~ }
  //~ }
  //~ if (SZ(hehs) > 1) {
    //~ Exit();
  //~ }
  //~ if (SZ(hehs)) {
    //~ return *(hehs.begin());
  //~ }
  //~ return 0;
//~ }
set<int> dynda[N];
int Zium(int a) {
  if (a % 2 == 1) {
    return a;
  }
  return Zium(a / 2);
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].insert(b);
    slo[b].insert(a);
    deg[a]++;
    deg[b]++;
  }
  //int internal = 0;
  RE (i, n) {
    if (SZ(slo[i]) == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    int ans = n - 1;
    cout<<Zium(ans)<<endl;
    return 0;
  }

  set<PII> que;
  //int shortest = n + 1;
  function<int(int, int)> GoUp = [&](int leaf, int add) {
    int cur = leaf;
    int cnt = 0;
    int prv = -1;
    while (2 <3 /* heart on valentine's day! yay! */) {
      vis1[cur] = 1;
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3) {
          prv = cur;
          cur = nei;
          cnt++;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    dynda[cur].insert(cnt + add);
    slo[cur].erase(prv);
    return cur;
  };

  VI lols;
  for (auto leaf : leaves) {
    lols.PB(GoUp(leaf, 0));
  }
  for (int ii = 0; ii < SZ(lols); ii++) {
    int v = lols[ii];
    if (cut[v]) { continue; }
    if (SZ(slo[v]) == 1 && SZ(dynda[v]) == 1) {
      cut[v] = 1;
      lols.PB(GoUp(v, *(dynda[v].begin())));
    }
  }
  VI notcut;
  RE (i, n) {
    if (deg[i] >= 3 && !cut[i]) {
      notcut.PB(i);
    }
  }
  if (SZ(notcut) > 1) {
    Exit();
  }
  int v = notcut[0];
  if (SZ(dynda[v]) > 2) {
    Exit();
  }
  int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  while (ans % 2 == 0) {
    ans /= 2;
  }
  cout<<ans<<endl;
  return 0;

  //~ RE (i, n) {
    //~ debug(i, dynda[i]);
    //~ if (dynda[i].empty()) { continue; }
    //~ que.insert({*(dynda[i].begin()), i});
  //~ }
  //~ VI roots;
  //~ while (!que.empty()) {
    //~ auto P = *(que.begin());
    //~ int v = P.nd;
    //~ debug(v, P.st);
    //~ que.erase(que.begin());
    //~ if (que.empty()) {
      //~ if (SZ(slo[v]) == 0) {
        //~ roots.PB(v);
        //~ continue;
      //~ }
    //~ }
    //~ if (SZ(dynda[v]) > 1) {
      //~ roots.PB(v);
      //~ continue;
      //~ Exit();
    //~ }
    //~ int guy;
    //~ if (SZ(dynda[v]) == 0) {
      //~ guy = GoUp(v, 0);
    //~ } else {
      //~ guy = GoUp(v, P.st);
    //~ }
    //~ if (SZ(slo[guy]) == 1) {
      //~ que.insert({*(dynda[guy].begin()), guy});
    //~ }
  //~ }
  //~ if (SZ(roots) != 1) {
    //~ Exit();
  //~ }
  //~ int v = roots[0];
  //~ if (SZ(dynda[v]) > 2) {
    //~ Exit();
  //~ }
  //~ int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  //~ while (ans % 2 == 0) {
    //~ ans /= 2;
  //~ }
  //~ cout<<ans<<endl;
  //~ return 0;
  //~
  //~

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], deg[N], vis2[N];
VI slo[N];
int root;
void Exit() {
  cout<<"-1\n";
  exit(0);
}
int Dfs(int v) {
  vis2[v] = 1;
  set<int> hehs;
  for (auto nei : slo[v]) {
    if (vis2[nei]) { continue; }
    hehs.insert(Dfs(nei) + 1);
  }
  if (SZ(hehs) > 1) {
    if (v == root && SZ(hehs) == 2) {
      cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      exit(0);
    } else {
      Exit();
    }
  }
  if (SZ(hehs)) {
    return *(hehs.begin());
  }
  return 0;
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].PB(b);
    slo[b].PB(a);
    deg[a]++;
    deg[b]++;
  }
  RE (i, n) {
    if (deg[i] == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    cout<<n-1<<endl;
    return 0;
  }
  int shortest = n + 1;
  for (auto leaf : leaves) {
    int cur = leaf;
    int cnt = 0;
    while (deg[cur] <3 /* heart in valentine's day! yay! */) {
      vis1[cur] = 1;
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3) {
          cur = nei;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    if (shortest > cnt) {
      shortest = cnt;
      root = cur;
    }
  }
  debug(root);
  Dfs(root);

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], vis2[N], deg[N];
set<int> slo[N];
int root;
int cut[N];
void Exit() {
  cout<<"-1\n";
  exit(0);
}
//~ int Dfs(int v) {
  //~ vis2[v] = 1;
  //~ set<int> hehs;
  //~ for (auto nei : slo[v]) {
    //~ if (vis2[nei]) { continue; }
    //~ hehs.insert(Dfs(nei) + 1);
  //~ }
  //~ if (v == root) {
    //~ if (SZ(hehs) == 1) {
      //~ cout<<2 * *(hehs.begin())<<endl;
      //~ exit(0);
    //~ } else if (SZ(hehs) == 2) {
      //~ cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      //~ exit(0);
    //~ }
  //~ }
  //~ if (SZ(hehs) > 1) {
    //~ Exit();
  //~ }
  //~ if (SZ(hehs)) {
    //~ return *(hehs.begin());
  //~ }
  //~ return 0;
//~ }
set<int> dynda[N];
int Zium(int a) {
  if (a % 2 == 1) {
    return a;
  }
  return Zium(a / 2);
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].insert(b);
    slo[b].insert(a);
    deg[a]++;
    deg[b]++;
  }
  //int internal = 0;
  RE (i, n) {
    if (SZ(slo[i]) == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    int ans = n - 1;
    cout<<Zium(ans)<<endl;
    return 0;
  }

  set<PII> que;
  //int shortest = n + 1;
  function<int(int, int)> GoUp = [&](int leaf, int add) {
    int cur = leaf;
    int cnt = 0;
    int prv = -1;
    debug(leaf, add);
    while (2 <3 /* heart on valentine's day! yay! */) {
      vis1[cur] = 1;
      //debug(cur);
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3 && !cut[nei]) {
          prv = cur;
          cur = nei;
          cnt++;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    dynda[cur].insert(cnt + add);
    slo[cur].erase(prv);
    debug(cur, cnt + add);
    return cur;
  };

  VI lols;
  for (auto leaf : leaves) {
    lols.PB(GoUp(leaf, 0));
  }
  for (int ii = 0; ii < SZ(lols); ii++) {
    int v = lols[ii];
    debug(v);
    if (cut[v]) { continue; }
    if (SZ(slo[v]) == 1 && SZ(dynda[v]) == 1) {
      cut[v] = 1;
      lols.PB(GoUp(v, *(dynda[v].begin())));
    }
  }
  VI notcut;
  RE (i, n) {
    if (deg[i] >= 3 && !cut[i]) {
      notcut.PB(i);
    }
  }
  if (SZ(notcut) > 1) {
    Exit();
  }
  int v = notcut[0];
  if (SZ(dynda[v]) > 2) {
    Exit();
  }
  int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  while (ans % 2 == 0) {
    ans /= 2;
  }
  cout<<ans<<endl;
  return 0;

  //~ RE (i, n) {
    //~ debug(i, dynda[i]);
    //~ if (dynda[i].empty()) { continue; }
    //~ que.insert({*(dynda[i].begin()), i});
  //~ }
  //~ VI roots;
  //~ while (!que.empty()) {
    //~ auto P = *(que.begin());
    //~ int v = P.nd;
    //~ debug(v, P.st);
    //~ que.erase(que.begin());
    //~ if (que.empty()) {
      //~ if (SZ(slo[v]) == 0) {
        //~ roots.PB(v);
        //~ continue;
      //~ }
    //~ }
    //~ if (SZ(dynda[v]) > 1) {
      //~ roots.PB(v);
      //~ continue;
      //~ Exit();
    //~ }
    //~ int guy;
    //~ if (SZ(dynda[v]) == 0) {
      //~ guy = GoUp(v, 0);
    //~ } else {
      //~ guy = GoUp(v, P.st);
    //~ }
    //~ if (SZ(slo[guy]) == 1) {
      //~ que.insert({*(dynda[guy].begin()), guy});
    //~ }
  //~ }
  //~ if (SZ(roots) != 1) {
    //~ Exit();
  //~ }
  //~ int v = roots[0];
  //~ if (SZ(dynda[v]) > 2) {
    //~ Exit();
  //~ }
  //~ int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  //~ while (ans % 2 == 0) {
    //~ ans /= 2;
  //~ }
  //~ cout<<ans<<endl;
  //~ return 0;
  //~
  //~

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], vis2[N], deg[N];
set<int> slo[N];
int root;
void Exit() {
  cout<<"-1\n";
  exit(0);
}
//~ int Dfs(int v) {
  //~ vis2[v] = 1;
  //~ set<int> hehs;
  //~ for (auto nei : slo[v]) {
    //~ if (vis2[nei]) { continue; }
    //~ hehs.insert(Dfs(nei) + 1);
  //~ }
  //~ if (v == root) {
    //~ if (SZ(hehs) == 1) {
      //~ cout<<2 * *(hehs.begin())<<endl;
      //~ exit(0);
    //~ } else if (SZ(hehs) == 2) {
      //~ cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      //~ exit(0);
    //~ }
  //~ }
  //~ if (SZ(hehs) > 1) {
    //~ Exit();
  //~ }
  //~ if (SZ(hehs)) {
    //~ return *(hehs.begin());
  //~ }
  //~ return 0;
//~ }
set<int> dynda[N];
int Zium(int a) {
  if (a % 2 == 1) {
    return a;
  }
  return Zium(a / 2);
}
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].insert(b);
    slo[b].insert(a);
    deg[a]++;
    deg[b]++;
  }
  //int internal = 0;
  RE (i, n) {
    if (SZ(slo[i]) == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    int ans = n - 1;
    cout<<Zium(ans)<<endl;
    return 0;
  }

  set<PII> que;
  //int shortest = n + 1;
  function<int(int, int)> GoUp = [&](int leaf, int add) {
    int cur = leaf;
    int cnt = 0;
    int prv = -1;
    while (2 <3 /* heart on valentine's day! yay! */) {
      vis1[cur] = 1;
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3) {
          prv = cur;
          cur = nei;
          cnt++;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    dynda[cur].insert(cnt + add);
    slo[cur].erase(prv);
    return cur;
  };

  for (auto leaf : leaves) {
    GoUp(leaf, 0);
  }
  RE (i, n) {
    debug(i, dynda[i]);
    if (dynda[i].empty()) { continue; }
    que.insert({*(dynda[i].begin()), i});
  }
  VI roots;
  while (!que.empty()) {
    auto P = *(que.begin());
    int v = P.nd;
    debug(v, P.st);
    que.erase(que.begin());
    if (que.empty()) {
      if (SZ(slo[v]) == 0) {
        roots.PB(v);
        continue;
      }
    }
    if (SZ(dynda[v]) > 1) {
      roots.PB(v);
      continue;
      Exit();
    }
    int guy;
    if (SZ(dynda[v]) == 0) {
      guy = GoUp(v, 0);
    } else {
      guy = GoUp(v, P.st);
    }
    if (SZ(slo[guy]) == 1) {
      que.insert({*(dynda[guy].begin()), guy});
    }
  }
  if (SZ(roots) != 1) {
    Exit();
  }
  int v = roots[0];
  if (SZ(dynda[v]) > 2) {
    Exit();
  }
  int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  while (ans % 2 == 0) {
    ans /= 2;
  }
  cout<<ans<<endl;
  return 0;

  return 0;
}


#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define int long long
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',')cerr<<*sdbg++; cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

const int N = 2e5 + 5;
int vis1[N], vis2[N], deg[N];
set<int> slo[N];
int root;
void Exit() {
  cout<<"-1\n";
  exit(0);
}
//~ int Dfs(int v) {
  //~ vis2[v] = 1;
  //~ set<int> hehs;
  //~ for (auto nei : slo[v]) {
    //~ if (vis2[nei]) { continue; }
    //~ hehs.insert(Dfs(nei) + 1);
  //~ }
  //~ if (v == root) {
    //~ if (SZ(hehs) == 1) {
      //~ cout<<2 * *(hehs.begin())<<endl;
      //~ exit(0);
    //~ } else if (SZ(hehs) == 2) {
      //~ cout<<*(hehs.begin()) + *(hehs.rbegin())<<endl;
      //~ exit(0);
    //~ }
  //~ }
  //~ if (SZ(hehs) > 1) {
    //~ Exit();
  //~ }
  //~ if (SZ(hehs)) {
    //~ return *(hehs.begin());
  //~ }
  //~ return 0;
//~ }
set<int> dynda[N];
int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;

  int n;
  cin>>n;
  vector<int> leaves;
  RE (i, n - 1) {
    int a, b;
    cin>>a>>b;
    slo[a].insert(b);
    slo[b].insert(a);
    deg[a]++;
    deg[b]++;
  }
  //int internal = 0;
  RE (i, n) {
    if (SZ(slo[i]) == 1) {
      leaves.PB(i);
    }
  }
  if (SZ(leaves) == 2) {
    cout<<n-1<<endl;
    return 0;
  }

  set<PII> que;
  //int shortest = n + 1;
  function<int(int, int)> GoUp = [&](int leaf, int add) {
    int cur = leaf;
    int cnt = 0;
    int prv = -1;
    while (2 <3 /* heart on valentine's day! yay! */) {
      vis1[cur] = 1;
      for (auto nei : slo[cur]) {
        if (deg[nei] >= 3) {
          prv = cur;
          cur = nei;
          cnt++;
          goto A;
        }
        if (vis1[nei]) {
          continue;
        }
        cnt++;
        cur = nei;
      }
    }
    A: ;
    dynda[cur].insert(cnt + add);
    slo[cur].erase(prv);
    return cur;
  };

  for (auto leaf : leaves) {
    GoUp(leaf, 0);
  }
  RE (i, n) {
    debug(i, dynda[i]);
    if (dynda[i].empty()) { continue; }
    que.insert({*(dynda[i].begin()), i});
  }
  VI roots;
  while (!que.empty()) {
    auto P = *(que.begin());
    int v = P.nd;
    debug(v, P.st);
    que.erase(que.begin());
    if (que.empty()) {
      if (SZ(slo[v]) == 0) {
        roots.PB(v);
        continue;
      }
    }
    if (SZ(dynda[v]) > 1) {
      roots.PB(v);
      continue;
      Exit();
    }
    int guy;
    if (SZ(dynda[v]) == 0) {
      guy = GoUp(v, 0);
    } else {
      guy = GoUp(v, P.st);
    }
    if (SZ(slo[guy]) == 1) {
      que.insert({*(dynda[guy].begin()), guy});
    }
  }
  if (SZ(roots) != 1) {
    Exit();
  }
  int v = roots[0];
  if (SZ(dynda[v]) > 2) {
    Exit();
  }
  int ans = *(dynda[v].begin()) + *(dynda[v].rbegin());
  while (ans % 2 == 0) {
    ans /= 2;
  }
  cout<<ans<<endl;
  return 0;

  return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];
int sol=N;
bool flag, possible;

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev, bool &flag)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v, flag)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) flag=0;
    if ((int)cur.size()>2 && v==c) flag=0;
    for (auto x: cur) ret+=x;

    return ret;
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    for (int i=1;i<=n;i++)
    {
        if (dist[i]==(int)p.first/2 || (p.first&1 && dist[i]==1+(int)p.first/2))
        {
            c=i;
            flag=true;
            int x=dfs (c, 0, flag);
            if (!flag) continue;
            possible=true;
            while (x%2==0) x>>=1;
            sol=min(sol, x);
        }
    }

    if (possible) printf ("%d", sol);
    else printf ("-1");

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];
int sol=N;
bool flag, possible;

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev, bool &flag)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v, flag)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) flag=0;
    if ((int)cur.size()>2 && v==c) flag=0;
    for (auto x: cur) ret+=x;

    return ret;
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    for (int i=1;i<=n;i++)
    {
        if (dist[i]==(int)p.first/2 || (p.first&1 && dist[i]==1+(int)p.first/2))
        {
            c=i;
            flag=true;
            int x=dfs (c, 0, flag);
            if (!flag) continue;
            possible=true;
            while (x%2==0) x>>=2;
            sol=min(sol, x);
        }
    }

    if (possible) printf ("%d", sol);
    else printf ("-1");

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];
int sol=N;
bool flag, possible;
set<int> path;

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev, bool &flag)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v, flag)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) flag=0;
    if ((int)cur.size()>2 && v==c) flag=0;
    for (auto x: cur) ret+=x;

    return ret;
}

void makePath (int v)
{
    path.insert(v);
    for (auto xt: g[v])
    {
        if (dist[xt]==dist[v]-1)
        {
            makePath(xt);
            return;
        }
    }
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    makePath(p.second);
    for (int i=1;i<=n;i++)
    {
        if ((dist[i]==(int)p.first/2 || (p.first&1 && dist[i]==1+(int)p.first/2)) && path.find(i)!=path.end())
        {
            c=i;
            flag=true;
            int x=dfs (c, 0, flag);
            if (!flag) continue;
            possible=true;
            while (x%2==0) x>>=1;
            sol=min(sol, x);
        }
    }

    if (possible) printf ("%d", sol);
    else printf ("-1");

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) finish();
    if ((int)cur.size()>2 && v==c) finish();
    for (auto x: cur) ret+=x;

    return ret;
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    for (int i=1;i<=n;i++) if (dist[i]==p.first/2) c=i;

    if (n==200000) cout << p.first << endl << endl;

    int d=dfs (c, 0);
    while (d%2==0) d>>=2;

    printf ("%d", d);

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];
int sol=N;
bool flag, possible;
bool path[N];

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev, bool &flag)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v, flag)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) flag=0;
    if ((int)cur.size()>2 && v==c) flag=0;
    for (auto x: cur) ret+=x;

    return ret;
}

void makePath (int v)
{
    path[v]=true;
    for (auto xt: g[v])
    {
        if (dist[xt]==dist[v]-1)
        {
            makePath(xt);
            return;
        }
    }
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    makePath(p.second);
    for (int i=1;i<=n;i++)
    {
        if ((dist[i]==(int)p.first/2 || (p.first&1 && dist[i]==1+(int)p.first/2)) && path[i])
        {
            c=i;
            flag=true;
            int x=dfs (c, 0, flag);
            if (!flag) continue;
            possible=true;
            while (x%2==0) x>>=1;
            sol=min(sol, x);
        }
    }

    if (possible) printf ("%d", sol);
    else printf ("-1");

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

void finish ()
{
    printf ("-1");
    exit(0);
}

int dfs (int v, int prev)
{
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) finish();
    if ((int)cur.size()>2 && v==c) finish();
    for (auto x: cur) ret+=x;

    return ret;
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    for (int i=1;i<=n;i++) if (dist[i]==p.first/2) c=i;

    if (n=200000) cout << p.first << endl << endl;

    int d=dfs (c, 0);
    while (d%2==0) d>>=2;

    printf ("%d", d);

    return 0;
}


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

const int N=2e5+10;

vector<int> g[N];
int n, c, dist[N];
int sol=N;
bool flag, possible;
bool path[N];

pair<int, int> findCenter (int v, int prev)
{
    dist[v]=dist[prev]+1;
    pair<int, int> ret={dist[v], v};
    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        ret=max(ret, findCenter(xt, v));
    }
    return ret;
}

int dfs (int v, int prev, bool &flag)
{
    if (!flag) return 0;
    vector<int> cur;
    int ret=0;

    for (auto xt: g[v])
    {
        if (xt==prev) continue;
        cur.push_back(dfs(xt, v, flag)+1);
    }

    sort (cur.begin(), cur.end());
    cur.resize(unique(cur.begin(), cur.end())-cur.begin());
    if ((int)cur.size()>1 && v!=c) flag=0;
    if ((int)cur.size()>2 && v==c) flag=0;
    for (auto x: cur) ret+=x;

    return ret;
}

void makePath (int v)
{
    path[v]=true;
    for (auto xt: g[v])
    {
        if (dist[xt]==dist[v]-1)
        {
            makePath(xt);
            return;
        }
    }
}

int main()
{
    scanf ("%d", &n);
    for (int i=1;i<n;i++)
    {
        int a, b;
        scanf ("%d%d", &a, &b);
        g[a].push_back(b);
        g[b].push_back(a);
    }

    dist[0]=-1;
    pair<int, int> p=findCenter(findCenter(1, 0).second, 0);
    makePath(p.second);
    for (int i=1;i<=n;i++)
    {
        if ((dist[i]==(int)p.first/2 || (p.first&1 && dist[i]==1+(int)p.first/2)) && path[i])
        {
            c=i;
            flag=true;
            int x=dfs (c, 0, flag);
            if (!flag) continue;
            possible=true;
            while (x%2==0) x>>=1;
            sol=min(sol, x);
        }
    }

    if (possible) printf ("%d", sol);
    else printf ("-1");

    return 0;
}


#include<bits/stdc++.h>

using namespace std;

const int SIZE = 200005;
typedef long long ll;

vector<int> g[SIZE];

int len = 0;
int v1 = 1;
void dfs1(int u, int d, int fa) {
    if(d >= len) {
        len = d;
        v1 = u;
    }
    for(int v: g[u]) {
        if(v == fa) continue;
        dfs1(v, d + 1, u);
    }
}

int l2 = 0;
int v2 = 1;
int pre[SIZE];
void dfs2(int u, int d, int fa) {
    pre[u] = fa;
    if(d >= l2) {
        l2 = d;
        v2 = u;
    }
    for(int v: g[u]) {
        if(v == fa) continue;
        dfs2(v, d + 1, u);
    }
}
int c;
bool dfs3(int u, int fa, int d) {
    int cnt = 0;
    bool res = true;
    for(int v: g[u]) {
        if(v == fa) continue;
        cnt++;
        res = res && dfs3(v, u, d + 1);
    }
    if(!cnt) {
        if(d!=l2/2) return false;
    }
    return res;
}

int dfs4(int u, int fa, int d) {
    bool gg = false;
    int last = -1;
    for(int v: g[u]) {
        if(v == fa) continue;
        int t = dfs4(v, u, d + 1);
        if(t == -1) return -1;
        if(last == -1) {
            last = t;
        }
        else {
            if(t != last) return -1;
        }
    }
    if(last == -1) return 1;
    //printf("u=%d res=%d\n",u,last+1);
    return last + 1;
}

int main() {
    int n;
    scanf("%d",&n);
    for(int i = 1; i < n; i++) {
        int a, b;
        scanf("%d%d",&a,&b);
        g[a].push_back(b);
        g[b].push_back(a);
    }
    dfs1(1, 0, -1);
    dfs2(v1, 0, -1);

    int t = l2 / 2;
    int d = t;
    c = v2;
    if(l2 % 2 == 1) {
        while(t--) c = pre[c];//printf("v1=%d v2=%d c=%d\n",v1,v2,c);
   // if(dfs3(c, -1, 0)) {
    //    while(d % 2 == 0) d /= 2;
   //     printf("%d\n",d);
   // }
   // else {

        set<int> S;
        int gg = 0;
        for(int u: g[c]) {
            int t = dfs4(u, c, 0);
            //printf("--------u=%d t=%d\n",u,t);
            if(t == -1) {
                gg = 1;
                break;
            }
            S.insert(t);
            if(S.size() > 2) {
                gg = 1;
                break;
            }
        }
        if(!gg)
        if(S.size() > 2) {
            gg = 1;
        }
        else if(S.size() == 1) {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        else {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        if(gg) {
            if(gg) printf("-1");
        }
        return 0;
    }
    while(t--) c = pre[c];//printf("v1=%d v2=%d c=%d\n",v1,v2,c);
   // if(dfs3(c, -1, 0)) {
    //    while(d % 2 == 0) d /= 2;
   //     printf("%d\n",d);
   // }
   // else {

        set<int> S;
        int gg = 0;
        for(int u: g[c]) {
            int t = dfs4(u, c, 0);
            //printf("--------u=%d t=%d\n",u,t);
            if(t == -1) {
                gg = 1;
                break;
            }
            S.insert(t);
            if(S.size() > 2) {
                gg = 1;
                break;
            }
        }
        if(!gg)
        if(S.size() > 2) {
            gg = 1;
        }
        else if(S.size() == 1) {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        else {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        if(gg) printf("-1\n");
   // }

}


#include<bits/stdc++.h>

using namespace std;

const int SIZE = 200005;
typedef long long ll;

vector<int> g[SIZE];

int len = 0;
int v1 = 1;
void dfs1(int u, int d, int fa) {
    if(d >= len) {
        len = d;
        v1 = u;
    }
    for(int v: g[u]) {
        if(v == fa) continue;
        dfs1(v, d + 1, u);
    }
}

int l2 = 0;
int v2 = 1;
int pre[SIZE];
void dfs2(int u, int d, int fa) {
    pre[u] = fa;
    if(d >= l2) {
        l2 = d;
        v2 = u;
    }
    for(int v: g[u]) {
        if(v == fa) continue;
        dfs2(v, d + 1, u);
    }
}
int c;
bool dfs3(int u, int fa, int d) {
    int cnt = 0;
    bool res = true;
    for(int v: g[u]) {
        if(v == fa) continue;
        cnt++;
        res = res && dfs3(v, u, d + 1);
    }
    if(!cnt) {
        if(d!=l2/2) return false;
    }
    return res;
}

int dfs4(int u, int fa, int d) {
    bool gg = false;
    int last = -1;
    for(int v: g[u]) {
        if(v == fa) continue;
        int t = dfs4(v, u, d + 1);
        if(t == -1) return -1;
        if(last == -1) {
            last = t;
        }
        else {
            if(t != last) return -1;
        }
    }
    if(last == -1) return 1;
    //printf("u=%d res=%d\n",u,last+1);
    return last + 1;
}

int main() {
    int n;
    scanf("%d",&n);
    for(int i = 1; i < n; i++) {
        int a, b;
        scanf("%d%d",&a,&b);
        g[a].push_back(b);
        g[b].push_back(a);
    }
    dfs1(1, 0, -1);
    dfs2(v1, 0, -1);

    int t = l2 / 2;
    int d = t;
    c = v2;
    if(l2 % 2 == 1) {
        while(t--) c = pre[c];//printf("v1=%d v2=%d c=%d\n",v1,v2,c);
   // if(dfs3(c, -1, 0)) {
    //    while(d % 2 == 0) d /= 2;
   //     printf("%d\n",d);
   // }
   // else {

        set<int> S;
        int gg = 0;
        for(int u: g[c]) {
            int t = dfs4(u, c, 0);
            //printf("--------u=%d t=%d\n",u,t);
            if(t == -1) {
                gg = 1;
                break;
            }
            S.insert(t);
            if(S.size() > 2) {
                gg = 1;
                break;
            }
        }
        if(!gg)
        if(S.size() > 2) {
            gg = 1;
        }
        else if(S.size() == 1) {
            while(d % 2 == 0) d /= 2;
            printf("%d\n",d);
        }
        else {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        if(gg) {
            if(gg) printf("-1");
        }
        return 0;
    }
    while(t--) c = pre[c];//printf("v1=%d v2=%d c=%d\n",v1,v2,c);
   // if(dfs3(c, -1, 0)) {
    //    while(d % 2 == 0) d /= 2;
   //     printf("%d\n",d);
   // }
   // else {

        set<int> S;
        int gg = 0;
        for(int u: g[c]) {
            int t = dfs4(u, c, 0);
            //printf("--------u=%d t=%d\n",u,t);
            if(t == -1) {
                gg = 1;
                break;
            }
            S.insert(t);
            if(S.size() > 2) {
                gg = 1;
                break;
            }
        }
        if(!gg)
        if(S.size() > 2) {
            gg = 1;
        }
        else if(S.size() == 1) {
            while(d % 2 == 0) d /= 2;
            printf("%d\n",d);
        }
        else {
            int dd = 0;
            for(int ddd: S) dd += ddd;
            //printf("dd=%d\n",dd);
            while(dd % 2 == 0) dd /= 2;
            printf("%d\n",dd);
        }
        if(gg) printf("-1\n");
   // }

}


#include<bits/stdc++.h>
#define  pb push_back
#define ins insert
#define mp make_pair

using namespace std;
vector<int> v[200005],path[200005],l,r,res;
int diameter=0,root=1,f[200005],midPoint,visited[200005];

int dfs(int node,int parent)
{
    int temp=0,pointer,length=0;
    for(int i=0;i<v[node].size();i++)
    {
        pointer=v[node][i];

        if(pointer==parent) continue;

        temp=dfs(pointer,node);

        if(node==midPoint)
        {
            if(temp==-1)
            return -1;

            else
            res.pb(temp);
        }

        else
        {
            if(length==0)
            length=temp;

            else if(length!=temp)
            return -1;
        }
    }

    return length+1;
}

void makePath1(int root)
{
    while(path[root].size()!=0)
    {
        l.pb(root);
        root=path[root][0];
    }

    l.pb(root);
}

void makePath2(int root)
{
    while(path[root].size()!=0)
    {
        r.pb(root);
        root=path[root][0];
    }

    r.pb(root);
}

void findRoot(int node,int parent)
{
    vector<pair<int,int> > fvalues;
    int i,pointer,sum=0;

    for(i=0;i<v[node].size();i++)
    {
        pointer=v[node][i];
        if(pointer==parent) continue;
        findRoot(pointer,node);
        fvalues.pb(mp(f[pointer],pointer));
    }

    f[node]=1;

    if(!fvalues.empty())
    {
        sort(fvalues.begin(),fvalues.end());

        if(fvalues.size()>=2)
        {
            sum=fvalues[fvalues.size()-1].first+ fvalues[fvalues.size()-2].first;
            path[node].pb(fvalues[fvalues.size()-1].second);
            path[node].pb(fvalues[fvalues.size()-2].second);
            f[node]=1+fvalues[fvalues.size()-1].first;
        }

        else
        {
            sum=fvalues[fvalues.size()-1].first;
            path[node].pb(fvalues[fvalues.size()-1].second);
            f[node]=1+fvalues[fvalues.size()-1].first;
        }
    }

    if(diameter!=max(diameter,1+sum))
    {
        root=node;
        diameter=1+sum;
    }
}

int main()
{
    int n,i,a,b,j,counter=0,sum=0;
    cin>>n;

    for(i=0;i<n-1;i++)
    {
        cin>>a>>b;
        v[a].pb(b);
        v[b].pb(a);
    }

    findRoot(1,1);

    if(path[root].size()==2)
    {
        makePath1(root);
        makePath2(path[root][1]);

        for(i=0;i<r.size();i++)
        l.ins(l.begin(),r[i]);
    }

    else
    makePath1(root);

    midPoint=l[l.size()/2];

    int temp=dfs(midPoint,midPoint);

    if(temp==-1)
    cout<<"-1\n";

    else
    {
        for(i=0;i<res.size();i++)
        visited[res[i]]=1;

        for(i=0;i<200006;i++)
        {
            if(visited[i]==1)
            counter++;
        }

        if(counter>2)
        cout<<"-1\n";

        else
        {
            for(i=0;i<200006;i++)
            {
                if(visited[i])
                sum=sum+i;
            }

            while(sum%2==0)
            {
                sum=sum/2;
            }

            cout<<sum<<endl;
        }

    }
}