Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where   <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive.  <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive.  <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent.There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.Your task is to write program which checks if given string is a correct Jabber ID.

The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.

def isvalid(jabberid):
   splitted=jabberid.split('@');
   if len(splitted)!=2:
      return False;

   username=splitted[0];
   for c in username:
      if not(c.isalpha() or c.isdigit() or c=='_'):
         return False;
   if len(username)<1 or len(username)>16:
      return False;
   splitted=splitted[1].split('/');
   if len(splitted)>2:
      return False;

   hostname=splitted[0];
   resource='noresource';
   if len(splitted)>1:
      resource=splitted[1];

   if len(hostname)<1 or len(hostname)>32:
      return False;
   words=hostname.split('.');
   for word in words:
      if len(word)<1 or len(word)>16:
         return False;
      for c in word:
         if not(c.isalpha() or c.isdigit() or c=='_'):
            return False;

   if len(resource)<1 or len(resource)>16:
      return False;
   for c in resource:
      if not(c.isalpha() or c.isdigit() or c=='_'):
         return False;

   return True;

jabberid=input();
if isvalid(jabberid):
   print('YES');
else:
   print('NO');

[{'input': ['mike@codeforces.com\r\n'], 'output': ['YES\r\n']}, {'input': ['john.smith@codeforces.ru/contest.icpc/12\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ri/abacaba\r\n'], 'output': ['YES\r\n']}, {'input': ['@ops\r\n'], 'output': ['NO\r\n']}, {'input': ['this-is-the-test\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@codeforces.commike@codeforces.com\r\n'], 'output': ['NO\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['w@S8/XU.5._R7fHq.@../e.WP!54Ey1L\x7f.9jv\r\n'], 'output': ['NO\r\n']}, {'input': ['lNC9D1L5U@.L!_!CcAOEEx.0z.aiW/S430sbQT\r\n'], 'output': ['NO\r\n']}, {'input': ['@/YTd.K1@lD\r\n'], 'output': ['NO\r\n']}, {'input': ['Fyi!d1l@.OesGopTnRn.81xdSb8q\x7f./MzuI\r\n'], 'output': ['NO\r\n']}, {'input': ['_TlPy65\x7fw/@.Vl@.8k\r\n'], 'output': ['NO\r\n']}, {'input': ['xpS@._s8.e0l\x7fJci/.LdiT\r\n'], 'output': ['NO\r\n']}, {'input': ['lGwo\x7f8.D2@.3\r\n'], 'output': ['NO\r\n']}, {'input': ['Ccz9T5rKZQuEerGo@6l.\r\n'], 'output': ['NO\r\n']}, {'input': ['Y@5nh@8.9P.Bx5AaY.1g.Tc_MK7.g_..0.\r\n'], 'output': ['NO\r\n']}, {'input': ['Q2/6y!SP9s\x7fG@7zIGr.Du_nR8.\r\n'], 'output': ['NO\r\n']}, {'input': ['eWfLL@gW!BEJUxF\x7fh@dghf.d4.FiYp/2.Pr7a/5O6zXdAkikjCEDrb\r\n'], 'output': ['NO\r\n']}, {'input': ['8oI/\x7fa@Q\r\n'], 'output': ['NO\r\n']}, {'input': ['J@Y9Gz550l@\x7fPqVZdQ!u\r\n'], 'output': ['NO\r\n']}, {'input': ['VTE6aTTta@DHe4xeG@6.c2R.J.O7sndWEEW.9j@.l..3Bs\r\n'], 'output': ['NO\r\n']}, {'input': ['aeo2XkK@UX.nQJN!Tg..wGN5YOi68U.oP2Yl3/\r\n'], 'output': ['NO\r\n']}, {'input': ['m13zREg8LbPr@T2.Z9@g.9u.v.A..XNH/1/tloIceXydZf3\r\n'], 'output': ['NO\r\n']}, {'input': ['4@@..f3ZT./oUGZ@\r\n'], 'output': ['NO\r\n']}, {'input': ['G.rVAxwDx@a.PVSe!KtpX4tzs/0yQGzZCPJPJoda\r\n'], 'output': ['NO\r\n']}, {'input': ['SV9T5RR425Sl0b@kzj.XT.PFWc..ho/VE7gjf\r\n'], 'output': ['NO\r\n']}, {'input': ['bgko@1../xwSj_\x7fJ\r\n'], 'output': ['NO\r\n']}, {'input': ['n5ymLC.bE@ukio.im2../.\r\n'], 'output': ['NO\r\n']}, {'input': ['zr.KB_6ZMSwI2GA5@R/4iP1ZKHpszW!YN/\r\n'], 'output': ['NO\r\n']}, {'input': ['@alK@pR\r\n'], 'output': ['NO\r\n']}, {'input': ['al_Y2I4IKp@A_N.\x7fruCw0VL/hRzJtx.S7sp/r!c.n9ffh\r\n'], 'output': ['NO\r\n']}, {'input': ['C1rE26_rTAVzLm@6@X5OGX.ibJ9./kkBEVlcU\r\n'], 'output': ['NO\r\n']}, {'input': ['feGSXP@eyUfr\x7f8.x4Re.JL.6B.r/fX_\r\n'], 'output': ['NO\r\n']}, {'input': ['Ht15T@50eo.E@.\r\n'], 'output': ['NO\r\n']}, {'input': ['k9MITs_Ar.JL2RRs4@VRq.wCuJ.6..amF.fE4.5I.6fJ7gz7\r\n'], 'output': ['NO\r\n']}, {'input': ['Mi\x7fWPE8@fc./IViqq4T4PSUuMdhH\r\n'], 'output': ['NO\r\n']}, {'input': ['pxSCmv!NbMvz2@pTQ.t!.Ntz/QEh_sl\r\n'], 'output': ['NO\r\n']}, {'input': ['s@mH@RO\x7f_/iWD\r\n'], 'output': ['NO\r\n']}, {'input': ['UP51i49wX@pvx@2LWm8w/G4M3J./9L6Szy\r\n'], 'output': ['NO\r\n']}, {'input': ['xC_5Vx8NgF..\x7fln@X1.drRTX..1vx.Xb3of@/PQYPeq@_y8!h_iF\r\n'], 'output': ['NO\r\n']}, {'input': ['qG3@LKp\r\n'], 'output': ['YES\r\n']}, {'input': ['flTq1knyb@2!Mtfss\r\n'], 'output': ['NO\r\n']}, {'input': ['/pqi7WXQPJFM4q1@hxUyUy\x7f/_pWo0n\r\n'], 'output': ['NO\r\n']}, {'input': ['zXme@.Dq.TWBs.fB.M\r\n'], 'output': ['NO\r\n']}, {'input': ['o3EaAnc3K6@h\r\n'], 'output': ['YES\r\n']}, {'input': ['G/AZdVMTzRLV4Ucm@eQ!..pq!..tRTi5.Ejkqa/HGpFYk\r\n'], 'output': ['NO\r\n']}, {'input': ['.c_V@L.1v!AFAEk7glM\x7fq.ag8Sy8@0.Qm/OLKoJpZlac\r\n'], 'output': ['NO\r\n']}, {'input': ['WKxNIM79u\x7f@I.RM\r\n'], 'output': ['NO\r\n']}, {'input': ['POTjlYcxAZsbyZPDh@sPm.z6aVaO.H1wEUhD9YvROQFUk/M_jTHS_6!\r\n'], 'output': ['NO\r\n']}, {'input': ['pbRIiuA@KZ2hVed2fMikA.@ebd.tE2Y\r\n'], 'output': ['NO\r\n']}, {'input': ['OlS_OwxYhH@im.0A7o/juNlxB\r\n'], 'output': ['YES\r\n']}, {'input': ['xkjHHDRBEFwgNP@G9TGStEs2Lu.BJge3EBXw3c9EfE\r\n'], 'output': ['YES\r\n']}, {'input': ['bK@8X7tQO.pXBHJpDewD\r\n'], 'output': ['YES\r\n']}, {'input': ['kKUXy6@0WefbXz39ywP.Q3r7uF\r\n'], 'output': ['YES\r\n']}, {'input': ['SllbRLdZ6@.T.E3x.BE2nIv.5db_.38./zgVGNjpldr\r\n'], 'output': ['NO\r\n']}, {'input': ['4lBJkY8c097oa@ZYmVbtiyyYN.gbj\r\n'], 'output': ['YES\r\n']}, {'input': ['F@JX4.SI1/0EY3XmYatfY\r\n'], 'output': ['YES\r\n']}, {'input': ['oLo01@B77Pu.9R.vtAZG0.HQSunv0J.\r\n'], 'output': ['NO\r\n']}, {'input': ['xLEctap0T@22U9W_fA/7iQeJGFu1lSgMZ\r\n'], 'output': ['YES\r\n']}, {'input': ['WYh@yUWfOQiF.gOK9k8aEa\r\n'], 'output': ['YES\r\n']}, {'input': ['BPxNVANhtEh@Oh_go.\r\n'], 'output': ['NO\r\n']}, {'input': ['mGIY@cHRNC8GlJ/2pcl3LYxpi3PaKGs\r\n'], 'output': ['YES\r\n']}, {'input': ['x6yfn7BGwqWd@.N/UXC\r\n'], 'output': ['NO\r\n']}, {'input': ['cUIr@cP.eGQC2xJXvI1X7\r\n'], 'output': ['YES\r\n']}, {'input': ['MLZ6e1vgZ4hOI@ktWk.Ro.o6C4/i8cnKHT\r\n'], 'output': ['YES\r\n']}, {'input': ['XCJIa@jFaP.Eu28YaoT9Z.Epk.Z/4TBzLWf724zE1r\r\n'], 'output': ['YES\r\n']}, {'input': ['Cz1U1xjg6iW0U@.97HoVA.YG.Qd.eI.DCXxtibi6HG.GV/0sN\r\n'], 'output': ['NO\r\n']}, {'input': ['nrKbWV@P0irxQoRxDsNvG/69WxCwCsfB\r\n'], 'output': ['YES\r\n']}, {'input': ['yI1nRv3FbuhgaI@.Y9vKe.8oc.BLi.6JfYT/tT5d36\r\n'], 'output': ['NO\r\n']}, {'input': ['IGsma3L6YTJRrXS@1g.yR3mC.c.xoCns7Wo1.9C.Oe.5ebkR/_97Ltj3\r\n'], 'output': ['YES\r\n']}, {'input': ['Uu538LDu9Bye@Gu0W0P5a.b9zA9nSaNhzB_TQ2.z/qfi5CZrH\r\n'], 'output': ['YES\r\n']}, {'input': ['bdHl525me@XzR_iO23v.YFXbnHUybbgw.i/WVEhm\r\n'], 'output': ['YES\r\n']}, {'input': ['NQsZ0K@eE8VMB.w2nYtKImB.4nUF\r\n'], 'output': ['YES\r\n']}, {'input': ['186@E.MmBaKLj.WYpt4wPZkzv93\r\n'], 'output': ['YES\r\n']}, {'input': ['hmhYxkGtWYRJFtBU@Drg3L7WKujE.lU61Ljqxv./FJ4X\r\n'], 'output': ['NO\r\n']}, {'input': ['t1RIUz9l3FA15@tOL9.rv.NjhouD.\r\n'], 'output': ['NO\r\n']}, {'input': ['_I4ytjyccT@q.WIc.Cqn\r\n'], 'output': ['YES\r\n']}, {'input': ['LwHHRYq@whOoq.e9b6i0xnoWBl7z.SGJiJe/iUij1x7\r\n'], 'output': ['YES\r\n']}, {'input': ['Yesx@9_KiJq2cBI6.\r\n'], 'output': ['NO\r\n']}, {'input': ['Zu5VFUtSbIw@ner5e\r\n'], 'output': ['YES\r\n']}, {'input': ['test@test.\r\n'], 'output': ['NO\r\n']}, {'input': ['test@.test\r\n'], 'output': ['NO\r\n']}, {'input': ['est.@test\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ru/\r\n'], 'output': ['NO\r\n']}, {'input': ['asd@asd@\r\n'], 'output': ['NO\r\n']}, {'input': ['@\r\n'], 'output': ['NO\r\n']}, {'input': ['/\r\n'], 'output': ['NO\r\n']}, {'input': ['.\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@\r\n'], 'output': ['NO\r\n']}, {'input': ['@mike\r\n'], 'output': ['NO\r\n']}, {'input': ['@mail.ru\r\n'], 'output': ['NO\r\n']}, {'input': ['test.me\r\n'], 'output': ['NO\r\n']}, {'input': ['$@ru\r\n'], 'output': ['NO\r\n']}, {'input': ['testme@o.o.o.o.o/ooooo\r\n'], 'output': ['YES\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['mail.ru/a\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@mail.ru/aaa\r\n'], 'output': ['YES\r\n']}, {'input': ['mike@mike.mike\r\n'], 'output': ['YES\r\n']}]


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1≤n≤10^5) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

