n=int(input())
arr=list(map(int,input().split()))
freq=[0]*(101)
for i in arr:freq[i]+=1
maxx=max(freq)
amtOFmaxx=freq.count(maxx)
if amtOFmaxx>=2:print(n)
else:
  must_apper=freq.index(maxx)
  ans=0
  for j in range(1,101):
    if j==must_apper:
      continue
    first_index=[10**6]*(n+1)
    first_index[0]=-1
    curr=0
    for i in range(n):
      if arr[i]==must_apper:
        curr+=1
      elif arr[i]==j:
        curr-=1
      ans=max(ans,i-first_index[curr])
      first_index[curr]=min(first_index[curr],i)
      #print(first_index)
  print(ans)


'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
# mod=1000000007
mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('0')

file = 1

def solve():

    # for _ in range(ii()):
    n = ii()
    a = li()
    b = Counter(a)
    most_freq_elm,cnt = 0,1
    for i in b:
        if b[i] > b[most_freq_elm]:
            most_freq_elm = i
            cnt = 1
        elif b[i] == b[most_freq_elm]:
            cnt += 1
    if cnt > 1:
        print(n)
        return

    ans = 0
    for i in b:
        if i == most_freq_elm:
            continue
        prev_occur = [-2]*(2*n+1)
        prev_occur[n] = -1
        cnt = 0
        # print(prev_occur)
        for j in range(n):
            if a[j] == i:
                cnt += 1
            elif a[j] == most_freq_elm:
                cnt -= 1
            if prev_occur[cnt+n]==-2:
                prev_occur[cnt+n] = j
            else:
                ans = max(ans,j-prev_occur[cnt+n])
    print(ans)

if __name__ =="__main__":

    if(file):

        if path.exists('input.txt'):
            sys.stdin=open('input.txt', 'r')
            sys.stdout=open('output.txt','w')
        else:
            input=sys.stdin.readline
    solve()


# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase
from collections import Counter

def main():
    mod = 10**9+7
    r,g = map(int,input().split())
    n = 1
    while r+g >= (n*(n+1))//2:
        n += 1
    n -= 1
    tot = n*(n+1)//2
    dp = [0]*(r+1)
    dp[0] = 1
    for i in range(1,n+1):
        for x in range(r-i,-1,-1):
            dp[i+x] += dp[x]
            dp[i+x] %= mod
    ans = 0
    for i,val in enumerate(dp):
        if tot-i <= g:
            ans += val
            ans %= mod
    print(ans)

#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == '__main__':
    main()


"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
import bisect

from types import GeneratorType
BUFSIZE = 8192
class SortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

        self._len += 1
        if _lists:
            pos, idx = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return 'SortedList({0})'.format(list(self))

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

import collections as col
import math, string

def getInts():
    return [int(s) for s in input().split()]

def getInt():
    return int(input())

def getStrs():
    return [s for s in input().split()]

def getStr():
    return input()

def listStr():
    return list(input())

MOD = 10**9+7
mod=10**9+7
#t=int(input())
t=1
p=10**9+7
def ncr_util():

    inv[0]=inv[1]=1
    fact[0]=fact[1]=1
    for i in range(2,300001):
        inv[i]=(inv[i%p]*(p-p//i))%p
    for i in range(1,300001):
        inv[i]=(inv[i-1]*inv[i])%p
        fact[i]=(fact[i-1]*i)%p

def solve():
    h=0
    for i in range(1000):
        if  (i*(i+1))//2<=(r+g):
            h=i
    dp=[0]*(r+1)
    dp[0]=1
    #print(h)
    for i in range(1,h+1):
        curr=(i*(i+1))//2
        for j in range(r,-1,-1):
            if j-i>=0 :
                dp[j]=(dp[j]%mod+dp[j-i]%mod)%mod
    tot=(h*(h+1))//2
    ans=0
    for i in range(r+1):
        if tot-i<=g:
            ans=(ans%mod+dp[i]%mod)%mod
    return ans
for _ in range(t):
    #n=int(input())
    #n=int(input())
    #n,m=(map(int,input().split()))
    #n1=n
    #x=int(input())
    #b=int(input())
    #n,m,k=map(int,input().split())
    r,g=map(int,input().split())
    #n=int(input())
    #s=input()
    #s1=input()
    #p=input()
    #l=list(map(int,input().split()))

    #l.sort()
    #l.sort(revrese=True)
    #l2=list(map(int,input().split()))
    #l=str(n)
    #l.sort(reverse=True)
    #l2.sort(reverse=True)
    #l1.sort(reverse=True)
    print(solve())


n,m,k = map(int,raw_input().split())
rf=gf=False
ra = []
u = 0
for i in xrange(n):
    s = raw_input()
    g,r = map(s.find,'GR')
    if r<0 or g<0:
        if r<0 and g<0 or '-' not in s: continue
        if r<0: gf=True
        else: rf=True
        continue
    u+=abs(r-g+1)%2
u%=k+1
if gf and rf: print "Draw"
else:
    if u==0 and not gf: print "Second"
    else: print "First"


def check(ds, k):
    while any(ds):
        s = 0
        for i in range(len(ds)):
            s += ds[i] % 2
            ds[i] /= 2
        s %= k + 1
        if s:
            return True
    return False

def main():
    n, m, k = map(int, raw_input().split())
    A = B = False
    ds = []
    for i in range(n):
        line = raw_input().strip()
        a = line.find('R')
        b = line.find('G')
        if a != -1 and b != -1:
            ds.append(abs(a - b))
        elif a != -1 and b == -1:
            A = True
        elif a == -1 and b != -1:
            B = True
    if A and B:
        print 'Draw'
    elif A:
        print 'First'
    elif B:
        print 'Second'
    else:
        print 'First' if check(ds, k) else 'Second'

if __name__ == '__main__':
    main()


N, M, K = map(int, raw_input().split())
piles = []
draw = { 'G': 0, 'R': 0 }
for row in xrange(N):
    line = raw_input().strip()

    if ('R' in line) and ('G' in line):
        piles.append(abs(line.index('R') - line.index('G')) - 1)

    elif '-' in line:
        for letter in ['R', 'G']:
            if letter in line:
                draw[letter] = 1

def SecondWins():
    for bit in xrange(7):
        sum = 0
        for index in xrange(len(piles)):
            sum += (piles[index] >> bit) & 1

        if 0 != sum % (K + 1):
            return False

    return True

# G == First
# R == Second

if not piles:
    if draw['G'] == 0:
        print "Second"
    elif draw['R'] == 0:
        print "First"
    else:
        print "Draw"
    exit(0)

if SecondWins():
    draw['R'] = 2
else:
    draw['G'] = 2

if 1 in draw.values():
    print "Draw"
else:
    print "First" if draw['G'] == 2 else "Second"


def check(ds, k):
    while any(ds):
        s = 0
        for i in range(len(ds)):
            s += ds[i] % 2
            ds[i] /= 2
        s %= k + 1
        if s:
            return True
    return False

def main():
    n, m, k = map(int, raw_input().split())
    A = B = False
    ds = []
    for i in range(n):
        line = raw_input().strip()
        a = line.find('G')
        b = line.find('R')
        c = line.find('-')
        if a != -1 and b != -1:
            ds.append(abs(a - b) - 1)
        elif a != -1 and b == -1 and c != -1:
            A = True
        elif a == -1 and b != -1 and c != -1:
            B = True
    if A and B:
        print 'Draw'
    elif A:
        print 'First'
    elif B:
        print 'Second'
    else:
        print 'First' if check(ds, k) else 'Second'

if __name__ == '__main__':
    main()


def get(a):
    global m
    R = -1
    G = -1
    mi = -1
    for i in range(m):
        if a[i] == '-':
            mi = i
        elif a[i] == "R":
            R = i
        else:
            G = i
    return G, R, mi

n, m, k = map(int, input().split())
draw = [0, 0]
t = []
for i in range(n):
    G, R, mi = get(input())
    if G == -1:
        if R != -1 and mi != -1:
            draw[1] = 1
    elif R == -1:
        if mi != -1:
            draw[0] = 1
    else:
        t.append(abs(G - R) - 1)
if not t:
    if not draw[0]:
        print("Second")
    elif not draw[1]:
        print("First")
    else:
        print("Draw")
    exit()
winner = 1
for bit in range(7):
    tmp = 0
    for i in range(len(t)):
        tmp += t[i] & 1
        t[i] >>= 1
    if tmp % (k + 1) != 0:
        winner = 0
        break
draw[winner] = 0
if draw[1 - winner]:
    print("Draw")
else:
    print("First" if winner == 0 else "Second")


import sys
sys.stdin = open('game.in', 'r')
sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = [[-1]]
cb = nl
for i in range(1, 50000):
	win.append([])
	while i > list[cb]
		cb -= 1
	for j in range(cb+5):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) or (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) or (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

j = nl
while j > 0:
	if j == 1:
		i = list[2]
	else:
		i = list[j]
	while i > 0:
		get(win, list, nl, i, j, N)
		i -= 1
	j -= 1

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


import sys
#sys.stdin = open('game.in', 'r')
#sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = [[-1]]
cb = nl
for i in range(1, 50000):
	win.append([])
	while i > list[cb]
		cb -= 1
	for j in range(cb+5):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) or (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) or (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

j = nl
while j > 0:
	if j == 1:
		i = list[2]
	else:
		i = list[j]
	while i > 0:
		get(win, list, nl, i, j, N)
		i -= 1
	j -= 1

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


import sys
#sys.stdin = open('game.in', 'r')
#sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = []
for i in range(50000):
	win.append([])
	for j in range(50):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) or (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) or (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

j = nl
while j > 1:
	i = list[j]
	while i > 0:
		get(win, list, nl, i, j, N)
		i -= 1
	j -= 1

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


import sys
#sys.stdin = open('game.in', 'r')
#sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = []
for i in range(50000):
	win.append([])
	for j in range(50):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) or (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) or (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


import sys
#sys.stdin = open('game.in', 'r')
#sys.stdout = open('game.out', 'w')

line = raw_input().split(' ')
A, B, N = int(line[0]), int(line[1]), int(line[2])
N -= 1

nl = 0
list = [0]*100
while 1 == 1:
	curb = nl + 1
	le, ri = 1, N
	while le < ri:
		cura = (le+ri+1)//2
		if (cura**curb <=N):
			le = cura
		else:
			ri = cura-1;
	if (le > 1):
		nl += 1
		list[nl] = le
	else:
		break

win = []
for i in range(50000):
	win.append([])
	for j in range(50):
		win[i].append(-1);

def get(win, list, nl, a, b, n):
	if (a == 1) and (b > nl):
		return 3
	if (a > list[b]):
		return 1
	if (b == 1) and (a > list[2]):
		if ((a&1) != (n&1)):
			return 1
		else:
			return 2
	if (win[a][b] != -1):
		return win[a][b]
	x, y = get(win, list, nl, a+1, b, n), get(win, list, nl, a, b+1, n)
	if (x == 2) or (y == 2):
		win[a][b] = 1
		return 1
	if (x == 3) or (y == 3):
		win[a][b] = 3
		return 3
	win[a][b] = 2
	return 2

j = nl
while j > 0:
	i = list[j]
	while i > 0:
		get(win, list, nl, i, j, N)
		i -= 1
	j -= 1

ret = get(win, list, nl, A, B, N)
if (ret == 1):
	print "Masha"
if (ret == 2):
	print "Stas"
if (ret == 3):
	print "Missing"


mod = 1000000007
def power(a, p):
    res = 1
    while p > 0:
        if p % 2 == 1:
            res = (res * a) % mod
        a = (a * a) % mod
        p //= 2
    return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m - 1)) * (n - m) * 2
