Input:
import sys

import itertools

input_lines = sys.stdin.read().splitlines()

N, K = [int(x) for x in input_lines[0].split(' ')]

x_grid = set()

y_grid = set()

d_grid = set()

for line in input_lines[1:]:

    x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(' ')]

    x_grid.add(x1)

    x_grid.add(x2)

    y_grid.add(y1)

    y_grid.add(y2)

    d_grid.add(d1)

    d_grid.add(d2)

x_grid = sorted(x_grid)

y_grid = sorted(y_grid)

d_grid = sorted(d_grid)

x_grid_index = {x[1]:x[0] for x in enumerate(x_grid)}

y_grid_index = {y[1]:y[0] for y in enumerate(y_grid)}

d_grid_index = {d[1]:d[0] for d in enumerate(d_grid)}

fish_dist = [[[0 for i in range(len(d_grid))] for i in range(len(y_grid))] for i in range(len(x_grid))]

for line in input_lines[1:]:

    x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(' ')]

    x1_index = x_grid_index[x1]

    x2_index = x_grid_index[x2]

    y1_index = y_grid_index[y1]

    y2_index = y_grid_index[y2]

    d1_index = d_grid_index[d1]

    d2_index = d_grid_index[d2]

    for x, y, d in itertools.product( list(range(x1_index, x2_index)), list(range(y1_index, y2_index)), list(range(d1_index, d2_index)) ):

        fish_dist[x][y][d] += 1

volume = 0

for x_index, y_index, d_index in itertools.product(list(range(len(x_grid))), list(range(len(y_grid))), list(range(len(d_grid)))):

    if fish_dist[x_index][y_index][d_index] >= K:

        x_begin = x_grid[x_index]

        y_begin = y_grid[y_index]

        d_begin = d_grid[d_index]

        x_end = x_grid[x_index + 1]

        y_end = y_grid[y_index + 1]

        d_end = d_grid[d_index + 1]

        volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)

print(volume)

import itertools

def main():

    input_lines = []

    input_lines.append(eval(input()))

    N, K = [int(x) for x in input_lines[0].split(' ')]

    for i in range(N):

        input_lines.append(eval(input()))

    grid = [set() for i in range(3)]

    data = []

    for line in input_lines[1:]:

        x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(' ')]

        data.append((x1, y1, d1, x2, y2, d2))

        grid[0].add(x1)

        grid[0].add(x2)

        grid[1].add(y1)

        grid[1].add(y2)

        grid[2].add(d1)

        grid[2].add(d2)

    grid = [sorted(g) for g in grid]

    grid_index = [{x[1]:x[0] for x in enumerate(g)} for g in grid]

    grid_len = [len(g) for g in grid]

    fish_dist = [[[0 for i in range(grid_len[2])] for i in range(grid_len[1])] for i in range(grid_len[0])]

    for x1, y1, d1, x2, y2, d2 in data:

        x1_index = grid_index[0][x1]

        x2_index = grid_index[0][x2]

        y1_index = grid_index[1][y1]

        y2_index = grid_index[1][y2]

        d1_index = grid_index[2][d1]

        d2_index = grid_index[2][d2]

        for x_index, y_index, d_index in itertools.product( list(range(x1_index, x2_index)), list(range(y1_index, y2_index)), list(range(d1_index, d2_index)) ):

            fish_dist[x_index][y_index][d_index] += 1

    volume = 0

    for x_index, y_index, d_index in itertools.product(list(range(grid_len[0])), list(range(grid_len[1])), list(range(grid_len[2]))):

        if fish_dist[x_index][y_index][d_index] >= K:

            x_begin = grid[0][x_index]

            y_begin = grid[1][y_index]

            d_begin = grid[2][d_index]

            x_end = grid[0][x_index + 1]

            y_end = grid[1][y_index + 1]

            d_end = grid[2][d_index + 1]

            volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)

    print(volume)

main()

import sys
import itertools

input_lines = sys.stdin.read().splitlines()
N, K = [int(x) for x in input_lines[0].split(" ")]
x_grid = set()
y_grid = set()
d_grid = set()
for line in input_lines[1:]:
    x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(" ")]
    x_grid.add(x1)
    x_grid.add(x2)
    y_grid.add(y1)
    y_grid.add(y2)
    d_grid.add(d1)
    d_grid.add(d2)
x_grid = sorted(x_grid)
y_grid = sorted(y_grid)
d_grid = sorted(d_grid)
x_grid_index = {x[1]: x[0] for x in enumerate(x_grid)}
y_grid_index = {y[1]: y[0] for y in enumerate(y_grid)}
d_grid_index = {d[1]: d[0] for d in enumerate(d_grid)}
fish_dist = [
    [[0 for i in range(len(d_grid))] for i in range(len(y_grid))]
    for i in range(len(x_grid))
]
for line in input_lines[1:]:
    x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(" ")]
    x1_index = x_grid_index[x1]
    x2_index = x_grid_index[x2]
    y1_index = y_grid_index[y1]
    y2_index = y_grid_index[y2]
    d1_index = d_grid_index[d1]
    d2_index = d_grid_index[d2]
    for x, y, d in itertools.product(
        list(range(x1_index, x2_index)),
        list(range(y1_index, y2_index)),
        list(range(d1_index, d2_index)),
    ):
        fish_dist[x][y][d] += 1
volume = 0
for x_index, y_index, d_index in itertools.product(
    list(range(len(x_grid))), list(range(len(y_grid))), list(range(len(d_grid)))
):
    if fish_dist[x_index][y_index][d_index] >= K:
        x_begin = x_grid[x_index]
        y_begin = y_grid[y_index]
        d_begin = d_grid[d_index]
        x_end = x_grid[x_index + 1]
        y_end = y_grid[y_index + 1]
        d_end = d_grid[d_index + 1]
        volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)
print(volume)

import itertools

def main():
    input_lines = []
    input_lines.append(eval(input()))
    N, K = [int(x) for x in input_lines[0].split(" ")]
    for i in range(N):
        input_lines.append(eval(input()))
    grid = [set() for i in range(3)]
    data = []
    for line in input_lines[1:]:
        x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(" ")]
        data.append((x1, y1, d1, x2, y2, d2))
        grid[0].add(x1)
        grid[0].add(x2)
        grid[1].add(y1)
        grid[1].add(y2)
        grid[2].add(d1)
        grid[2].add(d2)
    grid = [sorted(g) for g in grid]
    grid_index = [{x[1]: x[0] for x in enumerate(g)} for g in grid]
    grid_len = [len(g) for g in grid]
    fish_dist = [
        [[0 for i in range(grid_len[2])] for i in range(grid_len[1])]
        for i in range(grid_len[0])
    ]
    for x1, y1, d1, x2, y2, d2 in data:
        x1_index = grid_index[0][x1]
        x2_index = grid_index[0][x2]
        y1_index = grid_index[1][y1]
        y2_index = grid_index[1][y2]
        d1_index = grid_index[2][d1]
        d2_index = grid_index[2][d2]
        for x_index, y_index, d_index in itertools.product(
            list(range(x1_index, x2_index)),
            list(range(y1_index, y2_index)),
            list(range(d1_index, d2_index)),
        ):
            fish_dist[x_index][y_index][d_index] += 1
    volume = 0
    for x_index, y_index, d_index in itertools.product(
        list(range(grid_len[0])), list(range(grid_len[1])), list(range(grid_len[2]))
    ):
        if fish_dist[x_index][y_index][d_index] >= K:
            x_begin = grid[0][x_index]
            y_begin = grid[1][y_index]
            d_begin = grid[2][d_index]
            x_end = grid[0][x_index + 1]
            y_end = grid[1][y_index + 1]
            d_end = grid[2][d_index + 1]
            volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)
    print(volume)

main()

-N, K = [int(x) for x in input_lines[0].split(" ")]

-    x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(" ")]

-x_grid_index = {x[1]: x[0] for x in enumerate(x_grid)}

-y_grid_index = {y[1]: y[0] for y in enumerate(y_grid)}

-d_grid_index = {d[1]: d[0] for d in enumerate(d_grid)}

-    [[0 for i in range(len(d_grid))] for i in range(len(y_grid))]

-        list(range(x1_index, x2_index)),

-        list(range(y1_index, y2_index)),

-        list(range(d1_index, d2_index)),

+    N, K = [int(x) for x in input_lines[0].split(" ")]

+        input_lines.append(eval(input()))

+        x1, y1, d1, x2, y2, d2 = [int(x) for x in line.split(" ")]

+    grid_index = [{x[1]: x[0] for x in enumerate(g)} for g in grid]

+        [[0 for i in range(grid_len[2])] for i in range(grid_len[1])]

+    for x1, y1, d1, x2, y2, d2 in data:

+        for x_index, y_index, d_index in itertools.product(

+            list(range(x1_index, x2_index)),

+            list(range(y1_index, y2_index)),

+            list(range(d1_index, d2_index)),

+            fish_dist[x_index][y_index][d_index] += 1

+        list(range(grid_len[0])), list(range(grid_len[1])), list(range(grid_len[2]))

-for x_index, y_index, d_index in itertools.product(

-    list(range(len(x_grid))), list(range(len(y_grid))), list(range(len(d_grid)))

-    if fish_dist[x_index][y_index][d_index] >= K:

-        volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)

+        if fish_dist[x_index][y_index][d_index] >= K:

+            x_end = grid[0][x_index + 1]

+            y_end = grid[1][y_index + 1]

+            d_end = grid[2][d_index + 1]

+            volume += (x_end - x_begin) * (y_end - y_begin) * (d_end - d_begin)


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

amount = 0

if x < 4:

  amount += (4-x)*100000

if y < 4:

  amount += (4-y)*100000

if x ==1 and y==1:

  amount += 400000

print(amount)

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

def f(x):

  if x==3:

    return 100000

  elif x==2:

    return 200000

  elif x== 1:

    return 300000

  else:

    return 0

ans = f(x)+f(y)

if x == y== 1:

  ans += 400000

print(ans)

x, y = list(map(int, input().split()))
amount = 0
if x < 4:
    amount += (4 - x) * 100000
if y < 4:
    amount += (4 - y) * 100000
if x == 1 and y == 1:
    amount += 400000
print(amount)

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

def f(x):
    if x == 3:
        return 100000
    elif x == 2:
        return 200000
    elif x == 1:
        return 300000
    else:
        return 0

ans = f(x) + f(y)
if x == y == 1:
    ans += 400000
print(ans)


Input:
while True:

    try:

        n = int(input())

        area = 2

        for i in range(n-1):

            area += i+2

        print(area)

    except:

        break

while True:

    try:

        n = int(input())

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

    except:

        break

while True:
    try:
        n = int(input())
        area = 2
        for i in range(n - 1):
            area += i + 2
        print(area)
    except:
        break

while True:
    try:
        n = int(input())
        print(1 + n * (n + 1) / 2)
    except:
        break

-        area = 2
-        for i in range(n - 1):
-            area += i + 2
-        print(area)
+        print(1 + n * (n + 1) / 2)


Input:
n = int(eval(input()))

p = 1

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

    p = p * i % 1000000007

print(p)

n = int(eval(input()))

def training(n):

    power = 1

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

        power = power * i % 1000000007

    return power

print((training(n)))

n = int(eval(input()))
p = 1
for i in range(1, n + 1):
    p = p * i % 1000000007
print(p)

n = int(eval(input()))

def training(n):
    power = 1
    for i in range(1, n + 1):
        power = power * i % 1000000007
    return power

print((training(n)))

-p = 1
-for i in range(1, n + 1):
-    p = p * i % 1000000007
-print(p)
+
+
+def training(n):
+    power = 1
+    for i in range(1, n + 1):
+        power = power * i % 1000000007
+    return power
+
+
+print((training(n)))


Input:
def func(lv, id):

    sz = 4 * 2 ** lv - 3

    num = 2 * 2 ** lv - 1

    mid = (sz + 1) / 2

    if lv == 0:

        return 1

    if id == 1:

        return 0

    if id == mid:

        return num / 2 + 1

    if id == sz:

        return num

    if 1 < id < mid:

        return func(lv - 1, id - 1)

    if mid < id < sz:

        return func(lv - 1, id - sz / 2 - 1) + num / 2 + 1

print(func(*list(map(int, input().split()))))

def func(lv, id):

    sz = 4 * 2 ** lv - 3

    num = 2 * 2 ** lv - 1

    mid = (sz + 1) / 2

    if id < 1 or id > sz:

        return 0

    return [0, func(lv - 1, id - 1), num / 2 + 1, func(lv - 1, id - sz / 2 - 1) + num / 2 + 1, num, 1][(id > 1) + (id >= mid) + (id > mid) + (id >= sz) + (lv == 0) * 3]

print(func(*list(map(int, input().split()))))

def func(lv, id):
    sz = 4 * 2**lv - 3
    num = 2 * 2**lv - 1
    mid = (sz + 1) / 2
    if lv == 0:
        return 1
    if id == 1:
        return 0
    if id == mid:
        return num / 2 + 1
    if id == sz:
        return num
    if 1 < id < mid:
        return func(lv - 1, id - 1)
    if mid < id < sz:
        return func(lv - 1, id - sz / 2 - 1) + num / 2 + 1

print(func(*list(map(int, input().split()))))

def func(lv, id):
    sz = 4 * 2**lv - 3
    num = 2 * 2**lv - 1
    mid = (sz + 1) / 2
    if id < 1 or id > sz:
        return 0
    return [
        0,
        func(lv - 1, id - 1),
        num / 2 + 1,
        func(lv - 1, id - sz / 2 - 1) + num / 2 + 1,
        num,
        1,
    ][(id > 1) + (id >= mid) + (id > mid) + (id >= sz) + (lv == 0) * 3]

print(func(*list(map(int, input().split()))))

-        return func(lv - 1, id - sz / 2 - 1) + num / 2 + 1


Input:
#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

class UnionFind:

    def __init__(self, size):

        self.rank=[0]*size

        self.par =[int(i) for i in range(size)]

        self.grp =size

    def find(self, x):

        if x==self.par[x]: return x

        self.par[x]=self.find(self.par[x])

        return self.par[x]

    def same(self, x, y): #2つの頂点が同じグループであるかを判定する

        return self.find(x)==self.find(y)

    def unite(self, x, y): #辺で接続されている2つの頂点を投げて統合する

        x,y=self.find(x),self.find(y)

        if x==y:

            return

        self.grp-=1

        if self.rank[x]<self.rank[y]:

            self.par[x]=y

        else:

            self.par[y]=x

            if self.rank[x]==self.rank[y]:

                self.rank[x]+=1

    def group_num(self):

        return self.grp

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

uf=UnionFind(n)

for i in range(m):

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

    uf.unite(x-1,y-1)

print((uf.grp))

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

class UnionFind:

    def __init__(self, size):

        self.rank=[0]*size

        self.par =[int(i) for i in range(size)]

        self.grp =size

    def find(self, x):

        if x==self.par[x]: return x

        self.par[x]=self.find(self.par[x])

        return self.par[x]

    def same(self, x, y):

        return self.find(x)==self.find(y)

    def unite(self, x, y):

        x,y=self.find(x),self.find(y)

        if x==y:

            return

        self.grp-=1

        if self.rank[x]<self.rank[y]:

            self.par[x]=y

        else:

            self.par[y]=x

            if self.rank[x]==self.rank[y]:

                self.rank[x]+=1

    def group_num(self):

        return self.grp

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

uf=UnionFind(n)

ans=chk=0

for i in range(m):

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

    uf.unite(x-1,y-1)

print((uf.grp))

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class UnionFind:
    def __init__(self, size):
        self.rank = [0] * size
        self.par = [int(i) for i in range(size)]
        self.grp = size

    def find(self, x):
        if x == self.par[x]:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def same(self, x, y):  # 2つの頂点が同じグループであるかを判定する
        return self.find(x) == self.find(y)

    def unite(self, x, y):  # 辺で接続されている2つの頂点を投げて統合する
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        self.grp -= 1
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def group_num(self):
        return self.grp

n, m = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(m):
    x, y, z = list(map(int, input().split()))
    uf.unite(x - 1, y - 1)
print((uf.grp))

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class UnionFind:
    def __init__(self, size):
        self.rank = [0] * size
        self.par = [int(i) for i in range(size)]
        self.grp = size

    def find(self, x):
        if x == self.par[x]:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        self.grp -= 1
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def group_num(self):
        return self.grp

n, m = list(map(int, input().split()))
uf = UnionFind(n)
ans = chk = 0
for i in range(m):
    x, y, z = list(map(int, input().split()))
    uf.unite(x - 1, y - 1)
print((uf.grp))

-    def same(self, x, y):  # 2つの頂点が同じグループであるかを判定する

-    def unite(self, x, y):  # 辺で接続されている2つの頂点を投げて統合する


Input:
import sys

input = sys.stdin.buffer.readline

MOD = 10**9 + 7

N = int(eval(input()))

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

C = [0]

for i in range(1, len(A)):

    C.append(C[-1] + A[i])

ans = 0

for i in range(1, N):

    ans += A[i] * (C[-1] - C[i])

ans %= MOD

print(ans)

import sys

input = sys.stdin.buffer.readline

from itertools import accumulate

MOD = 10**9 + 7

N = int(eval(input()))

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

C = list(accumulate(A))

ans = 0

for i in range(1, N):

    ans += A[i] * (C[-1] - C[i])

ans %= MOD

print(ans)

+from itertools import accumulate
+
-C = [0]
-for i in range(1, len(A)):
-    C.append(C[-1] + A[i])
+C = list(accumulate(A))


Input:
N=eval(input())

if N[0]=="7" or N[1]=="7" or N[2]=="7":

  print("Yes")

else:

  print("No")

s=eval(input())

if "7" in s:

  print("Yes")

else:

  print("No")

s = eval(input())
if "7" in s:
    print("Yes")
else:
    print("No")


Input:
from collections import Counter,defaultdict,deque

from heapq import heappop,heappush,heapify

import sys,bisect,math,itertools

sys.setrecursionlimit(10**8)

mod = 10**9+7

mod2 = 998244353

INF = float('inf')

def inp(): return int(sys.stdin.readline())

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

def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n,k = inpl()

a = inpln(n)

a.sort()

res = INF

for i in range(n-k+1):

    res = min(res, a[i+k-1] - a[i])

print(res)

from collections import Counter,defaultdict,deque

from heapq import heappop,heappush,heapify

import sys,bisect,math,itertools,fractions

sys.setrecursionlimit(10**8)

mod = 10**9+7

INF = float('inf')

def inp(): return int(sys.stdin.readline())

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

n,k = inpl()

a = [inp() for _ in range(n)]

a.sort()

res = INF

for i in range(n-k+1):

    res = min(res, a[i+k-1] - a[i])

print(res)

from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools

sys.setrecursionlimit(10**8)
mod = 10**9 + 7
mod2 = 998244353
INF = float("inf")

def inp():
    return int(sys.stdin.readline())

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

def inpln(n):
    return list(int(sys.stdin.readline()) for i in range(n))

n, k = inpl()
a = inpln(n)
a.sort()
res = INF
for i in range(n - k + 1):
    res = min(res, a[i + k - 1] - a[i])
print(res)

from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools, fractions

sys.setrecursionlimit(10**8)
mod = 10**9 + 7
INF = float("inf")

def inp():
    return int(sys.stdin.readline())

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

n, k = inpl()
a = [inp() for _ in range(n)]
a.sort()
res = INF
for i in range(n - k + 1):
    res = min(res, a[i + k - 1] - a[i])
print(res)

+import sys, bisect, math, itertools, fractions

-    return list(int(sys.stdin.readline()) for i in range(n))


Input:
n = int(eval(input()))

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

v = sorted(v)

p = v[0]

for i in range(1, n):

  p = (v[i] + p)/2

print(p)

n = int(eval(input()))

v = sorted(list(map(int, input().split())))

ans = v[0]

for i in range(1,n):

  ans = (ans + v[i])/2

print(ans)

n = int(eval(input()))
v = list(map(int, input().split()))
v = sorted(v)
p = v[0]
for i in range(1, n):
    p = (v[i] + p) / 2
print(p)

n = int(eval(input()))
v = sorted(list(map(int, input().split())))
ans = v[0]
for i in range(1, n):
    ans = (ans + v[i]) / 2
print(ans)

+v = sorted(list(map(int, input().split())))


Input:
s = list(str(eval(input())))

for i in range(2**3):

    t = ['']

    ans = int(s[0])

    for j in range(3):

        if (i >> j) & 1:

            t.append('+')

            ans += int(s[j+1])

        else:

            t.append('-')

            ans -= int(s[j+1])

    if ans == 7:

        siki = ''

        for i in range(4):

            siki += t[i]+s[i]

        siki += '=7'

        print(siki)

        exit()

s = list(str(eval(input())))

import itertools

for p in itertools.product(('+', '-'), repeat=3):

    temp = [0]*7

    for i in range(4):

        temp[2*i] = s[i]

    for i in range(3):

        temp[2*i+1] = p[i]

    #print(temp)

    temp = ''.join(temp)

    if eval(temp) == 7:

        print((temp+'=7'))

        exit()

s = list(str(eval(input())))
for i in range(2**3):
    t = [""]
    ans = int(s[0])
    for j in range(3):
        if (i >> j) & 1:
            t.append("+")
            ans += int(s[j + 1])
        else:
            t.append("-")
            ans -= int(s[j + 1])
    if ans == 7:
        siki = ""
        for i in range(4):
            siki += t[i] + s[i]
        siki += "=7"
        print(siki)
        exit()

s = list(str(eval(input())))
import itertools

for p in itertools.product(("+", "-"), repeat=3):
    temp = [0] * 7
    for i in range(4):
        temp[2 * i] = s[i]
    for i in range(3):
        temp[2 * i + 1] = p[i]
    # print(temp)
    temp = "".join(temp)
    if eval(temp) == 7:
        print((temp + "=7"))
        exit()

+for p in itertools.product(("+", "-"), repeat=3):


Input:
N,M,V,P = list(map(int,input().split()))

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

B = A[:N-P+1]

S = [0]

for i in range(N-P+1):

    S.append(S[-1]+B[i])

ans = P-1

for i in range(N-P+1):

    if B[i]+M-B[-1]<0:

        continue

    if B[i]*(N-P-i)-(S[-1]-S[i+1])+M*(N-P)>=max(M*(V-P),0):

        ans += 1

print(ans)

N,M,V,P = list(map(int,input().split()))

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

S = [0]

for i in range(N-P+1):

    S += [S[-1]+A[i]]

a = P-1

for i in range(N-P+1):

    if A[i]+M>=A[N-P] and A[i]*(N-P-i)-(S[-1]-S[i+1])>=M*(V-N):

        a += 1

print(a)

N, M, V, P = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
B = A[: N - P + 1]
S = [0]
for i in range(N - P + 1):
    S.append(S[-1] + B[i])
ans = P - 1
for i in range(N - P + 1):
    if B[i] + M - B[-1] < 0:
        continue
    if B[i] * (N - P - i) - (S[-1] - S[i + 1]) + M * (N - P) >= max(M * (V - P), 0):
        ans += 1
print(ans)

N, M, V, P = list(map(int, input().split()))
A = sorted(list(map(int, input().split())))
S = [0]
for i in range(N - P + 1):
    S += [S[-1] + A[i]]
a = P - 1
for i in range(N - P + 1):
    if A[i] + M >= A[N - P] and A[i] * (N - P - i) - (S[-1] - S[i + 1]) >= M * (V - N):
        a += 1
print(a)


Input:
# AOJ 1126: The Secret Number

# Python3 2018.7.16 bal4u

while True:

	W, H = list(map(int, input().split()))

	if W == 0: break

	d = [list(eval(input())) for r in range(H)]

	a = [[0 for c in range(W)] for r in range(H)]

	ans = 0

	for r in range(H):

		for c in range(W):

			if not d[r][c].isdigit(): continue

			a[r][c] = k = int(d[r][c])

			if c > 0 and d[r][c-1].isdigit():

				a[r][c] = a[r][c-1]*10 + k

			if r > 0 and d[r-1][c].isdigit():

				t = a[r-1][c]*10 + k

				a[r][c] = max(a[r][c], t)

			ans = max(ans, a[r][c])

	print(ans);

# AOJ 1126: The Secret Number

# Python3 2018.7.16 bal4u

while True:

	W, H = list(map(int, input().split()))

	if W == 0: break

	d = [list(eval(input())) for r in range(H)]

	a = [[0 for c in range(W)] for r in range(H)]

	ans = 0

	for r in range(H):

		for c in range(W):

			if d[r][c] >= '0' and d[r][c] <= '9':

				k = int(d[r][c])

				k1 = k2 = 0

				if c > 0: k1 = a[r][c-1]*10 + k

				if r > 0: k2 = a[r-1][c]*10 + k

				a[r][c] = max(k, k1, k2)

				ans = max(ans, a[r][c])

	print(ans);

# AOJ 1126: The Secret Number
# Python3 2018.7.16 bal4u
while True:
    W, H = list(map(int, input().split()))
    if W == 0:
        break
    d = [list(eval(input())) for r in range(H)]
    a = [[0 for c in range(W)] for r in range(H)]
    ans = 0
    for r in range(H):
        for c in range(W):
            if not d[r][c].isdigit():
                continue
            a[r][c] = k = int(d[r][c])
            if c > 0 and d[r][c - 1].isdigit():
                a[r][c] = a[r][c - 1] * 10 + k
            if r > 0 and d[r - 1][c].isdigit():
                t = a[r - 1][c] * 10 + k
                a[r][c] = max(a[r][c], t)
            ans = max(ans, a[r][c])
    print(ans)

# AOJ 1126: The Secret Number
# Python3 2018.7.16 bal4u
while True:
    W, H = list(map(int, input().split()))
    if W == 0:
        break
    d = [list(eval(input())) for r in range(H)]
    a = [[0 for c in range(W)] for r in range(H)]
    ans = 0
    for r in range(H):
        for c in range(W):
            if d[r][c] >= "0" and d[r][c] <= "9":
                k = int(d[r][c])
                k1 = k2 = 0
                if c > 0:
                    k1 = a[r][c - 1] * 10 + k
                if r > 0:
                    k2 = a[r - 1][c] * 10 + k
                a[r][c] = max(k, k1, k2)
                ans = max(ans, a[r][c])
    print(ans)

-            if c > 0 and d[r][c - 1].isdigit():

-            if r > 0 and d[r - 1][c].isdigit():

+                ans = max(ans, a[r][c])


Input:
import sys

import itertools

# import numpy as np

import time

import math

import heapq

from collections import defaultdict

sys.setrecursionlimit(10 ** 7)

INF = 10 ** 18

MOD = 10 ** 9 + 7

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N, K = list(map(int, input().split()))

D = input().split()

for n in range(N, 100000):

    s = str(n)

    ok = True

    for c in s:

        if c in D:

            ok = False

    if ok:

        print(n)

        break

N, K = list(map(int, input().split()))

D = set(input().split())

for n in range(N, N * 10 + 1):

    ok = True

    for c in str(n):

        if c in D:

            ok = False

    if ok:

        print(n)

        break

import sys
import itertools

# import numpy as np
import time
import math
import heapq
from collections import defaultdict

sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
N, K = list(map(int, input().split()))
D = input().split()
for n in range(N, 100000):
    s = str(n)
    ok = True
    for c in s:
        if c in D:
            ok = False
    if ok:
        print(n)
        break

-import sys
-import itertools
-# import numpy as np
-import time
-import math
-import heapq
-from collections import defaultdict
-sys.setrecursionlimit(10**7)
-INF = 10**18
-MOD = 10**9 + 7
-read = sys.stdin.buffer.read
-readline = sys.stdin.buffer.readline
-readlines = sys.stdin.buffer.readlines
-# map(int, input().split())
-D = input().split()
-for n in range(N, 100000):
-    s = str(n)
+D = set(input().split())
+for n in range(N, N * 10 + 1):
-    for c in s:
+    for c in str(n):


Input:
from itertools import accumulate

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

s = eval(input())

a = []

i = 0

cnt = 0

now = s[0]

while i < n:

    if s[i] == now:

        cnt += 1

    else:

        a.append(cnt)

        now = s[i]

        cnt = 1

    if i == n-1:

        a.append(cnt)

    i += 1

if len(a) == 1 and s[0] == '1':

    print(n)

    exit()

if s[0] == '0':

    a = [0] + a

if s[-1] == '0':

    a.append(0)

r = list(accumulate(a))

lr = len(r)

ans = -float('inf')

kk = 2*k+1

for i in range(k*2, lr+1 , 2):

    if i == k*2:

        ans = max(ans, r[i])

    else:

        ans = max(ans, r[i] - r[i-kk])

if ans == -float('inf'):

    print(n)

    exit()

print(ans)

from itertools import accumulate

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

s = eval(input())

a = []

cnt = 0

now = s[0]

for ss in s:

    if ss == now:

        cnt += 1

    else:

        a.append(cnt)

        cnt = 1

        now = ss

a.append(cnt)

a = [0]*(1-int(s[0])) + a + [0]*(1-int(s[-1]))

la = len(a)

kk = 2*k+1

if la == 1 or la <= kk:

    print(n)

    exit()

ac = [0] + list(accumulate(a))

ans = -float('inf')

for i in range(kk, la+1, 2):

    ans = max(ans, ac[i] - ac[i-kk])

print(ans)

from itertools import accumulate

n, k = list(map(int, input().split()))
s = eval(input())
a = []
i = 0
cnt = 0
now = s[0]
while i < n:
    if s[i] == now:
        cnt += 1
    else:
        a.append(cnt)
        now = s[i]
        cnt = 1
    if i == n - 1:
        a.append(cnt)
    i += 1
if len(a) == 1 and s[0] == "1":
    print(n)
    exit()
if s[0] == "0":
    a = [0] + a
if s[-1] == "0":
    a.append(0)
r = list(accumulate(a))
lr = len(r)
ans = -float("inf")
kk = 2 * k + 1
for i in range(k * 2, lr + 1, 2):
    if i == k * 2:
        ans = max(ans, r[i])
    else:
        ans = max(ans, r[i] - r[i - kk])
if ans == -float("inf"):
    print(n)
    exit()
print(ans)

from itertools import accumulate

n, k = list(map(int, input().split()))
s = eval(input())
a = []
cnt = 0
now = s[0]
for ss in s:
    if ss == now:
        cnt += 1
    else:
        a.append(cnt)
        cnt = 1
        now = ss
a.append(cnt)
a = [0] * (1 - int(s[0])) + a + [0] * (1 - int(s[-1]))
la = len(a)
kk = 2 * k + 1
if la == 1 or la <= kk:
    print(n)
    exit()
ac = [0] + list(accumulate(a))
ans = -float("inf")
for i in range(kk, la + 1, 2):
    ans = max(ans, ac[i] - ac[i - kk])
print(ans)

-        ans = max(ans, r[i] - r[i - kk])


Input:
n,t=list(map(int,input().split()));c=[]

for i in range(n):

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

  if b<=t:

    c.append(a)

if c==[]:print("TLE")

else:c.sort();print((c[0]))

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

ans=10**9

for i in range(n):

  c,tt=list(map(int,input().split()))

  if tt<=t:ans=min(ans,c)

if ans==10**9:print("TLE")

else:print(ans)

n, t = list(map(int, input().split()))
c = []
for i in range(n):
    a, b = list(map(int, input().split()))
    if b <= t:
        c.append(a)
if c == []:
    print("TLE")
else:
    c.sort()
    print((c[0]))

n, t = list(map(int, input().split()))
ans = 10**9
for i in range(n):
    c, tt = list(map(int, input().split()))
    if tt <= t:
        ans = min(ans, c)
if ans == 10**9:
    print("TLE")
else:
    print(ans)

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

+    c, tt = list(map(int, input().split()))


Input:
n = int(eval(input()))

a = {}

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

    a[i] = []

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

for i in member:

    a[i].append(1)

for j in a:

    print((len(a[j])))

n = int(input())

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

member = [0] * n

for i in a:

    member[i-1] += 1

print(*member, sep='\n')

n = int(eval(input()))
a = {}
for i in range(1, n + 1):
    a[i] = []
member = list(map(int, input().split()))
for i in member:
    a[i].append(1)
for j in a:
    print((len(a[j])))

n = int(input())
a = list(map(int, input().split()))
member = [0] * n
for i in a:
    member[i - 1] += 1
print(*member, sep="\n")

-member = list(map(int, input().split()))


Input:
h, w, n = list(map(int, input().split()))

xy = sorted([list(map(int, input().split())) for _ in range(n)])

dx = 0

dy = 0

for x, y in xy:

  x -= dx

  y -= dy

  if x == y:

    dx += x-1

    dy += y-2

  elif y < x:

    print((dx+x-1))

    break

else:

  print(h)

import sys

input = sys.stdin.readline

def main():

  h, w, n = list(map(int, input().split()))

  xy = sorted([list(map(int, input().split())) for _ in range(n)])

  dx = 0

  dy = 0

  for x, y in xy:

    x -= dx

    y -= dy

    if x == y:

      dx += x-1

      dy += y-2

    elif y < x:

      print((dx+x-1))

      break

  else:

    print(h)

if __name__ == "__main__":

  main()

import sys

input = sys.stdin.readline

def main():
    h, w, n = list(map(int, input().split()))
    xy = sorted([list(map(int, input().split())) for _ in range(n)])
    dx = 0
    dy = 0
    for x, y in xy:
        x -= dx
        y -= dy
        if x == y:
            dx += x - 1
            dy += y - 2
        elif y < x:
            print((dx + x - 1))
            break
    else:
        print(h)

if __name__ == "__main__":
    main()

-h, w, n = list(map(int, input().split()))

-xy = sorted([list(map(int, input().split())) for _ in range(n)])

+    h, w, n = list(map(int, input().split()))

+    xy = sorted([list(map(int, input().split())) for _ in range(n)])


Input:
import numpy as np

N, M = list(map(int, input().split()))

P = []

Y = []

for _ in range(M):

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

    P.append(p)

    Y.append(y)

P = np.array(P)

Y = np.array(Y)

PY = np.c_[P, Y]

sort_ind = np.argsort(Y)

PY_sort = PY[sort_ind]

count = [0] * (int(1e+5) + 1)

id_list = []

for p, y in PY_sort:

    count[p] += 1

    id_list.append(str(p).zfill(6) + str(count[p]).zfill(6))

id_list = np.array(id_list)

id_list = id_list[np.argsort(sort_ind)]

for city_id in id_list:

    print(city_id)

import bisect

N, M = list(map(int, input().split()))

P, Y = [], []

pref = [[] for _ in range(N+1)] # non-0-indexed

for m in range(M):

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

    P.append(p)

    Y.append(y)

    pref[p].append(y)

for i, p in enumerate(pref):

    pref[i] = sorted(p)

for p,y in zip(P,Y):

    ans = "{:0>6}".format(p)

    i = bisect.bisect(pref[p], y)

    ans += "{:0>6}".format(i)

    print(ans)

import numpy as np

N, M = list(map(int, input().split()))
P = []
Y = []
for _ in range(M):
    p, y = list(map(int, input().split()))
    P.append(p)
    Y.append(y)
P = np.array(P)
Y = np.array(Y)
PY = np.c_[P, Y]
sort_ind = np.argsort(Y)
PY_sort = PY[sort_ind]
count = [0] * (int(1e5) + 1)
id_list = []
for p, y in PY_sort:
    count[p] += 1
    id_list.append(str(p).zfill(6) + str(count[p]).zfill(6))
id_list = np.array(id_list)
id_list = id_list[np.argsort(sort_ind)]
for city_id in id_list:
    print(city_id)

import bisect

N, M = list(map(int, input().split()))
P, Y = [], []
pref = [[] for _ in range(N + 1)]  # non-0-indexed
for m in range(M):
    p, y = list(map(int, input().split()))
    P.append(p)
    Y.append(y)
    pref[p].append(y)
for i, p in enumerate(pref):
    pref[i] = sorted(p)
for p, y in zip(P, Y):
    ans = "{:0>6}".format(p)
    i = bisect.bisect(pref[p], y)
    ans += "{:0>6}".format(i)
    print(ans)

+pref = [[] for _ in range(N + 1)]  # non-0-indexed

-    id_list.append(str(p).zfill(6) + str(count[p]).zfill(6))


Input:
n = int(eval(input()))

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

dp = [0 for i in range(n)]

for i in range(n):

    if i==0:

        dp[i] = 0

    elif i==1:

        dp[i] = abs(h[i]-h[i-1])

    else:

        dp[i] = min(dp[i-1]+abs(h[i]-h[i-1]), dp[i-2]+abs(h[i]-h[i-2]))

print((dp[n-1]))

N = int(eval(input()))

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

H = [0] + H

dp = [0] * (N+1)

for i in range(2,N+1):

    if i-2>=1:

        dp[i] = min(dp[i-1]+abs(H[i]-H[i-1]), dp[i-2]+abs(H[i]-H[i-2]))

    else:

        dp[i] = dp[i] + abs(H[i]-H[i-1])

res = dp[N]

print(res)

n = int(eval(input()))
h = [int(i) for i in input().split()]
dp = [0 for i in range(n)]
for i in range(n):
    if i == 0:
        dp[i] = 0
    elif i == 1:
        dp[i] = abs(h[i] - h[i - 1])
    else:
        dp[i] = min(dp[i - 1] + abs(h[i] - h[i - 1]), dp[i - 2] + abs(h[i] - h[i - 2]))
print((dp[n - 1]))

N = int(eval(input()))
H = list(map(int, input().split()))
H = [0] + H
dp = [0] * (N + 1)
for i in range(2, N + 1):
    if i - 2 >= 1:
        dp[i] = min(dp[i - 1] + abs(H[i] - H[i - 1]), dp[i - 2] + abs(H[i] - H[i - 2]))
    else:
        dp[i] = dp[i] + abs(H[i] - H[i - 1])
res = dp[N]
print(res)


Input:
import sys

def main() -> None:

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

    a = [0] * n

    b = [0] * n

    ans = 0

    for i in range(n):

        a[i], b[i] = list(map(int, sys.stdin.readline().split()))

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

        a[i] += ans

        if a[i] % b[i] != 0:

            ans += abs(a[i] % b[i] - b[i])

    print(ans)

if __name__ == '__main__':

    main()

import sys

def main() -> None:

    n = int(eval(input()))

    a = [0] * n

    b = [0] * n

    ans = 0

    for i in range(n):

        a[i], b[i] = list(map(int, sys.stdin.readline().split()))

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

        a[i] += ans

        if a[i] % b[i] != 0:

            ans += abs(a[i] % b[i] - b[i])

    print(ans)

if __name__ == '__main__':

    main()

import sys

def main() -> None:
    n = int(sys.stdin.readline())
    a = [0] * n
    b = [0] * n
    ans = 0
    for i in range(n):
        a[i], b[i] = list(map(int, sys.stdin.readline().split()))
    for i in range(n - 1, -1, -1):
        a[i] += ans
        if a[i] % b[i] != 0:
            ans += abs(a[i] % b[i] - b[i])
    print(ans)

if __name__ == "__main__":
    main()

import sys

def main() -> None:
    n = int(eval(input()))
    a = [0] * n
    b = [0] * n
    ans = 0
    for i in range(n):
        a[i], b[i] = list(map(int, sys.stdin.readline().split()))
    for i in range(n - 1, -1, -1):
        a[i] += ans
        if a[i] % b[i] != 0:
            ans += abs(a[i] % b[i] - b[i])
    print(ans)

if __name__ == "__main__":
    main()

-    n = int(sys.stdin.readline())
+    n = int(eval(input()))


Input:
from collections import deque

N,M,*L,S,T = list(map(int,open(0).read().split()))

G = [[] for _ in range(N)]

step = [[-1]*3 for _ in range(N)]

step[S-1][0] = 0

for u,v in zip(*[iter(L)]*2):

	G[u-1].append(v-1)

q = deque([(S-1,0)])

while q:

	cur,d = q.popleft()

	for nxt in G[cur]:

		if nxt==T-1 and (d+1)%3==0:

			print(((d+1)//3))

			exit()

		if step[nxt][(d+1)%3] < 0:

			step[nxt][(d+1)%3] = d+1

			q.append((nxt,d+1))

print((-1))

from collections import deque

N,M,*L,S,T = list(map(int,open(0).read().split()))

G = [[] for _ in range(N)]

step = [False for _ in range(3*N)]

step[(S-1)*3] = 0

for u,v in zip(*[iter(L)]*2):

	G[u-1].append(v-1)

q = deque([(S-1,0)])

while q:

	cur,d = q.popleft()

	for nxt in G[cur]:

		if nxt==T-1 and (d+1)%3==0:

			print(((d+1)//3))

			exit()

		if not step[nxt*3+(d+1)%3]:

			step[nxt*3+(d+1)%3] = True

			q.append((nxt,d+1))

print((-1))

from collections import deque

N, M, *L, S, T = list(map(int, open(0).read().split()))
G = [[] for _ in range(N)]
step = [[-1] * 3 for _ in range(N)]
step[S - 1][0] = 0
for u, v in zip(*[iter(L)] * 2):
    G[u - 1].append(v - 1)
q = deque([(S - 1, 0)])
while q:
    cur, d = q.popleft()
    for nxt in G[cur]:
        if nxt == T - 1 and (d + 1) % 3 == 0:
            print(((d + 1) // 3))
            exit()
        if step[nxt][(d + 1) % 3] < 0:
            step[nxt][(d + 1) % 3] = d + 1
            q.append((nxt, d + 1))
print((-1))

from collections import deque

N, M, *L, S, T = list(map(int, open(0).read().split()))
G = [[] for _ in range(N)]
step = [False for _ in range(3 * N)]
step[(S - 1) * 3] = 0
for u, v in zip(*[iter(L)] * 2):
    G[u - 1].append(v - 1)
q = deque([(S - 1, 0)])
while q:
    cur, d = q.popleft()
    for nxt in G[cur]:
        if nxt == T - 1 and (d + 1) % 3 == 0:
            print(((d + 1) // 3))
            exit()
        if not step[nxt * 3 + (d + 1) % 3]:
            step[nxt * 3 + (d + 1) % 3] = True
            q.append((nxt, d + 1))
print((-1))

+        if not step[nxt * 3 + (d + 1) % 3]:


Input:
import numpy as np

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

if N == 0:

    print(X)

else:

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

    app = [x for x in range(X - int(N / 2) - 1, X + int(N / 2) + 1) if x not in l]

    print((app[np.argmin([abs(x - X) for x in app])]))

#cited from ppunchi

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

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

l = X - 1

r = X + 1

if not X in p:

    print(X)

    exit()

while True:

    if not l in p:

        print(l)

        break

    elif not r in p:

        print(r)

        break

    l -= 1

    r += 1

# cited from ppunchi
X, N = list(map(int, input().split()))
p = list(map(int, input().split()))
l = X - 1
r = X + 1
if not X in p:
    print(X)
    exit()
while True:
    if not l in p:
        print(l)
        break
    elif not r in p:
        print(r)
        break
    l -= 1
    r += 1

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

-    app = [x for x in range(X - int(N / 2) - 1, X + int(N / 2) + 1) if x not in l]

-    print((app[np.argmin([abs(x - X) for x in app])]))


Input:
import collections

N=int(eval(input()))

s=[str(sorted(eval(input()))) for i in range(N)]

c=collections.Counter(s)

print((sum((v*(v-1))//2 for v in list(c.values()))))

N=int(eval(input()))

dictionary={}

count=0

for i in range(N):

    s=tuple(sorted(eval(input())))

    if s in dictionary:

        dictionary[s]+=1

        count+=dictionary[s]

    else:

        dictionary[s]=0

print(count)

import collections

N = int(eval(input()))
s = [str(sorted(eval(input()))) for i in range(N)]
c = collections.Counter(s)
print((sum((v * (v - 1)) // 2 for v in list(c.values()))))

N = int(eval(input()))
dictionary = {}
count = 0
for i in range(N):
    s = tuple(sorted(eval(input())))
    if s in dictionary:
        dictionary[s] += 1
        count += dictionary[s]
    else:
        dictionary[s] = 0
print(count)

-s = [str(sorted(eval(input()))) for i in range(N)]

-print((sum((v * (v - 1)) // 2 for v in list(c.values()))))


Input:
import math

n = int(eval(input()))

s = eval(input())

ans=0

for i in range(n):

    #print(i,n)

    maxim = i

    num=[0 for k in range(n-i)]

    count=0

    lmax=0

    for j in range(n-i):

        if(s[j]==s[i+j]):

            num[j]=1

            count+=1

            #print(count)

            if(lmax<count):

                lmax=count

        else:

            count=0

    #print(lmax)

    if(ans<lmax):

        ans=min(lmax,maxim)

print(ans)

n = int(eval(input()))

s = eval(input())

ans = 0

for i in range(1,n):

    chain = 0

    for j in range(n-i):

        if(s[j]==s[i+j]):

            chain+=1

            if(ans<chain):

                ans = min(chain,i)

                #print(ans,i,j)

        else:

            chain=0

print(ans)

import math

n = int(eval(input()))
s = eval(input())
ans = 0
for i in range(n):
    # print(i,n)
    maxim = i
    num = [0 for k in range(n - i)]
    count = 0
    lmax = 0
    for j in range(n - i):
        if s[j] == s[i + j]:
            num[j] = 1
            count += 1
            # print(count)
            if lmax < count:
                lmax = count
        else:
            count = 0
    # print(lmax)
    if ans < lmax:
        ans = min(lmax, maxim)
print(ans)

n = int(eval(input()))
s = eval(input())
ans = 0
for i in range(1, n):
    chain = 0
    for j in range(n - i):
        if s[j] == s[i + j]:
            chain += 1
            if ans < chain:
                ans = min(chain, i)
                # print(ans,i,j)
        else:
            chain = 0
print(ans)

-import math
-for i in range(n):
-    # print(i,n)
-    maxim = i
-    num = [0 for k in range(n - i)]
-    count = 0
-    lmax = 0
+for i in range(1, n):
+    chain = 0
-            num[j] = 1
-            count += 1
-            # print(count)
-            if lmax < count:
-                lmax = count
+            chain += 1
+            if ans < chain:
+                ans = min(chain, i)
+                # print(ans,i,j)
-            count = 0
-    # print(lmax)
-    if ans < lmax:
-        ans = min(lmax, maxim)
+            chain = 0


Input:
from collections import deque

N, M = list(map(int, input().split()))

g = {i:set() for i in range(N)}

v = [-1 for i in range(N)]

for _ in range(M):

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

  a, b = a-1, b-1

  g[a].add(b)

  g[b].add(a)

Q = deque()

ans = 0

for a in g:

  if v[a]==-1:

    v[a] = 1

    ans_tmp = 1

    Q.append(a)

    while len(Q)>0:

      na = Q.popleft()

      for nb in g[na]:

        if v[nb] == -1:

          v[nb] = 1

          ans_tmp += 1

          Q.append(nb)

    ans = max(ans, ans_tmp)

print(ans)

N, M = list(map(int, input().split()))

r = [i for i in range(N+1)]

n = [0 for i in range(N+1)]

buf = []

def root(x):

  if x==r[x]:

    return x

  else:

    r[x] = root(r[x])

    return r[x]

def unite(x, y):

  rx = root(x)

  ry = root(y)

  if rx < ry:

    r[ry] = rx

  elif rx > ry:

    r[rx] = ry

for _ in range(M):

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

  unite(a, b)

for x in range(1, N+1):

  if r[x] != x and r[r[x]] != r[x]:

    _ = root(x)

for x in r[1:]:

  n[x] += 1

ans = max(n[1:])

print(ans)

from collections import deque

N, M = list(map(int, input().split()))
g = {i: set() for i in range(N)}
v = [-1 for i in range(N)]
for _ in range(M):
    a, b = list(map(int, input().split()))
    a, b = a - 1, b - 1
    g[a].add(b)
    g[b].add(a)
Q = deque()
ans = 0
for a in g:
    if v[a] == -1:
        v[a] = 1
        ans_tmp = 1
        Q.append(a)
        while len(Q) > 0:
            na = Q.popleft()
            for nb in g[na]:
                if v[nb] == -1:
                    v[nb] = 1
                    ans_tmp += 1
                    Q.append(nb)
        ans = max(ans, ans_tmp)
print(ans)

N, M = list(map(int, input().split()))
r = [i for i in range(N + 1)]
n = [0 for i in range(N + 1)]
buf = []

def root(x):
    if x == r[x]:
        return x
    else:
        r[x] = root(r[x])
        return r[x]

def unite(x, y):
    rx = root(x)
    ry = root(y)
    if rx < ry:
        r[ry] = rx
    elif rx > ry:
        r[rx] = ry

for _ in range(M):
    a, b = list(map(int, input().split()))
    unite(a, b)
for x in range(1, N + 1):
    if r[x] != x and r[r[x]] != r[x]:
        _ = root(x)
for x in r[1:]:
    n[x] += 1
ans = max(n[1:])
print(ans)

-from collections import deque
+N, M = list(map(int, input().split()))
+r = [i for i in range(N + 1)]
+n = [0 for i in range(N + 1)]
+buf = []
-N, M = list(map(int, input().split()))
-g = {i: set() for i in range(N)}
-v = [-1 for i in range(N)]
+
+def root(x):
+    if x == r[x]:
+        return x
+    else:
+        r[x] = root(r[x])
+        return r[x]
+
+
+def unite(x, y):
+    rx = root(x)
+    ry = root(y)
+    if rx < ry:
+        r[ry] = rx
+    elif rx > ry:
+        r[rx] = ry
+
+
-    a, b = a - 1, b - 1
-    g[a].add(b)
-    g[b].add(a)
-Q = deque()
-ans = 0
-for a in g:
-    if v[a] == -1:
-        v[a] = 1
-        ans_tmp = 1
-        Q.append(a)
-        while len(Q) > 0:
-            na = Q.popleft()
-            for nb in g[na]:
-                if v[nb] == -1:
-                    v[nb] = 1
-                    ans_tmp += 1
-                    Q.append(nb)
-        ans = max(ans, ans_tmp)
+    unite(a, b)
+for x in range(1, N + 1):
+    if r[x] != x and r[r[x]] != r[x]:
+        _ = root(x)
+for x in r[1:]:
+    n[x] += 1
+ans = max(n[1:])


Input:
for e in iter(input,'0'):

 R=[set()for _ in[0]*-~int(e)]

 for _ in[0]*int(eval(input())):

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

  R[a]|={b}

  if a-1:R[b]|={a}

 for m in set(R[1]):

  R[1]|=R[m]

 print((len(R[1])))

for e in iter(input,'0'):

 R=[[]for _ in[0]*-~int(e)]

 for _ in[0]*int(eval(input())):

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

  R[a]+=[b];R[b]+=[a]

 for m in R[1][:]:R[1]+=R[m]

 print((len({*R[1]}-{1})))

for e in iter(input, "0"):
    R = [set() for _ in [0] * -~int(e)]
    for _ in [0] * int(eval(input())):
        a, b = list(map(int, input().split()))
        R[a] |= {b}
        if a - 1:
            R[b] |= {a}
    for m in set(R[1]):
        R[1] |= R[m]
    print((len(R[1])))

for e in iter(input, "0"):
    R = [[] for _ in [0] * -~int(e)]
    for _ in [0] * int(eval(input())):
        a, b = list(map(int, input().split()))
        R[a] += [b]
        R[b] += [a]
    for m in R[1][:]:
        R[1] += R[m]
    print((len({*R[1]} - {1})))


Input:
from decimal import Decimal

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

if(Decimal(a).sqrt()+Decimal(b).sqrt()<Decimal(c).sqrt()):

    print("Yes")

else:

    print("No")

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

print(("Yes" if 4*a*b<(c-a-b)**2 and c-a-b>0 else "No"))

from decimal import Decimal

a, b, c = list(map(int, input().split()))
if Decimal(a).sqrt() + Decimal(b).sqrt() < Decimal(c).sqrt():
    print("Yes")
else:
    print("No")

a, b, c = list(map(int, input().split()))
print(("Yes" if 4 * a * b < (c - a - b) ** 2 and c - a - b > 0 else "No"))

-if Decimal(a).sqrt() + Decimal(b).sqrt() < Decimal(c).sqrt():

+print(("Yes" if 4 * a * b < (c - a - b) ** 2 and c - a - b > 0 else "No"))


Input:
N=int(eval(input()))

S=eval(input())

tmp=0

w=[]

for s in S:

  if s=='W': tmp+=1

  w.append(tmp)

tmp=0

e=[]

for s in S[::-1]:

  if s=='E': tmp+=1

  e.append(tmp)

e=e[::-1]

ans=[]

for i in range(N):

  ans.append(w[i]+e[i]-1)

print((min(ans)))

N=int(eval(input()))

S=eval(input())

def cumsum_arr(s, w):

  arr=[]

  cnt=0

  for s_ in s:

    if s_==w: cnt+=1

    arr.append(cnt)

  return arr

w=cumsum_arr(S,      'W')

e=cumsum_arr(S[::-1],'E')

e=e[::-1]

ans=[w[i]+e[i]-1 for i in range(N)]

print((min(ans)))

N = int(eval(input()))
S = eval(input())
tmp = 0
w = []
for s in S:
    if s == "W":
        tmp += 1
    w.append(tmp)
tmp = 0
e = []
for s in S[::-1]:
    if s == "E":
        tmp += 1
    e.append(tmp)
e = e[::-1]
ans = []
for i in range(N):
    ans.append(w[i] + e[i] - 1)
print((min(ans)))

N = int(eval(input()))
S = eval(input())

def cumsum_arr(s, w):
    arr = []
    cnt = 0
    for s_ in s:
        if s_ == w:
            cnt += 1
        arr.append(cnt)
    return arr

w = cumsum_arr(S, "W")
e = cumsum_arr(S[::-1], "E")
e = e[::-1]
ans = [w[i] + e[i] - 1 for i in range(N)]
print((min(ans)))

+ans = [w[i] + e[i] - 1 for i in range(N)]


Input:
import math

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

sum_all = 0

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

    sum_n = 0

    m = i

    while(m > 0):

        sum_n += math.floor(m % 10)

        m /= 10

    if a <= sum_n <= b:

        sum_all += i

print(sum_all)

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

sum_all = 0

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

    m = str(i)

    sum_m = 0

    for j in range(len(m)):

        sum_m += int(m[j])

    if a <= sum_m <= b:

        sum_all += i

print(sum_all)

import math

n, a, b = list(map(int, input().split()))
sum_all = 0
for i in range(1, n + 1):
    sum_n = 0
    m = i
    while m > 0:
        sum_n += math.floor(m % 10)
        m /= 10
    if a <= sum_n <= b:
        sum_all += i
print(sum_all)

-import math
-    sum_n = 0
-    m = i
-    while m > 0:
-        sum_n += math.floor(m % 10)
-        m /= 10
-    if a <= sum_n <= b:
+    m = str(i)
+    sum_m = 0
+    for j in range(len(m)):
+        sum_m += int(m[j])
+    if a <= sum_m <= b:


Input:
# 解説放送

def main():

    S = eval(input())

    N = len(S)

    K = int(eval(input()))

    dp = [[[0] * 2 for _ in range(K + 1)] for _ in range(N + 1)]

    dp[0][0][0] = 1

    # dp[i][j][k]

    # i桁目まで決めてj個の非0を使って

    # k=0: そこまでの桁はSと一致

    # k=1: すでにS未満が確定

    for i, c in enumerate(S):  # 100

        for j in range(K + 1):  # 4

            for k in range(2):  # 2

                nd = int(c)

                for d in range(10):  # 10

                    ni, nj, nk = i + 1, j, k

                    if d != 0: nj += 1  # 次の桁の値dとして0以外を採用すると非0の個数njが増える

                    if nj > K: continue  # 非0の数字を使用してよい上限を超えており、加算対象ではない

                    if k == 0:  # そこまでSと一致しているとき

                        if d > nd: continue  # 次の桁の値dがS[i]を超えており、採用するとSを超えるため、加算対象ではない

                        if d < nd: nk = 1  # 次の桁の値dがs[i]を下回っており、採用すると未満が確定する

                    dp[ni][nj][nk] += dp[i][j][k]

    print((sum(dp[N][K])))

if __name__ == '__main__':

    main()

def main():

    EQ = 0

    LESS = 1

    *S, = list(map(int, eval(input())))

    L = len(S)

    K = int(eval(input()))

    dp = [[[0] * 2 for _ in range(K + 2)] for _ in range(L + 1)]

    dp[0][0][EQ] = 1

    for i, x in enumerate(S):

        for k in range(K + 1):  # ここをrange(K)にしてバグらせた

            if x == 0:

                dp[i + 1][k][EQ] += dp[i][k][EQ]  # x

            else:

                dp[i + 1][k + 1][EQ] += dp[i][k][EQ]  # x

                dp[i + 1][k + 1][LESS] += dp[i][k][EQ] * (x - 1)  # <x

                dp[i + 1][k][LESS] += dp[i][k][EQ]  # ==0

            dp[i + 1][k + 1][LESS] += dp[i][k][LESS] * 9  # !=0

            dp[i + 1][k][LESS] += dp[i][k][LESS]  # ==0

    print((sum(dp[L][K])))  # 全部0はK個の0でない数字を含まないので除去する必要がない

if __name__ == '__main__':

    main()

# 解説放送
def main():
    S = eval(input())
    N = len(S)
    K = int(eval(input()))
    dp = [[[0] * 2 for _ in range(K + 1)] for _ in range(N + 1)]
    dp[0][0][0] = 1
    # dp[i][j][k]
    # i桁目まで決めてj個の非0を使って
    # k=0: そこまでの桁はSと一致
    # k=1: すでにS未満が確定
    for i, c in enumerate(S):  # 100
        for j in range(K + 1):  # 4
            for k in range(2):  # 2
                nd = int(c)
                for d in range(10):  # 10
                    ni, nj, nk = i + 1, j, k
                    if d != 0:
                        nj += 1  # 次の桁の値dとして0以外を採用すると非0の個数njが増える
                    if nj > K:
                        continue  # 非0の数字を使用してよい上限を超えており、加算対象ではない
                    if k == 0:  # そこまでSと一致しているとき
                        if d > nd:
                            continue  # 次の桁の値dがS[i]を超えており、採用するとSを超えるため、加算対象ではない
                        if d < nd:
                            nk = 1  # 次の桁の値dがs[i]を下回っており、採用すると未満が確定する
                    dp[ni][nj][nk] += dp[i][j][k]
    print((sum(dp[N][K])))

if __name__ == "__main__":
    main()

def main():
    EQ = 0
    LESS = 1
    (*S,) = list(map(int, eval(input())))
    L = len(S)
    K = int(eval(input()))
    dp = [[[0] * 2 for _ in range(K + 2)] for _ in range(L + 1)]
    dp[0][0][EQ] = 1
    for i, x in enumerate(S):
        for k in range(K + 1):  # ここをrange(K)にしてバグらせた
            if x == 0:
                dp[i + 1][k][EQ] += dp[i][k][EQ]  # x
            else:
                dp[i + 1][k + 1][EQ] += dp[i][k][EQ]  # x
                dp[i + 1][k + 1][LESS] += dp[i][k][EQ] * (x - 1)  # <x
                dp[i + 1][k][LESS] += dp[i][k][EQ]  # ==0
            dp[i + 1][k + 1][LESS] += dp[i][k][LESS] * 9  # !=0
            dp[i + 1][k][LESS] += dp[i][k][LESS]  # ==0
    print((sum(dp[L][K])))  # 全部0はK個の0でない数字を含まないので除去する必要がない

if __name__ == "__main__":
    main()

+    (*S,) = list(map(int, eval(input())))

-    dp = [[[0] * 2 for _ in range(K + 1)] for _ in range(N + 1)]

-    # i桁目まで決めてj個の非0を使って

-    # k=0: そこまでの桁はSと一致

-    # k=1: すでにS未満が確定

-                for d in range(10):  # 10

-                    ni, nj, nk = i + 1, j, k

-                        nj += 1  # 次の桁の値dとして0以外を採用すると非0の個数njが増える

-                        continue  # 非0の数字を使用してよい上限を超えており、加算対象ではない

-                    if k == 0:  # そこまでSと一致しているとき

-                            continue  # 次の桁の値dがS[i]を超えており、採用するとSを超えるため、加算対象ではない

-                            nk = 1  # 次の桁の値dがs[i]を下回っており、採用すると未満が確定する

+    dp = [[[0] * 2 for _ in range(K + 2)] for _ in range(L + 1)]

+        for k in range(K + 1):  # ここをrange(K)にしてバグらせた

+    print((sum(dp[L][K])))  # 全部0はK個の0でない数字を含まないので除去する必要がない


Input:
import sys

sys.setrecursionlimit(10 ** 7)

f_inf = float('inf')

mod = 10 ** 9 + 7

def resolve():

    s = eval(input())

    ss = []

    for i in s:

        if i != "x":

            ss.append(i)

    if ss != ss[::-1]:

        print((-1))

    else:

        n = len(ss) + 1

        cnt = 0

        cnt_x = [0] * (n)

        pos = 0

        for i in range(len(s)):

            if s[i] == "x":

                cnt += 1

            if s[i] != "x" or i == len(s) - 1:

                cnt_x[pos] = cnt

                cnt = 0

                pos += 1

        res = 0

        for i in range(n // 2):

            res += abs(cnt_x[i] - cnt_x[-(i + 1)])

        print(res)

if __name__ == '__main__':

    resolve()

import sys

sys.setrecursionlimit(10 ** 7)

f_inf = float('inf')

mod = 10 ** 9 + 7

def resolve():

    s = eval(input())

    n = len(s)

    ss = "".join(s.replace("x", ""))

    if ss != ss[::-1]:

        print((-1))

        exit()

    res = 0

    left = 0

    right = n - 1

    while left <= right:

        if s[left] == s[right]:

            left += 1

            right -= 1

        else:

            if s[left] == "x":

                left += 1

            else:

                right -= 1

            res += 1

    print(res)

if __name__ == '__main__':

    resolve()

import sys

sys.setrecursionlimit(10**7)
f_inf = float("inf")
mod = 10**9 + 7

def resolve():
    s = eval(input())
    ss = []
    for i in s:
        if i != "x":
            ss.append(i)
    if ss != ss[::-1]:
        print((-1))
    else:
        n = len(ss) + 1
        cnt = 0
        cnt_x = [0] * (n)
        pos = 0
        for i in range(len(s)):
            if s[i] == "x":
                cnt += 1
            if s[i] != "x" or i == len(s) - 1:
                cnt_x[pos] = cnt
                cnt = 0
                pos += 1
        res = 0
        for i in range(n // 2):
            res += abs(cnt_x[i] - cnt_x[-(i + 1)])
        print(res)

if __name__ == "__main__":
    resolve()

import sys

sys.setrecursionlimit(10**7)
f_inf = float("inf")
mod = 10**9 + 7

def resolve():
    s = eval(input())
    n = len(s)
    ss = "".join(s.replace("x", ""))
    if ss != ss[::-1]:
        print((-1))
        exit()
    res = 0
    left = 0
    right = n - 1
    while left <= right:
        if s[left] == s[right]:
            left += 1
            right -= 1
        else:
            if s[left] == "x":
                left += 1
            else:
                right -= 1
            res += 1
    print(res)

if __name__ == "__main__":
    resolve()


Input:
N,K = list(map(int, input().split()))

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

accum = [0] * N

for i in range(N):

    if i == 0:

        accum[i] = A[i]

    else:

        accum[i] = accum[i-1] + A[i]

B = []

for l in range(N):

    for r in range(l, N):

        if l == 0:

            B.append(accum[r])

        else:

            B.append(accum[r] - accum[l-1])

ans = 0

for i in range(50, -1, -1):

    cnt = 0

    nxt_B = []

    for b in B:

        if b & (1 << i):

            cnt += 1

            nxt_B.append(b)

    if cnt >= K:

        ans += 2**i

        B = nxt_B

print(ans)

N,K = list(map(int, input().split()))

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

accum = [0] * N

accum[0] = A[0]

for i in  range(1,N):

    accum[i] = accum[i-1] + A[i]

B = []

for l in range(N):

    for r in range(l,N):

        if l == 0:

            B.append(accum[r])

        else:

            B.append(accum[r] - accum[l-1])

ans = 0

for i in range(45,-1,-1):

    used = []

    cnt = 0

    for b in B:

        if b & (1 << i):

            cnt += 1

            used.append(b)

    if cnt >= K:

        ans += pow(2,i)

        B = used

print(ans)

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
accum = [0] * N
for i in range(N):
    if i == 0:
        accum[i] = A[i]
    else:
        accum[i] = accum[i - 1] + A[i]
B = []
for l in range(N):
    for r in range(l, N):
        if l == 0:
            B.append(accum[r])
        else:
            B.append(accum[r] - accum[l - 1])
ans = 0
for i in range(50, -1, -1):
    cnt = 0
    nxt_B = []
    for b in B:
        if b & (1 << i):
            cnt += 1
            nxt_B.append(b)
    if cnt >= K:
        ans += 2**i
        B = nxt_B
print(ans)

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
accum = [0] * N
accum[0] = A[0]
for i in range(1, N):
    accum[i] = accum[i - 1] + A[i]
B = []
for l in range(N):
    for r in range(l, N):
        if l == 0:
            B.append(accum[r])
        else:
            B.append(accum[r] - accum[l - 1])
ans = 0
for i in range(45, -1, -1):
    used = []
    cnt = 0
    for b in B:
        if b & (1 << i):
            cnt += 1
            used.append(b)
    if cnt >= K:
        ans += pow(2, i)
        B = used
print(ans)

-for i in range(N):
-    if i == 0:
-        accum[i] = A[i]
-    else:
-        accum[i] = accum[i - 1] + A[i]
+accum[0] = A[0]
+for i in range(1, N):
+    accum[i] = accum[i - 1] + A[i]
-for i in range(50, -1, -1):
+for i in range(45, -1, -1):
+    used = []
-    nxt_B = []
-            nxt_B.append(b)
+            used.append(b)
-        ans += 2**i
-        B = nxt_B
+        ans += pow(2, i)
+        B = used


Input:
import cmath

import numpy as np

import sys

INF=10**18

MOD=10**9+7

MAX=10**5+7

def main():

    N=int(eval(input()))

    dp=[0, 0, 0]

    for _ in range(N):

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

        ndp=[0, 0, 0]

        ndp[0]=max(dp[1], dp[2])+a

        ndp[1]=max(dp[2], dp[0])+b

        ndp[2]=max(dp[0], dp[1])+c

        dp=ndp

    print((max(dp)))

if __name__=='__main__':

    main()

import sys

INF=10**18

MOD=10**9+7

MAX=10**5+7

def main():

    N=int(eval(input()))

    dp=[0, 0, 0]

    for line in sys.stdin.readlines():

        a,b,c=list(map(int, line.split()))

        ndp=[0, 0, 0]

        ndp[0]=max(dp[1], dp[2])+a

        ndp[1]=max(dp[2], dp[0])+b

        ndp[2]=max(dp[0], dp[1])+c

        dp=ndp

    print((max(dp)))

main()

import cmath
import numpy as np
import sys

INF = 10**18
MOD = 10**9 + 7
MAX = 10**5 + 7

def main():
    N = int(eval(input()))
    dp = [0, 0, 0]
    for _ in range(N):
        a, b, c = list(map(int, input().split()))
        ndp = [0, 0, 0]
        ndp[0] = max(dp[1], dp[2]) + a
        ndp[1] = max(dp[2], dp[0]) + b
        ndp[2] = max(dp[0], dp[1]) + c
        dp = ndp
    print((max(dp)))

if __name__ == "__main__":
    main()

import sys

INF = 10**18
MOD = 10**9 + 7
MAX = 10**5 + 7

def main():
    N = int(eval(input()))
    dp = [0, 0, 0]
    for line in sys.stdin.readlines():
        a, b, c = list(map(int, line.split()))
        ndp = [0, 0, 0]
        ndp[0] = max(dp[1], dp[2]) + a
        ndp[1] = max(dp[2], dp[0]) + b
        ndp[2] = max(dp[0], dp[1]) + c
        dp = ndp
    print((max(dp)))

main()

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

+        a, b, c = list(map(int, line.split()))


Input:
from itertools import chain

R = lambda: list(map(int, input().split()))

n, k = R()

v = list(R())

a = sorted((x, i) for i, x in enumerate(v) if x < 0)

r = 0

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

    for j in range(i):

        r1, r2 = i - j, n - j

        s = sum(v[m] for m in chain(list(range(r1)), list(range(r2, n))))

        j = i

        for x, m in a:

            if j == k:

                break

            if m < r1 or m >= r2:

                s -= x

                j += 1

        r = max(r, s)

print(r)

from itertools import chain, islice

R = lambda: list(map(int, input().split()))

n, k = R()

v = list(R())

a = sorted((x, i) for i, x in enumerate(v) if x < 0)

ans = max(sum(v[m] for m in chain(list(range(i - j)), list(range(n - j, n)))) -

          sum(islice((x for x, m in a if m < i - j or m >= n - j), k - i))

          for i in range(1, min(n, k) + 1) for j in range(i))

print(ans)

from itertools import chain, islice

R = lambda: list(map(int, input().split()))
n, k = R()
v = list(R())
a = sorted((x, i) for i, x in enumerate(v) if x < 0)
ans = max(
    sum(v[m] for m in chain(list(range(i - j)), list(range(n - j, n))))
    - sum(islice((x for x, m in a if m < i - j or m >= n - j), k - i))
    for i in range(1, min(n, k) + 1)
    for j in range(i)
)
print(ans)

-        s = sum(v[m] for m in chain(list(range(r1)), list(range(r2, n))))

+    sum(v[m] for m in chain(list(range(i - j)), list(range(n - j, n))))

+    - sum(islice((x for x, m in a if m < i - j or m >= n - j), k - i))


Input:
from collections import deque

N, u, v = list(map(int, input().split()))

u -= 1

v -= 1

edge = [[] for _ in range(N)]

for _ in range(N - 1):

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

    edge[A - 1].append(B - 1)

    edge[B - 1].append(A - 1)

INF = 10 ** 6

lenA = [INF] * N

q = deque()

q.append((v, 0))

lenA[v] = 0

while len(q) > 0:

    p, step = q.popleft()

    for np in edge[p]:

        if lenA[np] == INF:

            lenA[np] = step + 1

            q.append((np, step + 1))

lenT = [INF] * N

q = deque()

q.append((u, 0))

lenT[u] = 0

ans = 0

while len(q) > 0:

    p, step = q.popleft()

    if len(edge[p]) == 1:

        ans = max(ans, step + (lenA[p] - step) - 1)

    for np in edge[p]:

        if lenT[np] == INF and lenA[np] > step + 1:

            lenT[np] = step + 1

            q.append((np, step + 1))

print(ans)

from collections import deque

import sys

N, u, v = list(map(int, input().split()))

u -= 1; v -= 1

edge = [[] for _ in range(N)]

for s in sys.stdin.readlines():

    A, B = [int(x) - 1 for x in s.split()]

    edge[A].append(B)

    edge[B].append(A)

INF = float('inf')

# Aoki

pathV = [INF] * N

pathV[v] = 0

q = deque()

q.append((v, 0))

while q:

    p, d = q.popleft()

    nd = d + 1

    for np in edge[p]:

        if pathV[np] > nd:

            pathV[np] = nd

            q.append((np, nd))

# Takahashi

ans = 0

pathU = [INF] * N

pathU[u] = 0

q = deque()

q.append((u, 0))

while q:

    p, d = q.popleft()

    nd = d + 1

    if len(edge[p]) == 1:

        ans = max(ans, pathV[p] - 1)

    for np in edge[p]:

        if pathU[np] > nd and pathV[np] > nd:

            pathU[np] = nd

            q.append((np, nd))

print(ans)

from collections import deque

N, u, v = list(map(int, input().split()))
u -= 1
v -= 1
edge = [[] for _ in range(N)]
for _ in range(N - 1):
    A, B = list(map(int, input().split()))
    edge[A - 1].append(B - 1)
    edge[B - 1].append(A - 1)
INF = 10**6
lenA = [INF] * N
q = deque()
q.append((v, 0))
lenA[v] = 0
while len(q) > 0:
    p, step = q.popleft()
    for np in edge[p]:
        if lenA[np] == INF:
            lenA[np] = step + 1
            q.append((np, step + 1))
lenT = [INF] * N
q = deque()
q.append((u, 0))
lenT[u] = 0
ans = 0
while len(q) > 0:
    p, step = q.popleft()
    if len(edge[p]) == 1:
        ans = max(ans, step + (lenA[p] - step) - 1)
    for np in edge[p]:
        if lenT[np] == INF and lenA[np] > step + 1:
            lenT[np] = step + 1
            q.append((np, step + 1))
print(ans)

from collections import deque
import sys

N, u, v = list(map(int, input().split()))
u -= 1
v -= 1
edge = [[] for _ in range(N)]
for s in sys.stdin.readlines():
    A, B = [int(x) - 1 for x in s.split()]
    edge[A].append(B)
    edge[B].append(A)
INF = float("inf")
# Aoki
pathV = [INF] * N
pathV[v] = 0
q = deque()
q.append((v, 0))
while q:
    p, d = q.popleft()
    nd = d + 1
    for np in edge[p]:
        if pathV[np] > nd:
            pathV[np] = nd
            q.append((np, nd))
# Takahashi
ans = 0
pathU = [INF] * N
pathU[u] = 0
q = deque()
q.append((u, 0))
while q:
    p, d = q.popleft()
    nd = d + 1
    if len(edge[p]) == 1:
        ans = max(ans, pathV[p] - 1)
    for np in edge[p]:
        if pathU[np] > nd and pathV[np] > nd:
            pathU[np] = nd
            q.append((np, nd))
print(ans)

-    A, B = list(map(int, input().split()))

+    A, B = [int(x) - 1 for x in s.split()]

-        ans = max(ans, step + (lenA[p] - step) - 1)

-        if lenT[np] == INF and lenA[np] > step + 1:

+        if pathU[np] > nd and pathV[np] > nd:


Input:
def solve():

    S = eval(input())

    T = eval(input())

    N = len(S)

    M = 2 * N

    S += S

    nxt = [[M] * 26 for i in range(M + 1)]

    for i in range(M - 1, -1, -1):

        for j in range(26):

            nxt[i][j] = nxt[i + 1][j]

        nxt[i][ord(S[i]) - ord('a')] = i

    ans = 0

    i = 0

    for c in T:

        pos = ord(c) - ord('a')

        if nxt[i][pos] == M:

            return -1

        ans += nxt[i][pos] - i + 1

        i = (nxt[i][pos] + 1) % N

    return ans

print((solve()))

def solve():

    S = eval(input())

    T = eval(input())

    N = len(S)

    M = 2 * N

    S += S

    nxt = [[M] * 26 for i in range(M + 1)]

    for i in range(M - 1, -1, -1):

        for j in range(26):

            nxt[i][j] = nxt[i + 1][j]

        nxt[i][ord(S[i]) - ord('a')] = i

    ans = -1

    for c in T:

        i = ans % N

        pos = ord(c) - ord('a')

        if nxt[i + 1][pos] == M:

            return -1

        ans += nxt[i + 1][pos] - i

    return ans + 1

print((solve()))

def solve():
    S = eval(input())
    T = eval(input())
    N = len(S)
    M = 2 * N
    S += S
    nxt = [[M] * 26 for i in range(M + 1)]
    for i in range(M - 1, -1, -1):
        for j in range(26):
            nxt[i][j] = nxt[i + 1][j]
        nxt[i][ord(S[i]) - ord("a")] = i
    ans = 0
    i = 0
    for c in T:
        pos = ord(c) - ord("a")
        if nxt[i][pos] == M:
            return -1
        ans += nxt[i][pos] - i + 1
        i = (nxt[i][pos] + 1) % N
    return ans

print((solve()))

def solve():
    S = eval(input())
    T = eval(input())
    N = len(S)
    M = 2 * N
    S += S
    nxt = [[M] * 26 for i in range(M + 1)]
    for i in range(M - 1, -1, -1):
        for j in range(26):
            nxt[i][j] = nxt[i + 1][j]
        nxt[i][ord(S[i]) - ord("a")] = i
    ans = -1
    for c in T:
        i = ans % N
        pos = ord(c) - ord("a")
        if nxt[i + 1][pos] == M:
            return -1
        ans += nxt[i + 1][pos] - i
    return ans + 1

print((solve()))

-    ans = 0
-    i = 0
+    ans = -1
+        i = ans % N
-        if nxt[i][pos] == M:
+        if nxt[i + 1][pos] == M:
-        ans += nxt[i][pos] - i + 1
-        i = (nxt[i][pos] + 1) % N
-    return ans
+        ans += nxt[i + 1][pos] - i
+    return ans + 1


Input:
def main():

    n = int(eval(input()))

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

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

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

    point = sum(b)

    for i in range(1,n):

        if a[i-1] +1 == a[i]:

            point += c[a[i-1]-1]

    print(point)

if __name__ == '__main__':

    main()

def main():

    n = int(eval(input()))

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

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

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

    total_score = sum(b)

    for i in range(1, n):

        prev = a[i - 1]

        if prev + 1 == a[i]:

            total_score += c[prev - 1]

    print(total_score)

if __name__ == '__main__':

    main()

def main():
    n = int(eval(input()))
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    c = list(map(int, input().split()))
    point = sum(b)
    for i in range(1, n):
        if a[i - 1] + 1 == a[i]:
            point += c[a[i - 1] - 1]
    print(point)

if __name__ == "__main__":
    main()

def main():
    n = int(eval(input()))
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    c = list(map(int, input().split()))
    total_score = sum(b)
    for i in range(1, n):
        prev = a[i - 1]
        if prev + 1 == a[i]:
            total_score += c[prev - 1]
    print(total_score)

if __name__ == "__main__":
    main()

-    point = sum(b)
+    total_score = sum(b)
-        if a[i - 1] + 1 == a[i]:
-            point += c[a[i - 1] - 1]
-    print(point)
+        prev = a[i - 1]
+        if prev + 1 == a[i]:
+            total_score += c[prev - 1]
+    print(total_score)


Input:
a=eval(input())

one=0

zero=0

for i in a:

  if i=="0":

    zero+=1

  else:

    one+=1

print((2*min(zero,one)))

S = eval(input())

red = S.count('0')

blue = S.count('1')

print((min(red, blue)*2))

a = eval(input())
one = 0
zero = 0
for i in a:
    if i == "0":
        zero += 1
    else:
        one += 1
print((2 * min(zero, one)))

S = eval(input())
red = S.count("0")
blue = S.count("1")
print((min(red, blue) * 2))

-a = eval(input())
-one = 0
-zero = 0
-for i in a:
-    if i == "0":
-        zero += 1
-    else:
-        one += 1
-print((2 * min(zero, one)))
+S = eval(input())
+red = S.count("0")
+blue = S.count("1")
+print((min(red, blue) * 2))


Input:
S = eval(input())

w = int(eval(input()))

newS = [""] * ((len(S) - 1 + w) // w)

for i in range(len(newS)):

    newS[i] = S[w * i]

print(("".join(newS)))

S = eval(input())

w = int(eval(input()))

newS =[""]

i = 0

while i<len(S):

    newS.append(S[i])

    i = i+w

print(("".join(newS)))

S = eval(input())
w = int(eval(input()))
newS = [""]
i = 0
while i < len(S):
    newS.append(S[i])
    i = i + w
print(("".join(newS)))

-newS = [""] * ((len(S) - 1 + w) // w)
-for i in range(len(newS)):
-    newS[i] = S[w * i]
+newS = [""]
+i = 0
+while i < len(S):
+    newS.append(S[i])
+    i = i + w


Input:
import sys

from itertools import accumulate

read = sys.stdin.read

N, K, *p = list(map(int, read().split()))

p = [(1 + i) / 2 for i in p]

p = [0] + p

P = list(accumulate(p))

answer = max(P[i] - P[i - K] for i in range(K, N + 1))

print(answer)

import sys

from itertools import accumulate

read = sys.stdin.read

N, K, *p = list(map(int, read().split()))

p = [(1 + i) / 2 for i in p]

p = [0] + p

P = list(accumulate(p))

answer = max(b - a for a, b in zip(P, P[K:]))

print(answer)

-answer = max(P[i] - P[i - K] for i in range(K, N + 1))

+answer = max(b - a for a, b in zip(P, P[K:]))


Input:
n = int(eval(input()))

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

m = int(eval(input()))

px = [list(map(int, input().split())) for _ in range(m)]

for i in px:

  sumt = sum(t) - t[i[0] - 1] + i[1]

  print(sumt)

n = int(eval(input()))

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

m = int(eval(input()))

PX = [list(map(int, input().split())) for _ in range(m)]

total = sum(T)

for p, x in PX:

  ans = total - T[p-1] + x

  print(ans)

n = int(eval(input()))
T = list(map(int, input().split()))
m = int(eval(input()))
PX = [list(map(int, input().split())) for _ in range(m)]
total = sum(T)
for p, x in PX:
    ans = total - T[p - 1] + x
    print(ans)

-px = [list(map(int, input().split())) for _ in range(m)]

+PX = [list(map(int, input().split())) for _ in range(m)]


Input:
n=int(eval(input()))

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

cnt=0

def gcd(a,b):

    if a==0: return b

    else: return gcd(b%a,a)

# print(gcd(a,b))

def gcd_3(a,b,c):

    if gcd(a,b)==0: return c

    else: return gcd(c % gcd(a,b),gcd(a,b))

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

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

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

            # print(i,j,k)

            cnt+=gcd_3(i,j,k)

print(cnt)

def main():

    from math import gcd

    K = int(eval(input()))

    result = 0

    for a in range(1, K + 1):

        for b in range(1, K + 1):

            t = gcd(a, b)

            for c in range(1, K + 1):

                result += gcd(t, c)

    print(result)

main()

n = int(eval(input()))
# a,b,c=map(int,input().split())
cnt = 0

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

# print(gcd(a,b))
def gcd_3(a, b, c):
    if gcd(a, b) == 0:
        return c
    else:
        return gcd(c % gcd(a, b), gcd(a, b))

for i in range(1, n + 1):
    for j in range(1, n + 1):
        for k in range(1, n + 1):
            # print(i,j,k)
            cnt += gcd_3(i, j, k)
print(cnt)

-        return gcd(c % gcd(a, b), gcd(a, b))


Input:
a,b=list(map(int,input().split()))

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

z=0

for i in range(a-b):

  z+=l[i]

print(z)

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

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

z=0

l=sorted(l)

for i in range(a-b):

  z+=l[i]

print(z)

a, b = list(map(int, input().split()))
l = sorted(list(map(int, input().split())))
z = 0
for i in range(a - b):
    z += l[i]
print(z)

a, b = list(map(int, input().split()))
l = list(map(int, input().split()))
z = 0
l = sorted(l)
for i in range(a - b):
    z += l[i]
print(z)

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


Input:
N , M = list(map(int, input().split()))

mod = 10 ** 9 + 7

if abs(N - M) >1:

    print((0))

elif N == M:

    n = 1

    m = 1

    for i in range(N):

        n = n * (i + 1) % mod

    for i in range(M):

        m = m * (i + 1) % mod

    print((2 * m * n % mod))

else:

    n = 1

    m = 1

    for i in range(N):

        n = n * (i + 1) % mod

    for i in range(M):

        m = m * (i + 1) % mod

    print((m * n % mod))

N , M = list(map(int, input().split()))

mod = 10 ** 9 + 7

def factorial(n):

    ans = 1

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

        ans = ans * i % mod

    return ans

if abs(N - M) >1:

    print((0))

elif N == M:

    print((2 * factorial(N) ** 2 % mod))

else:

    print((factorial(min(M, N)) ** 2 * max(M, N) % mod))

N, M = list(map(int, input().split()))
mod = 10**9 + 7
if abs(N - M) > 1:
    print((0))
elif N == M:
    n = 1
    m = 1
    for i in range(N):
        n = n * (i + 1) % mod
    for i in range(M):
        m = m * (i + 1) % mod
    print((2 * m * n % mod))
else:
    n = 1
    m = 1
    for i in range(N):
        n = n * (i + 1) % mod
    for i in range(M):
        m = m * (i + 1) % mod
    print((m * n % mod))

N, M = list(map(int, input().split()))
mod = 10**9 + 7

def factorial(n):
    ans = 1
    for i in range(2, n + 1):
        ans = ans * i % mod
    return ans

if abs(N - M) > 1:
    print((0))
elif N == M:
    print((2 * factorial(N) ** 2 % mod))
else:
    print((factorial(min(M, N)) ** 2 * max(M, N) % mod))

+    print((2 * factorial(N) ** 2 % mod))

+    print((factorial(min(M, N)) ** 2 * max(M, N) % mod))


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

ans = 0

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

    if a <= sum(list(map(int, list(str(i))))) <= b:

        ans += i

print(ans)

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

ans = 0

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

    sum = 0

    j = i

    while j != 0:

        sum += j % 10

        j = j // 10

    if a <= sum <= b:

        ans += i

print(ans)

n, a, b = list(map(int, input().split()))
ans = 0
for i in range(1, n + 1):
    if a <= sum(list(map(int, list(str(i))))) <= b:
        ans += i
print(ans)

n, a, b = list(map(int, input().split()))
ans = 0
for i in range(1, n + 1):
    sum = 0
    j = i
    while j != 0:
        sum += j % 10
        j = j // 10
    if a <= sum <= b:
        ans += i
print(ans)

-    if a <= sum(list(map(int, list(str(i))))) <= b:


Input:
from collections import deque

N = int(eval(input()))

R = [list(map(int,input().split())) for _ in range(N)]

B = [list(map(int,input().split())) for _ in range(N)]

graph = [[] for _ in range(2*N+2)] #残余グラフを構成　0を始点，1を終点とする

for i in range(N):

    forward = [2+i,1,None] #[行き先，流量，逆辺の情報]

    forward[2] = backward = [0,0,forward]

    graph[0].append(forward)

    graph[2+i].append(backward)

for i in range(N):

    forward = [1,1,None]

    forward[2] = backward = [2+N+i,0,forward]

    graph[2+N+i].append(forward)

    graph[1].append(backward)

for i in range(N):

    for j in range(N):

        if R[i][0]<B[j][0] and R[i][1]<B[j][1]:

            forward = [2+N+j,1,None]

            forward[2] = backward = [2+i,0,forward]

            graph[2+i].append(forward)

            graph[2+N+j].append(backward)

flow = 0

while True:

    queue = deque([0])

    level = [None for _ in range(2*N+2)]

    level[0] = 0

    while queue:

        node = queue.popleft()

        for adj,adjcap,_ in graph[node]:

            if adjcap>0 and level[adj] is None:

                level[adj] = level[node]+1

                queue.append(adj)

    if level[1] is None:

        break

    stack = [0]

    visited = [0 for _ in range(2*N+2)]

    visited[0] = 1

    parent = [None for _ in range(2*N+2)]

    parent[0] = 0

    #*it, = map(iter, graph)

    while stack:

        node = stack.pop()

        for adj,adjcap,adjrev in graph[node]:

            if not visited[adj] and adjcap>0 and level[node]<level[adj]:

                visited[adj] = 1

                parent[adj] = node

                stack.append(adj)

    if visited[1]:

        flow += 1

        node = 1

        prev = parent[node]

        while node != 0:

            for g in graph[prev]:

                adj,adjcap,adjrev = g

                if adj == node:

                    g[1] = 0

                    adjrev[1] = 1

            node = prev

            prev = parent[node]

print(flow)

class Node():

    def __init__(self, idx=None):

        self.idx = idx

        self.edge = []

        self.level = None

        self.par = None

class Edge():

    def __init__(self, to, cap, rev=None):

        self.to = to

        self.cap = cap

        self.rev = rev

from collections import deque

class BipartiteMatching():

    def __init__(self, n, m):

        self.n = n

        self.m = m

        self.inf = 10**18

        self.source = Node()

        self.sink = Node()

        self.lt = [Node(i) for i in range(n)]

        self.rt = [Node(i) for i in range(m)]

        for i in range(n):

            edge = Edge(self.lt[i], 1)

            rev = Edge(self.source, 0)

            edge.rev, rev.rev = rev, edge

            self.source.edge.append(edge)

            self.lt[i].edge.append(rev)

        for i in range(m):

            edge = Edge(self.sink, 1)

            rev = Edge(self.rt[i], 0)

            edge.rev, rev.rev = rev, edge

            self.rt[i].edge.append(edge)

            self.sink.edge.append(rev)

    def add(self, x, y):

        lt = self.lt[x]

        rt = self.rt[y]

        edge = Edge(rt, 1)

        rev = Edge(lt, 0)

        edge.rev, rev.rev = rev, edge

        lt.edge.append(edge)

        rt.edge.append(rev)

    def maximum_matching(self):

        flow = 0

        while True:

            queue = deque([self.source])

            self.source.level = 0

            self.sink.level = None

            for i in range(self.n):

                self.lt[i].level = None

            for i in range(self.m):

                self.rt[i].level = None

            while queue:

                node = queue.popleft()

                for edge in node.edge:

                    to = edge.to

                    if edge.cap and to.level is None:

                        to.level = node.level + 1

                        queue.append(to)

            if self.sink.level is None: break

            stack = [self.source]

            self.source.par = None

            self.sink.par = None

            for i in range(self.n):

                self.lt[i].par = None

            for i in range(self.m):

                self.rt[i].par = None

            while stack:

                node = stack.pop()

                if node is self.sink:

                    break

                for edge in node.edge:

                    to = edge.to

                    if edge.cap and node.level < to.level:

                        to.par = edge.rev

                        stack.append(to)

            node = self.sink

            while node is not self.source:

                node.par.cap = 1

                node.par.rev.cap = 0

                node = node.par.to

            flow += 1

        return flow

N = int(eval(input()))

R = [tuple(map(int, input().split())) for _ in range(N)]

B = [tuple(map(int, input().split())) for _ in range(N)]

bip = BipartiteMatching(N, N)

for i in range(N):

    a, b = R[i]

    for j in range(N):

        c, d = B[j]

        if a < c and b < d:

            bip.add(i, j)

print((bip.maximum_matching()))

from collections import deque

N = int(eval(input()))
R = [list(map(int, input().split())) for _ in range(N)]
B = [list(map(int, input().split())) for _ in range(N)]
graph = [[] for _ in range(2 * N + 2)]  # 残余グラフを構成　0を始点，1を終点とする
for i in range(N):
    forward = [2 + i, 1, None]  # [行き先，流量，逆辺の情報]
    forward[2] = backward = [0, 0, forward]
    graph[0].append(forward)
    graph[2 + i].append(backward)
for i in range(N):
    forward = [1, 1, None]
    forward[2] = backward = [2 + N + i, 0, forward]
    graph[2 + N + i].append(forward)
    graph[1].append(backward)
for i in range(N):
    for j in range(N):
        if R[i][0] < B[j][0] and R[i][1] < B[j][1]:
            forward = [2 + N + j, 1, None]
            forward[2] = backward = [2 + i, 0, forward]
            graph[2 + i].append(forward)
            graph[2 + N + j].append(backward)
flow = 0
while True:
    queue = deque([0])
    level = [None for _ in range(2 * N + 2)]
    level[0] = 0
    while queue:
        node = queue.popleft()
        for adj, adjcap, _ in graph[node]:
            if adjcap > 0 and level[adj] is None:
                level[adj] = level[node] + 1
                queue.append(adj)
    if level[1] is None:
        break
    stack = [0]
    visited = [0 for _ in range(2 * N + 2)]
    visited[0] = 1
    parent = [None for _ in range(2 * N + 2)]
    parent[0] = 0
    # *it, = map(iter, graph)
    while stack:
        node = stack.pop()
        for adj, adjcap, adjrev in graph[node]:
            if not visited[adj] and adjcap > 0 and level[node] < level[adj]:
                visited[adj] = 1
                parent[adj] = node
                stack.append(adj)
    if visited[1]:
        flow += 1
        node = 1
        prev = parent[node]
        while node != 0:
            for g in graph[prev]:
                adj, adjcap, adjrev = g
                if adj == node:
                    g[1] = 0
                    adjrev[1] = 1
            node = prev
            prev = parent[node]
print(flow)

class Node:
    def __init__(self, idx=None):
        self.idx = idx
        self.edge = []
        self.level = None
        self.par = None

class Edge:
    def __init__(self, to, cap, rev=None):
        self.to = to
        self.cap = cap
        self.rev = rev

from collections import deque

class BipartiteMatching:
    def __init__(self, n, m):
        self.n = n
        self.m = m
        self.inf = 10**18
        self.source = Node()
        self.sink = Node()
        self.lt = [Node(i) for i in range(n)]
        self.rt = [Node(i) for i in range(m)]
        for i in range(n):
            edge = Edge(self.lt[i], 1)
            rev = Edge(self.source, 0)
            edge.rev, rev.rev = rev, edge
            self.source.edge.append(edge)
            self.lt[i].edge.append(rev)
        for i in range(m):
            edge = Edge(self.sink, 1)
            rev = Edge(self.rt[i], 0)
            edge.rev, rev.rev = rev, edge
            self.rt[i].edge.append(edge)
            self.sink.edge.append(rev)

    def add(self, x, y):
        lt = self.lt[x]
        rt = self.rt[y]
        edge = Edge(rt, 1)
        rev = Edge(lt, 0)
        edge.rev, rev.rev = rev, edge
        lt.edge.append(edge)
        rt.edge.append(rev)

    def maximum_matching(self):
        flow = 0
        while True:
            queue = deque([self.source])
            self.source.level = 0
            self.sink.level = None
            for i in range(self.n):
                self.lt[i].level = None
            for i in range(self.m):
                self.rt[i].level = None
            while queue:
                node = queue.popleft()
                for edge in node.edge:
                    to = edge.to
                    if edge.cap and to.level is None:
                        to.level = node.level + 1
                        queue.append(to)
            if self.sink.level is None:
                break
            stack = [self.source]
            self.source.par = None
            self.sink.par = None
            for i in range(self.n):
                self.lt[i].par = None
            for i in range(self.m):
                self.rt[i].par = None
            while stack:
                node = stack.pop()
                if node is self.sink:
                    break
                for edge in node.edge:
                    to = edge.to
                    if edge.cap and node.level < to.level:
                        to.par = edge.rev
                        stack.append(to)
            node = self.sink
            while node is not self.source:
                node.par.cap = 1
                node.par.rev.cap = 0
                node = node.par.to
            flow += 1
        return flow

N = int(eval(input()))
R = [tuple(map(int, input().split())) for _ in range(N)]
B = [tuple(map(int, input().split())) for _ in range(N)]
bip = BipartiteMatching(N, N)
for i in range(N):
    a, b = R[i]
    for j in range(N):
        c, d = B[j]
        if a < c and b < d:
            bip.add(i, j)
print((bip.maximum_matching()))

+    def __init__(self, to, cap, rev=None):

+        self.lt = [Node(i) for i in range(n)]

+        self.rt = [Node(i) for i in range(m)]

+            edge.rev, rev.rev = rev, edge

+            self.source.edge.append(edge)

+            self.lt[i].edge.append(rev)

+            edge.rev, rev.rev = rev, edge

+            self.rt[i].edge.append(edge)

+            queue = deque([self.source])

+                self.lt[i].level = None

+                self.rt[i].level = None

+                    if edge.cap and to.level is None:

+                        to.level = node.level + 1

+                        queue.append(to)

+            if self.sink.level is None:

+                    if edge.cap and node.level < to.level:

+                        to.par = edge.rev

+                        stack.append(to)

+            while node is not self.source:

-R = [list(map(int, input().split())) for _ in range(N)]

-B = [list(map(int, input().split())) for _ in range(N)]

-graph = [[] for _ in range(2 * N + 2)]  # 残余グラフを構成　0を始点，1を終点とする

+R = [tuple(map(int, input().split())) for _ in range(N)]

+B = [tuple(map(int, input().split())) for _ in range(N)]

-    forward = [2 + i, 1, None]  # [行き先，流量，逆辺の情報]

-    forward[2] = backward = [0, 0, forward]

-    forward[2] = backward = [2 + N + i, 0, forward]

-            forward = [2 + N + j, 1, None]

-            forward[2] = backward = [2 + i, 0, forward]

-            graph[2 + i].append(forward)

-            graph[2 + N + j].append(backward)

-    level = [None for _ in range(2 * N + 2)]

-        for adj, adjcap, _ in graph[node]:

-            if adjcap > 0 and level[adj] is None:

-                level[adj] = level[node] + 1

-    visited = [0 for _ in range(2 * N + 2)]

-    parent = [None for _ in range(2 * N + 2)]

-        for adj, adjcap, adjrev in graph[node]:

-            if not visited[adj] and adjcap > 0 and level[node] < level[adj]:

-                adj, adjcap, adjrev = g


Input:
N = int(eval(input()))

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

# memo = [0] + [abs(H[i] - H[i-1]) for i in range(1, N)]

# memo = [H[i] - H[i-1] for i in range(1, N)]

memo = [sum(H)] * (N+2)

memo[0] = 0

for i in range(N):

    memo[i+1] = min(memo[i+1], memo[i] + abs(H[i+1] - H[i]))

    if i > N-3:

        break

    memo[i+2] = min(memo[i+2], memo[i] + abs(H[i+2] - H[i]))

print((memo[N-1]))

N = int(eval(input()))

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

dp = [0] * N

dp[1] = abs(H[1] - H[0])

for i in range(2, N):

    dp[i] = min(dp[i-1] + abs(H[i] - H[i-1]), dp[i-2] + abs(H[i] - H[i-2]))

print((dp[N-1]))

N = int(eval(input()))
H = list(map(int, input().split()))
# memo = [0] + [abs(H[i] - H[i-1]) for i in range(1, N)]
# memo = [H[i] - H[i-1] for i in range(1, N)]
memo = [sum(H)] * (N + 2)
memo[0] = 0
for i in range(N):
    memo[i + 1] = min(memo[i + 1], memo[i] + abs(H[i + 1] - H[i]))
    if i > N - 3:
        break
    memo[i + 2] = min(memo[i + 2], memo[i] + abs(H[i + 2] - H[i]))
print((memo[N - 1]))

N = int(eval(input()))
H = list(map(int, input().split()))
dp = [0] * N
dp[1] = abs(H[1] - H[0])
for i in range(2, N):
    dp[i] = min(dp[i - 1] + abs(H[i] - H[i - 1]), dp[i - 2] + abs(H[i] - H[i - 2]))
print((dp[N - 1]))

-# memo = [0] + [abs(H[i] - H[i-1]) for i in range(1, N)]

-# memo = [H[i] - H[i-1] for i in range(1, N)]

-    memo[i + 1] = min(memo[i + 1], memo[i] + abs(H[i + 1] - H[i]))

-    memo[i + 2] = min(memo[i + 2], memo[i] + abs(H[i + 2] - H[i]))


Input:
import math

def abs(x):

  return math.fabs(x)

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

c=int(abs(b)-abs(a))

print((int(abs(c))+(c*a<0)+(c*b<0) if c!=0 else 1))

import math

def abs(x):
    return math.fabs(x)

a, b = list(map(int, input().split()))
c = int(abs(b) - abs(a))
print((int(abs(c)) + (c * a < 0) + (c * b < 0) if c != 0 else 1))

-import math
-def abs(x):
-    return math.fabs(x)


Input:
N = eval(input())

def r(s):

    me = all(('3' in s, '5' in s, '7' in s))

    if len(s) < len(N):

        return r(s+'3') + r(s+'5') + r(s+'7') + me

    elif s<=N:

        return me

    else:

        return 0

print((r('')))

N = eval(input())

def r(s):

    me = '3' in s and '5' in s and '7' in s

    if len(s) < len(N):

        return r(s+'3') + r(s+'5') + r(s+'7') + me

    elif s<=N:

        return me

    else:

        return 0

print((r('')))

N = eval(input())

def r(s):
    me = all(("3" in s, "5" in s, "7" in s))
    if len(s) < len(N):
        return r(s + "3") + r(s + "5") + r(s + "7") + me
    elif s <= N:
        return me
    else:
        return 0

print((r("")))

N = eval(input())

def r(s):
    me = "3" in s and "5" in s and "7" in s
    if len(s) < len(N):
        return r(s + "3") + r(s + "5") + r(s + "7") + me
    elif s <= N:
        return me
    else:
        return 0

print((r("")))

+    me = "3" in s and "5" in s and "7" in s


Input:
def solve(n, a):

    from itertools import accumulate

    inf = (400 ** 2) * (10 ** 9) + 10

    # [l,r)

    def dfs(l, r):

        if memo[l][r] != -1:

            return memo[l][r]

        if r - l == 1:

            return 0

        res = inf

        for c in range(l + 1, r):

            # [l, c), [c, r)

            res = min(res, dfs(l, c) + dfs(c, r))

        res += acc[r] - acc[l]

        memo[l][r] = res

        return res

    acc = (0,) + tuple(accumulate(a))

    memo = [[-1] * (n + 1) for _ in range(n + 1)]

    return dfs(0, n)

if __name__ == '__main__':

    n = int(eval(input()))

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

    print((solve(n, a)))

def solve(n, a):

    from itertools import accumulate

    inf = (400 ** 2) * (10 ** 9) + 10

    acc = (0,) + tuple(accumulate(a))

    cost = [[inf] * (n + 1) for _ in range(n + 1)]

    for i in range(n):

        cost[i][i + 1] = 0

    for l in range(n - 1, -1, -1):

        for r in range(l + 2, n + 1):

            for c in range(l + 1, r):

                cost[l][r] = min(cost[l][r], cost[l][c] + cost[c][r])

            cost[l][r] += acc[r] - acc[l]

    return cost[0][n]

if __name__ == '__main__':

    n = int(eval(input()))

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

    print((solve(n, a)))

def solve(n, a):
    from itertools import accumulate

    inf = (400**2) * (10**9) + 10
    # [l,r)
    def dfs(l, r):
        if memo[l][r] != -1:
            return memo[l][r]
        if r - l == 1:
            return 0
        res = inf
        for c in range(l + 1, r):
            # [l, c), [c, r)
            res = min(res, dfs(l, c) + dfs(c, r))
        res += acc[r] - acc[l]
        memo[l][r] = res
        return res

    acc = (0,) + tuple(accumulate(a))
    memo = [[-1] * (n + 1) for _ in range(n + 1)]
    return dfs(0, n)

if __name__ == "__main__":
    n = int(eval(input()))
    a = tuple(map(int, input().split()))
    print((solve(n, a)))

def solve(n, a):
    from itertools import accumulate

    inf = (400**2) * (10**9) + 10
    acc = (0,) + tuple(accumulate(a))
    cost = [[inf] * (n + 1) for _ in range(n + 1)]
    for i in range(n):
        cost[i][i + 1] = 0
    for l in range(n - 1, -1, -1):
        for r in range(l + 2, n + 1):
            for c in range(l + 1, r):
                cost[l][r] = min(cost[l][r], cost[l][c] + cost[c][r])
            cost[l][r] += acc[r] - acc[l]
    return cost[0][n]

if __name__ == "__main__":
    n = int(eval(input()))
    a = tuple(map(int, input().split()))
    print((solve(n, a)))

-            res = min(res, dfs(l, c) + dfs(c, r))

+    cost = [[inf] * (n + 1) for _ in range(n + 1)]

+                cost[l][r] = min(cost[l][r], cost[l][c] + cost[c][r])

+            cost[l][r] += acc[r] - acc[l]


Input:
n = int(eval(input()))

d = sorted(list(map(int, input().split())))

m = len(d)//2

print((d[m]-d[m-1]))

n = int(eval(input()))

d = sorted(list(map(int, input().split())))

x = d[n//2-1]

y = d[n//2]

print((y-x))

n = int(eval(input()))
d = sorted(list(map(int, input().split())))
m = len(d) // 2
print((d[m] - d[m - 1]))

n = int(eval(input()))
d = sorted(list(map(int, input().split())))
x = d[n // 2 - 1]
y = d[n // 2]
print((y - x))