import sys

SEPARATOR = "\n"
UNICODE = "utf-8"

def count_stripes(arr: list) -> int:
    arr_sum = sum(arr)
    if arr_sum % 3 != 0:
        return 0
    length = len(arr)
    counter = 0
    pref = 0
    stipe_arr = [0] * (length + 1)
    for i in range(1, length+1):
        pref += arr[i-1]
        stipe_arr[i] = stipe_arr[i-1] + (pref*3 == arr_sum)
    # print(stipe_arr)
    suf = 0
    for i in range(length-1, 1, -1):
        suf += arr[i]
        if suf*3 == arr_sum:
            if arr_sum == 0:
                counter += stipe_arr[i-1]
            else:
                counter += stipe_arr[i]
    return counter

lines = sys.stdin.buffer.readlines()
print(count_stripes([int(n) for n in lines[1].decode(UNICODE).strip().split()]))


Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of n 3-words. A 3-word is a sequence of exactly 3 lowercase letters of the first 24 letters of the English alphabet (a to x). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct.Iahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels.Iahubina wants to know the xor of the squared answers to all the possible questions. There are 2^24 different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.

The first line contains one integer, n (1≤n≤10^4). Each of the next n lines contains a 3-word consisting of 3 lowercase letters. There will be no two identical 3-words.

Print one number, the xor of the squared answers to the queries.

import sys
readline=sys.stdin.readline

N=int(readline())
dp=[0]*(1<<24)
dp[-1]=N
for _ in range(N):
    bit=(1<<24)-1
    for a in readline().rstrip():
        a=ord(a)-97
        if bit&1<<a:
            bit^=1<<a
    dp[bit]-=1
for i in range(24):
    for bit in range((1<<24)-1,-1,-1):
        if not bit&1<<i:
            dp[bit]+=dp[bit^1<<i]
ans=0
for x in dp:
    ans^=x**2
print(ans)


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1≤n≤10^5) and k (0≤k≤10^6) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1≤hi≤10^6) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters.
In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

from collections import deque

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

"""
i - left pointer
j - right pointer
mx - maximum length of the valid subarrays so far
res - the subarrrays with the maximum length
"""

i, mx, res = 0, 0, []

inc, dec = deque(), deque()

for j, x in enumerate(h):

    while inc and h[inc[-1]] >= x:
        inc.pop()
    inc.append(j)

    while dec and h[dec[-1]] <= x:
        dec.pop()
    dec.append(j)

    while h[dec[0]] - h[inc[0]] > k:
        if dec[0] < inc[0]:
            i = max(i, dec.popleft() + 1)
        else:
            i = max(i, inc.popleft() + 1)

    if j - i + 1 > mx:
        res = []
        mx = j - i + 1

    if j - i + 1 == mx:
        res.append((i + 1, j + 1))

print(mx, len(res))
for i, j in res:
    print(i, j)


All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table $$$n \times m$$$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $$$1$$$ to $$$n$$$ from top to bottom and columns with consecutive integers from $$$1$$$ to $$$m$$$ from left to right. Denote the cell in $$$r$$$-th row and $$$c$$$-th column as $$$(r, c)$$$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $$$(n, m)$$$.Vasya got off the ship in cell $$$(1, 1)$$$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $$$(x, y)$$$ he can move only to cells $$$(x+1, y)$$$ and $$$(x, y+1)$$$. Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $$$(1, 1)$$$ where Vasya got off his ship and $$$(n, m)$$$ where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

First line of input contains two positive integers $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$), sizes of the island.
Following $$$n$$$ lines contains strings $$$s_i$$$ of length $$$m$$$ describing the island, $$$j$$$-th character of string $$$s_i$$$ equals "#" if cell $$$(i, j)$$$ contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $$$(1, 1)$$$, i.e. the first cell of the first row, and he wants to reach cell $$$(n, m)$$$, i.e. the last cell of the last row.
It's guaranteed, that cells $$$(1, 1)$$$ and $$$(n, m)$$$ are empty.

Print the only integer $$$k$$$, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.

import sys
from array import array

input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
out, tests = [], 1

def solve(x, y) -> bool:
    passable = 0
    while x < n and y > -1:
        if passbe[x][y] and passen[x][y]:
            passable += 1

        x += 1
        y -= 1

    return passable == 1

for _ in range(tests):
    n, m = inp(int)
    a = [input() for _ in range(n)]
    passbe = [array('b', [0] * (m + 1)) for _ in range(n + 1)]
    passen = [array('b', [0] * (m + 1)) for _ in range(n + 1)]
    passbe[-1][0] = passen[-1][m - 1] = 1

    for i in range(n):
        for j in range(m):
            passbe[i][j] = (passbe[i - 1][j] or passbe[i][j - 1]) and (a[i][j] != '#')

    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            passen[i][j] = (passen[i + 1][j] or passen[i][j + 1]) and (a[i][j] != '#')

    if not passbe[n - 1][m - 1]:
        out.append(0)
        continue

    ans = 2
    for j in range(1, m):
        if solve(0, j):
            ans = 1
            break

    for j in range(1, n - 1):
        if solve(j, m - 1):
            ans = 1
            break

    out.append(ans)