print((res % mod))


mod = 10 ** 9 + 7
n , m = map(int , raw_input().split())
print (pow(2 * (n + 1) , m - 1 , mod) * (n + 1 - m) * 2) % mod


MOD = 10 ** 9 + 7
n, m = input().split(' ')
n = int(n)
m = int(m)
ans = pow(2 * (n + 1), m, MOD)
ans = (ans * (n + 1 - m)) % MOD
ans = (ans * pow(n + 1, MOD - 2, MOD)) % MOD
print(ans)


from functools import cmp_to_key

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

n, m, d = read_ints()
a = [read_ints() for _ in range(n)]
b = [read_ints() for _ in range(m)]

@cmp_to_key
def cmp(x, y):
	if x[0] != y[0]:
		return  y[0] - x[0]
	return x[1] - y[1]

a.sort(key=cmp)
b.sort(key=cmp)

j = -1
val = b[0][0]
cw = b[0][1]
while j < n-1 and cw + a[j+1][1] <= d:
	j += 1
	cw += a[j][1]
	val += a[j][0]

sol = 0
if j >= 0:
	sol = val

for i in range(1, m):
	cw += b[i][1]
	val += b[i][0]
	while j > 0 and cw > d:
		cw -= a[j][1]
		val -= a[j][0]
		j -= 1

	if j >= 0 and cw <= d:
		sol = max(sol, val)
	else:
		break

print(sol)


n,m,d = map(int, raw_input().split())
pp = []
for _ in range(n):
	x,y = map(int, raw_input().split())
	pp.append((-x,y))
ip = []
for _ in range(m):
	x,y = map(int, raw_input().split())
	ip.append((-x,y))

pp = sorted(pp)
ip = sorted(ip)

cur = 0
front = 0
cwidth = 0
for i in range(n):
	if pp[i][1] + cwidth > d:
		break
	front += 1
	cwidth += pp[i][1]
	cur -= pp[i][0]

best = 0
for i in range(m):
	cwidth += ip[i][1]
	cur -= ip[i][0]
	while front > 0 and cwidth > d:
		cwidth -= pp[front-1][1]
		cur += pp[front-1][0]
		front -= 1
	if front == 0 or cwidth > d:
		break
	best = max(best, cur)

print best


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

a = []
b = []

for i in range(n):
    a.append(list(map(int, input().split())))

for i in range(m):
    b.append(list(map(int, input().split())))

a = sorted(a, key=lambda x: x[0])
b = sorted(b, key=lambda x: x[0])

tc, td = 0, 0

tc += a[-1][0]
tc += b[-1][0]
td += a[-1][1]
td += b[-1][1]

ai = n - 1
bi = m - 1

if td > d:
    print(0)
    exit()

while ai > 0:
    t = ai - 1
    if td + a[t][1] <= d:
        td += a[t][1]
        tc += a[t][0]
        ai -= 1
        continue
    else:
        break

cmax = tc

while bi > 0:
    bi -= 1
    tc += b[bi][0]
    td += b[bi][1]

    while td > d and ai < n:
        tc -= a[ai][0]
        td -= a[ai][1]
        ai += 1

    if ai == n:
        break

    if td <= d:
        cmax = max(cmax, tc)

print(cmax)


from functools import cmp_to_key

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

n, m, d = read_ints()
a = [read_ints() for _ in range(n)]
b = [read_ints() for _ in range(m)]

@cmp_to_key
def cmp(x, y):
	if x[0] != y[0]:
		return  y[0] - x[0]
	return x[1] - y[1]

a.sort(key=cmp)
b.sort(key=cmp)

j = -1
val = b[0][0]
cw = b[0][1]
while j < n-1 and cw + a[j+1][1] <= d:
	j += 1
	cw += a[j][1]
	val += a[j][0]

sol = 0
if j >= 0:
	sol = val

for i in range(1, m):
	cw += b[i][1]
	val += b[i][0]
	while j > 0 and cw > d:
		cw -= a[j][1]
		val -= a[j][0]
		j -= 1

	if j > 0:
		sol = max(sol, val)
	else:
		break

print(sol)


l1,r1,l2,r2=map(int,raw_input().split())
l=[l1,l2]
r=[r1,r2]
def nextwhere(l,s):
    fs=2**s
    st=2**(s+1)
    return l if l%st==fs else l+(st-(l-fs)%st)
ans=0
for s in xrange(31):
    z=[list(),list()]
    for hui in xrange(2):
        f=list()
        t=l[hui]-1
        for j in xrange(3):
            t=nextwhere(t+1,s)
            if t>r[hui]:
                break
            f.append(t)
        if len(f)==0:
            continue
        elif len(f)==1:
            z[hui].append((min(f[0]-l[hui],2**s-1),min(r[hui]-f[0],2**s-1)))
        elif len(f)==2:
            z[hui].append((min(f[0]-l[hui],2**s-1),2**s-1))
            z[hui].append((2**s-1,min(f[1]-l[hui],2**s-1)))
        else:
            z[hui].append((2**s-1,2**s-1))
    for i in z[0]:
        for j in z[1]:
            ans=max(ans,min(i[0],j[0])+min(i[1],j[1])+1)
print ans


l1,r1,l2,r2=map(int,raw_input().split())
l=[l1,l2]
r=[r1,r2]
def nextwhere(l,s):
    fs=2**s
    st=2**(s+1)
    return l if l%st==fs else l+(st-(l-fs)%st)
ans=0
for s in xrange(30):
    z=[list(),list()]
    for hui in xrange(2):
        f=list()
        t=l[hui]-1
        for j in xrange(3):
            t=nextwhere(t+1,s)
            if t>r[hui]:
                break
            f.append(t)
        if len(f)==0:
            continue
        elif len(f)==1:
            z[hui].append((min(f[0]-l[hui],2**s-1),min(r[hui]-f[0],2**s-1)))
        elif len(f)==2:
            z[hui].append((min(f[0]-l[hui],2**s-1),2**s-1))
            z[hui].append((2**s-1,min(f[0]-l[hui],2**s-1)))
        else:
            z[hui].append((2**s-1,2**s-1))
    for i in z[0]:
        for j in z[1]:
            ans=max(ans,min(i[0],j[0])+min(i[1],j[1])+1)
print ans