print('\n'.join(map(str, out)))


Monocarp has arranged $$$n$$$ colored marbles in a row. The color of the $$$i$$$-th marble is $$$a_i$$$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color). In other words, Monocarp wants to rearrange marbles so that, for every color $$$j$$$, if the leftmost marble of color $$$j$$$ is $$$l$$$-th in the row, and the rightmost marble of this color has position $$$r$$$ in the row, then every marble from $$$l$$$ to $$$r$$$ has color $$$j$$$.To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.

The first line contains one integer $$$n$$$ $$$(2 \le n \le 4 \cdot 10^5)$$$ — the number of marbles.
The second line contains an integer sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 20)$$$, where $$$a_i$$$ is the color of the $$$i$$$-th marble.

Print the minimum number of operations Monocarp has to perform to achieve his goal.

from sys import stdin
input = stdin.readline

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

N = 20

def solve(mask):

    if(mask == (1 << N) - 1):return 0
    if(dp[mask] != -1):return dp[mask]

    p = 0
    for i in range(N):
        if(mask >> i & 1):
            p += count[i]

    ans = float('inf')
    for i in range(N):
        if(mask >> i & 1):continue

        addval = total[i]
        for j in range(N):
            if(mask >> j & 1 == 0 and i != j):continue
            addval -= val[i][j]

        ans = min(ans , solve(mask | (1 << i)) + addval)

    dp[mask] = ans
    return ans

def answer():

    global dp , val , total , count

    total = [0 for i in range(N)]
    val = [[0 for i in range(N)] for j in range(N)]
    count = [0 for i in range(N)]
    for i in range(n):

        for j in range(N):
            val[a[i]][j] += count[j]

        total[a[i]] += i
        count[a[i]] += 1

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

    ans = solve(0)
    return ans

for T in range(1):

    n = int(input())
    a = inp()

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

    print(answer())


The only difference between the easy and the hard versions is the maximum value of $$$k$$$.You are given an infinite sequence of form "112123123412345$$$\dots$$$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $$$1$$$ to $$$1$$$, the second one — from $$$1$$$ to $$$2$$$, the third one — from $$$1$$$ to $$$3$$$, $$$\dots$$$, the $$$i$$$-th block consists of all numbers from $$$1$$$ to $$$i$$$. So the first $$$56$$$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $$$1$$$-st element of the sequence is $$$1$$$, the $$$3$$$-rd element of the sequence is $$$2$$$, the $$$20$$$-th element of the sequence is $$$5$$$, the $$$38$$$-th element is $$$2$$$, the $$$56$$$-th element of the sequence is $$$0$$$.Your task is to answer $$$q$$$ independent queries. In the $$$i$$$-th query you are given one integer $$$k_i$$$. Calculate the digit at the position $$$k_i$$$ of the sequence.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries.
The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — the description of the corresponding query.

Print $$$q$$$ lines. In the $$$i$$$-th line print one digit $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — the answer to the query $$$i$$$, i.e. $$$x_i$$$ should be equal to the element at the position $$$k_i$$$ of the sequence.

import sys
from collections import deque
input = sys.stdin.readline
def fgh():
    return [int(xx) for xx in input().split()]
def fg():
    return int(input())
step = [1]
for i in range(22):
    step.append(step[-1] * 10)
def f(n):
    ans = 0
    for i in range(20):
        ans += max(0, n - step[i] + 1)
    return ans
def g(n):
    ans = 0
    for i in range(20):
        q = max(0, n - step[i] + 1)
        ans += q * (q + 1) // 2 + q * max(0, n - (step[i] + q))
    return ans
for __ in range(fg()):
    n = fg()
    l = 0
    r = 10 ** 19
    while r - l > 1:
        m = (l + r) // 2
        if g(m) < n:
            l = m
        else:
            r = m
    n -= g(l)
    r = l + 1
    l = 0
    while r - l > 1:
        m = (l + r) // 2
        if f(m) < n:
            l = m
        else:
            r = m
    n -= f(l)
    print(str(l + 1)[n - 1])


The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries.
The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^{18})$$$ — the description of the corresponding query.

from math import *

def quick_pow(n, p):
    ret = 1
    while p:
        if p & 1:
            ret *= n
        n *= n
        p >>= 1
    return ret

def len(n):
    cnt = 0
    while n:
        cnt += 1
        n = int(n/10)
    return cnt

sum = [0, 45, 9045, 1395495, 189414495, 23939649495, 2893942449495,
       339393974949495, 38939394344949495, 4393939398494949495]
pre = [0, 9, 189, 2889, 38889, 488889,
       5888889, 68888889, 788888889, 8888888889]
# int q, l
# llk, start, cnt, finish_int, i, left, right, mid, a, b, c
q = int(input())
for a in range(q):
    k = int(input())
    # l = upper_bound(sum, sum + 10, k) - sum
    for l in range(11):
        if sum[l] >= k:
            break
    k -= sum[l - 1]
    start = pre[l - 1] + l
    # // left = 0, right = quick_pow(10, l) - quick_pow(10, l - 1) - 1
    # // while (left < right) {
    #     // mid = (left + right) >> 1
    #     // if ((start + start + l * (mid - 1)) * mid / 2 < k)
    #     // left = mid + 1
    #     // else
    #     // right = mid - 1
    #     // }
    # // if ((start + start + l * (right - 1)) * right / 2 > k)
    # // --right
    a = l
    b = 2 * start + l
    c = 2 * start - 2 * k
    cnt = int(ceil((-b + sqrt(b * b - 4 * a * c)) / (2 * a)))
    # print(int((start + start + (cnt - 1) * l) * cnt))
    # print(int(int((start + start + (cnt - 1) * l) * cnt)//2))
    k -= ((start + start + (cnt - 1) * l) * cnt // 2)
    # // if (right > 1)
    # // k -= pre[len(right) - 1] + len(right - 1) * (right - 1 - quick_pow(10, len(right) - 1) + 1)
    finish_int = quick_pow(10, l - 1) + cnt
    left = 1
    right = finish_int
    while left < right:
        mid = (left + right) >> 1
        t = len(mid)
        if pre[t - 1] + len(mid) * (mid - quick_pow(10, t - 1) + 1) < k:
            left = mid + 1
        else:
            right = mid
    t = len(right)
    if right > 1:
        k -= pre[t - 1] + len(right - 1) * (right - quick_pow(10, t - 1))
    # stringstream ss
    # string str
    # ss << left
    # ss >> str
    # cout << str[k - 1] << endl
    right = str(right)
    print(right[k-1])


You are given a directed graph with $$$n$$$ vertices and $$$m$$$ directed edges without self-loops or multiple edges.Let's denote the $$$k$$$-coloring of a digraph as following: you color each edge in one of $$$k$$$ colors. The $$$k$$$-coloring is good if and only if there no cycle formed by edges of same color.Find a good $$$k$$$-coloring of given digraph with minimum possible $$$k$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — the number of vertices and edges in the digraph, respectively.
Next $$$m$$$ lines contain description of edges — one per line. Each edge is a pair of integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — there is directed edge from $$$u$$$ to $$$v$$$ in the graph.
It is guaranteed that each ordered pair $$$(u, v)$$$ appears in the list of edges at most once.

In the first line print single integer $$$k$$$ — the number of used colors in a good $$$k$$$-coloring of given graph.
In the second line print $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is a color of the $$$i$$$-th edge (in order as they are given in the input).
If there are multiple answers print any of them (you still have to minimize $$$k$$$).

class Graph:
    def __init__(self, n, m):
        self.nodes = n
        self.edges = m
        self.adj = [[] for i in range(n)]
        self.color = [1 for i in range(m)]
        self.vis = [0 for i in range(n)]
        self.colors = 1

    def add_edge(self, u, v, i):
        self.adj[u].append((i, v))

    def dfs(self, u):
        self.vis[u] = 1
        for i, v in self.adj[u]:
            if self.vis[v] == 1:
                self.colors = 2
                self.color[i] = 2
            if self.vis[v] == 0:
                self.dfs(v)
        self.vis[u] = 2

    def solve(self):
        for i in range(self.nodes):
            if self.vis[i] == 0:
                self.dfs(i)
        print(self.colors)
        print(' '.join(map(str, self.color)))

n, m = map(int, input().split(' '))
graph = Graph(n, m)
for i in range(m):
    u, v = map(int, input().split(' '))
    graph.add_edge(u-1, v-1, i)
graph.solve()


You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?

The first line of the input contains single integer number n (1≤n≤1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.

The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.

n = int(input())
segments = []

for _ in range(n):
    l, r = sorted(map(int, input().split()))
    segments.append([l, r])

segments.sort(key = lambda s: s[1])

pinz = []

for l, r in segments:
    if len(pinz) == 0 or l > pinz[-1]:
        pinz.append(r)

print(len(pinz))
print(*pinz)


Cosider a sequence, consisting of n integers: a1, a2, ..., an. Jeff can perform the following operation on sequence a:  take three integers v, t, k (1≤v,t≤n; 0≤k; v+tk≤n), such that av = av+t, av+t = av+2t, ..., av+t(k-1) = av+tk;  remove elements av, av+t, ..., av+t·k from the sequence a, the remaining elements should be reindexed a1,a2,...,an-k-1.  permute in some order the remaining elements of sequence a. A beauty of a sequence a is the minimum number of operations that is needed to delete all elements from sequence a.Jeff's written down a sequence of m integers b1, b2, ..., bm. Now he wants to ask q questions. Each question can be described with two integers li,ri. The answer to the question is the beauty of sequence bli, bli+1, ..., bri. You are given the sequence b and all questions. Help Jeff, answer all his questions.

The first line contains integer m (1≤m≤10^5). The next line contains m integers b1, b2, ..., bm (1≤bi≤10^5).
The third line contains integer q (1≤q≤10^5) — the number of questions. The next q lines contain pairs of integers, i-th of them contains a pair of integers li, ri (1≤li≤ri≤m) — the description of i-th question.

In q lines print the answers to Jeff's queries. Print the answers according to the order of questions in input.

from bisect import bisect_left, bisect_right
import sys
readline=sys.stdin.readline

class Segment_Tree:
    def __init__(self,N,f,e,lst=None):
        self.f=f
        self.e=e
        self.N=N
        if lst==None:
            self.segment_tree=[self.e]*2*self.N
        else:
            assert len(lst)<=self.N
            self.segment_tree=[self.e]*self.N+[x for x in lst]+[self.e]*(N-len(lst))
            for i in range(self.N-1,0,-1):
                self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])

    def __getitem__(self,i):
        if type(i)==int:
            if -self.N<=i<0:
                return self.segment_tree[i+self.N*2]
            elif 0<=i<self.N:
                return self.segment_tree[i+self.N]
            else:
                raise IndexError('list index out of range')
        else:
            a,b,c=i.start,i.stop,i.step
            if a==None:
                a=self.N
            else:
                a+=self.N
            if b==None:
                b=self.N*2
            else:
                b+=self.N
            return self.segment_tree[slice(a,b,c)]

    def __setitem__(self,i,x):
        if -self.N<=i<0:
            i+=self.N*2
        elif 0<=i<self.N:
            i+=self.N
        else:
            raise IndexError('list index out of range')
        self.segment_tree[i]=x
        while i>1:
            i>>= 1
            self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])

    def Build(self,lst):
        for i,x in enumerate(lst,self.N):
            self.segment_tree[i]=x
        for i in range(self.N-1,0,-1):
            self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])

    def Fold(self,L=None,R=None):
        if L==None:
            L=self.N
        else:
            L+=self.N
        if R==None:
            R=self.N*2
        else:
            R+=self.N
        vL=self.e
        vR=self.e
        while L<R:
            if L&1:
                vL=self.f(vL,self.segment_tree[L])
                L+=1
            if R&1:
                R-=1
                vR=self.f(self.segment_tree[R],vR)
            L>>=1
            R>>=1
        return self.f(vL,vR)

    def Fold_Index(self,L=None,R=None):
        if L==None:
            L=self.N
        else:
            L+=self.N
        if R==None:
            R=self.N*2
        else:
            R+=self.N
        if L==R:
            return None
        x=self.Fold(L-self.N,R-self.N)
        while L<R:
            if L&1:
                if self.segment_tree[L]==x:
                    i=L
                    break
                L+=1
            if R&1:
                R-=1
                if self.segment_tree[R]==x:
                    i=R
                    break
            L>>=1
            R>>=1
        while i<self.N:
            if self.segment_tree[i]==self.segment_tree[i<<1]:
                i<<=1
            else:
                i<<=1
                i|=1
        i-=self.N
        return i

    def Bisect_Right(self,l=None,f=None):
        if l==self.N:
            return self.N
        if l==None:
            l=0
        if f(self.Fold(l,self.N)):
            return self.N
        l+=self.N
        v=self.e
        while True:
            while l%2==0:
                l>>=1
            vv=self.f(v,self.segment_tree[l])
            if f(vv):
                v=vv
                l+=1
                if 2*self.N==l<<(self.N.bit_length()-l.bit_length()+1):
                    return self.N
            else:
                while l<self.N:
                    l<<=1
                    vv=self.f(v,self.segment_tree[l])
                    if f(vv):
                        v=vv
                        l+=1
                return l-self.N

    def Bisect_Left(self,r=None,f=None):
        if r==0:
            return 0
        if r==None:
            r=self.N
        if f(self.Fold(0,r)):
            return 0
        r+=self.N
        v=self.e
        while True:
            r-=1
            while r>1 and r%2:
                r>>=1
            vv=self.f(self.segment_tree[r],v)
            if f(vv):
                v=vv
                if 2*self.N==r<<(self.N.bit_length()-r.bit_length()+1):
                    return 0
            else:
                while r<self.N:
                    r=2*r+1
                    vv=self.f(self.segment_tree[r],v)
                    if f(vv):
                        v=vv
                        r-=1
                return r+1-self.N

    def __str__(self):
        return '['+', '.join(map(str,self.segment_tree[self.N:]))+']'

class Dual_Segment_Tree:
    def __init__(self,N,f_act,e_act,operate,lst):
        self.N=N
        self.f_act=f_act
        self.e_act=e_act
        self.operate=operate
        self.lst=[None]*self.N
        for i,x in enumerate(lst):
            self.lst[i]=x
        self.segment_tree_act=[self.e_act]*(self.N+self.N)

    def __getitem__(self,i):
        if type(i) is int:
            if -self.N<=i<0:
                i+=self.N*2
            elif 0<=i<self.N:
                i+=self.N
            else:
                raise IndexError('list index out of range')
            self.Propagate_Above(i)
            return self.Operate_At(i)
        else:
            a,b,c=i.start,i.stop,i.step
            if a==None or a<-self.N:
                a=0
            elif self.N<=a:
                a=self.N
            elif a<0:
                a+=self.N
            if b==None or self.N<=b:
                b=self.N
            elif b<-self.N:
                b=0
            elif b<0:
                b+=self.N
            return self.lst[slice(a,b,c)]

    def Operate_At(self,i):
        return self.operate(self.lst[i-self.N],self.segment_tree_act[i])

    def Propagate_At(self,i):
        self.segment_tree_act[i<<1]=self.f_act(self.segment_tree_act[i<<1],self.segment_tree_act[i])
        self.segment_tree_act[i<<1|1]=self.f_act(self.segment_tree_act[i<<1|1],self.segment_tree_act[i])
        self.segment_tree_act[i]=self.e_act

    def Propagate_Above(self,i):
        H=i.bit_length()-1
        for h in range(H,0,-1):
            self.Propagate_At(i>>h)

    def Operate_Range(self,a,L=None,R=None):
        if L==None or L<-self.N:
            L=self.N
        elif self.N<=L:
            L=self.N*2
        elif L<0:
            L+=self.N*2
        else:
            L+=self.N
        if R==None or self.N<=R:
            R=self.N*2
        elif R<-self.N:
            R=self.N
        elif R<0:
            R+=self.N*2
        else:
            R+=self.N
        L0=L//(L&-L)
        R0=R//(R&-R)-1
        self.Propagate_Above(L0)
        self.Propagate_Above(R0)
        while L<R:
            if L&1:
                self.segment_tree_act[L]=self.f_act(self.segment_tree_act[L],a)
                L+=1
            if R&1:
                R-=1
                self.segment_tree_act[R]=self.f_act(self.segment_tree_act[R],a)
            L>>=1
            R>>=1

    def Update(self):
        for i in range(1,self.N):
            self.Propagate_At(i)
            self.segment_tree_act[i]=self.e_act

    def __str__(self):
        self.Update()
        return '['+', '.join(map(str,[self.operate(x,a) for x,a in zip(self.lst,self.segment_tree_act[self.N:])]))+']'

M=int(readline())
B=list(map(int,readline().split()))
Q=int(readline())
query=[[] for l in range(M)]
for i in range(Q):
    l,r=map(int,readline().split())
    l-=1
    query[l].append((r,i))
max_B=max(B)
idx=[[] for b in range(max_B+1)]
for i in range(M-1,-1,-1):
    idx[B[i]].append(i)
ans_lst=[None]*Q
ST=Segment_Tree(M,lambda x,y:x+y,0)
for lst in idx:
    if lst:
        ST[lst.pop()]+=1
for l in range(M):
    for r,i in query[l]:
        ans_lst[i]=ST.Fold(l,r)
    b=B[l]
    if idx[b]:
        ST[idx[b].pop()]+=1