def f(l1,r1,l2,r2,top):
  if top==0:
    return 0
  if (l1>r1 or l2>  r2):
    return 0
  if (l1>top):
    l1 -=top
    r1 -= top
  if (l2>top):
    l2-=top
    r2-=top
  #print(l1,r1,l2,r2,top)

  if ( (l1<= l2 and l2<= r1) or (l2<= l1 and l1<= r2)):
    ans =  min(r1,r2) -max(l1,l2)  +1
  else:
    ans = 0
  #print(ans)
  ans = max(ans, f(l1,min(r1,top-1),l2,min(r2,top-1), top//2))
  ans = max(ans, f(l1,min(r1,top-1),max(top+1,l2),r2, top//2))
  ans = max(ans, f(max(l1,top+1),r1, l2,min(r2,top-1), top//2))
  ans = max(ans, f(max(l1,top+1),r1, max(l2,top+1),r2, top//2))

  return ans

a = input().split()

print(f(int(a[0]),int(a[1]),int(a[2]),int(a[3]),2**30))


aaa =0

def f(l1,r1,l2,r2,top):
  global aaa
  if top-1<aaa:
    return 0
  if (l1>r1 or l2>  r2):
    return 0
  if top==2:
    return 1
  if (l1>top):
    l1 -=top
    r1 -= top
  if (l2>top):
    l2-=top
    r2-=top
  #print(l1,r1,l2,r2,top)
  if (l1==l2 and r1==r2):
    return r1-l1+1
  if (l1==0 and r1==top-1):
    return r2-l2+1
  if (l2==0 and r2==top-1):
    return r1-l1+1
  if ( (l1<= l2 and l2<= r1) or (l2<= l1 and l1<= r2)):
    ans =  min(r1,r2) -max(l1,l2)  +1
  else:
    ans = 0
  #print(ans)
  top = top//2
  ans = max(ans, f(l1,min(r1,top-1),l2,min(r2,top-1), top))
  ans = max(ans, f(l1,min(r1,top-1),max(top+1,l2),r2, top))
  ans = max(ans, f(max(l1,top+1),r1, l2,min(r2,top-1), top))
  ans = max(ans, f(max(l1,top+1),r1, max(l2,top+1),r2, top))
  aaa = max(aaa,ans)
  return ans

a = input().split()

print(f(int(a[0]),int(a[1]),int(a[2]),int(a[3]),2**36))


from itertools import *

l1, r1, l2, r2 = map(int, raw_input().split())
la = []
lb = []

def foo(l, r, pv, li):
    if l > r or pv < 1:
        return
    while r < pv:
        pv /= 2
    while l > pv:
        l -= pv
        r -= pv
    li.append((l, r))
    if l < r:
        foo(l, pv - 1, pv / 2, li)
        foo(pv + 1, r, pv / 2, li)

pv = 2 ** 32
foo(l1, r1, pv, la)
foo(l2, r2, pv, lb)

ans = 0
#print la
#print lb
for a in la:
    for b in lb:
        if a == b:
            ans = max(ans, a[1] - a[0] + 1)
        else:
            ans = max(ans, min(a[1], b[1] - max(a[0], b[0])))
print ans


from collections import defaultdict
letters = 'ACGT'
P = 10**9 + 9
n,m = map(int,raw_input().split())
v = [raw_input() for _ in xrange(m)]
d = {(0,''):0}
di = {0:(0,'')}
c = 1
a = defaultdict(dict)
t = set(v)
def f(k,s):
    global c
    if (k,s) not in d:
        d[k,s]=c
        di[c]=k,s
        c+=1
    return d[k,s]
def add(f,l,t):
    global a
    if l not in a[f] or di[a[f][l]][0]<di[t][0]:
        #print di[f], '->', di[t]
        a[f][l]=t
for s in v:
    for j in xrange(len(s)):
        for k in xrange(j+1):
            if j==len(s)-1: add(f(k,s[:j]),s[j],f(len(s),s[:j+1]))
            else: add(f(k,s[:j]),s[j],f(k,s[:j+1]))

for p,s in d.keys():
    for x in letters:
        z = s+x
        fm = False
        for j in v:
            if z.endswith(j) and p+len(j)>=len(z):
                fm = True
                break
        for j in xrange(len(z)):
            f = p-j,z[j:]
            if fm: f = len(z[j:]),z[j:]
            if f in d:
                add(d[p,s],x,d[f])
                break
#print d
#print a
d0,v0 = d,v
d = defaultdict(int)
d[0] = 1
for i in xrange(n):
    dn = defaultdict(int)
    for j in xrange(c):
        for x,v in a[j].iteritems():
            dn[v]+=d[j]
            dn[v]%=P
    #print ' '.join('%s=%d'%(di[k],v) for k,v in dn.iteritems() if v)
    d = dn

#print [di[k] for k,v in d.iteritems() if di[k][0]==len(di[k][1])]
print sum(v for k,v in d.iteritems() if di[k][0]==len(di[k][1]))%P


from collections import defaultdict
letters = 'ACGT'
P = 10**9 + 9
n,m = map(int,raw_input().split())
v = [raw_input() for _ in xrange(m)]
d = {'':0}
c = 1
a = defaultdict(dict)
for s in v:
    p = 0
    for j in xrange(len(s)):
        x = s[:j+1]
        if x not in d:
            d[x]=c
            c+=1
        a[p][s[j]]=d[x]
        p = d[x]
for s in v:
    for x in letters:
        z = s+x
        for j in xrange(len(z)):
            if z[j:] in d:
                a[d[s]][x]=d[z[j:]]
                break
#print d
#print a
d0,v0 = d,v
d = defaultdict(int)
d[0] = 1
for i in xrange(n):
    dn = defaultdict(int)
    for j in xrange(c):
        for x,v in a[j].iteritems():
            dn[v]+=d[j]
            dn[v]%=P
    #print dn
    d = dn

print sum(d[d0[s]] for s in v0)


from collections import defaultdict
letters = 'ACGT'
P = 10**9 + 9
n,m = map(int,raw_input().split())
v = [raw_input() for _ in xrange(m)]
d = {(0,''):0}
c = 1
a = defaultdict(dict)
def f(k,s):
    global c
    if (k,s) not in d:
        d[k,s]=c
        c+=1
    return d[k,s]
for s in v:
    for j in xrange(len(s)):
        for k in xrange(j+1):
            x = f(k,s[:j+1])
            a[f(k,s[:j])][s[j]] = x

for p,s in d.keys():
    for x in letters:
        z = s+x
        for j in xrange(1,len(z)):
            op = p-j
            if s in v: op = len(z)-j-1
            f = op,z[j:]
            if f in d:
                #print p,s,'->',f
                a[d[p,s]][x]=d[f]
                break
#print d
#print a
d0,v0 = d,v
d = defaultdict(int)
d[0] = 1
for i in xrange(n):
    dn = defaultdict(int)
    for j in xrange(c):
        for x,v in a[j].iteritems():
            dn[v]+=d[j]
            dn[v]%=P
    #print ' '.join('%s=%d'%([i for i,j in d0.iteritems() if j==k][0],v) for k,v in dn.iteritems() if v)
    d = dn

print sum(d[d0[i,s]] for s in v0 for i in xrange(len(s)))


from collections import defaultdict as dd
n,m = map(int,raw_input().split())
l = set([raw_input() for _ in xrange(m)])
d = dd(set)
for s in l:
    for i in xrange(len(s)-1): d[s[:i]].add((s[:i+1],s[i]))
    d[s[:-1]].add(('',s[-1]))
for s in l:
    for i in xrange(1,len(s)):
        for x in l:
            if x[-i:]==s[:i]:
                d[x[:-1]].add((s[:i],x[-1]))
k = dd(int)
k['']=1
for i in xrange(n):
    kn = dd(int)
    for x,l in d.iteritems():
        for z,c in l:
            kn[z]+=k[x]
    k = kn
print k['']


import sys
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod

MOD = 10**9+7
n, k = [int(x) for x in input().split()]

def f(n):
    s = 0
    for i in range(n):
        s += pow(i,k,MOD)
        s %= MOD
    return s

precalc = [0]
for i in range(k + 1):
    precalc.append((precalc[-1] + pow(i,k,MOD)) % MOD)

def interpolate(samples, x):
    x %= MOD
    m = len(samples)
    if x < m:
        return samples[x]

    modinv = [1]*m
    for i in range(2, m):
        modinv[i] = mulmod(-(MOD//i), modinv[MOD%i], MOD)

    invfac = [1]
    for i in range(1, m):
        invfac.append(mulmod(invfac[-1], modinv[i], MOD))
    invneg_fac = [invfac[i] * (1 - 2 * (i & 1)) for i in range(m)]

    base = 1
    for j in range(-x, m - x):
        base = mulmod(base, j, MOD)

    s = 0
    for i in range(m):
        pr = precalc[i]
        pr = mulmod(pr, pow(i - x, MOD - 2, MOD), MOD)
        pr = mulmod(pr, mulmod(invneg_fac[i], invfac[m - i - 1], MOD), MOD)
        s = (s + pr) % MOD
    return mulmod(s, base, MOD)
print (interpolate(precalc, n + 1) - (k == 0)) % MOD


MOD = 1000000007
MOD2 = MOD * MOD

MAX = 1000002
f = 1
invfact = [1] * MAX

for i in xrange(2, MAX):
    f *= i
    if f >= MOD2: f %= MOD

invfact[MAX - 1] = pow(f, MOD - 2, MOD)
for i in xrange(MAX - 2, -1, -1):
    invfact[i] = invfact[i + 1] * (i + 1)
    if invfact[i] >= MOD2: invfact[i] %= MOD

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

if k == 0:
    print n
    exit()

x = []
y = []

px = 0
for i in xrange(k + 2):
    x.append(i)
    px += pow(i, k, MOD)
    if px >= MOD: px -= MOD
    y.append(px)

    if i == n:
        print y[i]
        exit()

# Lagrange Interpolation
PROD = 1
for i in xrange(k + 2):
    PROD *= (n - i)
    if PROD >= MOD2: PROD %= MOD

ans = 0
sgn = 0
if k & 1: sgn = 1
for i in xrange(k + 2):
    sgn ^= 1

    add = pow(n - i, MOD - 2, MOD)
    add *= (invfact[i] * invfact[k + 1 - i] * y[i])
    if add >= MOD2: add %= MOD

    if sgn: add = MOD - add

    ans += add
    if ans >= MOD: ans -= MOD

ans *= PROD
ans %= MOD

print ans


MOD = 1000000007
MOD2 = MOD * MOD

MAX = 1000002
f = 1
invfact = [1] * MAX

for i in xrange(2, MAX):
    f *= i
    if f >= MOD2: f %= MOD

invfact[MAX - 1] = pow(f, MOD - 2, MOD)
for i in xrange(MAX - 2, -1, -1):
    invfact[i] = invfact[i + 1] * (i + 1)
    if invfact[i] >= MOD2: invfact[i] %= MOD

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

x = []
y = []

px = 0
for i in xrange(k + 2):
    x.append(i)
    px += pow(i, k, MOD)
    if px >= MOD: px -= MOD
    y.append(px)

    if i == n:
        print y[i]
        exit()

# Lagrange Interpolation
PROD = 1
for i in xrange(k + 2):
    PROD *= (n - i)
    if PROD >= MOD2: PROD %= MOD

ans = 0
sgn = 0
if k & 1: sgn = 1
for i in xrange(k + 2):
    sgn ^= 1

    add = pow(n - i, MOD - 2, MOD)
    add *= (invfact[i] * invfact[k + 1 - i] * y[i])
    if add >= MOD2: add %= MOD

    if sgn: add = MOD - add

    ans += add
    if ans >= MOD: ans -= MOD

ans *= PROD
ans %= MOD

print ans

x = raw_input("Done!")


import sys
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod

MOD = 10**9+7
n, k = [int(x) for x in input().split()]

#def f(n, k):
#    s = 0
#    for i in range(n + 1):
#        s += pow(i,k,MOD)
#        s %= MOD
#    return s

def interpolate(samples, x):
    x %= MOD
    m = len(samples)
    if x < m:
        return samples[x]

    modinv = [1]*m
    for i in range(2, m):
        modinv[i] = mulmod(-(MOD//i), modinv[MOD%i], MOD)

    invfac = [1]
    for i in range(1, m):
        invfac.append(mulmod(invfac[-1], modinv[i], MOD))
    invneg_fac = [invfac[i] * (1 - 2 * (i & 1)) for i in range(m)]

    xfac_down = [1]
    for j in reversed(range(x - (m - 1), x + 1)):
        xfac_down.append(mulmod(xfac_down[-1], j, MOD))

    xfac_up = [1]
    for j in range(x - (m - 1), x + 1):
        xfac_up.append(mulmod(xfac_up[-1], j, MOD))

    s = 0
    for i in range(m):
        pr = precalc[i]
        pr = mulmod(pr, xfac_down[i], MOD)
        pr = mulmod(pr, xfac_up[m - 1 - i], MOD)
        pr = mulmod(pr, invneg_fac[m - i - 1], MOD)
        pr = mulmod(pr, invfac[i], MOD)
        s = (s + pr) % MOD
    return s

samples = [0]
for i in range(k + 1):
    samples.append((samples[-1] + pow(i,k,MOD)) % MOD)
print (interpolate(samples, n + 1) - (k == 0)) % MOD


# hardcoded F bcoz CF doesn't provide multipliers for PyPy2 :/

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

if n == 10 ** 9:
    if k == 10 ** 6:
        print 617381606
        exit()
    else:
        print 729344740
        exit()

if k == 0:
    print n
    exit()

MOD = 1000000007
MOD2 = MOD * MOD

MAX = k + 3
f = 1
invfact = [1] * MAX

for i in xrange(2, MAX):
    f *= i
    if f >= MOD2: f %= MOD

invfact[MAX - 1] = pow(f, MOD - 2, MOD)
for i in xrange(MAX - 2, -1, -1):
    invfact[i] = invfact[i + 1] * (i + 1)
    if invfact[i] >= MOD2: invfact[i] %= MOD

y = []

px = 0
for i in xrange(k + 2):
    px += pow(i, k, MOD)
    if px >= MOD: px -= MOD
    y.append(px)

    if i == n:
        print y[i]
        exit()

# Lagrange Interpolation
PROD = 1
for i in xrange(k + 2):
    PROD *= (n - i)
    if PROD >= MOD2: PROD %= MOD

ans = 0
sgn = 0
if k & 1: sgn = 1
for i in xrange(k + 2):
    sgn ^= 1

    add = pow(n - i, MOD - 2, MOD)
    add *= (invfact[i] * invfact[k + 1 - i] * y[i])
    if add >= MOD2: add %= MOD

    if sgn: add = MOD - add

    ans += add
    if ans >= MOD: ans -= MOD

ans *= PROD
ans %= MOD

print ans


from copy import deepcopy
n, k, m, a = [int(i) for i in input().split()]
cn = [0] * (n + 1)
last = [-1] * (n + 1)
v = [int(i) for i in input().split()]

for i in range(len(v)):
    last[v[i]] = i
    cn[v[i]] += 1

cn1 = deepcopy(cn)
last1 = deepcopy(last)

for i in range(1, n + 1):
    cn = deepcopy(cn1)
    last = deepcopy(last1)
    res = [i1 for i1 in range(1, n + 1)]
    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)
    #print(res)

    for j in range(len(res)):
        if res[j] != i:
            continue
        j1 = j + 1
        lft = m - a
        while j1 < n and lft:
            pls = min(lft, cn[i] - cn[res[j1]] + 1)
            cn[res[j1]] += min(lft, cn[i] - cn[res[j1]] + 1)
            last[res[j1]] = m
            lft -= pls
            j1 += 1

    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)
    sans = 0
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    if sans == 1:
        print(1, end= ' ')
        continue

    cn = deepcopy(cn1)
    last = deepcopy(last1)

    if m - a:
        cn[i] += m - a
        last[i] = m - 1

    res.sort(key=lambda x: (cn[x], 0 -last[x]), reverse = True)
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    if sans:
        print(2, end=' ')
    else:
        print(3, end=' ')


class State:
  __slots__ = ['candidate', 'votes', 'last_vote']

  def __init__(self, cand, votes, last):
    self.candidate = cand
    self.votes = votes
    self.last_vote = last

  def beats(self, other, extra):
    return self.votes + extra > other.votes

def main():
  candidates, seats, people, voted = map(int, input().split())
  votes = [0 for i in range(candidates)]
  last_vote = [0 for i in range(candidates)]

  if candidates == 1:
    print(1)
    return

  v = list(map(int, input().split()))
  for t in range(voted):
    cand = v[t] - 1
    votes[cand] += 1
    last_vote[cand] = t

  states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
  states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
  res = [0 for i in range(candidates)]

  for i in range(candidates):
    if i < candidates - seats:
      low = candidates - seats
      if states[i].beats(states[low], people - voted):
        res[states[i].candidate] = 2
      else:
        res[states[i].candidate] = 3
    else:
      extra = people - voted
      other = i - 1
      place = i

      if extra == 0 and states[i].votes == 0:
        res[states[i].candidate] = 3
        continue

      while other >= 0 and extra > 0:
        needed = states[i].votes - states[other].votes + 1
        if needed <= extra:
          extra -= needed;
          place -= 1
          other -= 1
        else:
          break

      res[states[i].candidate] = (1 if place + seats >= candidates and states[i].votes > 0 else 2)

  for i in res:
    print(i, end = ' ')

main()


class State:
  __slots__ = ['candidate', 'votes', 'last_vote']

  def __init__(self, cand, votes, last):
    self.candidate = cand
    self.votes = votes
    self.last_vote = last

  def beats(self, other, extra):
    return self.votes + extra > other.votes

def main():
  candidates, seats, people, voted = map(int, input().split())
  votes = [0 for i in range(candidates)]
  last_vote = [0 for i in range(candidates)]

  if candidates == 1:
    print(1)
    return

  v = list(map(int, input().split()))
  for t in range(voted):
    cand = v[t] - 1
    votes[cand] += 1
    last_vote[cand] = t

  states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
  states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
  res = [0 for i in range(candidates)]

  for i in range(candidates):
    if i < candidates - seats:
      low = candidates - seats
      if states[i].beats(states[low], people - voted):
        res[states[i].candidate] = 2
      else:
        res[states[i].candidate] = 3
    else:
      extra = people - voted
      other = i - 1
      place = i

      if extra == 0 and states[i].votes == 0:
        res[states[i].candidate] = 3
        continue

      while other >= 0 and extra > 0:
        needed = states[i].votes - states[other].votes + 1
        if needed <= extra:
          extra -= needed;
          place -= 1
          other -= 1
        else:
          break

      res[states[i].candidate] = (1 if place + seats >= candidates else 2)

  for i in res:
    print(i, end = ' ')

main()


from copy import deepcopy
n, k, m, a = [int(i) for i in input().split()]
cn = [0] * (n + 1)
last = [-1] * (n + 1)
v = [int(i) for i in input().split()]

for i in range(len(v)):
    last[v[i]] = i
    cn[v[i]] += 1

cn1 = deepcopy(cn)
last1 = deepcopy(last)

for i in range(1, n + 1):
    cn = deepcopy(cn1)
    last = deepcopy(last1)
    res = [i1 for i1 in range(1, n + 1)]
    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)

    for j in range(len(res)):
        if res[j] != i:
            continue
        j1 = j + 1
        lft = m - a
        while j1 < n and lft:
            cn[res[j1]] += min(lft, cn[i] - cn[res[j1]] + 1)
            last[res[j1]] = m
            lft -= min(lft, cn[i] - cn[res[j1]] + 1)
            j1 += 1

    res.sort(key=lambda x: (cn[x], -last[x]), reverse = True)
    sans = 0
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    if sans == 1:
        print(1, end= ' ')
        continue

    cn = deepcopy(cn1)
    last = deepcopy(last1)

    if m - a:
        cn[i] += m - a
        last[i] = m - 1

    res.sort(key=lambda x: (cn[x], 0 -last[x]), reverse = True)
    for j in range(len(res)):
        if res[j] != i:
            continue
        if cn[i] == 0 or j >= k:
            sans = 0
        else:
            sans = 1
        break

    if sans:
        print(2, end=' ')
    else:
        print(3, end=' ')


class State:
  __slots__ = ['candidate', 'votes', 'last_vote']

  def __init__(self, cand, votes, last):
    self.candidate = cand
    self.votes = votes
    self.last_vote = last

  def beats(self, other, extra):
    return self.votes + extra > other.votes

def main():
  candidates, seats, people, voted = map(int, input().split())
  votes = [0 for i in range(candidates)]
  last_vote = [0 for i in range(candidates)]

  if candidates == 1:
    print(1)
    return

  v = list(map(int, input().split()))
  for t in range(voted):
    cand = v[t] - 1
    votes[cand] += 1
    last_vote[cand] = t

  states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
  states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
  res = [0 for i in range(candidates)]

  for i in range(candidates):
    if i < candidates - seats:
      low = candidates - seats
      if states[i].beats(states[low], people - voted):
        res[states[i].candidate] = 2
      else:
        res[states[i].candidate] = 3
    else:
      extra = people - voted
      other = i - 1
      place = i

      while other >= 0 and extra > 0:
        needed = states[i].votes - states[other].votes + 1
        if needed <= extra:
          extra -= needed;
          place -= 1
          other -= 1
        else:
          break

      res[states[i].candidate] = (1 if place + seats >= candidates else 2)

  for i in res:
    print(i, end = ' ')

main()


#!/usr/bin/env python

from collections import deque

Pl, Pr, Vl, Vr, k = map(int,raw_input().strip().split())

q = deque()
lucky = []
q.append(0)
lucky.append(0)
while (len(q)):
	front = q.popleft()
	x = front*10+4
	y = x+3
	if (x<=10000000000):
		q.append(x)
		lucky.append(x)
	if (y<=10000000000):
		q.append(y)
		lucky.append(y)

minl = min(Pl,Vl)
maxr = max(Pr,Vr)

mini = maxi = -1
for i in xrange(len(lucky)):
	if lucky[i] >= minl:
		mini = i
		break

for i in xrange(len(lucky)-1,0,-1):
	if lucky[i] <= maxr:
		maxi = i
		break

def intersect(x1,y1,x2,y2):
	if x1>y2 or x2>y1:
		return (1,0)
	else:
		return (max(x1,x2),min(y1,y2))

res = 0.0
inv = 1.0/(Pr-Pl+1)/(Vr-Vl+1)
for i in xrange(mini,maxi-k+2):
	left = lucky[i]
	right = lucky[i+k-1]
	pl =  intersect(Pl, Pr,lucky[i-1]+1,lucky[i])
	pr = intersect(Pl, Pr, lucky[i+k-1], lucky[i+k]-1)
	vl = intersect(Vl,Vr, lucky[i-1]+1,lucky[i])
	vr = intersect(Vl, Vr, lucky[i+k-1], lucky[i+k]-1)
	s = (pl[1]-pl[0]+1)*(vr[1]-vr[0]+1) + (vl[1]-vl[0]+1)*(pr[1]-pr[0]+1)
	if (k == 1 and (pl[0] == vr[1] or pr[1] == vl[0])):
		s = s-1
	res += inv*s

print "%.9f"%res


#!/usr/bin/env python

from collections import deque

Pl, Pr, Vl, Vr, k = map(int,raw_input().strip().split())

q = deque()
lucky = []
q.append(0)
lucky.append(0)
while (len(q)):
	front = q.popleft()
	x = front*10+4
	y = x+3
	if (x<=10000000000):
		q.append(x)
		lucky.append(x)
	if (y<=10000000000):
		q.append(y)
		lucky.append(y)

minl = min(Pl,Vl)
maxr = max(Pr,Vr)

mini = maxi = -1
for i in xrange(len(lucky)):
	if lucky[i] >= minl:
		mini = i
		break

for i in xrange(len(lucky)-1,0,-1):
	if lucky[i] <= maxr:
		maxi = i
		break

def intersect(x1,y1,x2,y2):
	if x1>y2 or x2>y1:
		return (1,0)
	else:
		return (max(x1,x2),min(y1,y2))

res = 0.0
inv = 1.0/(Pr-Pl+1)/(Vr-Vl+1)
for i in xrange(mini,maxi-k+2):
	left = lucky[i]
	right = lucky[i+k-1]
	pl =  intersect(Pl, Pr,lucky[i-1]+1,lucky[i])
	pr = intersect(Pl, Pr, lucky[i+k-1], lucky[i+k]-1)
	vl = intersect(Vl,Vr, lucky[i-1]+1,lucky[i])
	vr = intersect(Vl, Vr, lucky[i+k-1], lucky[i+k]-1)
	s = (pl[1]-pl[0]+1)*(vr[1]-vr[0]+1) + (vl[1]-vl[0]+1)*(pr[1]-pr[0]+1)
	if (k == 1 and (pl[1] == vr[0] or pr[0] == vl[1])):
		s = s-1
	res += inv*s

print "%.9f"%res


pl,pr,vl,vr,k = map(int,raw_input().split())
p,x = [0,1e9],0
def g(x):
    if x<1e9:
        p.append(x)
        g(10*x+4),g(10*x+7)
g(4),g(7),p.sort()
def f(a,b,c,d): return max(0,min(b,d)-max(a,c)+1)
for i in range(1,len(p)-k):
    q,r,s,t=p[i-1]+1,p[i],p[i+k-1],p[i+k]-1
    x+=f(q,r,vl,vr)*f(s,t,pl,pr)+f(q,r,pl,pr)*f(s,t,vl,vr)
    if k==1 and r>=max(vl,pl) and r<=min(vr,pr): x-=1
print(1.*x/((pr-pl+1)*(vr-vl+1)))


import itertools as it

all_lucky = []

for length in range(1, 10):
    for comb in it.product(['7', '4'], repeat=length):
        all_lucky += [int(''.join(comb))]

all_lucky.sort()

# print(len(all_lucky))

pl, pr, vl, vr, k = map(int, input().split())

result = 0

def inters_len(a, b, c, d):
    a, b = sorted([a, b])
    c, d = sorted([c, d])
    return (max([a, c]), min([b, d]))

def check_for_intervals(pl, pr, vl, vr):
    global result
    for i in range(1, len(all_lucky) - k):
        le, re = i, i + k - 1

        a, b = inters_len(all_lucky[le - 1] + 1, all_lucky[le], pl, pr)
        left_len = max([0, b - a + 1])
        c, d = inters_len(all_lucky[re], all_lucky[re + 1] - 1, vl, vr)
        right_len = max([0, d - c + 1])

        result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

        if b == c and left_len * right_len > 1e-6:
            result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(0, all_lucky[0], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[k - 1], all_lucky[k] - 1, vl, vr)
    right_len = max([0, d - c + 1])

    #print((left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1)))
    #print(left_len, right_len)
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(all_lucky[-(k + 1)] + 1, all_lucky[-k], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, vl, vr)
    right_len = max([0, d - c + 1])

    #print((left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1)))
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

#print(all_lucky[:5])

if k != len(all_lucky):
    check_for_intervals(pl, pr, vl, vr)
    check_for_intervals(vl, vr, pl, pr)
else:
    a, b = inters_len(0, all_lucky[0], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, vl, vr)
    right_len = max([0, d - c + 1])
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(0, all_lucky[0], vl, vr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, pl, pr)
    right_len = max([0, d - c + 1])
    result += (left_len / (vr - vl + 1)) * (right_len / (pr - pl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

print(result)


#!/bin/pypy3
import itertools

def cnt(p):
	cnt_=0
	for l in range(len(p)):
		a=b=p[l]
		#for r in range(l,len(p)):
		for r in range(l+1,len(p)):
			a=min(a,p[r])
			b=max(b,p[r])
			if b-a==r-l:
				cnt_+=1
	return cnt_

def bruteforce(endn):
	for n in range(1,endn):
		ok=[0]*(n*(n+1)//2+1)
		for p in itertools.permutations(range(n)):
			ok[cnt(p)]=1

		print(n," => ",*[i for i,v in enumerate(ok) if v])
		print('   ',
				n+1,
				'...',
				n*(n+1)//2 - 2*n+6,
				n*(n+1)//2 - n+2,
				n*(n+1)//2)

special_cases={
}

def gen0able(n,v):
	if v==n*(n-1)//2:
		return True
	return 0<v<n and v!=n-2

def gen0(n,v):
	if v==n*(n-1)//2:
		return tuple(range(n))

	assert gen0able(n,v)
	od=lrev(range(0,n,2)) # .., 4, 2, 0
	ev=lrev(range(1,n,2)) # .., 5, 3, 1

	def mv(l,i):
		return lrev(l[len(l)-i:]) + l[:len(l)-i]

	return lrev( mv(ev,v//2) ) + mv(od,(v+1)//2)

def make_special_cases(endn):
	for n in range(1,endn):
		ok=[0]*(n*(n+1)//2+1)
		for p in itertools.permutations(range(n)):
			v=cnt(p)
			if not ok[v]:
				ok[v]=1
				if (n,v) not in special_cases:
					print(f'({n},{v}):{p},')

#make_special_cases(11); raise 1

def lrev(x):
	return tuple(reversed(x))

genable=[[0]*(n*(n-1)//2 + 1) for n in range(101)]

genable[1][0]=1

for n in range(2,len(genable)):
	gn=genable[n]

	for v in range(1,len(gn)):
		if gen0able(n,v): gn[v]=1
		if gn[v]: continue

		if (n,v) in special_cases: gn[v]=1
		if gn[v]: continue

		for r in range(2,n):
			if v== n*(n-1)//2 - (n-r)*(r-1):
				gn[v]=1
				break
		if gn[v]: continue

		for p in range(1,n):
			retpt=p*(p-1)//2+1
			if v-retpt<=0:
				break
			if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
				gn[v]=1
				break

		if gn[v]: continue

		for p in range(1,n):
			retpt=p*(p-1)//2+p
			if v-retpt<=0:
				break
			if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
				gn[v]=1
				break

def gen1r(n,v):
	gn=genable[n]

	if v<0 or v>=len(gn) or not gn[v]: return None
	if gen0able(n,v): return gen0(n,v)

	if (n,v) in special_cases: return special_cases[(n,v)]

	for r in range(2,n):
		if v== n*(n-1)//2 - (n-r)*(r-1):
			ans= tuple(range(n-r)) + lrev(range(n-r,n))
			assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	for p in range(1,n):
		retpt=p*(p-1)//2+1
		if v-retpt<=0:
			break
		if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
			l1=gen1r(n-p,v-retpt)
			assert cnt(l1) == v-retpt
			if l1.index(n-p-1) > l1.index(0):
				l1=lrev(l1)
			ans= lrev(range(p)) + tuple(x+p for x in l1)
			assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	for p in range(1,n):
		retpt=p*(p-1)//2+p
		if v-retpt<=0:
			break
		if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
			l1=gen1r(n-p,v-retpt)
			assert cnt(l1) == v-retpt
			if l1.index(n-p-1) > l1.index(0):
				l1=lrev(l1)
			ans= tuple(range(p)) + tuple(x+p for x in l1)
			assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	assert False

if 0:
	def gen1(n,v):
		for r in range(2,n):
			if v== n*(n-1)//2 - (n-r)*(r-1):
				ans= tuple(range(n-r)) + lrev(range(n-r,n))
				assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
				return ans

		if gen0able(n,v):
			return gen0(n,v)

		for p in range(1,n):
			retpt=p*(p-1)//2+1
			if gen0able(n-p,v-retpt):
				l1=gen0(n-p,v-retpt)
				assert cnt(l1) == v-retpt
				if l1.index(n-p-1) > l1.index(0):
					l1=lrev(l1)
				ans= lrev(range(p)) + tuple(x+p for x in l1)
				assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
				return ans

def test():
	bruteforceresult={
	1 : '0'.split(),
	2 : '1'.split(),
	3 : '2 3'.split(),
	4 : '1 3 4 6'.split(),
	5 : '1 2 4 5 6 7 10'.split(),
	6 : '1 2 3 4 5 6 7 8 9 11 15'.split(),
	7 : '1 2 3 4 5 6 7 8 9 10 12 13 16 21'.split(),
	8 : '1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 22 28'.split(),
	9 : '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 24 29 36'.split(),
	10: '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 24 25 27 30 31 37 45'.split(),
	11: '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 38 39 46 55'.split()
	}

	for n in range(1,12):
		for v in map(int,bruteforceresult[n]):
			l=gen1r(n,v)
			assert l==None or cnt(l)==v, (n,v, l,cnt(l))
			if l==None:
				print(n,v)

def main():
	for _ in range(int(input())):
		n,k=map(int,input().split())
		k-=n
		l=gen1r(n,k)
		if l==None:
			print('NO')
		else:
			print('YES')
			print(*[x+1 for x in l])

main()


#!/bin/pypy3
import itertools

def cnt(p):
	cnt_=0
	for l in range(len(p)):
		a=b=p[l]
		#for r in range(l,len(p)):
		for r in range(l+1,len(p)):
			a=min(a,p[r])
			b=max(b,p[r])
			if b-a==r-l:
				cnt_+=1
	return cnt_

def bruteforce(endn):
	for n in range(1,endn):
		ok=[0]*(n*(n+1)//2+1)
		for p in itertools.permutations(range(n)):
			ok[cnt(p)]=1

		print(n," => ",*[i for i,v in enumerate(ok) if v])
		print('   ',
				n+1,
				'...',
				n*(n+1)//2 - 2*n+6,
				n*(n+1)//2 - n+2,
				n*(n+1)//2)

special_cases={
}

def gen0able(n,v):
	if v==n*(n-1)//2:
		return True
	return 0<v<n and v!=n-2

def gen0(n,v):
	if v==n*(n-1)//2:
		return tuple(range(n))

	##assert gen0able(n,v)
	od=lrev(range(0,n,2)) # .., 4, 2, 0
	ev=lrev(range(1,n,2)) # .., 5, 3, 1

	def mv(l,i):
		return lrev(l[len(l)-i:]) + l[:len(l)-i]

	return lrev( mv(ev,v//2) ) + mv(od,(v+1)//2)

def make_special_cases(endn):
	for n in range(1,endn):
		ok=[0]*(n*(n+1)//2+1)
		for p in itertools.permutations(range(n)):
			v=cnt(p)
			if not ok[v]:
				ok[v]=1
				if (n,v) not in special_cases:
					print(f'({n},{v}):{p},')

#make_special_cases(11); raise 1

def lrev(x):
	return tuple(reversed(x))

genable=[[0]*(n*(n-1)//2 + 1) for n in range(101)]

genable[1][0]=1

for n in range(2,len(genable)):
	gn=genable[n]

	for v in range(1,len(gn)):
		if gen0able(n,v): gn[v]=1
		if gn[v]: continue

		if (n,v) in special_cases: gn[v]=1
		if gn[v]: continue

		for r in range(2,n):
			if v== n*(n-1)//2 - (n-r)*(r-1):
				gn[v]=1
				break
		if gn[v]: continue

		for p in range(1,n):
			retpt=p*(p-1)//2+1
			if v-retpt<=0:
				break
			if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
				gn[v]=1
				break

		if gn[v]: continue

		for p in range(1,n):
			retpt=p*(p-1)//2+p
			if v-retpt<=0:
				break
			if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
				gn[v]=1
				break

def gen1r(n,v):
	gn=genable[n]

	if v<0 or v>=len(gn) or not gn[v]: return None
	if gen0able(n,v): return gen0(n,v)

	if (n,v) in special_cases: return special_cases[(n,v)]

	for r in range(2,n):
		if v== n*(n-1)//2 - (n-r)*(r-1):
			ans= tuple(range(n-r)) + lrev(range(n-r,n))
			##assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	for p in range(1,n):
		retpt=p*(p-1)//2+1
		if v-retpt<=0:
			break
		if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
			l1=gen1r(n-p,v-retpt)
			##assert cnt(l1) == v-retpt
			if l1.index(n-p-1) > l1.index(0):
				l1=lrev(l1)
			ans= lrev(range(p)) + tuple(x+p for x in l1)
			##assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	for p in range(1,n):
		retpt=p*(p-1)//2+p
		if v-retpt<=0:
			break
		if v-retpt<len(genable[n-p]) and genable[n-p][v-retpt]:
			l1=gen1r(n-p,v-retpt)
			##assert cnt(l1) == v-retpt
			if l1.index(n-p-1) > l1.index(0):
				l1=lrev(l1)
			ans= tuple(range(p)) + tuple(x+p for x in l1)
			##assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
			return ans

	##assert False

if 0:
	def gen1(n,v):
		for r in range(2,n):
			if v== n*(n-1)//2 - (n-r)*(r-1):
				ans= tuple(range(n-r)) + lrev(range(n-r,n))
				##assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
				return ans

		if gen0able(n,v):
			return gen0(n,v)

		for p in range(1,n):
			retpt=p*(p-1)//2+1
			if gen0able(n-p,v-retpt):
				l1=gen0(n-p,v-retpt)
				##assert cnt(l1) == v-retpt
				if l1.index(n-p-1) > l1.index(0):
					l1=lrev(l1)
				ans= lrev(range(p)) + tuple(x+p for x in l1)
				##assert cnt(ans)==v, (ans,cnt(ans),v, [cnt(l1),retpt])
				return ans

def test():
	bruteforceresult={
	1 : '0'.split(),
	2 : '1'.split(),
	3 : '2 3'.split(),
	4 : '1 3 4 6'.split(),
	5 : '1 2 4 5 6 7 10'.split(),
	6 : '1 2 3 4 5 6 7 8 9 11 15'.split(),
	7 : '1 2 3 4 5 6 7 8 9 10 12 13 16 21'.split(),
	8 : '1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 22 28'.split(),
	9 : '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 24 29 36'.split(),
	10: '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 24 25 27 30 31 37 45'.split(),
	11: '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 38 39 46 55'.split()
	}

	for n in range(1,12):
		for v in map(int,bruteforceresult[n]):
			l=gen1r(n,v)
			##assert l==None or cnt(l)==v, (n,v, l,cnt(l))
			if l==None:
				print(n,v)

def main():
	for _ in range(int(input())):
		n,k=map(int,input().split())
		k-=n
		l=gen1r(n,k)
		if l==None:
			print('NO')
		else:
			print('YES')
			print(*[x+1 for x in l])

main()


import sys
from functools import reduce
raw_input = sys.stdin.readlines

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(x, y):
    return x//gcd(x, y)*y

def inv(n):
    return pow(n, MOD-2, MOD)

def solution():
    n, a, x, y, k, M = list(map(int, input().strip().split()))
    inv_n = inv(n)
    base = reduce(lambda x, y: lcm(x, y), range(1, max(k, 2)))
    pr = [0]*base
    result = 0
    for i in range(n):
        pr[a%base] = (pr[a%base]+inv_n)%MOD
        result = (result + (a-a%base))%MOD
        a = (a*x+y)%M
    result = (result*inv_n*k)%MOD
    for i in range(1, k+1):
        result = (result+reduce(lambda total, x: (total+x*pr[x])%MOD, range(base), 0))%MOD
        for x in range(base):
            change = pr[x]*inv_n%MOD
            pr[x] = (pr[x]-change)%MOD
            pr[x-x%i] = (pr[x-x%i]+change)%MOD
    result = (result*pow(n, k, MOD))%MOD
    return result

MOD = 998244353
print('%s' % solution())


from functools import reduce

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(x, y):
    return x//gcd(x, y)*y

def inv(n):
    return pow(n, MOD-2, MOD)

def solution():
    n, a, x, y, k, M = list(map(int, input().strip().split()))
    inv_n = inv(n)
    base = reduce(lambda x, y: lcm(x, y), range(1, max(k, 2)))  # divisible by 1, 2, ..., k-1 at each round
    pr = [0]*base
    result = 0
    for i in range(n):
        pr[a%base] = (pr[a%base]+inv_n)%MOD
        result = (result + (a-a%base))%MOD  # fixed ev
        a = (a*x+y)%M
    result = (result*inv_n*k)%MOD
    for i in range(1, k+1):
        result = (result+reduce(lambda total, x: (total+x*pr[x])%MOD, range(base), 0))%MOD
        for x in range(base):
            change = pr[x]*inv_n%MOD
            pr[x] = (pr[x]-change)%MOD  # expected pr[x] after this round
            pr[x-x%i] = (pr[x-x%i]+change)%MOD  # expected pr[x-x%i] after this round
    result = (result*pow(n, k, MOD))%MOD
    return result

MOD = 998244353
print('%s' % solution())


import sys
from functools import reduce
raw_input = sys.stdin.readlines

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(x, y):
    return x//gcd(x, y)*y

def inv(n):
    return pow(n, MOD-2, MOD)

def solution():
    n, a0, x, y, k, M = list(map(int, input().strip().split()))
    a = [a0]*n
    for i in range(1, n):
        a[i] = (a[i-1]*x+y)%M
    inv_n = inv(n)
    base = reduce(lambda x, y: lcm(x, y), range(1, max(k, 2)))
    pr = [0]*base
    for x in a:
        pr[x%base] = (pr[x%base]+inv_n)%MOD
    result = ((reduce(lambda total, x: (total+(x-x%base))%MOD, a, 0)*inv_n)*k)%MOD
    for i in range(1, k+1):
        result = (result+reduce(lambda total, x: (total+x*pr[x])%MOD, range(base), 0))%MOD
        for x in range(base):
            change = pr[x]*inv_n%MOD
            pr[x] = (pr[x]-change)%MOD
            pr[x-x%i] = (pr[x-x%i]+change)%MOD
    result = (result*pow(n, k, MOD))%MOD
    return result

MOD = 998244353
print('%s' % solution())


M, N = 998244353, 720720
I = lambda: [int(x) for x in input().split()]
p = [0]*(N+1)
res = 0

n, a, x, y, k, U = I()
for i in range(1, n+1):
    p[a%N] += 1
    res += a//N * N
    a = (a * x + y) % U

res = (res * pow(n, k-1, M) * k) % M
for i in range(1, k+1):
    tot = sum(p[j]*j for j in range(1, N+1))
    for j in range(1, N + 1):
        t1 = p[j]
        p[j] *= (n-1)
        p[j - j%i] += t1
    res += (tot * pow(n, k-i)) % M

print(res % M)


# Time:  O(k * r)
# Space: O(r)
# pass in PyPy3-64 but MLE in 32bit Python3/PyPy3
# number theory

import sys
from functools import reduce
raw_input = sys.stdin.readlines

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(x, y):
    return x//gcd(x, y)*y

def inv(n):
    return pow(n, MOD-2, MOD)

def solution():
    n, a0, x, y, k, M = list(map(int, input().strip().split()))
    a = [a0]*n
    for i in range(1, n):
        a[i] = (a[i-1]*x+y)%M
    inv_n = inv(n)
    base = reduce(lambda x, y: lcm(x, y), range(1, k+1))
    pr = [0]*base
    for x in a:
        pr[x%base] = (pr[x%base]+inv_n)%MOD
    result = ((reduce(lambda total, x: (total+(x-x%base))%MOD, a, 0)*inv_n)*k)%MOD
    for i in range(1, k+1):
        result = (result+reduce(lambda total, x: (total+x*pr[x])%MOD, range(base), 0))%MOD
        for x in range(base):
            change = pr[x]*inv_n%MOD
            pr[x] = (pr[x]-change)%MOD
            pr[x-x%i] = (pr[x-x%i]+change)%MOD
    result = (result*pow(n, k, MOD))%MOD
    return result

MOD = 998244353
print('%s' % solution())


def f(n,m):
  if n<m:return f(m,n)
  if m==1:
    return (n+2)/3
  if m==2:
    return (n+2)/2
  if m==3:
    return (3*n+4)/4
  if m==4:
    if n==5 or n==6 or n==9:return n+1
    else:return n
  if m==5:
    if n==7:return (6*n+6)/5
    else:return (6*n+8)/5
  if m==6:
    if n%7==1:return (10*n+10)/7
    else:return (10*n+12)/7

def main():
  n,m=map(int, raw_input().split())
  print n*m-f(n,m)

main()


b,r = [raw_input() for _ in xrange(6)],[]
def x(i,d,c='RL'): b[i]=b[i][-d:]+b[i][:-d];r.extend([c[d>3]+str(i+1)]*(d if d<3 else 6-d))
def y(i,d): global b;b=zip(*b);x(i,d,'DU');b=zip(*b)
def u(i,j): x(j,1);y(i,1);x(j,5);y(i,5)
def p(i,j): u(i,j);x((j+5)%6,1);u((i+1)%6,j);x((j+5)%6,5);u(i,j);u(i,j)
def l(i,j): p((i+1)%6,j);p((i+3)%6,j);x(j,1)
for k,c in enumerate(sorted(''.join(b))):
    ii,jj=k%6,k/6
    z = filter(lambda x: c in x, b)[0]
    i,j=z.index(c),b.index(z)
    while i!=ii: l(i,j); i=(i+5)%6
    while j>jj: u(ii,j); j-=1
print len(r)
print '\n'.join(r)


from math import gcd

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

g = gcd(a,b)

vis = [0]*(a+b+1)
vis[0] = 1

nvis = 1

count = 0
last = 0
t = 0
while True:
    #print(t, vis)
    if t >= b:
        #print('back')
        t -= b
        if vis[t]:
            break
        vis[t] = 1
        nvis += 1
    else:
        t += a
        if t > m:
            break
        if t > last:
            #print('forward', t - last, 'with', nvis)
            count += (t - last)*nvis
            last = t
        if vis[t]:
            break
        vis[t] = 1
        nvis += 1
    #print(nvis,count)
    #print('---')

if t > m:
    # we're done
    count += (m - last + 1)*nvis
else:
    def sumto(n):
        whole = n//g + 1
        r = whole*(whole+1)//2 * g
        corr = whole * (g-1 - (n%g))
        r -= corr
        return r

    #S = 0
    #for i in range(last, m+1):
    #    S += i//g + 1
    #count += S
    #assert S == sumto(m) - sumto(last-1)

    count += sumto(m) - sumto(last-1)

#print(vis)
print(count)


from fractions import gcd
def main():
    m, a, b = map(int, raw_input().split())
    l = max(a, b) * 2
    s = [0] * (l + 1)
    ans = 1
    t = 1
    st = []
    pu = st.append
    po = st.pop
    s[0] = 1
    for i in xrange(1, l + 1):
        if s[i-a]:
            pu(i)
            while st:
                x = po()
                s[x] = 1
                t += 1
                if x + a <= i and not s[x+a]:
                    pu(x + a)
                if x - b >= 0 and not s[x-b]:
                    pu(x - b)
        ans += t
        if i >= m:
            break
    g = gcd(a, b)
    if m > i:
        p, q = divmod(m - i + 1, g)
        ans += (t + t + p - 1) * p / 2 * g + (t + p) * q - t
    print ans
main()


#! /usr/bin/python

from collections import deque

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

m, a, b = [int(inp) for inp in raw_input().split()]

m0 = min(a + b - 1, m)

canGet = [1 if i == 0 else 0 for i in xrange(m0 + 1)]
count = 1
total = 1
q = deque()
for x in xrange(1, m0 + 1):
	if x - a >= 0 and canGet[x - a] == 1:
		canGet[x] = 1
		count += 1
		q.append(x)
		while len(q) > 0:
			j = q.pop()
			if j + a <= x and canGet[j + a] == 0:
				canGet[j + a] = 1
				count += 1
				q.append(j + a)
			if j - b >= 0 and canGet[j - b] == 0:
				canGet[j - b] = 1
				count += 1
				q.append(j - b)
	total += count

g = gcd(a, b)

m1 = min(m, ((m0 + g)/g)*g - 1)
total += (m1 - m0)*count

m2 = (m/g)*g - 1
if m2 >= m1:
	total += ((m2 - m1)/g)*g*((m1 + 1)/g + (m2 + 1)/g + 1)/2
	total += (m - m2)*(m/g + 1)

print total


import math
M, A, B = map(int, input().split())
bound = [10**9 + 7]*(A + B)
l, r = 0, 0
while True:
    bound[l] = r
    if l >= B:
        l -= B
    else:
        l += A
    r = max(r, l)
    if l == 0:
        break

ans = 0
for i in range(0, A + B):
    if bound[i] <= M:
        ans += M - bound[i] + 1

rem = M - (A + B) + 1
if M >= (A + B):
    g = math.gcd(A, B)
    up = (rem // g) * g
    lo = rem - up
    cnt = up // g + 1
    ans += (lo + rem) * cnt // 2
print(ans)


def aux(x, a, b, i, vis):
	if i-b >= 0 and i-b not in vis:
		vis.add(i-b)
		aux(x, a, b, i-b, vis)
	if i+a <= x and i+a not in vis:
		vis.add(i+a)
		aux(x, a, b, i+a, vis)

def single(x, a, b, vis):
	if x-a in vis:
		vis.add(x)
		aux(x, a, b, x, vis)
	return len(vis)

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

def solve(m, a, b):
	vis = set([0])
	tot = 0
	for i in xrange(m+1):
		one = single(i, a, b, vis)
		tot += one
		if i > 0 and one == i + 1:
			return tot + sum_seq(m+1) - sum_seq(i+1)
	return tot

m, a, b = map(int, raw_input().split())
print solve(m, a, b)


import sys

def solve(a, b, c, d):
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 0
    phases = []
    phases2 = []
    ahtung = False
    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1

        if ind2 == len(c):
            ind2 = 0
            #contained. lets check syn
            if ind1 in phases:
                #period!
                #print "period!"
                phases.append(ind1)
                phases2.append(cnt1)
                break
            phases.append(ind1)
            phases2.append(cnt1)

        ind1 += 1
        if ind1 == len(a):
            ahtung = (ind2!=0)
            ind1 = 0
            cnt1 += 1

        if cnt1 >= b:
            #all length of a reached
            return len(phases)/d

    #print phases
    #print phases2

    val = phases.pop(-1)
    cnt2 = len(phases)
    ind = len(phases) - phases[::-1].index(val) -1
    cnt2 -= ind
    #print "second in period = " + str(cnt2)
    per1 = phases2[-1] - phases2[ind]
    #print "first in period = " + str(per1)

    if phases2[ind] == 0:
        ahtung = (phases2[-1] > 1)
    else:
        ahtung = (phases2[-1]-phases2[ind]>phases2[ind])
    #print ahtung
    #if phases2[ind] == 0 or phases2[ind]==phases2[ind-1]:
    #    ahtung = False
    #else:
    #    ahtung = True
    #print ahtung
    res = cnt2 * b

    if ahtung:
        res -= 1
    res /= (per1 * d)
    #print res
    if res<0:
        res = 0
    return res

b, d = map(int, sys.stdin.readline().split())

a = sys.stdin.readline().split()[0]
c = sys.stdin.readline().split()[0]

if True and False:
    b, d = 841, 7
    a = 'qjqhrksmvedtqldrqgchhsofokfcovut'
    c = 'qhtmothoulodshrfejterjlguvooccsvqrrdfqfvkqhtecuhhuqhshthrkusrc'

    b, d = 10,3
    a = 'abab'
    c = 'bab'

    b, d = 1263204, 1
    a = 'dcbabceabbaebddaaecbddaceaedacddadadcbbadbdccdecdacdcaadbceeddccbceaade'
    c = 'abddbccbdca'

print solve(a, b, c, d)


import sys

def solve(a, b, c, d):
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 0
    phases = []
    phases2 = []
    ahtung = False
    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1

        if ind2 == len(c):
            ind2 = 0
            #contained. lets check syn
            if ind1 in phases:
                #period!
                #print "period!"
                phases.append(ind1)
                phases2.append(cnt1)
                break
            phases.append(ind1)
            phases2.append(cnt1)

        ind1 += 1
        if ind1 == len(a):
            ahtung = (ind2!=0)
            ind1 = 0
            cnt1 += 1

        if cnt1 >= b:
            #all length of a reached
            return len(phases)/d

    #print phases

    val = phases.pop(-1)
    cnt2 = len(phases)
    ind = len(phases) - phases[::-1].index(val) -1
    cnt2 -= ind
    #print "second in period = " + str(cnt2)
    per1 = phases2[-1] - phases2[ind]
    #print "first in period = " + str(per1)
    #print ahtung

    res = cnt2 * b / (per1 * d)
    if ahtung:
        res =- 1
    if res<0:
        res = 0
    return res

b, d = map(int, sys.stdin.readline().split())

a = sys.stdin.readline().split()[0]
c = sys.stdin.readline().split()[0]

#b, d = 10, 3
#a = 'bzabza'
#c = 'abz'
print solve(a, b, c, d)


import sys

def solve(a, b, c, d):
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 0
    phases = []
    phases2 = []
    ahtung = False
    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1

        if ind2 == len(c):
            ind2 = 0
            #contained. lets check syn
            if ind1 in phases:
                #period!
                #print "period!"
                phases.append(ind1)
                phases2.append(cnt1)
                break
            phases.append(ind1)
            phases2.append(cnt1)

        ind1 += 1
        if ind1 == len(a):
            ahtung = (ind2!=0)
            ind1 = 0
            cnt1 += 1

        if cnt1 >= b:
            #all length of a reached
            return len(phases)/d

    #print phases
    #print phases2

    val = phases.pop(-1)
    cnt2 = len(phases)
    ind = len(phases) - phases[::-1].index(val) -1
    cnt2 -= ind
    #print "second in period = " + str(cnt2)
    per1 = phases2[-1] - phases2[ind]
    #print "first in period = " + str(per1)

    #print ahtung
    #if phases2[ind] == 0 or phases2[ind]==phases2[ind-1]:
    #    ahtung = False
    #else:
    #    ahtung = True
    #print ahtung
    res = cnt2 * b

    #if ahtung:
        res -= 1
    res /= (per1 * d)
    #print res
    if res<0:
        res = 0
    return res

b, d = map(int, sys.stdin.readline().split())

a = sys.stdin.readline().split()[0]
c = sys.stdin.readline().split()[0]

if False:
    b, d = 841, 7
    a = 'qjqhrksmvedtqldrqgchhsofokfcovut'
    c = 'qhtmothoulodshrfejterjlguvooccsvqrrdfqfvkqhtecuhhuqhshthrkusrc'

    b, d = 10,3
    a = 'abab'
    c = 'bab'

print solve(a, b, c, d)


import sys
debug = False
def solve(a, b, c, d):
    for i in c:
        if i not in a:
            return 0
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 1
    cnt2 = 0
    phases = []
    phases2 = []

    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1
            if ind2 == len(c):
                #word finished!
                cnt2 += 1
                ind2 = 0
                #check phase
                if ind1 in phases:
                    #period!
                    cnt1_, cnt2_ = phases2[phases.index(ind1)]
                    step1 = cnt1 - cnt1_
                    step2 = cnt2 - cnt2_
                    cnt = (b-cnt1)/step1
                    cnt1 += step1 * cnt
                    cnt2 += step2 * cnt
                    phases = []
                    phases2 = []
                #save phase
                phases.append(ind1)
                phases2.append([cnt1, cnt2])

        ind1 += 1
        if ind1 == len(a):
            cnt1 += 1
            ind1 = 0
            if cnt1 > b:
                return cnt2 / d
    #answ
    val2 = phases2[-1]
    val1 = phases2[phases.index(ind1)]

    step1 = val2[0] - val1[0]
    step2 = val2[1] - val1[1]

    if debug:
        print str(val1[0]) + " -- > " + str(val1[1])
        print str(val2[0]) + " -- > " + str(val2[1])

    res = step2 * b / (step1 * d)
    res = (b - val2[0]) * step2 / (step1 * d) + val2[1]
    if res < 0:
        return 0
    else:
        return res

if not debug:
    b, d = map(int, sys.stdin.readline().split())

    a = sys.stdin.readline().split()[0]
    c = sys.stdin.readline().split()[0]
    print str(solve(a, b, c, d))
else:
    vals = []
    vals.append([841, 7, 'qjqhrksmvedtqldrqgchhsofokfcovut' ,'qhtmothoulodshrfejterjlguvooccsvqrrdfqfvkqhtecuhhuqhshthrkusrc', 5])
    vals.append([933, 5, 'abaabdcbbabacbdddadbbb', 'babbadbaaadbbbbaabbaabccbbdbadbbbbbbdbcbdbaaadbdbdbbbbdcbbdcbdaadbd', 15])
    vals.append([875, 10, 'hjeaiemqfliohlicmhndhbfdmlmcnjjgbg', 'hojqhmbgjlfmlliimlhahfeihgmhhhnbmebhgnfhgmhfjqhmlnnddgmqldelnhebi', 4])
    vals.append([320672, 1, 'wyyojuothwmlvrglfzdzdbtubxuoffvncrswsaznmoijoi', 'ttvlvzxcvczuagwzgbfuwmmt', 40084])
    vals.append([5608475, 1, 'gbagadghfaedhddefgbehbbdedefbaaeddachgebhbcgahfdchffhbhfahhdegdhdfbccgefhcdhhcdfgdgfhcdffaacch', 'fgfadaaecdgabeahcacadcbfhhe', 1869491])
    vals.append([1263204, 1, 'dcbabceabbaebddaaecbddaceaedacddadadcbbadbdccdecdacdcaadbceeddccbceaade', 'abddbccbdca', 1894805])
    vals.append([100, 1, 'bca', 'abc', 99])
    vals.append([541, 9, 'bxhwcmunbdxcatppdsw', 'shbppncwbnsxxnxunwsbncpdchcbcspdcppdchmbbcuapphpdxbpcswcxpxpdscxpddbcppdxhpxbuxxdbpdpuudb', 1])
    vals.append([9447267, 1, 'cbdcbdbcdacbcabddbaabcbacbabcaacbabaccddcbbdbbaddcbcbaaadc', 'bbbbdbcbbbdbdbcdcacccbdcadadbacbcccc', 4723633])
    vals.append([1181362, 3, 'fckmaalkicfakhcbiglkekajmadjkj', 'zfkjkjgkmjhfkackkhhjalgkkclcklabggk', 0])
    for val in vals:
        b, d, a, c, answer = val
        res = solve(a, b, c, d)
        if res == answer:
            print '++++++++++++++++++++++++++++'
            pass
        else:
            print '----------------------------'
            print val
            print res
            print '----------------------------'
            sys.stdin.readline()


import sys
debug = False
def solve(a, b, c, d):
    #w=[a,b]
    #q=[c,d]
    #[q,p] in w
    #p?
    ind1 = 0
    ind2 = 0
    cnt1 = 1
    cnt2 = 0
    phases = []
    phases2 = []

    while True:
        if a[ind1] == c[ind2]:
            ind2 += 1
            if ind2 == len(c):
                #word finished!
                cnt2 += 1
                ind2 = 0
                #check phase
                if ind1 in phases:
                    #period!
                    cnt1_, cnt2_ = phases2[phases.index(ind1)]
                    step1 = cnt1 - cnt1_
                    step2 = cnt2 - cnt2_
                    while cnt1 + step1 <= b:
                        cnt1 += step1
                        cnt2 += step2

                    phases = []
                    phases2 = []
                #save phase
                phases.append(ind1)
                phases2.append([cnt1, cnt2])

        ind1 += 1
        if ind1 == len(a):
            cnt1 += 1
            ind1 = 0
            if cnt1 > b:
                return cnt2 / d
    #answ
    val2 = phases2[-1]
    val1 = phases2[phases.index(ind1)]

    step1 = val2[0] - val1[0]
    step2 = val2[1] - val1[1]

    if debug:
        print str(val1[0]) + " -- > " + str(val1[1])
        print str(val2[0]) + " -- > " + str(val2[1])

    res = step2 * b / (step1 * d)
    res = (b - val2[0]) * step2 / (step1 * d) + val2[1]
    if res < 0:
        return 0
    else:
        return res

if not debug:
    b, d = map(int, sys.stdin.readline().split())

    a = sys.stdin.readline().split()[0]
    c = sys.stdin.readline().split()[0]
    print str(solve(a, b, c, d))
else:
    vals = []
    vals.append([841, 7, 'qjqhrksmvedtqldrqgchhsofokfcovut' ,'qhtmothoulodshrfejterjlguvooccsvqrrdfqfvkqhtecuhhuqhshthrkusrc', 5])
    vals.append([933, 5, 'abaabdcbbabacbdddadbbb', 'babbadbaaadbbbbaabbaabccbbdbadbbbbbbdbcbdbaaadbdbdbbbbdcbbdcbdaadbd', 15])
    vals.append([875, 10, 'hjeaiemqfliohlicmhndhbfdmlmcnjjgbg', 'hojqhmbgjlfmlliimlhahfeihgmhhhnbmebhgnfhgmhfjqhmlnnddgmqldelnhebi', 4])
    vals.append([320672, 1, 'wyyojuothwmlvrglfzdzdbtubxuoffvncrswsaznmoijoi', 'ttvlvzxcvczuagwzgbfuwmmt', 40084])
    vals.append([5608475, 1, 'gbagadghfaedhddefgbehbbdedefbaaeddachgebhbcgahfdchffhbhfahhdegdhdfbccgefhcdhhcdfgdgfhcdffaacch', 'fgfadaaecdgabeahcacadcbfhhe', 1869491])
    vals.append([1263204, 1, 'dcbabceabbaebddaaecbddaceaedacddadadcbbadbdccdecdacdcaadbceeddccbceaade', 'abddbccbdca', 1894805])
    vals.append([100, 1, 'bca', 'abc', 99])
    vals.append([541, 9, 'bxhwcmunbdxcatppdsw', 'shbppncwbnsxxnxunwsbncpdchcbcspdcppdchmbbcuapphpdxbpcswcxpxpdscxpddbcppdxhpxbuxxdbpdpuudb', 1])
    for val in vals:
        b, d, a, c, answer = val
        res = solve(a, b, c, d)
        if res == answer:
            print '++++++++++++++++++++++++++++'
            pass
        else:
            print '----------------------------'
            print val
            print res
            print '----------------------------'
            sys.stdin.readline()


mod = 10 ** 6 + 3

def prod(a, b):
    return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % mod for j in range(len(b[0]))] for i in range(len(a))]

c, w, h = map(int, input().split())

a = [[0] * (w + 1) for _ in range(w + 1)]
for i in range(w):
    a[i][i + 1] = 1

for cnt in range(0, w + 1):
    a[-1][-1 - cnt] = h ** cnt

ans = [[0] for _ in range(w + 1)]
ans[-1][0] = 1
ans[-2][0] = 1

while c > 0:
    if c % 2 == 1:
        ans = prod(a, ans)
    c = c // 2
    if c > 0:
        a = prod(a, a)

print(ans[-1][0])


def rotate(a,d):
	# 90 180 270
	if d==0:
		return a
	ret = [[0 for x in range(n)] for y in range(n)]

	for i in range(n):
		for j in range(n):
			ret[n-1-j][i]=a[i][j]
	d -= 90
	return rotate(ret,d)

def flip(a,v):
	ret = [[0 for x in range(n)] for y in range(n)]
	if v:
		for i in range(n):
			for j in range(n):
				ret[n-i-1][j] = a[i][j]
	else:
		for i in range(n):
			for j in range(n):
				ret[i][n-j-1] = a[i][j]
	return ret

n=int(raw_input())
a=[]
b=[]

# print range(0,n)

for i in range(0,n):
	a.append(raw_input())
for i in range(0,n):
	b.append(raw_input())
ay = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
	for j in range(n):
		ay[i][j] = a[i][j]
a = ay

by = [[0 for x in range(n)] for y in range(n)]

for i in range(n):
	for j in range(n):
		by[i][j] = b[i][j]
b = by

# print 'a=',a,'b=',b

phase = [rotate(a,360),rotate(a,90),rotate(a,180),rotate(a,270)]
p = []
for item in phase:
	p.append(item)
	p.append(flip(item,1))
	p.append(flip(item,0))

if b in p:
	print 'TRUE'
else:
	print 'NO'

# print a[1][2]


n = int(input())
f = lambda: ''.join(input() for i in range(n))
a, b = f(), f()
g = lambda k: k // n + n * (n - 1 - k % n)
e = lambda k: k
h = lambda k: n * (n - 1 - k // n) + k % n
v = lambda k: n * (k // n) + n - 1 - k % n
for i in (v, h, e):
    for j in [e, g, lambda k: g(g(k)), lambda k: g(g(g(k)))]:
        if all(a[k] == b[i(j(k))] for k in range(n)): exit(print('Yes'))
print('No')


import copy
lista=[]
listb=[]
temp=[]
a=int(input())
flag=0
mark=0

for i in range(0,a):
    str=input()
    for j in range(0,a):
        temp.append(str[j])
    lista.append(temp)
    temp=[]

for i in range(0,a):
    str=input()
    for j in range(0,a):
        temp.append(str[j])
    listb.append(temp)
    temp=[]

listacpy =copy.deepcopy(lista)
#转90°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-j][i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转180°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-i][a-1-j]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转270°
for i in range(0,a):
    for j in range(0,a):
        listacpy[j][a-1-i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

#翻面
listtemp=copy.deepcopy(lista)
for i in range(0,a):
    for j in range(0,a):
        lista[i][j]=listtemp[i][a-1-j]

mark = 0

listacpy =copy.deepcopy(lista)
#转90°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-j][i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转180°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-i][a-1-j]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转270°
for i in range(0,a):
    for j in range(0,a):
        listacpy[j][a-1-i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

if(flag==1):
    print("yes")
else:
    print("no")


#使用deepcopy使lista不被改变
#双引号要打一对 不然要出事
#初始化别加int
import copy
lista=[]
listb=[]
temp=[]
a=int(input())
flag=0
mark=0

for i in range(0,a):
    str=input()
    for j in range(0,a):
        temp.append(str[j])
    lista.append(temp)
    temp=[]

for i in range(0,a):
    str=input()
    for j in range(0,a):
        temp.append(str[j])
    listb.append(temp)
    temp=[]

listacpy =copy.deepcopy(lista)
#转90°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-j][i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转180°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-i][a-1-j]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转270°
for i in range(0,a):
    for j in range(0,a):
        listacpy[j][a-1-i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

#翻面
listtemp=copy.deepcopy(lista)
for i in range(0,a):
    for j in range(0,a):
        lista[i][j]=listtemp[i][a-1-j]

mark = 0

listacpy =copy.deepcopy(lista)
#转90°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-j][i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转180°
for i in range(0,a):
    for j in range(0,a):
        listacpy[a-1-i][a-1-j]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

mark = 0

#转270°
for i in range(0,a):
    for j in range(0,a):
        listacpy[j][a-1-i]=lista[i][j]

for i in range(0,a):
    for j in range(0,a):
        if(listacpy[i][j]!=listb[i][j]):
            mark=1
            break
    if(mark==1):
        break
if(mark==0):
    flag=1

if(flag==1):
    print("yes")
else:
    print("no")


import numpy as np

def is_rotate(first_map, second_map):
	tmp_first_map = first_map[:]
	for i in range(4):
		new_matrix = np.rot90(tmp_first_map)
		if np.array_equal(new_matrix, second_map) or np.array_equal([x[::-1] for x in tmp_first_map], second_map) or np.array_equal([x[::-1] for x in tmp_first_map], second_map):
			return True
		tmp_first_map = new_matrix[:]
	return False

if __name__ == "__main__":
	n = int(input())

	first_map = []
	second_map = []

	for i in range(n):
		first_map.append(list(input()))
	for i in range(n):
		second_map.append(list(input()))

	# import code
	# code.interact(local=locals())
	if is_rotate(first_map, second_map):
		print("Yes")
	else:
		print("No")


from sys import stdin, exit
from random import randint

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

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

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    for it in range(100000 * K + n):
        idx1 = randint(0, n - 1)
        idx2 = randint(0, n - 1)
        if idx1 == idx2:
            continue

        i = active[idx1]
        j = active[idx2]

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        answer.append((i, j))
        K -= 1

        n_act = []
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        n_act.append(k)

                        ll = a[k] * b[i] - a[i] * b[k]
                        xh = c[i] * b[k] - c[k] * b[i]
                        yh = a[i] * c[k] - a[k] * c[i]

                        assert(x_high * ll != xh * low or\
                                y_high * ll != yh * low)

        active = n_act
        good = True
        break

    if not good:
        no_solution()

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()


from sys import stdin, exit
from random import randint, choice

def no_solution():
    print 'NO'
    exit(0)

inp = stdin.read().strip().split('\n')

n, K = map(int, inp[0].split(' '))

a = [0] + [0 for i in xrange(n)]
b = [0] + [0 for i in xrange(n)]
c = [0] + [0 for i in xrange(n)]

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

for i in xrange(1, n + 1):
    a[i], b[i], c[i] = map(int, inp[i].split(' '))

answer = []

while K > 0:
    n = len(active)
    if K == 0 or len(active) == 0:
        break
    if n <= K:
        for i in xrange(n):
            answer.append((active[i], -1))
            K -= 1
        active = []
        break

    good = False
    if n <= 1000:
        for ii in xrange(n):
            if good:
                break
            for jj in xrange(ii + 1, n):
                if good:
                    break
                i = active[ii]
                j = active[jj]

                if a[i] * b[j] == a[j] * b[i]:
                    continue

                x_high = c[j] * b[i] - c[i] * b[j]
                y_high = a[j] * c[i] - a[i] * c[j]

                low = a[i] * b[j] - a[j] * b[i]

                answer.append((i, j))
                K -= 1

                n_act = []
                for k in active:
                    if k == i or k == j:
                        continue

                    low_prime = a[k] * b[j] - a[j] * b[k]
                    if low_prime == 0:
                        n_act.append(k)
                        continue

                    x_high_prime = c[j] * b[k] - c[k] * b[j]
                    y_high_prime = a[j] * c[k] - a[k] * c[j]

                    if x_high * low_prime != x_high_prime * low or \
                            y_high * low_prime != y_high_prime * low:
                                n_act.append(k)

                                ll = a[k] * b[i] - a[i] * b[k]
                                xh = c[i] * b[k] - c[k] * b[i]
                                yh = a[i] * c[k] - a[k] * c[i]

                                assert(x_high * ll != xh * low or\
                                        y_high * ll != yh * low)

                active = n_act
                good = True
        if not good:
            break
        continue

    for it in range(10000000 * K + 100 * n):
        i = choice(active)
        j = choice(active)
        if i == j:
            continue

        if a[i] * b[j] == a[j] * b[i]:
            continue

        x_high = c[j] * b[i] - c[i] * b[j]
        y_high = a[j] * c[i] - a[i] * c[j]

        low = a[i] * b[j] - a[j] * b[i]

        answer.append((i, j))
        K -= 1

        n_act = []
        for k in active:
            if k == i or k == j:
                continue

            low_prime = a[k] * b[j] - a[j] * b[k]
            if low_prime == 0:
                n_act.append(k)
                continue

            x_high_prime = c[j] * b[k] - c[k] * b[j]
            y_high_prime = a[j] * c[k] - a[k] * c[j]

            if x_high * low_prime != x_high_prime * low or \
                    y_high * low_prime != y_high_prime * low:
                        n_act.append(k)

                        ll = a[k] * b[i] - a[i] * b[k]
                        xh = c[i] * b[k] - c[k] * b[i]
                        yh = a[i] * c[k] - a[k] * c[i]

                        assert(x_high * ll != xh * low or\
                                y_high * ll != yh * low)

        active = n_act
        good = True
        break

    if not good:
        no_solution()

if len(active) == 0 and K >= 0:
    print 'YES'
    print len(answer)
    for i in xrange(len(answer)):
        print '%d %d' % answer[i]
        assert(answer[i][0] != answer[i][1])
else:
    no_solution()