for i in range(M):
    idx[B[i]].append(i)
inf=1<<30
DST=Dual_Segment_Tree(M+1,lambda x,y:x+y,0,lambda x,y:x+y,[0]*(M+1))
bound=[[] for i in range(max_B+1)]
for b in range(max_B+1):
    if not idx[b]:
        continue
    l=len(idx[b])
    for i in range(1,l-1):
        if idx[b][i]*2!=idx[b][i-1]+idx[b][i+1]:
            bound[b].append(i)
    l=idx[b][0]+1
    if bound[b]:
        r=idx[b][bound[b][0]+1]+1
    else:
        r=M+1
    DST.Operate_Range(1,l,r)
for l in range(M):
    for r,i in query[l]:
        if DST[r]==0:
            ans_lst[i]+=1
    b=B[l]
    if idx[b][-1]==l:
        DST.Operate_Range(-1,l+1,M+1)
    else:
        i=bisect_left(idx[b],l)
        j=bisect_left(bound[b],i+1)
        if j==len(bound[b]):
            DST.Operate_Range(-1,l+1,idx[b][i+1]+1)
        else:
            DST.Operate_Range(-1,l+1,idx[b][bound[b][j]+1]+1)
            i+=1
            j=bisect_left(bound[b],i+1)
            if j==len(bound[b]):
                r=M+1
            else:
                r=idx[b][bound[b][j]+1]+1
            DST.Operate_Range(1,idx[b][i]+1,r)
print(*ans_lst,sep="\n")


Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($$$1, 2, 3, \ldots$$$). The node with a number $$$x$$$ ($$$x > 1$$$), is directly connected with a node with number $$$\frac{x}{f(x)}$$$, with $$$f(x)$$$ being the lowest prime divisor of $$$x$$$.Vanessa's mind is divided into $$$n$$$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $$$i$$$-th fragment is now located at the node with a number $$$k_i!$$$ (a factorial of $$$k_i$$$).To maximize the chance of successful awakening, Ivy decides to place the samples in a node $$$P$$$, so that the total length of paths from each fragment to $$$P$$$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $$$P$$$ needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $$$P$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — number of fragments of Vanessa's mind. The second line contains $$$n$$$ integers: $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), denoting the nodes where fragments of Vanessa's mind are located: the $$$i$$$-th fragment is at the node with a number $$$k_i!$$$.

Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $$$P$$$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $$$P$$$ needs to be counted multiple times as well.

NoteConsidering the first $$$24$$$ nodes of the system, the node network will look as follows (the nodes $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ are drawn bold):For the first example, Ivy will place the emotion samples at the node $$$1$$$. From here:  The distance from Vanessa's first fragment to the node $$$1$$$ is $$$1$$$.  The distance from Vanessa's second fragment to the node $$$1$$$ is $$$0$$$.  The distance from Vanessa's third fragment to the node $$$1$$$ is $$$4$$$. The total length is $$$5$$$.For the second example, the assembly node will be $$$6$$$. From here:  The distance from Vanessa's first fragment to the node $$$6$$$ is $$$0$$$.  The distance from Vanessa's second fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's third fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's fourth fragment to the node $$$6$$$ is again $$$2$$$. The total path length is $$$6$$$.

from sys import stdin, stdout

prime = list()
factor = list()
count = list()
dist = list()
N = 0

def find_prime():
    global prime
    for i in range(2, 5010):
        is_prime = True
        for j in prime:
            if i % j == 0:
                is_prime = False
                break
        if is_prime is True:
            prime.append(i)

def calculate_factor(max):
    global prime
    global factor
    global dist
    factor = [[0 for x in range(len(prime))] for y in range(5010)]
    dist = [0] * (max+1)
    d = 0
    for i in range(1, max+1):
        temp = i
        factor[i] = list(factor[i-1])
        for j,x in enumerate(prime):
            while temp % x == 0:
                factor[i][j] +=1
                temp = temp / x
                d += 1
            if temp == 1:
                dist[i] = d
                break

def dynamic_count():
    global count
    for i in range (1,len(count)):
        count[i] += count[i-1]

def moving(i, left, right, d, current_factor):
    global count
    global prime
    global factor
    global N
    while (factor[left][i] == factor[right][i]):
        d += ((2 * (count[right] - count[left-1])) - N) * (factor[right][i] - current_factor[i])
        current_factor[i] = factor[right][i]
        i -= 1
        if i < 0:
            return d
    d += ((2 * (count[right] - count[left-1])) - N) * (factor[left][i] - current_factor[i])
    current_factor[i] = factor[left][i]

    temp_left = right
    while temp_left >= left:
        if (factor[temp_left-1][i] != factor[right][i] or temp_left == left ) and count[right] - count[temp_left-1] > int(N/2):
            if (temp_left > left):
                d += ((2 * (count[temp_left-1] - count[left-1]))) * (factor[left][i] - current_factor[i])
            return moving(i, temp_left, right, d, current_factor)
        elif factor[temp_left-1][i] != factor[right][i]:
            i -= 1
            right = temp_left - 1
            if i < 0:
                return d
        temp_left -= 1
    return d

def unanem():
    global prime
    global count
    global N

    if count[1] > int(N/2):
        return 0
    current_factor = [0] * 5010
    if count[5000] - count[4998] > int(N/2):
        return moving(len(prime)-3, 4999, 5000, 0, current_factor)
    for i,x in enumerate(prime):
        counter = 0
        if i == 0:
            counter = count[1]
        else:
            counter = count[prime[i] - 1] - count[prime[i-1] - 1]
        if counter>int(N/2):
            return moving (i, prime[i-1], prime[i] - 1, 0 , current_factor)
    return 0

def main():
    global prime
    global factor
    global count
    global N
    global debugs
    N = int(stdin.readline())
    num_list = list(map(int, stdin.readline().split()))
    max = 0
    for i in num_list:
        if max < i:
            max = i

    count = [0] * (5010)
    for i in num_list:
        count[i] += 1

    find_prime()
    calculate_factor(max)
    dynamic_count()

    d = unanem()
    overall_dist = 0
    for i,c in enumerate(count):
        if i == max + 1:
            break
        if i == 0:
            continue
        overall_dist += (count[i] - count[i-1])*dist[i]
    print(overall_dist - d)

main()


The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes $$$n$$$ pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $$$i$$$-th picture has a non-negative weight $$$w_i$$$, and the probability of the $$$i$$$-th picture being displayed is $$$\frac{w_i}{\sum_{j=1}^nw_j}$$$. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $$$1$$$ to its weight; otherwise, she would subtract $$$1$$$ from its weight.Nauuo will visit the website $$$m$$$ times. She wants to know the expected weight of each picture after all the $$$m$$$ visits modulo $$$998244353$$$. Can you help her?The expected weight of the $$$i$$$-th picture can be denoted by $$$\frac {q_i} {p_i}$$$ where $$$\gcd(p_i,q_i)=1$$$, you need to print an integer $$$r_i$$$ satisfying $$$0\le r_i<998244353$$$ and $$$r_i\cdot p_i\equiv q_i\pmod{998244353}$$$. It can be proved that such $$$r_i$$$ exists and is unique.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 2\cdot 10^5$$$, $$$1\le m\le 3000$$$) — the number of pictures and the number of visits to the website. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$a_i$$$ is either $$$0$$$ or $$$1$$$) — if $$$a_i=0$$$ , Nauuo does not like the $$$i$$$-th picture; otherwise Nauuo likes the $$$i$$$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $$$n$$$ positive integers $$$w_1,w_2,\ldots,w_n$$$ ($$$w_i \geq 1$$$) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed $$$998244352-m$$$.

The output contains $$$n$$$ integers $$$r_1,r_2,\ldots,r_n$$$ — the expected weights modulo $$$998244353$$$.

NoteIn the first example, if the only visit shows the first picture with a probability of $$$\frac 2 3$$$, the final weights are $$$(1,1)$$$; if the only visit shows the second picture with a probability of $$$\frac1 3$$$, the final weights are $$$(2,2)$$$.So, both expected weights are $$$\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$$$ .Because $$$332748119\cdot 3\equiv 4\pmod{998244353}$$$, you need to print $$$332748119$$$ instead of $$$\frac4 3$$$ or $$$1.3333333333$$$.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $$$w_1$$$ will be increased by $$$1$$$.So, the expected weight is $$$1+2=3$$$.Nauuo is very naughty so she didn't give you any hint of the third example.

P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
    PO[i] = pow((SU+i)%P, P-2, P)

def calc(L):
    su = sum(L)
    pl = 0
    pd = 0
    RE = []
    for i in range(len(L)):
        a = li + i
        b = di - (len(L) - 1 - i)
        pd = b * L[i] * PO[a+b-SU]
        RE.append((pl+pd)%P)
        pl = a * L[i] * PO[a+b-SU]
    RE.append(pl%P)
    return RE

for i in range(M):
    X = calc(X)
ne = 0
po = 0
for i in range(M+1):
    po = (po + X[i] * (li + i)) % P
    ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
    print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P)


Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.


Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.Given number n, can you find the two digit permutations that have this property?

The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.

Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.

num = [0] * 10
line = list(raw_input())
for i in line:
  num[ord(i) - ord('0')] += 1
ans = 0
retstr1 = retstr2 = ''.join(sorted(line))
for first_i in range(1, 10):
  first_j = (10 - first_i) % 10
  cntx = [0] * 10
  cnty = [0] * 10
  cntx[first_i] += 1
  cnty[first_j] += 1
  if cntx[first_i] > num[first_i] or cnty[first_j] > num[first_j]:
    continue
  tmpstr1 = chr(ord('0') + first_i)
  tmpstr2 = chr(ord('0') + first_j)
  tmp = 1
  for i in range(10):
    l = min(num[i] - cntx[i], num[9-i] - cnty[9-i])
    cntx[i] += l
    cnty[9-i] += l
    tmp += l
    tmpstr1 += chr(ord('0') + i) * l
    tmpstr2 += chr(ord('0') + 9 - i) * l
  l = min(num[0] - cntx[0], num[0] - cnty[0])
  cntx[0] += l
  cnty[0] += l
  tmp += l
  tmpstr1 = chr(ord('0')) * l + tmpstr1
  tmpstr2 = chr(ord('0')) * l + tmpstr2
  for i in range(10):
    tmpstr1 += chr(ord('0') + i) * (num[i] - cntx[i])
    tmpstr2 += chr(ord('0') + i) * (num[i] - cnty[i])
  if ans < tmp:
    ans = tmp
    retstr1 = tmpstr1
    retstr2 = tmpstr2
print retstr1[::-1]
print retstr2[::-1]


Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).

The first line contains two space-separated integers: n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 ≤ si < ti ≤ n).

Print the only number — the number of ways to get to the school modulo 1000000007 (109 + 7).

NoteThe first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16.

a,b=map(int,input().split())
z=[]
g=10**9+7
def f():
    return map(int,input().split())
if b==0:
    print (0)
else:
    s=set()
    for i in range(b):
        x,y=f()
        z.append((x,y))
        s.add(x)
        s.add(y)
    s.add (0)
    s.add (a)
    s = sorted(list(s))
    a=len(s)-1
    s=dict([(s[j],j) for j in range(a+1)])
    z=[(s[x],s[y]) for (x,y)in z]
    z.sort(key=lambda x:x[1])
    x=[0]*(a+1)
    x[0]=1
    y=[0]*(a+2)
    i=0
    j=0
    for i in range (a+1):
        while j<b and z[j][1]==i:
            q,p=z[j]
            x[p]+=y[p]-y[q]
            j+=1
        y[i+1]=y[i]+x[i]
        y[i+1]%=g
    print (x[a]%g)


As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si — how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.

The first line contains three integers n, m and h (1 ≤ n ≤ 100, 1 ≤ m ≤ 1000, 1 ≤ h ≤ m) — the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly.  The second line contains a single-space-separated list of m integers si (1 ≤ si ≤ 100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa.

Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10 - 6.

NoteIn the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.In the second example, there are not enough players.In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.

import sys

def genPrimes(bound):
	isPrime = [True] * max(bound + 1, 2)
	isPrime[0] = isPrime[1] = False
	for i in range(4, len(isPrime), 2):
		isPrime[i] = False
	for i in range(3, len(isPrime), 2):
		if isPrime[i]:
			for j in range(i * i, len(isPrime), 2 * i):
				isPrime[j] = False
	return [x for x in range(len(isPrime)) if isPrime[x]]

def div(f1, f2):
	return [f1[i] - f2[i] for i in range(len(f1))]

def fact(primes, n):
	res = [0] * len(primes)
	for i in range(len(primes)):
		q = primes[i]
		while n / q > 0:
			res[i] += n / q
			q *= primes[i]
	return res

def c(primes, n, k):
	return div(div(fact(primes, n), fact(primes, k)), fact(primes, n - k))

#cin = open("input.txt", "rt")
cin = sys.stdin
n, m, h = [int(x) for x in cin.readline().split()]
a = [int(x) for x in cin.readline().split()]

h -= 1
n -= 1
a[h] -= 1
a[h], a[-1] = a[-1], a[h]
left, right = sum(a[:-1]), a[-1]

if left + right < n:
	print -1
	sys.exit(0)
if n > left:
	print 1
	sys.exit(0)

primes = genPrimes(left + right)

num = c(primes, left, n)
den = c(primes, left + right, n)

for i in range(len(primes)):
	v = min(num[i], den[i])
	num[i] -= v
	den[i] -= v

ans = 1.0
for i in range(len(primes)):
	for _ in range(num[i]):
		ans *= primes[i]
	for _ in range(den[i]):
		ans /= primes[i]
print "%.6f" % (1.0 - ans)


Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.The program is interpreted using movement of instruction pointer (IP) which consists of three parts: current block pointer (BP); note that there is no concept of current pixel within the block; direction pointer (DP) which can point left, right, up or down; block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of CP. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).You are given a Piet program. You have to figure out which block of the program will be current after n steps.

The first line of the input contains two integer numbers m (1 ≤ m ≤ 50) and n (1 ≤ n ≤ 5·107). Next m lines contain the rows of the program. All the lines have the same length between 1 and 50 pixels, and consist of characters 0-9. The first character of the first line will not be equal to 0.

Output the color of the block which will be current after n steps of program interpretation.

NoteIn the first example IP changes in the following way. After step 1 block 2 becomes current one and stays it after two more steps. After step 4 BP moves to block 3, after step 7 — to block 4, and finally after step 10 BP returns to block 1.  The sequence of states of IP is shown on the image: the arrows are traversed clockwise, the main arrow shows direction of DP, the side one — the direction of CP.

class Piet:
    inc = [{'x':0,'y':-1},{'x':1,'y':0},{'x':0,'y':1},{'x':-1,'y':0}]
    def __init__(self):
        self.BP = {'x':0,'y':0}
        self.DP = 1
        self.CP = 0
        self.getdata()
        self.go()
    def getdata(self):
        in_line = raw_input().split()
        self.m = int(in_line[0])
        self.n = int(in_line[1])
        self.pixels = []
        for i in range(self.m):
            self.pixels.append(raw_input())
    def is_out_limit(self,x,y):
        if x >= len(self.pixels[0]) or y >= self.m or x<0 or y<0:
            return True
        else:
            return False
    def go(self):
        ans = []
        info = []
        for t in xrange(self.n):
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.DP]['x']
                    self.BP['y'] += Piet.inc[self.DP]['y']
                else:
                    break
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.CP]['x'],self.BP['y']+Piet.inc[self.CP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.CP]['y']][self.BP['x']+Piet.inc[self.CP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.CP]['x']
                    self.BP['y'] += Piet.inc[self.CP]['y']
                else:
                    break
            if  self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']) or self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']] == '0':
                if self.DP == (self.CP + 1)%4:
                    self.CP = (self.CP + 2)%4
                else:
                    self.DP = (self.DP + 1)%4
                    self.CP = (self.DP - 1)%4
            else:
                self.BP['x'] += Piet.inc[self.DP]['x']
                self.BP['y'] += Piet.inc[self.DP]['y']
            #print(self.BP['x'],self.BP['y'],self.DP,self.CP)
            if (self.BP['x'],self.BP['y'],self.DP,self.CP) in info:
                dot = info.index( (self.BP['x'],self.BP['y'],self.DP,self.CP) )
                print ans[dot-1+(self.n-dot)%(len(ans)-dot)]
                break
            else:
                ans.append(self.pixels[self.BP['y']][self.BP['x']])
                info.append( (self.BP['x'],self.BP['y'],self.DP,self.CP) )
        else:
            print ans[-1]

def main():
    p = Piet()

if __name__ == '__main__':
    main()


The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

from bisect import *
n,k=map(int,input().split())
h=list(map(int,input().split()))
l=[]
q=[]
aa=-1
j=0
for i in range(n):
    l.insert(bisect(l,h[i]),h[i])
    while l[-1]-l[0]>k:
        l.pop(bisect(l,h[j])-1)
        j+=1
    if i-j+1>aa:
        aa=i-j+1
        q=[]
    if i-j+1==aa:
        q.append([j+1,i+1])
print(aa,len(q))
for i in q:
    print(i[0],i[1])


Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.

The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp.

If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO".

import math,sys
eps = 1e-8
n = input()
al = [map(int,raw_input().split()) for i in xrange(n+1)]
vp,vs = map(int,raw_input().split())
px,py,pz = map(int,raw_input().split())
al = [(x-px,y-py,z-pz) for x,y,z in al]

d3=lambda x,y,z:x*x+y*y+z*z
t0 = 0
rt,pt = None,0
ts = 0

for i in range(n):
    c = [y-x for x,y in zip(al[i],al[i+1])]
    ll = d3(*c)
    l = ll**0.5
    ts+=l
    te = ts/vs
    v = [vs*x for x in c]
    s = [l*x-a*t0 for x,a in zip(al[i],v)]
    a = d3(*v)-vp*vp*ll
    b = 2*sum(x*i for x,i in zip(s,v))
    c = d3(*s)
    d = b*b-4*a*c
    fa = abs(a)<eps
    def tsol(t):
        global rt,pt
        if t0-eps<t<te+eps and (rt is None or rt>t):
            rt,pt=t,[(x+a*t)/l for x,a in zip(s,v)]
    if fa:
        if abs(b)>eps: tsol(-c/b)
    elif d>-eps:
        if d<eps: d=0
        a*=2.0
        d**=0.5
        tsol((-b+d)/a)
        tsol((-b-d)/a)
    t0 = te
if rt is None: print "NO"
else:
    print "YES"
    print "%.10f"%rt
    print "%.10f"%(pt[0]+px),"%.10f"%(pt[1]+py),"%.10f"%(pt[2]+pz)


Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line.  Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.

The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.

Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.

NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.

from bisect import bisect_left as bl
I=10000000
n=int(input())+1
c=[0]*n
for i,x in enumerate(map(int,input().split())): c[x]=i
d = [n-c[int(x)] for x in input().split()]
c=[I]*n
for i in d: c[bl(c,i)]=i
print( c.index(I))


Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

class Scroll:
	def __init__(self, id, power, damage):
		self.id = id
		self.power = power
		self.damage = damage
		self.active = False

num_scrolls, boss_max, regenerate = map(int, input().split())
scrolls = [Scroll(i+1, *map(int, input().split())) for i in range(num_scrolls)]
scrolls.sort(key = lambda scroll: -scroll.damage)
boss_curr = boss_max
scroll_damage = 0
active_scrolls = []
tick = 0
while True:
	boss_prev = boss_curr
	boss_curr -= scroll_damage
	boss_curr = min(boss_max, boss_curr + regenerate)
	if boss_curr <= 0:
		print('YES')
		print(tick, len(active_scrolls))
		for scroll in active_scrolls:
			print(scroll.start, scroll.id)
		break
	found = False
	for scroll in scrolls:
		if not scroll.active and 100*boss_curr <= scroll.power*boss_max:
			scroll.start = tick
			scroll.active = True
			active_scrolls.append(scroll)
			scroll_damage += scroll.damage
			found = True
			break
	if not found and boss_curr >= boss_prev:
		print('NO')
		break
	tick += 1


Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di — the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.

The first line contains integer A (1 ≤ A < 10300). It is guaranteed that the number doesn't contain leading zeros.

On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO.  If the answer is YES, then you also have to print number k — the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers — a1, a2, ..., ak. Those numbers have to be output in the increasing order. On the next line you should output number p — how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number — the sought number of residents. Those number also have to go in the increasing order.  If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros.

a = int(input())
ans = set()
def work(i, z, y):
    z.add(y)
    # print(">>", i, y)
    if y == a:
        ans.add(i)
    if len(z) > 1000:
        z.remove(max(z))

pos = [set(), set([2])]
for i in range(2):
    for x in pos[i]:
        if x == a:
            ans.add(i)

def dfs(i, last, cur):
    if i > 988:
        return
    while len(pos) - 1 < i:
        pos.append(set())
    if len(pos[i]) == 0 and cur > a:
        return
    if cur in pos[i]:
        return
    work(i, pos[i], cur)
    dfs(i + 1, cur, last * 12)
    dfs(i + 1, cur, cur * 13 - last * 12)

dfs(2, 2, 13)

if len(ans) == 0:
    print("NO")
else:
    print("YES")
    count = 0
    print(min(1000, len(ans)))
    z = set()
    for i in sorted(ans):
        if count < 1000:
            print(i)
            count += 1
        for y in pos[i]:
            if y != a:
                z.add(y)
            if len(z) > 1000:
                z.remove(max(z))
    count = 0
    print(min(1000, len(z)))
    for i in sorted(z):
        print(i)
        count += 1
        if count >= 1000:
            break


Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

from itertools import combinations

def calculate(s, dif):
	x = int(s, 2)
	for j in combinations(range(len(s)), dif):
		y = x
		for k in j:
			y ^= (2**k)
		yield y

def calculate2(s, dif, arr):
	y = int(s, 2)
	for x in arr:
	    if(bin(y ^ x).count('1') == dif):
	        yield x

n, m = map(int, input().split())
result = []
(st, dif) = input().split()
total = calculate(st, int(dif))
for i in range(1, m):
	st, dif = input().split()
	total = calculate2(st, int(dif), total)

print(len(list(total)))


In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not.    Figure 1     Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.

The first line of the test case will consist of the number of vertices n (3 ≤ n ≤ 1000). Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≤ xi, yi ≤ 106) separated by a space. The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2).

Output consists of a single line containing the number of points where the watchtower can be set up.

NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0.

from math import floor,ceil
n = input()
x,y = zip(*[map(int,raw_input().split()) for _ in xrange(n)])
nr,mr=min(x[:2]),max(x[:2])
for j in xrange(3,n):
    i = j-1
    dx = x[j]-x[i]
    dy = y[j]-y[i]
    t = 1.*(y[0]-y[i])*dx;
    r = t/dy+x[i] if dy else 1e9
    if t-dy*(mr-x[i])>0 and r<mr: mr=r;
    if t-dy*(nr-x[i])>0 and r>nr: nr=r;
mr = floor(mr)-ceil(nr)
print "%.0f"%(0. if mr<-1e-14 else mr+1.1)


Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.

The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.

Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".

NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.

I = lambda: map(int, raw_input().split())

n = input()
S = [None]*n
S = I()
#print S
counter = 1
decr = 0
alpha = 0.0
lower = 0.0

for i in xrange(n):
    if(i == 0):
        alpha = 10*S[0]+10
        decr = 10*S[0]
        counter += 1
    else:
        decr = 10*(S[i]-S[i-1]) + decr
        alpha = min(alpha,(decr + 10 )/float (counter))
        #print " alpha = " , alpha
        if S[i]-1 != S[i-1]:
            lower = max(lower, ( decr )/float (counter))
            #print "lower = ", lower
        counter += 1

alpha = alpha - 0.0000000001
if lower == 0.0 : lower = 10.0

#print " alpha = " , alpha

fuel = counter*alpha - decr
least = counter*lower - decr
#print fuel , least

if int(fuel)/10 == int(least)/10 :
    print "unique"
    print S[n-1]+ int(fuel)/10
else:
    print "not unique"


You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.The track's map is represented by a rectangle n × m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once — at the very beginning, and T must be visited exactly once — at the very end.Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.

The first input line contains three integers n, m and k (1 ≤ n, m ≤ 50, n·m ≥ 2, 1 ≤ k ≤ 4). Then n lines contain the map. Each line has the length of exactly m characters and consists of lowercase Latin letters and characters S and T. It is guaranteed that the map contains exactly one character S and exactly one character T. Pretest 12 is one of the maximal tests for this problem.

If there is a path that satisfies the condition, print it as a sequence of letters — the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character S in the beginning and T in the end. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.

import sys
from array import array  # noqa: F401
from itertools import combinations
from collections import deque

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n, m, k = map(int, input().split())
chars = (
    ['}' * (m + 2)]
    + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' else c for c in input().rstrip()) + '}' for _ in range(n)]
    + ['}' * (m + 2)]
)
cbit = [[1 << (ord(c) - 97) for c in chars[i]] for i in range(n + 2)]

si, sj, ti, tj = 0, 0, 0, 0
for i in range(1, n + 1):
    for j in range(1, m + 1):
        if chars[i][j] == '{':
            si, sj = i, j
            cbit[i][j] = 0
        if chars[i][j] == '|':
            ti, tj = i, j

ans = inf = '*' * (n * m)

for comb in combinations([1 << i for i in range(26)], r=k):
    enabled = sum(comb)

    dp = [[inf] * (m + 2) for _ in range(n + 2)]
    dp[ti][tj] = ''
    dq = deque([(ti, tj, '')])
    while dq:
        i, j, s = dq.popleft()
        if dp[i][j] < s:
            continue
        for di, dj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
            if (cbit[di][dj] & enabled) != cbit[di][dj]:
                continue
            pre = chars[di][dj] if cbit[di][dj] else ''
            l = 1 if cbit[di][dj] else 0
            if (len(dp[di][dj]) > len(s) + l or len(dp[di][dj]) == len(s) + l and dp[di][dj] > pre + s):
                dp[di][dj] = pre + s
                if l:
                    dq.append((di, dj, pre + s))

    if len(ans) > len(dp[si][sj]) or len(ans) == len(dp[si][sj]) and ans > dp[si][sj]:
        ans = dp[si][sj]

print(ans if ans != inf else -1)

[{'input': '5 3 2\r\nSba\r\nccc\r\naac\r\nccc\r\nabT\r\n', 'output': ['bcccc\r\n']}, {'input': '3 4 1\r\nSxyy\r\nyxxx\r\nyyyT\r\n', 'output': ['xxxx\r\n']}, {'input': '1 3 3\r\nTyS\r\n', 'output': ['y\r\n']}, {'input': '1 4 1\r\nSxyT\r\n', 'output': ['-1\r\n']}, {'input': '1 3 3\r\nSaT\r\n', 'output': ['a\r\n']}, {'input': '3 4 1\r\nSbbT\r\naaaa\r\nabba\r\n', 'output': ['bb\r\n']}, {'input': '3 5 2\r\nSbcaT\r\nacbab\r\nacccb\r\n', 'output': ['aacccaa\r\n']}, {'input': '3 4 1\r\nSbbb\r\naaaT\r\nabbc\r\n', 'output': ['aaa\r\n']}, {'input': '3 4 2\r\nSbbb\r\naabT\r\nabbc\r\n', 'output': ['aab\r\n']}, {'input': '1 2 1\r\nST\r\n', 'output': ['\r\n']}, {'input': '4 5 3\r\nabaaa\r\nbabaT\r\nSabba\r\naaaaa\r\n', 'output': ['aaba\r\n']}, {'input': '6 6 3\r\npkhipk\r\nmlfmak\r\naqmbae\r\ndlbfSj\r\ndpbjcr\r\naTbqbm\r\n', 'output': ['cbqb\r\n']}, {'input': '1 20 3\r\nacbccbbddbffScTadffd\r\n', 'output': ['c\r\n']}, {'input': '1 30 2\r\nbmjcfldkloleiqqiTnmdjpaSckkijf\r\n', 'output': ['-1\r\n']}, {'input': '1 40 1\r\nfaSfgfTcfadcdfagfbccbffbeaaebagbfcfcgdfd\r\n', 'output': ['-1\r\n']}, {'input': '1 50 3\r\nSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaTaaaaaaaaaaa\r\n', 'output': ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n']}, {'input': '5 10 4\r\naaaaaaaaaa\r\naaaaaTaaaa\r\naaaaaaaSaa\r\naaaaaaaaaa\r\naaaaaaaaaa\r\n', 'output': ['aa\r\n']}, {'input': '5 3 4\r\naaT\r\nacc\r\nbbb\r\nbbc\r\ncSb\r\n', 'output': ['bbbc\r\n']}, {'input': '5 5 1\r\ncaTbc\r\ndccac\r\ndacda\r\naacaS\r\ncdcab\r\n', 'output': ['-1\r\n']}, {'input': '10 8 2\r\nbdcdcbfa\r\ndecffcce\r\ndTffdacb\r\neeedcdbb\r\nfdbbbcba\r\nddabfcda\r\nabdbSeed\r\nbdcdcffa\r\ncadbaffa\r\nfcccddad\r\n', 'output': ['bbbbee\r\n']}, {'input': '20 10 3\r\nebebccacdb\r\neeebccddeT\r\neadebecaac\r\nadeeeaccbc\r\nbaccccdaed\r\ndeabceabba\r\ndadbecbaaa\r\neacbbcedcb\r\naeeScdbbab\r\nbabaecaead\r\nbacdbebeae\r\naacbadbeec\r\nacddceecca\r\nacaeaebaba\r\ncdddeaaeae\r\neabddadade\r\nddddaeaeed\r\nbccbaacadd\r\ndccccbabdc\r\necdaebeccc\r\n', 'output': ['bbbcccaccaac\r\n']}, {'input': '15 10 4\r\nsejwprqjku\r\npnjsiopxft\r\nrsplgvwixq\r\nendglkchxl\r\nftihbbexgh\r\nsxtxbbavge\r\njcdkusfnmr\r\nskgsqvflia\r\nkcxmcxjpae\r\namaiwcfile\r\nnjgjSunmwd\r\nldxvahgreu\r\necmrajbjuT\r\nnaioqigols\r\npbwrmxkltj\r\n', 'output': ['aajbju\r\n']}, {'input': '15 3 4\r\nllv\r\nttT\r\nhbo\r\nogc\r\nkfe\r\ngli\r\nfbx\r\nkfp\r\nspm\r\ncxc\r\nndw\r\nSoa\r\npfh\r\nedr\r\nxmv\r\n', 'output': ['-1\r\n']}, {'input': '15 15 3\r\ncbbdccabdcbacbd\r\nbcabdcacadacdbc\r\ncbcddbbcdbddcad\r\nddcabdbbdcabbdc\r\naabadcccTcabdbb\r\ncbacaaacaabdbbd\r\ndbdcbSdabaadbdb\r\ndbbaddcdddaadbb\r\nbbddcdcbaccbbaa\r\nadadadbdbbddccc\r\ncddbbdaddcbbdcc\r\nbbaadcdbbcaacca\r\nadbdcdbbcbddbcd\r\ncdadbcccddcdbda\r\ncbcdaabdcabccbc\r\n', 'output': ['aaca\r\n']}, {'input': '20 20 2\r\nddadfcdeTaeccbedeaec\r\nacafdfdeaffdeabdcefe\r\nabbcbefcdbbbcdebafef\r\nfdafdcccbcdeeaedeffc\r\ndfdaabdefdafabaabcef\r\nfebdcabacaaaabfacbbe\r\nabfcaacadfdbfdbaaefd\r\ndacceeccddccaccdbbce\r\ncacebecabedbddfbfdad\r\ndacbfcabbebfddcedffd\r\ncfcdfacfadcfbcebebaa\r\nddfbebafaccbebeefbac\r\nebfaebacbbebdfcbcbea\r\ndfbaebcfccacfeaccaad\r\nedeedeceebcbfdbcdbbe\r\nafaacccfbdecebfdabed\r\nddbdcedacedadeccaeec\r\necbSeacbdcccbcedafef\r\ncfdbeeffbeeafccfdddb\r\ncefdbdfbabccfdaaadbf\r\n', 'output': ['-1\r\n']}, {'input': '10 10 2\r\nbaaaaaaaaa\r\nbffacffffa\r\nbggaccggga\r\nbbbSccchha\r\nbdddddccia\r\nbjddccccca\r\nbkkdddTaaa\r\nblllddblla\r\nbmmmmdbmma\r\nbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '10 20 3\r\nbaaaaaaaaaaaaaaaaaaa\r\nbfffffffacfffffffffa\r\nbgggggggaccgggggggga\r\nbbbbbbbbSccchhhhhhha\r\nbiiiiidddddcciiiiiia\r\nbjjjjjjddcccccjjjjja\r\nbkkkkkkkdddTaaaaaaaa\r\nbllllllllddbllllllla\r\nbmmmmmmmmmdbmmmmmmma\r\nbbbbbbbbbbbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '20 10 4\r\nbaaaaaaaaa\r\nbffacffffa\r\nbggaccggga\r\nbhhaccchha\r\nbiiaccccia\r\nbjjaccccca\r\nbkkakkkkka\r\nbllallllla\r\nbbbSmmmmma\r\nbnnnnnnnna\r\nbooooooooa\r\nbpppppTaaa\r\nbqqqqqbqqa\r\nbrrrrrbrra\r\nbdddddbssa\r\nbtddddbtta\r\nbuudddbuua\r\nbvvvddbvva\r\nbwwwwdbwwa\r\nbbbbbbbbbb\r\n', 'output': ['mmmno\r\n']}, {'input': '20 20 2\r\nbaaaaaaaaaaaaaaaaaaa\r\nbfffffffacfffffffffa\r\nbgggggggaccgggggggga\r\nbhhhhhhhaccchhhhhhha\r\nbiiiiiiiacccciiiiiia\r\nbjjjjjjjacccccjjjjja\r\nbkkkkkkkacccccckkkka\r\nblllllllacccccccllla\r\nbbbbbbbbSccccccccmma\r\nbddddddddddcccccccna\r\nbodddddddcccccccccca\r\nbppddddddddTaaaaaaaa\r\nbqqqdddddddbqqqqqqqa\r\nbrrrrddddddbrrrrrrra\r\nbsssssdddddbsssssssa\r\nbttttttddddbttttttta\r\nbuuuuuuudddbuuuuuuua\r\nbvvvvvvvvddbvvvvvvva\r\nbwwwwwwwwwdbwwwwwwwa\r\nbbbbbbbbbbbbbbbbbbbb\r\n', 'output': ['ccccc\r\n']}, {'input': '1 2 4\r\nST\r\n', 'output': ['\r\n']}, {'input': '3 3 1\r\naaa\r\naaa\r\nTSa\r\n', 'output': ['\r\n']}, {'input': '2 1 1\r\nS\r\nT\r\n', 'output': ['\r\n']}, {'input': '1 10 2\r\nbaaSaaTacb\r\n', 'output': ['aa\r\n']}, {'input': '2 1 4\r\nS\r\nT\r\n', 'output': ['\r\n']}]