Datasets:

Languages:
code
Multilinguality:
monolingual
Size Categories:
unknown
ArXiv:
Tags:
License:
problem_id
int64
0
5k
question
stringlengths
50
14k
solutions
stringlengths
12
1.21M
input_output
stringlengths
0
23.6M
difficulty
stringclasses
3 values
url
stringlengths
36
108
starter_code
stringlengths
0
1.4k
0
Polycarp has $n$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100". Polycarp wants to offer his set of $n$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001". Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011". Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that: the final set of $n$ words still contains different words (i.e. all words are unique); there is a way to put all words of the final set of words in the order so that the final sequence of $n$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. The first line of a test case contains one integer $n$ ($1 \le n \le 2\cdot10^5$) — the number of words in the Polycarp's set. Next $n$ lines contain these words. All of $n$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $4\cdot10^6$. All words are different. Guaranteed, that the sum of $n$ for all test cases in the input doesn't exceed $2\cdot10^5$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $4\cdot10^6$. -----Output----- Print answer for all of $t$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $k$ ($0 \le k \le n$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $k$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $1$ to $n$ in the order they appear. If $k=0$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them. -----Example----- Input 4 4 0001 1000 0011 0111 3 010 101 0 2 00000 00001 4 01 001 0001 00001 Output 1 3 -1 0 2 1 2
["for _ in range(int(input())):\n n = int(input())\n mass = []\n zo = 0\n oz = 0\n zz = 0\n oo = 0\n ozs = []\n zos = []\n ozss = set()\n zoss = set()\n for j in range(n):\n k = input()\n mass.append(k)\n if k[0] == '0' and k[-1] == '1':\n zoss.add(k)\n zos.append(j + 1)\n zo += 1\n elif k[0] == '1' and k[-1] == '0':\n ozss.add(k)\n ozs.append(j + 1)\n oz += 1\n elif k[0] == '0' and k[-1] == '0':\n zz += 1\n else:\n oo += 1\n if zz and oo and not oz and not zo:\n print(-1)\n continue\n else:\n if zo > oz:\n print((zo - oz) // 2)\n ans = []\n need = (zo - oz) // 2\n i = 0\n while need:\n zzz = mass[zos[i] - 1][len(mass[zos[i] - 1]) - 1:: -1]\n if zzz not in ozss:\n ans.append(zos[i])\n need -= 1\n i += 1\n print(*ans)\n else:\n print((oz - zo) // 2)\n ans = []\n need = (oz - zo) // 2\n i = 0\n while need:\n zzz = mass[ozs[i] - 1][len(mass[ozs[i] - 1]) - 1:: -1]\n if zzz not in zoss:\n ans.append(ozs[i])\n need -= 1\n i += 1\n print(*ans)\n", "k = int(input())\nfor i in range(k):\n is_t = set()\n a = dict()\n a['00'] = []\n a['11'] = []\n a['01'] = []\n a['10'] = [] \n n = int(input())\n s = []\n for i in range(n):\n b = input()\n a[b[0] + b[-1]].append(i)\n s.append(b)\n is_t.add(b)\n c = len(a['10'])\n d = len(a['01'])\n if c + d == 0:\n if len(a['00']) == 0 or len(a['11']) == 0:\n print(0)\n else:\n print(-1)\n elif c > d:\n ans = []\n i = 0\n m = (d + c) // 2\n while d != m and i < len(a['10']):\n s1 = s[a['10'][i]]\n if s1[::-1] not in is_t:\n d += 1\n ans.append(a['10'][i] + 1)\n i += 1\n if d != m:\n print(-1)\n else:\n print(len(ans))\n print(*ans)\n else:\n ans = []\n i = 0\n m = (d + c) // 2\n while c != m and i < len(a['01']):\n s1 = s[a['01'][i]]\n if s1[::-1] not in is_t:\n c += 1\n ans.append(a['01'][i] + 1)\n i += 1\n if c != m:\n print(-1)\n else:\n print(len(ans))\n print(*ans)\n", "N = int(input())\n\ndef ceildiv(x, y):\n if x % y == 0:\n return x // y\n else:\n return x // y + 1\n\nfor _ in range(N):\n doms = []\n oc, zc = 0, 0\n n = int(input())\n\n used = set()\n fulls = dict()\n\n for i in range(n):\n d = input()\n used.add(d)\n if d[0] != d[-1]:\n fulls[i] = d\n doms.append((i, (d[0], d[-1])))\n else:\n if d[0] == '0':\n zc = 1\n else:\n oc = 1\n\n if len(doms) == 0:\n if zc == 1 and oc == 1:\n print(-1)\n else:\n print(0)\n else:\n # print(doms)\n\n _01 = 0\n _10 = 0\n\n _01_indexes = []\n _10_indexes = []\n\n\n for dom in doms:\n if dom[1] == ('0', '1'):\n _01 += 1\n _01_indexes.append(dom[0])\n else:\n _10 += 1\n _10_indexes.append(dom[0])\n\n if _10 < _01:\n _01, _10 = _10, _01\n _01_indexes, _10_indexes = _10_indexes, _01_indexes\n\n _10_indexes = [x for x in _10_indexes if fulls[x][::-1] not in used] \n\n need = ceildiv(_10-_01-1, 2)\n if len(_10_indexes) >= need:\n print(need)\n print( ' '.join(list([str(x+1) for x in _10_indexes[:need]])) )\n else:\n print(-1)\n\n # print(\"===\")\n # print(ceil(abs(doms.count(('0', '1')) - doms.count(('1', '0'))) - 1, 2))\n\n", "t=int(input())\nfor _ in range(t):\n n=int(input())\n k={\"01\":0,\"00\":0,\"11\":0,\"10\":0}\n ab=[]\n ba=[]\n a=[]\n ra=set()\n rb=set()\n for i in range(n):\n s=input()\n ts=s[0]+s[-1]\n k[ts]+=1\n if ts==\"01\":\n ab.append([str(i+1),s])\n ra.add(s)\n if ts==\"10\":\n ba.append([str(i+1),s])\n rb.add(s)\n if k[\"01\"]==0 and k[\"10\"]==0 and k[\"00\"]>0 and k[\"11\"]>0:\n ans=-1\n else:\n if k[\"01\"]==k[\"10\"] or k[\"01\"]==k[\"10\"]+1 or k[\"01\"]==k[\"10\"]-1:\n ans=0\n else:\n m=(k[\"01\"]+k[\"10\"])//2 if (k[\"01\"]+k[\"10\"])%2==0 else (k[\"01\"]+k[\"10\"])//2+1\n if k[\"01\"]>m:\n ans=k[\"01\"]-m\n for i in range(len(ab)):\n psp=ab[i][1]\n nn=list(psp)\n nn.reverse()\n psp=\"\".join(nn)\n c1=len(rb)\n rb.add(psp)\n c2=len(rb)\n if c1!=c2:\n a.append(ab[i][0])\n if len(a)>=ans:\n a=a[:ans]\n else:\n ans=-1\n else:\n ans=k[\"10\"]-m\n for i in range(len(ba)):\n psp=ba[i][1]\n nn=list(psp)\n nn.reverse()\n psp=\"\".join(nn)\n c1=len(ra)\n ra.add(psp)\n c2=len(ra)\n if c1!=c2:\n a.append(ba[i][0])\n if len(a)>=ans:\n a=a[:ans]\n else:\n ans=-1\n print(ans)\n if ans>0:\n print(\" \".join(a))\n", "t=int(input())\nfor i in range(t):\n n=int(input())\n i0,i1=[],[]\n l0,l1=[],[]\n h0,h1=False,False\n for i in range(n):\n t=input()\n if t[0]=='0' and t[-1]=='1':\n i0.append(i)\n l0.append(t)\n elif t[0]=='1' and t[-1]=='0':\n i1.append(i)\n l1.append(t)\n elif t[0]==t[-1]=='1':\n h1=True\n elif t[0]==t[-1]=='0':\n h0=True\n c0,c1=len(l0),len(l1)\n req,sl=0,[]\n s0=set(l0)\n s1=set(l1)\n if c0>0 or c1>0:\n if c0-c1>1:\n req=(c0-c1)//2\n sel=0\n sl=[]\n for tt in range(len(l0)):\n t=l0[tt]\n if not t[::-1] in s1:\n req-=1\n sl.append(i0[tt]+1)\n if req==0:\n break\n elif c1-c0>1:\n req=(c1-c0)//2\n sel=0\n sl=[]\n for tt in range(len(l1)):\n t=l1[tt]\n if not t[::-1] in s0:\n req-=1\n sl.append(i1[tt]+1)\n if req==0:\n break\n if req>0:\n print(-1)\n else:\n print(len(sl))\n print(*sl)\n else:\n if h0 and h1:\n print(-1)\n else:\n print(0)\n print(*[])\n"]
{ "inputs": [ "4\n4\n0001\n1000\n0011\n0111\n3\n010\n101\n0\n2\n00000\n00001\n4\n01\n001\n0001\n00001\n" ], "outputs": [ "1\n3 \n-1\n0\n\n2\n1 2 \n" ] }
interview
https://codeforces.com/problemset/problem/1259/D
1
Mikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $(0, 0)$, he can go to any of the following points in one move: $(1, 0)$; $(1, 1)$; $(0, 1)$; $(-1, 1)$; $(-1, 0)$; $(-1, -1)$; $(0, -1)$; $(1, -1)$. If Mikhail goes from the point $(x1, y1)$ to the point $(x2, y2)$ in one move, and $x1 \ne x2$ and $y1 \ne y2$, then such a move is called a diagonal move. Mikhail has $q$ queries. For the $i$-th query Mikhail's target is to go to the point $(n_i, m_i)$ from the point $(0, 0)$ in exactly $k_i$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $(0, 0)$ to the point $(n_i, m_i)$ in $k_i$ moves. Note that Mikhail can visit any point any number of times (even the destination point!). -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 10^4$) — the number of queries. Then $q$ lines follow. The $i$-th of these $q$ lines contains three integers $n_i$, $m_i$ and $k_i$ ($1 \le n_i, m_i, k_i \le 10^{18}$) — $x$-coordinate of the destination point of the query, $y$-coordinate of the destination point of the query and the number of moves in the query, correspondingly. -----Output----- Print $q$ integers. The $i$-th integer should be equal to -1 if Mikhail cannot go from the point $(0, 0)$ to the point $(n_i, m_i)$ in exactly $k_i$ moves described above. Otherwise the $i$-th integer should be equal to the the maximum number of diagonal moves among all possible movements. -----Example----- Input 3 2 2 3 4 3 7 10 1 9 Output 1 6 -1 -----Note----- One of the possible answers to the first test case: $(0, 0) \to (1, 0) \to (1, 1) \to (2, 2)$. One of the possible answers to the second test case: $(0, 0) \to (0, 1) \to (1, 2) \to (0, 3) \to (1, 4) \to (2, 3) \to (3, 2) \to (4, 3)$. In the third test case Mikhail cannot reach the point $(10, 1)$ in 9 moves.
["q=int(input())\n\nfor e in range(q):\n x,y,k=list(map(int,input().split()))\n x,y=abs(x),abs(y)\n x,y=max(x,y),min(x,y)\n \n if(x%2!=k%2):\n k-=1\n y-=1\n \n \n if(x>k):\n print(-1)\n continue\n if((x-y)%2):\n k-=1\n x-=1\n print(k)\n \n \n \n", "# \nimport collections, atexit, math, sys, bisect \n\nsys.setrecursionlimit(1000000)\ndef getIntList():\n return list(map(int, input().split())) \n\ntry :\n #raise ModuleNotFoundError\n import numpy\n def dprint(*args, **kwargs):\n print(*args, **kwargs, file=sys.stderr)\n dprint('debug mode')\nexcept ModuleNotFoundError:\n def dprint(*args, **kwargs):\n pass\n\n\n\ninId = 0\noutId = 0\nif inId>0:\n dprint('use input', inId)\n sys.stdin = open('input'+ str(inId) + '.txt', 'r') #\u6807\u51c6\u8f93\u51fa\u91cd\u5b9a\u5411\u81f3\u6587\u4ef6\nif outId>0:\n dprint('use output', outId)\n sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #\u6807\u51c6\u8f93\u51fa\u91cd\u5b9a\u5411\u81f3\u6587\u4ef6\n atexit.register(lambda :sys.stdout.close()) #idle \u4e2d\u4e0d\u4f1a\u6267\u884c atexit\n \nQ, = getIntList()\nfor _ in range(Q):\n N, M, K = getIntList()\n if max(N,M) >K:\n print(-1)\n continue\n r = K\n if N%2!= K%2:\n r-=1\n if M%2!= K%2:\n r-=1\n print(r)\n\n\n\n\n\n\n", "q = int(input())\nfor i in range(q):\n x, y, k = list(map(int, input().split()))\n if x > y: x, y = y, x\n m = y\n d = y\n if (y - x) % 2 == 1:\n d -= 1\n if k < m:\n print(-1)\n continue\n r = k - m\n if r % 2 != 0:\n r -= 1\n if d != m:\n d += 1\n else:\n d -= 1\n d += r\n print(d)\n", "q = int(input())\notvet = []\nfor i in range(q):\n g = input().split()\n n = int(g[0])\n m = int(g[1])\n k = int(g[2])\n if n < 0:\n n = -n\n if m < 0:\n m = -m\n if m > k or n > k:\n otvet.append(-1)\n elif m % 2 == k % 2 and n % 2 == k % 2:\n otvet.append(k)\n elif m % 2 == k % 2 or n % 2 == k % 2:\n otvet.append(k - 1)\n else:\n otvet.append(k - 2)\nfor i in otvet:\n print(i)\n", "q = int(input())\nfor i in range(q):\n a, b, k = list(map(int, input().split()))\n if a < b:\n a, b, = b, a\n if a > k:\n print(-1)\n elif a % 2 == b % 2 != k % 2:\n print(k - 2)\n elif (a + b) % 2 != 0:\n print(k - 1)\n else:\n print(k)\n", "q = int(input())\nfor i in range(q):\n n, m, k = list(map(int, input().split()))\n m, n = abs(m), abs(n)\n mx = max(m, n)\n remaining = k - mx\n if remaining < 0:\n print(-1)\n elif m == n == 0:\n if k == 1:\n print(-1)\n elif k % 2:\n print(k - 1)\n else:\n print(k)\n elif abs(m - n) % 2 == 0:\n if remaining % 2 == 0:\n print(k)\n else:\n print(k - 2)\n else:\n if not remaining:\n print(k - 1)\n elif remaining % 2 == 0:\n print(k - 1)\n else:\n print(k - 1)\n", "from collections import deque\nfrom sys import stdin\nlines = deque(line.strip() for line in stdin.readlines())\n\ndef nextline():\n return lines.popleft()\n\ndef types(cast, sep=None):\n return tuple(cast(x) for x in strs(sep=sep))\n\ndef ints(sep=None):\n return types(int, sep=sep)\n\ndef strs(sep=None):\n return tuple(nextline()) if sep == '' else tuple(nextline().split(sep=sep))\n\ndef main():\n # lines will now contain all of the input's lines in a list\n T = int(nextline())\n for testCase in range(1, T + 1):\n n, m, k = ints()\n min_k = max(n, m)\n if min_k > k:\n print(-1)\n continue\n if (n - m) % 2 == 0:\n if k % 2 == n % 2:\n print(k)\n continue\n print(k - 2)\n continue\n print(k - 1)\n\ndef __starting_point():\n main()\n\n__starting_point()", "\n\nq = int(input())\n\nfor _ in range(q):\n n, m, k = list(map(int, input().split()))\n if max([n, m]) > k:\n print(-1)\n else:\n if (n + m) % 2 == 0:\n if max([n, m]) % 2 != k % 2:\n print(k - 2)\n else:\n print(k)\n else:\n print((k - 1));\n", "import math\n\nq = int(input())\n\nfor i in range(q):\n x, y, k = map(int, input().split())\n if x > k or y > k:\n print(-1)\n else:\n if (x+y)%2 == 0:\n if (k-max(x,y)) % 2 == 0:\n print(k)\n else:\n print(k - 2)\n else:\n if (k-max(x,y)) % 2 == 0:\n print(k-1)\n else:\n print(k-1)", "q = int(input())\n\nfor _ in range(q):\n n, m, k = list(map(int, input().split()))\n if k == 0:\n if n == 0 and m == 0:\n print(0)\n else:\n print(-1)\n elif k == 1:\n if max(abs(n), abs(m)) != 1:\n print(-1)\n elif abs(n) == abs(m) == 1:\n print(1)\n else:\n print(0)\n else:\n if max(abs(n), abs(m)) > k:\n print(-1)\n elif abs(n) == abs(m):\n if (k - abs(n)) % 2 == 0:\n print(k)\n else:\n print(k - 2)\n elif (max(abs(n), abs(m)) - min(abs(n), abs(m))) % 2 == 0:\n if (k - max(abs(n), abs(m))) % 2 == 0:\n print(k)\n else:\n print(k - 2)\n else:\n print(k - 1)\n\n\n\n", "\nimport sys\n#sys.stdin=open(\"data.txt\")\ninput=sys.stdin.readline\n\nfor _ in range(int(input())):\n n,m,k=list(map(int,input().split()))\n n=abs(n)\n m=abs(m)\n if max(n,m)>k:\n print(\"-1\")\n else:\n # you can't 0 0 1 me :D\n bad1=((n+k)%2==1)\n bad2=((m+k)%2==1)\n print(k-bad1-bad2)\n", "USE_STDIO = False\n\nif not USE_STDIO:\n try: import mypc\n except: pass\n\ndef main():\n q, = list(map(int, input().split(' ')))\n for _ in range(q):\n n, m, k = list(map(int, input().split(' ')))\n if n > k or m > k:\n print(-1)\n elif (n - m) % 2:\n print(k - 1)\n elif (n - k) % 2:\n print(k - 2)\n else:\n print(k)\n\ndef __starting_point():\n main()\n\n\n\n\n__starting_point()", "q=int(input())\n\nQ=[list(map(int,input().split())) for i in range(q)]\n\nfor n,m,k in Q:\n if n>k or m>k:\n print(-1)\n continue\n\n x=max(n,m)-min(n,m)\n y=k-max(n,m)\n\n if x%2==0 and y%2==0:\n print(k)\n elif x%2==0 and y%2==1:\n print(k-2)\n elif x%2==1 and y%2==0:\n print(k-1)\n elif x%2==1 and y%2==1:\n print(k-1)\n", "n = int(input())\nfor i in range(n):\n a, b, c = [int(el) for el in input().split()]\n if ( a > c or b > c):\n print(-1)\n else:\n if (a% 2 + b % 2 == 1):\n print(c - 1)\n elif (a%2 == b%2 == c%2):\n print(c)\n else:\n print(c - 2)\n", "Q = int(input())\nsrc = [tuple(map(int,input().split())) for i in range(Q)]\nans = []\nfor x,y,k in src:\n d = max(x,y)\n if (x+y)%2:\n ans.append(-1 if d > k else k-1)\n else:\n if d > k:\n ans.append(-1)\n else:\n ans.append(k-2 if (d+k)%2 else k)\n\nprint(*ans,sep='\\n')\n", "def m():\n\t[x, y, k] = [int(i) for i in input().split()]\n\td=min(x, y)\n\tx-=d\n\ty-=d\n\tk-=d\n\t\n\tif k-x-y<0:\n\t\tprint(-1)\n\telse:\n\t\tx+=y\n\t\tif x%2 > 0 and k%2>0:\n\t\t\tprint(d+k-1)\n\t\telif x%2 >0:\n\t\t\tprint(d+k-1)\n\t\telif k%2>0:\n\t\t\tprint(d+k-2)\n\t\telse:\n\t\t\tprint(d+k)\n\t\t\t\n\t\t\n\t\t\t\n\t\nn=int(input())\nfor i in range(n):\n\tm()", "q = int(input())\n\nfor i in range(q):\n (x, y, k) = list(map(int, input().split()))\n\n if max(x, y) > k:\n print(-1)\n elif x == y and k == x + 1:\n print(k - 2)\n continue\n elif x % 2 == 1 and y % 2 == 1 and k % 2 == 0:\n print(k - 2)\n continue\n elif x % 2 == 0 and y % 2 == 0 and k % 2 == 1:\n print(k - 2)\n continue\n elif (x + y) % 2 == 0:\n print(k)\n else:\n print(k - 1)\n", "n = int(input())\nfor q in range(n):\n x, y, k = list(map(int, input().split()))\n if max(x, y) > k:\n print(-1)\n else:\n if 0 == (x + y) % 2:\n if k % 2 == max(x, y) % 2:\n print(k)\n else:\n print(k - 2)\n else:\n print(k - 1)\n", "def go():\n n = int(input())\n for i in range(n):\n a, b, d = [int(i) for i in input().split(' ')]\n if a > d or b > d:\n print(-1)\n elif a % 2 == b % 2:\n if a % 2 == d % 2:\n print(d)\n else:\n print(d - 2)\n else:\n if a % 2 == b % 2:\n if d % 2 == a % 2:\n print(d)\n else:\n print(d - 2)\n else:\n print(d - 1)\ngo()\n", "q = int(input())\n\nfor i in range(q):\n n, m, k = map(int, input().split())\n p = min(m, n)\n r = max(n, m) - p\n if (p+r) > k:\n print(-1)\n elif r % 2 == 1:\n print(k - 1)\n elif (k - p) % 2 == 0:\n print(k)\n else:\n print(k - 2)", "q = int(input())\nfor i in range(q):\n\tn, m, k = map(int, input().split())\n\tost = max(n, m) - min(n, m)\n\tplus = 0\n\tif ost % 2 != 0:\n\t\tplus = 1\n\t\tost -= 1\n\tmini = min(n, m) + ost + plus\n\t#print('mini: ' + str(mini))\n\tif k < mini:\n\t\tprint(-1)\n\telif (k - mini) % 2 == 0 or plus == 1:\n\t\tprint(k - plus)\n\telse:\n\t\tprint(k - plus - 2)\t", "q=int(input())\n\nfor i in range(q):\n\tn,m,k=list(map(int,input().split()))\n\n\tif n>k or m>k:\n\t\tprint(-1)\n\n\telse:\n\t\tif n%2==0 and m%2==0:\n\t\t\tif k%2==0:\n\t\t\t\tprint(k)\n\t\t\telse:\n\t\t\t\tprint(k-2)\n\n\t\telif (n%2==0 and m%2==1) or (n%2==1 and m%2==0):\n\t\t\tprint(k-1)\n\n\t\telif n%2==1 and m%2==1:\n\t\t\tif k%2==0:\n\t\t\t\tprint(k-2)\n\t\t\telse:\n\t\t\t\tprint(k)\n", "q=int(input())\nfor i in range(q):\n n, m, k = map(int, input().split())\n ans=max(n,m)\n diff=k-ans\n if diff<0:\n print(-1)\n else:\n if (n%2==0 and m%2==0) or (n%2!=0 and m%2!=0):\n if diff%2==0:\n ans+=diff\n else:\n ans+=diff-2\n else:\n ans+=diff-1\n print(ans)", "\"\"\"\nKA YM KA AS KA ASKA YASK KA SKAYMA \nKA KA SKAY SK SK AS AY AY SK SKAY AS AS \nKA AS AS YM KA AS AS YM KA SK AS YM AS \nKAYM MA MA AYMA AS MASK SK MA MA SKAYMA \nKA AS YMASKAYMAS YM AS AS SK YMASKAYMAS AS \nKA KA AY SK YM AS SK AY SK AS AS \nKA YM KA KA YM AS SK KA KA SKAYMA \n\"\"\"\nn=int(input())\nfor i in range(n):\n\tx,y,k=map(int,input().split())\n\tx,y=abs(x),abs(y)\n\tmin_moves=max(x,y)\n\tif min_moves>k:\n\t\tprint(-1)\n\telse:\n\t\tans=min(x,y)\n\t\tx-=ans\n\t\ty-=ans\n\t\tp=max(x,y)\n\t\tk-=ans\n\t\tif k==p and p%2==0:\n\t\t\tprint(ans+k)\n\t\telif k==p and p%2==1:\n\t\t\tprint(ans+k-1)\n\t\telif p%2==0 and k%2==0:\n\t\t\tprint(ans+k)\n\t\telif p%2==0 and k%2==1:\n\t\t\tprint(ans+k-2)\n\t\telif p%2==1:\n\t\t\tprint(ans+k-1)"]
{ "inputs": [ "3\n2 2 3\n4 3 7\n10 1 9\n" ], "outputs": [ "1\n6\n-1\n" ] }
interview
https://codeforces.com/problemset/problem/1036/B
2
You are given three sequences: $a_1, a_2, \ldots, a_n$; $b_1, b_2, \ldots, b_n$; $c_1, c_2, \ldots, c_n$. For each $i$, $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$. Find a sequence $p_1, p_2, \ldots, p_n$, that satisfy the following conditions: $p_i \in \{a_i, b_i, c_i\}$ $p_i \neq p_{(i \mod n) + 1}$. In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $i,i+1$ adjacent for $i<n$ and also elements $1$ and $n$) will have equal value. It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence. -----Input----- The first line of input contains one integer $t$ ($1 \leq t \leq 100$): the number of test cases. The first line of each test case contains one integer $n$ ($3 \leq n \leq 100$): the number of elements in the given sequences. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$). The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \leq b_i \leq 100$). The fourth line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 100$). It is guaranteed that $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$ for all $i$. -----Output----- For each test case, print $n$ integers: $p_1, p_2, \ldots, p_n$ ($p_i \in \{a_i, b_i, c_i\}$, $p_i \neq p_{i \mod n + 1}$). If there are several solutions, you can print any. -----Example----- Input 5 3 1 1 1 2 2 2 3 3 3 4 1 2 1 2 2 1 2 1 3 4 3 4 7 1 3 3 1 1 1 1 2 4 4 3 2 2 4 4 2 2 2 4 4 2 3 1 2 1 2 3 3 3 1 2 10 1 1 1 2 2 2 3 3 3 1 2 2 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 2 2 3 Output 1 2 3 1 2 1 2 1 3 4 3 2 4 2 1 3 2 1 2 3 1 2 3 1 2 3 2 -----Note----- In the first test case $p = [1, 2, 3]$. It is a correct answer, because: $p_1 = 1 = a_1$, $p_2 = 2 = b_2$, $p_3 = 3 = c_3$ $p_1 \neq p_2 $, $p_2 \neq p_3 $, $p_3 \neq p_1$ All possible correct answers to this test case are: $[1, 2, 3]$, $[1, 3, 2]$, $[2, 1, 3]$, $[2, 3, 1]$, $[3, 1, 2]$, $[3, 2, 1]$. In the second test case $p = [1, 2, 1, 2]$. In this sequence $p_1 = a_1$, $p_2 = a_2$, $p_3 = a_3$, $p_4 = a_4$. Also we can see, that no two adjacent elements of the sequence are equal. In the third test case $p = [1, 3, 4, 3, 2, 4, 2]$. In this sequence $p_1 = a_1$, $p_2 = a_2$, $p_3 = b_3$, $p_4 = b_4$, $p_5 = b_5$, $p_6 = c_6$, $p_7 = c_7$. Also we can see, that no two adjacent elements of the sequence are equal.
["import sys\nimport random\nfrom fractions import Fraction\nfrom math import *\n \ndef input():\n return sys.stdin.readline().strip()\n \ndef iinput():\n return int(input())\n\ndef finput():\n return float(input())\n\ndef tinput():\n return input().split()\n\ndef linput():\n return list(input())\n \ndef rinput():\n return list(map(int, tinput()))\n\ndef fiinput():\n return list(map(float, tinput()))\n \ndef rlinput():\n return list(map(int, input().split()))\ndef trinput():\n return tuple(rinput())\n\ndef srlinput():\n return sorted(list(map(int, input().split())))\n\ndef NOYES(fl):\n if fl:\n print(\"NO\")\n else:\n print(\"YES\")\ndef YESNO(fl):\n if fl:\n print(\"YES\")\n else:\n print(\"NO\")\n \ndef main():\n n = iinput()\n #k = iinput() \n #m = iinput() \n #n = int(sys.stdin.readline().strip()) \n #n, k = rinput()\n #n, m = rinput()\n #m, k = rinput()\n #n, k, m = rinput()\n #n, m, k = rinput()\n #k, n, m = rinput()\n #k, m, n = rinput() \n #m, k, n = rinput()\n #m, n, k = rinput()\n q = [rlinput(), rlinput(), rlinput()]\n #q = linput()\n ans = q[0].copy()\n for i in range(1, n):\n if ans[i] == ans[i - 1]:\n ans[i] = q[1][i]\n if i == n - 1:\n o = 0\n while q[o][i] == ans[n - 2] or q[o][i] == ans[0]:\n o += 1\n ans[i] = q[o][i]\n print(*ans)\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n\nfor i in range(iinput()):\n main()\n", "for _ in range(int(input())):\n n=int(input())\n a=list(map(int,input().split()))\n b=list(map(int,input().split()))\n c=list(map(int,input().split()))\n p=a\n for i in range(n):\n if p[i]==p[(i+1)%n]:\n if p[i]!=b[i] and p[(i-1)%n]!=b[i]:p[i]=b[i]\n else:p[i]=c[i]\n print(*p)", "for __ in range(int(input())):\n n = int(input())\n ar1 = list(map(int, input().split()))\n ar2 = list(map(int, input().split()))\n ar3 = list(map(int, input().split()))\n ans = [ar1[0]]\n for i in range(1, n - 1):\n if ar1[i] != ans[-1]:\n ans.append(ar1[i])\n elif ar2[i] != ans[-1]:\n ans.append(ar2[i])\n elif ar3[i] != ans[-1]:\n ans.append(ar3[i])\n if ar1[-1] != ans[-1] and ar1[-1] != ans[0]:\n ans.append(ar1[-1])\n elif ar2[-1] != ans[-1] and ar2[-1] != ans[0]:\n ans.append(ar2[-1])\n elif ar3[-1] != ans[-1] and ar3[-1] != ans[0]:\n ans.append(ar3[-1])\n print(*ans)", "T = int(input())\n\nfor t in range(T):\n N = int(input())\n A = [int(_) for _ in input().split()]\n B = [int(_) for _ in input().split()]\n C = [int(_) for _ in input().split()]\n\n R = []\n\n for i in range(N):\n if i == 0:\n R.append(A[i])\n continue\n if i == N-1:\n if A[i] != R[0] and A[i] != R[-1]:\n R.append(A[i])\n elif B[i] != R[0] and B[i] != R[-1]:\n R.append(B[i])\n else:\n R.append(C[i])\n continue\n\n if A[i] != R[-1]:\n R.append(A[i])\n else:\n R.append(B[i])\n\n print(' '.join(map(str, R)))\n", "gans = []\nfor _ in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n c = list(map(int, input().split()))\n ans = [a[0]]\n for i in range(1, n - 1):\n if a[i] != ans[i - 1]:\n ans.append(a[i])\n else:\n ans.append(b[i])\n if a[-1] != ans[-1] and a[-1] != ans[0]:\n ans.append(a[-1])\n elif b[-1] != ans[-1] and b[-1] != ans[0]:\n ans.append(b[-1])\n else:\n ans.append(c[-1])\n gans.append(' '.join(map(str, ans)))\nprint('\\n'.join(gans))\n", "from math import *\nfrom bisect import *\nfrom collections import *\nfrom random import *\nfrom decimal import *\nimport sys\ninput=sys.stdin.readline\ndef inp():\n return int(input())\ndef st():\n return input().rstrip('\\n')\ndef lis():\n return list(map(int,input().split()))\ndef ma():\n return list(map(int,input().split()))\nt=inp()\nwhile(t):\n t-=1\n n=inp()\n a=lis()\n b=lis()\n c=lis()\n r=[a[0]]\n for i in range(1,n):\n if(i==n-1):\n if(a[i]!=r[0] and a[i]!=r[-1]):\n r.append(a[i])\n continue\n if(b[i]!=r[0] and b[i]!=r[-1]):\n r.append(b[i])\n continue\n if(c[i]!=r[0] and c[i]!=r[-1]):\n r.append(c[i])\n continue\n if(a[i]!=r[-1]):\n r.append(a[i])\n continue\n if(b[i]!=r[-1]):\n r.append(b[i])\n continue\n if(c[i]!=r[-1]):\n r.append(c[i])\n continue\n print(*r)\n \n \n \n"]
{ "inputs": [ "5\n3\n1 1 1\n2 2 2\n3 3 3\n4\n1 2 1 2\n2 1 2 1\n3 4 3 4\n7\n1 3 3 1 1 1 1\n2 4 4 3 2 2 4\n4 2 2 2 4 4 2\n3\n1 2 1\n2 3 3\n3 1 2\n10\n1 1 1 2 2 2 3 3 3 1\n2 2 2 3 3 3 1 1 1 2\n3 3 3 1 1 1 2 2 2 3\n" ], "outputs": [ "1 2 3\n1 2 1 2\n1 3 4 1 2 1 4\n1 2 3\n1 2 1 2 3 2 3 1 3 2\n" ] }
interview
https://codeforces.com/problemset/problem/1408/A
3
You have $n$ barrels lined up in a row, numbered from left to right from one. Initially, the $i$-th barrel contains $a_i$ liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $x$ and $y$ (the $x$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $x$ to barrel $y$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times. Some examples: if you have four barrels, each containing $5$ liters of water, and $k = 1$, you may pour $5$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $[5, 0, 5, 10]$, and the difference between the maximum and the minimum is $10$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $0$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$) — the number of barrels and the number of pourings you can make. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{9}$), where $a_i$ is the initial amount of water the $i$-th barrel has. It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times. -----Example----- Input 2 4 1 5 5 5 5 3 2 0 0 0 Output 10 0
["def solve():\n n, k = map(int,input().split())\n lst = list(map(int,input().split()))\n lst.sort()\n ans = 0\n for i in range(n - k - 1, n):\n ans += lst[i]\n print(ans)\nfor i in range(int(input())):\n solve()", "t=int(input())\nfor i in range(t):\n n,k=[int(i) for i in input().split()]\n a=[int(i) for i in input().split()]\n a.sort(reverse=True)\n print(sum(a[:k+1]))", "# map(int, input().split())\nrw = int(input())\nfor wewq in range(rw):\n n, k = list(map(int, input().split()))\n a = list(map(int, input().split()))\n a.sort()\n a.reverse()\n f = 0\n for i in range(k + 1):\n f += a[i]\n print(f)\n", "t=int(input())\nfor you in range(t):\n l=input().split()\n n=int(l[0])\n k=int(l[1])\n l=input().split()\n li=[int(i) for i in l]\n if(k==0):\n print(max(li)-min(li))\n continue\n z=0\n li.sort()\n li.reverse()\n for i in range(k+1):\n z+=li[i]\n print(z)\n", "for _ in range (int(input())):\n n,k=map(int,input().split())\n a=list(map(int,input().split()))\n a.sort(reverse=True)\n for i in range (1,k+1):\n a[0]+=a[i]\n a[i]=0\n print(a[0]-a[1])", "for __ in range(int(input())):\n n, k = list(map(int, input().split()))\n ar = list(map(int, input().split()))\n ar.sort(reverse=True)\n ans = 0\n for i in range(min(n, k + 1)):\n ans += ar[i]\n print(ans)", "import sys, math\nimport io, os\n#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline\nfrom bisect import bisect_left as bl, bisect_right as br, insort\nfrom heapq import heapify, heappush, heappop\nfrom collections import defaultdict as dd, deque, Counter\n#from itertools import permutations,combinations\ndef data(): return sys.stdin.readline().strip()\ndef mdata(): return list(map(int, data().split()))\ndef outl(var) : sys.stdout.write('\\n'.join(map(str, var))+'\\n')\ndef out(var) : sys.stdout.write(str(var)+'\\n')\n#from decimal import Decimal\n#from fractions import Fraction\n#sys.setrecursionlimit(100000)\nINF = float('inf')\nmod=10**9+7\n\n\nfor t in range(int(data())):\n n,k=mdata()\n a=sorted(mdata(),reverse=True)\n s=sum(a[:k+1])\n out(s)\n", "import sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor i in range(t):\n n,k = map(int,input().split())\n a = list(map(int,input().split()))\n a.sort()\n a.reverse()\n cum = [a[0]]\n for i in range(n-1):\n cum.append(cum[i]+a[i+1])\n cum.append(cum[-1])\n print(cum[k])", "t = int(input())\nfor _ in range(t):\n #n = int(input())\n n, k=map(int, input().split())\n a = list(map(int, input().split()))\n a.sort()\n s=0\n for i in range(k+1):\n s+=a[n-1-i]\n print(s)", "def main():\n N, K = list(map(int, input().split()))\n *A, = list(map(int, input().split()))\n \n A.sort()\n print(A[-1] + sum(A[-K-1:-1]))\n\ndef __starting_point():\n for __ in [0]*int(input()):\n main()\n\n__starting_point()", "import sys\nimport random\n# import numpy as np\nimport math\nimport copy\nfrom heapq import heappush, heappop, heapify\nfrom functools import cmp_to_key\nfrom bisect import bisect_left, bisect_right\nfrom collections import defaultdict, deque, Counter\n# sys.setrecursionlimit(1000000)\n# input aliases\ninput = sys.stdin.readline\ngetS = lambda: input().strip()\ngetN = lambda: int(input())\ngetList = lambda: list(map(int, input().split()))\ngetZList = lambda: [int(x) - 1 for x in input().split()]\n\nINF = float(\"inf\")\n\nMOD = 10 ** 9 + 7\ndivide = lambda x: pow(x, MOD-2, MOD)\n\ndef judge(at, ax, ay, bt, bx, by):\n if abs(at - bt) >= abs(ax - bx) + abs(ay - by):\n return True\n else:\n return False\n\n\ndef solve():\n n, k = getList()\n li = getList()\n\n if k >= n:\n print(sum(li))\n return\n\n li.sort(reverse=True)\n print(sum(li[:k+1]))\n\n return\n\ndef main():\n n = getN()\n for _ in range(n):\n solve()\n\n return\ndef __starting_point():\n main()\n # solve()\n\n__starting_point()", "from sys import stdin\nt = int(stdin.readline())\nfor _ in range(t):\n n, k = tuple(int(x) for x in stdin.readline().split())\n lst = sorted(int(x) for x in stdin.readline().split())\n print(sum(lst[-k-1:]))\n", "t = int(input())\nfor _ in range(t):\n n,k = [int(x) for x in input().split()]\n l = [int(x) for x in input().split()]\n l.sort()\n l.reverse()\n print(sum(l[:min(k+1,n)]))", "for _ in range(int(input())):\n\tn, k = list(map(int, input().split()))\n\tA = list(map(int, input().split()))\n\n\tA.sort(reverse=True)\n\tif k == 0:\n\t\tprint(max(A) - min(A))\n\telse:\n\t\tprint(A[0] + sum(A[1:k+1]))\n", "n = int(input())\n\nfor _ in range(n):\n n, k = list(map(int, input().split()))\n arr = list(map(int, input().split()))\n arr.sort(reverse=True)\n\n print(sum(arr[:k+1]))\n", "\"\"\"T=int(input())\nfor _ in range(0,T):\n n=int(input())\n a,b=map(int,input().split())\n s=input()\n s=[int(x) for x in input().split()]\n for i in range(0,len(s)):\n a,b=map(int,input().split())\"\"\"\n\n\nT=int(input())\nfor _ in range(0,T):\n n,k=list(map(int,input().split()))\n s=[int(x) for x in input().split()]\n s.sort()\n s=s[::-1]\n for i in range(1,min(k+1,len(s))):\n s[0]+=s[i]\n\n print(s[0])\n", "t=int(input())\nwhile t:\n\tt-=1\n\tn,k=list(map(int,input().split()))\n\ta=[int(i) for i in input().split()]\n\ta.sort()\n\tans=0\n\ta.reverse()\n\tfor i in range(k+1):\n\t\tans+=a[i]\n\t\t\n\tprint(ans)\n"]
{ "inputs": [ "2\n4 1\n5 5 5 5\n3 2\n0 0 0\n" ], "outputs": [ "10\n0\n" ] }
interview
https://codeforces.com/problemset/problem/1430/B
4
You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$. For example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$; if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$; if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$; it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$ for $m = 2$ and for $m = 4$. You are given a permutation $p=[p_1, p_2, \ldots, p_n]$. For all $m$ ($1 \le m \le n$) determine if it is a beautiful number or not. -----Input----- The first line contains the only integer $t$ ($1 \le t \le 1000$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the given permutation $p$. The next line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$, all $p_i$ are different) — the given permutation $p$. It is guaranteed, that the sum of $n$ from all test cases in the input doesn't exceed $2 \cdot 10^5$. -----Output----- Print $t$ lines — the answers to test cases in the order they are given in the input. The answer to a test case is the string of length $n$, there the $i$-th character is equal to $1$ if $i$ is a beautiful number and is equal to $0$ if $i$ is not a beautiful number. -----Example----- Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 -----Note----- The first test case is described in the problem statement. In the second test case all numbers from $1$ to $5$ are beautiful: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 4$ we will have a permutation $[1, 2]$ for $m = 2$; if $l = 2$ and $r = 4$ we will have a permutation $[3, 1, 2]$ for $m = 3$; if $l = 2$ and $r = 5$ we will have a permutation $[3, 1, 2, 4]$ for $m = 4$; if $l = 1$ and $r = 5$ we will have a permutation $[5, 3, 1, 2, 4]$ for $m = 5$.
["for _ in range(int(input())):\n input()\n nums = [int(x) for x in input().split()]\n new_ar = list(zip(nums,[i for i in range(len(nums))]))\n new_ar.sort()\n \n maxx = new_ar[0][1]\n minn = new_ar[0][1]\n s=\"1\"\n for j in range(1,len(new_ar)):\n if(new_ar[j][1]>maxx):\n maxx = new_ar[j][1]\n if(new_ar[j][1]<minn):\n minn = new_ar[j][1]\n if(maxx-minn<j+1):\n s+=\"1\"\n else:\n s+=\"0\"\n \n print(s)", "import sys\ndef I():\n return sys.stdin.readline().rstrip()\n\nfor _ in range(int(I())):\n n = int(I())\n l = list(map(int,I().split()))\n r = list(range(n))\n r.sort(key=lambda x: l[x])\n mn, mx = None, None\n for i in range(n):\n if mn is None:\n mn = mx = r[ i ]\n else:\n mn = min( mn, r[ i ] )\n mx = max( mx, r[ i ] )\n l[ i ] = '1' if mx - mn == i else '0'\n print(\"\".join(l))\n", "from sys import stdin\ndef rl():\n return [int(w) for w in stdin.readline().split()]\n\nk, = rl()\nfor _ in range(k):\n n, = rl()\n p = rl()\n\n q = [0] * n\n for i, x in enumerate(p):\n q[x-1] = i\n\n l = r = q[0]\n m = []\n for k, i in enumerate(q):\n if i < l:\n l = i\n elif i > r:\n r = i\n m.append('1' if r - l == k else '0')\n print(''.join(m))\n", "# @author \n\nimport sys\n\nclass BBeautifulNumbers:\n def solve(self):\n for _ in range(int(input())):\n n = int(input())\n p = [int(_) - 1 for _ in input().split()]\n\n mn_index = [float('inf')] * n\n mx_index = [-float('inf')] * n\n prev = [0] * n\n for i in range(n):\n prev[p[i]] = i\n # print(prev)\n for i in range(n):\n mn_index[i] = min(mn_index[i - 1], prev[i])\n mx_index[i] = max(mx_index[i - 1], prev[i])\n\n ans = ['0'] * n\n # print(mn_index, mx_index)\n for i in range(n):\n l, r = mn_index[i], mx_index[i]\n ans[i] = '1' if r - l + 1 == i + 1 else '0'\n\n print(''.join(ans))\n\nsolver = BBeautifulNumbers()\ninput = sys.stdin.readline\n\nsolver.solve()\n", "def f(L):\n n=len(L)\n M=[0]*(len(L)+1)\n for i in range(len(L)):\n M[L[i]]=i\n s=[0]*len(L)\n s[0]=1\n sumof=M[1]\n mx=M[1]\n mi=M[1]\n for i in range(2,n):\n k=M[i]\n if k>mx:mx=k\n if k<mi:mi=k\n sumof+=k\n if sumof==(mx*(mx+1))//2-((mi-1)*mi)//2:\n s[i-1]=1\n s[n-1]=1\n return s\nfor i in ' '*int(input()):\n n=int(input())\n s=f(list(map(int,input().split())))\n for i in s:print(i,end='')\n print()", "t=int(input())\nfor _ in range(t):\n n=int(input())\n a=list(map(int,input().split()))\n pos=[0 for i in range(n+1)]\n for i in range(n):\n pos[a[i]]=i\n ans=[-1 for i in range(n)]\n ans[0]=1\n l,r=pos[1],pos[1]\n for i in range(2,n+1):\n l=min(l,pos[i])\n r=max(r,pos[i])\n if r-l==i-1:\n ans[i-1]=1\n else:\n ans[i-1]=0\n print(\"\".join(map(str,ans)))", "t = int(input())\n\nfor t_i in range(t):\n n = int(input())\n P = input().split()\n l, r = -1, -1\n for i in range(n):\n P[i] = int(P[i])\n if P[i] == 1:\n l = i\n r = i\n max_seen = 1\n beaut = ['1']\n for _ in range(n - 1):\n if l == 0:\n l_cand = 10**8\n else:\n l_cand = P[l - 1]\n if r == n - 1:\n r_cand = 10**8\n else:\n r_cand = P[r + 1]\n if r_cand > l_cand:\n l -= 1\n max_seen = max(l_cand, max_seen)\n else:\n r += 1\n max_seen = max(r_cand, max_seen)\n beaut.append('1' if max_seen == r - l + 1 else '0')\n print(''.join(beaut))\n \n", "for _ in range(int(input())):\n n = int(input())\n a = list(map(int,input().split()))\n d = {}\n for i in range(n):\n d[a[i]] = i\n\n ans = ''\n mn = 200001\n mx = -1\n for i in range(1,n+1):\n if(mn > d[i]):\n mn = d[i]\n if(mx < d[i]):\n mx = d[i]\n\n \n if(mx - mn + 1 > i):\n ans += '0'\n\n else:\n ans += '1'\n\n\n print(ans)\n", "from math import *\nfrom collections import *\nimport sys\nsys.setrecursionlimit(10**9)\n\nt = int(input())\nfor y in range(t):\n\tn = int(input())\n\ta = list(map(int,input().split()))\n\tans = ['1']\n\tle = 1\n\tl = a.index(1)\n\tl -= 1\n\tr = l + 2\n\tm = 1\n\twhile(le < n):\n\t\tif(l != -1 and r != n):\n\t\t\tif(a[l] > a[r]):\n\t\t\t\tm = max(m,a[r])\n\t\t\t\tr += 1\n\t\t\t\tif(m == le+1):\n\t\t\t\t\tans.append('1')\n\t\t\t\telse:\n\t\t\t\t\tans.append('0')\n\t\t\telse:\n\t\t\t\tm = max(m,a[l])\n\t\t\t\tl -= 1\n\t\t\t\tif(m == le+1):\n\t\t\t\t\tans.append('1')\n\t\t\t\telse:\n\t\t\t\t\tans.append('0')\n\t\telif(l != -1):\n\t\t\tm = max(m,a[l])\n\t\t\tl -= 1\n\t\t\tif(m == le+1):\n\t\t\t\tans.append('1')\n\t\t\telse:\n\t\t\t\tans.append('0')\n\t\telse:\n\t\t\tm = max(m,a[r])\n\t\t\tr += 1\n\t\t\tif(m == le+1):\n\t\t\t\tans.append('1')\n\t\t\telse:\n\t\t\t\tans.append('0')\n\t\tle += 1\n\tprint(\"\".join(ans))\n\n\n\n", "t = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n pos = [0]*(n+1)\n for i, x in enumerate(a):\n pos[x] = i\n\n used = [0, 1] + [0]*n\n ans = [0]*n\n l, r = pos[1], pos[1]\n count = 1\n\n for x in range(1, n+1):\n if not used[x]:\n if pos[x] < l:\n while not used[x]:\n l -= 1\n used[a[l]] = 1\n count += 1\n else:\n while not used[x]:\n r += 1\n used[a[r]] = 1\n count += 1\n\n if count == x:\n ans[x-1] = 1\n\n print(*ans, sep='')", "def mi():\n return map(int, input().split())\n\n'''\n3\n6\n4 5 1 3 2 6\n5\n5 3 1 2 4\n4\n1 4 3 2\n3\n6\n4 5 1 3 2 6\n5\n5 3 1 2 4\n4\n1 4 3 2\n'''\nfor _ in range(int(input())):\n n = int(input())\n a = list(mi())\n t = a.index(1)\n dist = [0]*(n+1)\n dic = [0]*n\n for i in range(n):\n dist[a[i]] = abs(t-i)\n dic[i] = [a[i], i]\n dic.sort()\n lm = dic[0][1]\n rm = dic[0][1]\n print (1, end = '')\n for i in range(1, n):\n if (dic[i][1]<lm):\n lm = dic[i][1]\n if (dic[i][1]>rm):\n rm = dic[i][1]\n if rm-lm<i+1:\n print (1, end = '')\n else:\n print (0, end = '')\n print()", "from sys import stdin\ninput = stdin.readline\n\n\nt = int(input())\n\nfor _ in range(t):\n\n n = int(input())\n a = list(map(int,input().split()))\n\n start = 0\n for i,v in enumerate(a):\n if v == 1:\n start = i\n break\n ans = [0]*-~n\n ans[n-1] = 1\n mx = 1\n l = start\n r = start\n\n def move(x):\n nonlocal l,r,mx\n if x:\n mx = max(a[r+1],mx)\n r += 1\n else:\n mx = max(a[l-1],mx)\n l -= 1\n\n\n while mx < n:\n if mx == r-l+1:\n ans[mx-1] = 1\n if l == 0:\n move(1)\n elif r == n-1:\n move(0)\n else:\n if a[l-1] > a[r+1]:\n move(1)\n else:\n move(0)\n\n print(\"\".join(map(str,ans[:n])))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "#!/usr/bin/env python3\nfrom itertools import combinations\nimport sys\ninput = sys.stdin.readline\nINF = 10**9\n\nt = int(input())\nfor i in range(t):\n n = int(input())\n a = [INF] + [int(item) for item in input().split()] + [INF]\n ans = [1]\n l = r = a.index(1)\n max_val = 1\n for i in range(2, n+1):\n if i == max(max_val, a[l-1]):\n ans.append(1)\n l -= 1\n max_val = i\n elif i == max(max_val, a[r+1]):\n ans.append(1)\n r += 1\n max_val = i\n elif a[l-1] < a[r+1]:\n ans.append(0)\n max_val = max(max_val, a[l-1])\n l -= 1\n else:\n ans.append(0)\n max_val = max(max_val, a[r+1])\n r += 1\n print(\"\".join([str(item) for item in ans]))", "for j in range(int(input())):\n n = int(input())\n c = list(map(int,input().split()))\n index = [0]*n\n for i in range(n):\n index[c[i]-1]=i\n ma = 0\n mi = n\n ans = ['0']*n\n # print(index)\n for k in range(n):\n ma = max(index[k],ma)\n mi = min(index[k],mi)\n #print(k,mr,index[k]-index[0])\n if ma-mi<=k:\n ans[k]='1'\n print(''.join(ans))", "q=int(input())\nfor t in range(q):\n n=int(input())\n a=list(map(int,input().split()))\n ma=1\n ans='1'\n uk1=a.index(1)\n uk2=uk1\n while uk2-uk1+1!=n:\n if uk2==n-1:\n uk1-=1\n ma=max(ma,a[uk1])\n if ma==uk2-uk1+1:\n ans=ans+'1'\n else:\n ans=ans+'0'\n else:\n if uk1==0:\n uk2+=1\n ma=max(ma,a[uk2])\n if ma == uk2 - uk1 + 1:\n ans = ans + '1'\n else:\n ans=ans+'0'\n else:\n if a[uk1-1]<a[uk2+1]:\n uk1 -= 1\n ma = max(ma, a[uk1])\n if ma == uk2 - uk1 + 1:\n ans = ans + '1'\n else:\n ans = ans + '0'\n else:\n uk2 += 1\n ma = max(ma, a[uk2])\n if ma == uk2 - uk1 + 1:\n ans = ans + '1'\n else:\n ans = ans + '0'\n print(ans)", "\nlpn = int(input())\n\nfor loop in range(lpn):\n\n n = int(input())\n p = list(map(int,input().split()))\n\n for i in range(n):\n\n if p[i] == 1:\n oneind = i\n break\n\n l = oneind\n r = oneind\n nmax = 1\n ans = [0] * n\n ans[0] = 1\n\n for i in range(n-1):\n\n if l == 0 or( r != n-1 and p[l-1] > p[r+1]):\n r += 1\n nmax = max(nmax,p[r])\n if i+2 == nmax:\n ans[i+1] = 1 \n else:\n l -= 1\n nmax = max(nmax,p[l])\n\n if i+2 == nmax:\n ans[i+1] = 1 \n \n print(\"\".join(map(str,ans)))\n", "t = int(input())\nfor i in range(t):\n n = int(input())\n a = [int(i) for i in input().split()]\n ans = ['0'] * n\n ans[0] = '1'\n ans[-1] = '1'\n l = 0\n r = n - 1\n now = n\n while (r - l) > 1:\n if a[r] > now:\n r -= 1\n continue\n if a[l] > now:\n l += 1\n continue\n if (r - l + 1) == now:\n ans[r - l] = '1'\n now -= 1\n if (r - l + 1) == now:\n ans[r - l] = '1'\n print(''.join(ans))\n\n\n", "# https://codeforces.com/contest/1265/problem/B\n\ndef main():\n n = int(input())\n p = list(map(int, input().split()))\n idx = [0] * n\n for i in range(n):\n idx[p[i]-1] = i\n ans = ''\n left = n\n right = 0\n for i in range(n):\n left = min(left, idx[i])\n right = max(right, idx[i])\n if right - left == i:\n ans += '1'\n else:\n ans += '0'\n return ans\n\nt = int(input())\nfor i in range(t):\n print(main())\n", "def f():\n n = int(input())\n A = [int(s) for s in input().split()]\n ans = [0]*n\n ans[0] = 1\n ans[n-1] = 1\n i = 0\n j = n-1\n outMin = n+1\n while j>i:\n if A[i] > A[j]:\n if A[i] < outMin:\n outMin = A[i]\n i += 1\n else:\n if A[j] < outMin:\n outMin = A[j]\n j -= 1\n if j-i == outMin-2:\n ans[j-i] = 1\n print(''.join(str(i) for i in ans))\n\n\nt = int(input())\nfor i in range(t):\n f()", "n = int(input())\nfor _ in range(n):\n k = int(input())\n pos = [0] * k\n arr = list(map(int, input().split(' ')))\n for i in range(k):\n pos[arr[i] - 1] = i\n\n #print(pos)\n\n left, right = [0] * k, [0] * k\n left[0], right[0] = pos[0], pos[0]\n for i in range(1, k):\n left[i] = min(left[i - 1], pos[i])\n right[i] = max(right[i - 1], pos[i])\n\n #print(left)\n #print(right)\n for i in range(k):\n if right[i] - left[i] == i:\n print(1, end=\"\")\n else:\n print(0, end=\"\")\n print()", "for kkk in range(int(input())):\n\tn = int(input())\n\tl = list(map(int, input().split()))\n\td = {}\n\tfor i in range(n):\n\t\td[l[i]] = i\n\tans = [\"0\" for i in range(n+1)]\n\tans[1] = \"1\"\n\tposleft = d[1]\n\tposright = d[1]\n\tfor j in range(2, n+1):\n\t\tif(d[j]==posleft-1 or d[j]==posright+1):\n\t\t\tif(ans[j-1]==\"1\"):\n\t\t\t\tans[j] = \"1\"\n\t\telif(d[j]<posright and d[j]>posleft):\n\t\t\tif(posright - posleft + 1 == j):\n\t\t\t\tans[j] = \"1\"\n\t\tif(d[j]<posleft):\n\t\t\tposleft = d[j]\n\t\tif(d[j]>posright):\n\t\t\tposright = d[j]\n\tprint(''.join(ans[1:]))", "import sys\nimport math\nimport bisect\n \n \nsys.setrecursionlimit(1000000000)\ndef input():\n return sys.stdin.readline().strip()\n \ndef iinput():\n return int(input())\n \ndef finput():\n return float(input())\n \ndef tinput():\n return input().split()\n \ndef rinput():\n return map(int, tinput())\n \ndef rlinput():\n return list(rinput())\n\ndef main():\n n = iinput()\n c = rlinput()\n q, res, w, e = [0] * n, ['0'] * n, 0, n\n for i in range(n):\n q[c[i] - 1] = i\n for i in range(n):\n w = max(q[i], w)\n e = min(q[i], e)\n if w <= i + e:\n res[i] = '1'\n print(''.join(res))\n \nfor j in range(int(input())):\n main()", "from math import floor, ceil\n\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n pos = dict()\n for p, i in enumerate(a):\n pos[i] = p\n minpos = [None] + [pos[1]] + [None]*(n-1)\n maxpos = [None] + [pos[1]] + [None]*(n-1)\n\n for i in range(2, n+1):\n minpos[i] = min(minpos[i-1], pos[i])\n maxpos[i] = max(maxpos[i-1], pos[i])\n\n\n good = ['0']*n \n for i in range(1, n+1):\n if maxpos[i] - minpos[i] + 1 == i:\n good[i-1] = '1'\n\n print(''.join(good))\n\n \n"]
{ "inputs": [ "3\n6\n4 5 1 3 2 6\n5\n5 3 1 2 4\n4\n1 4 3 2\n" ], "outputs": [ "101011\n11111\n1001\n" ] }
interview
https://codeforces.com/problemset/problem/1265/B
5
The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation. Dreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$. Now Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$. You are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.) -----Input----- The first line contains an integer $t$ ($1 \le t \le 10\,000$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $n$ ($2 \leq n \leq 200\,000$): the length of $a$. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n-1$). The total sum of $n$ is less than $200\,000$. -----Output----- For each test case, the first line of output should contain one integer $k$: the number of ways to divide $a$ into permutations $p_1$ and $p_2$. Each of the next $k$ lines should contain two integers $l_1$ and $l_2$ ($1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$), denoting, that it is possible to divide $a$ into two permutations of length $l_1$ and $l_2$ ($p_1$ is the first $l_1$ elements of $a$, and $p_2$ is the last $l_2$ elements of $a$). You can print solutions in any order. -----Example----- Input 6 5 1 4 3 2 1 6 2 4 1 3 2 1 4 2 1 1 3 4 1 3 3 1 12 2 1 3 4 5 6 7 8 9 1 10 2 3 1 1 1 Output 2 1 4 4 1 1 4 2 0 0 1 2 10 0 -----Note----- In the first example, two possible ways to divide $a$ into permutations are $\{1\} + \{4, 3, 2, 1\}$ and $\{1,4,3,2\} + \{1\}$. In the second example, the only way to divide $a$ into permutations is $\{2,4,1,3\} + \{2,1\}$. In the third example, there are no possible ways.
["def possible(a):\n ans = set()\n s = set()\n lmax = 0\n for i in range(len(a)):\n lmax = max(lmax, a[i])\n s.add(a[i])\n if lmax == i + 1 and len(s) == i + 1:\n ans.add(i + 1)\n return ans\n\n\nt = int(input())\nfor case_num in range(t):\n n = int(input())\n a = list(map(int, input().split(' ')))\n left = possible(a)\n a.reverse()\n right = possible(a)\n ans = []\n for l in left:\n if n - l in right:\n ans.append(l)\n print(len(ans))\n for l in ans:\n print(l, n - l)\n", "import sys\ninput=sys.stdin.readline\nt=int(input())\nfor _ in range(t):\n n=int(input())\n aa=list(map(int,input().split()))\n ss=set()\n \n st=0\n ind=1\n pre=[0 for i in range(n)]\n for i in range(n):\n if aa[i] in ss:\n break\n ss.add(aa[i])\n while ind<=len(ss):\n if ind in ss:\n ind+=1\n else:\n break\n if len(ss)!=ind-1:\n pre[i]=0\n else:\n pre[i]=ind\n ind=1\n # print(pre)\n ss=set()\n suff=[0 for i in range(n)]\n for i in range(n-1,-1,-1):\n if aa[i] in ss:\n break\n ss.add(aa[i])\n while ind<=len(ss):\n if ind in ss:\n ind+=1\n else:\n break\n if len(ss)!=ind-1:\n suff[i]=0\n else:\n suff[i]=ind\n tot=0\n ans=[]\n for i in range(n-1):\n if pre[i]>0 and suff[i+1]>0:\n tot+=1\n ans.append([i+1,n-i-1])\n print(tot)\n for i in ans:\n print(i[0],i[1])\n \n\n", "# @author \n\nimport sys\n\nclass BDreamoonLikesPermutations:\n def solve(self):\n for _ in range(int(input())):\n \n def is_perm(a):\n return len(set(a)) == len(a) and min(a) == 1 and max(a) == len(a)\n \n n = int(input())\n a = [int(_) for _ in input().split()]\n done = set()\n ans = set()\n i = 0\n for i in range(n):\n if a[i] in done:\n break\n done.add(a[i])\n \n if is_perm(a[:i]) and is_perm(a[i:]):\n ans.add((i, n - i))\n\n done = set()\n for i in range(n - 1, -1, -1):\n if a[i] in done:\n break\n done.add(a[i])\n\n if is_perm(a[:i + 1]) and is_perm(a[i + 1:]):\n ans.add((i + 1, n - i - 1))\n\n print(len(ans))\n for sol in ans:\n print(*sol)\n\nsolver = BDreamoonLikesPermutations()\ninput = sys.stdin.readline\n\nsolver.solve()\n", "def readIntArray():\n return list(map(int,input().split()))\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = readIntArray()\n mp = {}\n for val in a:\n if val not in mp:\n mp[val] = 0\n mp[val] += 1\n l1 = max(a)\n l2 = n - l1\n if l2 <= 0:\n print(0)\n continue\n good = True\n for i in range(1, l2 + 1):\n if i not in mp or mp[i] != 2:\n good = False\n break\n for i in range(l2 + 1, l1 + 1):\n if i not in mp or mp[i] != 1:\n good = False\n break\n if not good:\n print(0)\n continue\n mp = {}\n ans = set()\n cur = 0\n st = set()\n used = set()\n for i in range(n):\n if a[i] in used:\n break\n st.add(a[i])\n used.add(a[i])\n while cur + 1 in st:\n st.remove(cur + 1)\n cur += 1\n if cur == l1 or cur == l2 and len(st) == 0:\n ans.add((cur, n - cur))\n print(len(ans))\n for val in ans:\n print(val[0], val[1])\n", "t = int(input())\nfor _ in range(t):\n n = int(input())\n a = [int(x) for x in input().split()]\n mx = max(a)\n sols = []\n if mx < n:\n l1 = list(sorted(a[:mx]))\n l2 = list(sorted(a[mx:]))\n rl1 = list(range(1, mx+1))\n rl2 = list(range(1, n-mx+1))\n if l1 == rl1 and l2 == rl2:\n sols.append((mx, n - mx))\n l1 = list(sorted(a[:n-mx]))\n l2 = list(sorted(a[n-mx:]))\n if mx*2 != n and l1 == rl2 and l2 == rl1:\n sols.append((n-mx, mx))\n print(len(sols))\n for p in sols:\n print(*p)\n", "from collections import deque\nt = int(input())\nfor _ in range(t):\n n = int(input())\n liste = list(map(int, input().split()))\n vis = [0 for i in range(n)]\n can = [0 for i in range(n)]\n can2 = [0 for i in range(n)]\n maxi = 0\n for i in range(1, n):\n if (vis[liste[i-1]]):\n break\n vis[liste[i-1]] = 1\n maxi = max(maxi, liste[i-1])\n if (maxi == i):\n can[maxi] = 1\n liste = liste[::-1]\n maxi = 0\n vis = [0 for i in range(n)]\n for i in range(1, n):\n if (vis[liste[i-1]]):\n break\n vis[liste[i-1]] = 1\n maxi = max(maxi, liste[i-1])\n if (maxi == i):\n can2[maxi] = 1\n count = 0\n for i in range(1, n):\n if (can[i] and can2[n-i]):\n count += 1\n print(count)\n for i in range(1, n):\n if (can[i] and can2[n-i]):\n print(i, n-i)", "for _ in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n dpF = [0 for i in range(n)]\n dpB = [0 for i in range(n)]\n noRep = 1\n r = {}\n m = 0\n for i in range(n):\n if r.get(a[i]) == None:\n r[a[i]] = 1\n m = max(m, a[i])\n if m == i + 1:\n dpF[i] = 1\n else:\n break\n r = {}\n m = 0\n for i in range(n - 1, -1, -1):\n if r.get(a[i]) == None:\n r[a[i]] = 1\n m = max(m, a[i])\n if m == n - i:\n dpB[i] = 1\n else:\n break\n # print(dpF)\n # print(dpB)\n ans = 0\n ansList = []\n for i in range(n - 1):\n if dpF[i] == 1 and dpB[i + 1] == 1:\n ans += 1\n ansList.append([i + 1, n - i - 1])\n print(ans)\n for i in ansList:\n print(i[0], i[1])", "from math import *\n\nmod = 1000000007\n\nfor zz in range(int(input())):\n n = int(input())\n a = [int(i) for i in input().split()]\n ans = []\n cs = set()\n d = {}\n c = 0\n for i in range(n):\n if a[i] not in d:\n c += 1\n d[a[i]] = 0\n d[a[i]] += 1\n mv = 0\n m = [0] * n\n m[-1] = a[-1]\n for i in range(n - 2, -1, -1):\n m[i] = max(m[i + 1], a[i])\n\n for i in range(n):\n mv = max(a[i], mv)\n if a[i] in cs:\n break\n cs.add(a[i])\n d[a[i]] -= 1\n if d[a[i]] <= 0:\n c -= 1\n if mv == i + 1 and c == n - i - 1 and m[i + 1] == n - i - 1:\n ans.append(i)\n print(len(ans))\n for i in ans:\n print(i + 1, n - i - 1)\n", "def per(X):\n S=set(X)\n if not len(X)==len(S):\n return False\n for i in range(1,len(X)+1):\n if i not in S: return False\n return True\nfor y in range(int(input())):\n n=int(input())\n L=list(map(int,input().split()))\n m=max(L)\n r=[]\n if n!=m:\n if per(L[:m]) and per(L[m:]):\n r.append((m,n-m))\n if per(L[-m:]) and per(L[:-m]):\n r.append((n-m,m))\n r=list(set(r))\n print(len(r))\n for a,b in r:\n print(a,b)", "import sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n seen = [False] * (n+1)\n ans = set()\n for i, x in enumerate(a):\n if seen[x]:\n if sorted(a[:i]) == list(range(1, i+1)) and sorted(a[i:]) == list(range(1, n-i+1)):\n ans.add((i, n-i))\n break\n seen[x] = True\n seen = [False] * (n+1)\n for i, x in list(enumerate(a))[::-1]:\n if seen[x]:\n if sorted(a[:i+1]) == list(range(1, i+2)) and sorted(a[i+1:]) == list(range(1, n-i)):\n ans.add((i+1, n-i-1))\n break\n seen[x] = True\n print(len(ans))\n for l1, l2 in ans:\n print(l1, l2)\n\n", "import sys\ninput=sys.stdin.readline\nt=int(input())\nfor _ in range(t):\n n=int(input())\n arr=list(map(int,input().split()))\n d=dict()\n demand=1\n pre=[0]*n\n post=[0]*n\n for i in range(n):\n d[arr[i]]=1\n if(demand in d):\n while(demand in d):\n demand+=1\n pre[i]=demand-1\n d2=dict()\n #print(pre)\n demand=1\n for i in range(n-1,-1,-1):\n d2[arr[i]]=1\n if(demand in d2):\n while(demand in d2):\n demand+=1\n post[i]=demand-1\n #print(post)\n l=[]\n for i in range(1,n):\n if(post[i]+pre[i-1]==n):\n l+=[[pre[i-1],post[i]]]\n print(len(l))\n for i in l:\n print(*i)\n \n \n", "import heapq, sys\n\n\ndef ps(l):\n n = len(l)\n nxt = 1\n heap = []\n ans = []\n for i in range(n):\n heapq.heappush(heap, l[i])\n while heap and heap[0] == nxt:\n nxt += 1\n heapq.heappop(heap)\n if not heap:\n ans.append(i)\n return ans\n\n\nfor q in range(int(sys.stdin.readline())):\n n = int(sys.stdin.readline())\n d = [int(i) for i in sys.stdin.readline().split()]\n st = set(ps(d))\n # print(st)\n d.reverse()\n anss = []\n ap = ps(d)\n # print(ap)\n for a in ap:\n b = n-2-a\n if b in st:\n anss.append(str(b+1)+' '+ str(n - b - 1) + '\\n')\n sys.stdout.write(str(len(anss)) + '\\n')\n sys.stdout.write(''.join(anss))\n\n\n"]
{ "inputs": [ "6\n5\n1 4 3 2 1\n6\n2 4 1 3 2 1\n4\n2 1 1 3\n4\n1 3 3 1\n12\n2 1 3 4 5 6 7 8 9 1 10 2\n3\n1 1 1\n" ], "outputs": [ "2\n1 4\n4 1\n1\n4 2\n0\n0\n1\n2 10\n0\n" ] }
interview
https://codeforces.com/problemset/problem/1330/B
6
Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot. A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks. Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. Formally, after closing some of the spots, there should not be a path that consists of two or more tracks. Arthur doesn't want to close too many spots. He will be happy to find any way to close at most $\frac{4}{7}n$ spots so that the remaining part is safe. Help him find any suitable way to do so. -----Input----- The first line contains a single positive integer $T$ — the number of test cases. $T$ test case description follows. The first line of each description contains two integers $n$ and $m$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of landing spots and tracks respectively. The following $m$ lines describe the tracks. Each of these lines contains two integers $x$ and $y$ ($1 \leq x < y \leq n$) — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, print a single integer $k$ ($0 \leq k \leq \frac{4}{7}n$) — the number of spots to be closed. In the next line, print $k$ distinct integers — indices of all spots to be closed, in any order. If there are several answers, you may output any of them. Note that you don't have to minimize $k$. It can be shown that a suitable answer always exists. -----Example----- Input 2 4 6 1 2 1 3 2 3 2 4 3 4 3 4 7 6 1 2 1 3 2 4 2 5 3 6 3 7 Output 2 3 4 4 4 5 6 7 -----Note----- In the first sample case, closing any two spots is suitable. In the second sample case, closing only the spot $1$ is also suitable.
["import sys\ninput = sys.stdin.readline\nfor f in range(int(input())):\n n,m=list(map(int,input().split()))\n neig=[0]*n\n for i in range(n):\n neig[i]=[0]\n \n for i in range(m):\n a,b=list(map(int,input().split()))\n a-=1\n b-=1\n neig[a][0]+=1\n neig[a].append(b)\n lev=[1]*n\n for i in range(n):\n for j in range(1,neig[i][0]+1):\n x=lev[i]+1\n if x==4:\n x=1\n lev[neig[i][j]]=max(lev[neig[i][j]],x)\n sol=0\n s=[]\n for i in range(n):\n if lev[i]==3:\n sol+=1\n s.append(i+1)\n print(sol)\n print(*s)\n \n", "import sys\ninput = sys.stdin.readline\nfrom heapq import heapify,heappush,heappop\nt = int(input())\nfor _ in range(t):\n n,m = map(int,input().split())\n ab = [list(map(int,input().split())) for i in range(m)]\n go = [[] for i in range(n+1)]\n come = [[] for i in range(n+1)]\n for a,b in ab:\n go[a].append(b)\n come[b].append(a)\n exist = [1]*(n+1)\n flg = [10]*(n+1)\n for i in range(1,n+1):\n if flg[i] == 10:\n flg[i] = 2\n if flg[i] == 0:\n exist[i] = 0\n if go[i]:\n if flg[i] == 0:\n for j in go[i]:\n flg[j] = min(flg[j],2)\n else:\n for j in go[i]:\n flg[j] = min(flg[j],flg[i]-1)\n print(exist.count(0))\n ansls = []\n for i in range(1,n+1):\n if exist[i] == 0:\n ansls.append(i)\n print(*ansls)", "import sys\n\nT = int(sys.stdin.readline().strip())\nfor t in range (0, T):\n n, m = list(map(int, sys.stdin.readline().strip().split()))\n P = [[] for i in range (0, n)]\n G = [0] * n\n for i in range (0, m):\n x, y = list(map(int, sys.stdin.readline().strip().split()))\n x, y = x-1, y-1\n P[y].append(x)\n ans = []\n for i in range (0, n):\n for j in P[i]:\n for k in P[j]:\n if G[j] == 0 and G[k] == 0:\n if G[i] == 0:\n ans.append(str(i+1))\n G[i] = 1\n \n print(len(ans))\n print(\" \".join(ans))\n", "import sys\ninputr = lambda: sys.stdin.readline().rstrip('\\n')\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n\tn, m = list(map(int, input().split()))\n\n\n\tadj = [[] for _ in range(n)]\n\n\tfor _ in range(m):\n\t\ta, b = list(map(int, input().split()))\n\t\ta -= 1\n\t\tb -= 1\n\t\tadj[a].append(b)\n\n\tLP = [0] * n\n\n\tfor i in range(n):\n\t\tif LP[i] < 2:\n\t\t\tfor j in adj[i]:\n\t\t\t\tLP[j] = max(LP[j], LP[i] + 1)\n\n\tr = [i+1 for i in range(n) if LP[i] >= 2]\n\n\tprint(len(r))\n\tprint(' '.join(map(str, r)))\n\n\tassert 7 * len(r) <= 4 * n\n\n", "import sys\ninputr = lambda: sys.stdin.readline().rstrip('\\n')\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n\tn, m = list(map(int, input().split()))\n\tadj = [[] for _ in range(n)]\n\n\tfor _ in range(m):\n\t\ta, b = list(map(int, input().split()))\n\t\ta -= 1\n\t\tb -= 1\n\t\tadj[a].append(b)\n\n\tLP = [0] * n\n\tr = []\n\n\tfor i in range(n):\n\t\tif LP[i] < 2:\n\t\t\tfor j in adj[i]:\n\t\t\t\tLP[j] = max(LP[j], LP[i] + 1)\n\t\telse:\n\t\t\tr.append(str(i+1))\n\n\tprint(len(r))\n\tprint(*r)\n\n\tassert 7 * len(r) <= 4 * n\n\n", "#!/usr/bin/env python3\nimport sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nclass DirectedGraph:\n def __init__(self, adj):\n self.n = len(adj)\n self.adj = adj\n self.is_asyclic = False\n self.max_path_len = None\n\n def topological_sort(self):\n indegree = [0] * self.n\n for vs in self.adj:\n for dest in vs:\n indegree[dest] += 1\n zero_v = []\n for v, indeg in enumerate(indegree):\n if indeg == 0:\n zero_v.append(v)\n max_path_len = 1\n tp_sorted = []\n to_be_added = []\n while True:\n while zero_v:\n v = zero_v.pop()\n tp_sorted.append(v)\n for dest in self.adj[v]:\n indegree[dest] -= 1\n if indegree[dest] == 0:\n to_be_added.append(dest)\n if len(to_be_added) > 0:\n zero_v.extend(to_be_added)\n to_be_added = []\n max_path_len += 1\n else:\n break\n if len(tp_sorted) == self.n:\n self.is_asyclic = True\n self.max_path_len = max_path_len\n return tp_sorted\n else:\n self.is_asyclic = False\n return None\n\nt = int(input())\nfor case in range(t):\n n, m = map(int, input().split())\n forward = [[] for _ in range(n)]\n backward = [[] for _ in range(n)]\n\n seen = set()\n for _ in range(m):\n u, v = map(int, input().split())\n u -= 1; v -= 1\n if (u, v) in seen:\n continue\n seen.add((u, v))\n forward[u].append(v)\n backward[v].append(u)\n \n DG = DirectedGraph(forward)\n tps = DG.topological_sort()\n state = [-1] * n\n state[0] = 0\n for v in tps:\n if len(backward[v]) == 0:\n state[v] = 0\n for pv in backward[v]:\n state[v] = max(state[v], (state[pv] + 1) % 3)\n \n ans = []\n for i, color in enumerate(state):\n if color == 2:\n ans.append(i + 1)\n print(len(ans))\n print(*ans)", "import sys\ndef rs(): return sys.stdin.readline().rstrip()\ndef ri(): return int(sys.stdin.readline())\ndef ria(): return list(map(int, sys.stdin.readline().split()))\ndef ws(s): sys.stdout.write(s + '\\n')\ndef wi(n): sys.stdout.write(str(n) + '\\n')\ndef wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\\n')\n\n\ndef solve(n, m, g):\n dp = [0] * n\n ans = []\n for i in range(n):\n for w in g[i]:\n dp[i] = max(dp[i], dp[w] + 1)\n if dp[i] >= 2:\n dp[i] = -1\n ans.append(i+1)\n wi(len(ans))\n wia(ans)\n\n\ndef main():\n for _ in range(ri()):\n n, m = ria()\n g = [[] for i in range(n)]\n for __ in range(m):\n u, v = ria()\n g[v-1].append(u-1)\n solve(n, m, g)\n\n\ndef __starting_point():\n main()\n\n__starting_point()"]
{ "inputs": [ "2\n4 6\n1 2\n1 3\n2 3\n2 4\n3 4\n3 4\n7 6\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n" ], "outputs": [ "2\n3 4 \n4\n4 5 6 7 \n" ] }
interview
https://codeforces.com/problemset/problem/1368/E
7
The only difference between easy and hard versions is constraints. Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you. There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free. Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$. Calculate the minimum number of coins you have to spend so that everyone votes for you. -----Input----- The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of voters. The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$). It is guaranteed that the sum of all $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you. -----Example----- Input 3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5 Output 8 0 7 -----Note----- In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$. In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$. In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: ${2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}$.
["import sys\ndef I():\n return sys.stdin.readline().rstrip()\n\nclass Heap:\n def __init__( self ):\n self.l = [ -1 ]\n self.n = 0\n def n( self ):\n return self.n\n def top( self ):\n return self.l[ 1 ]\n def ins( self, x ):\n self.l.append( x )\n n = len( self.l ) - 1\n i = n\n while i > 1:\n j = i // 2\n if self.l[ j ] > self.l[ i ]:\n self.l[ j ], self.l[ i ] = self.l[ i ], self.l[ j ]\n i = j\n else:\n break\n def pop( self ):\n r = self.l[ 1 ]\n l = self.l.pop()\n n = len( self.l ) - 1\n if n:\n self.l[ 1 ] = l\n i = 1\n while True:\n j = i * 2\n k = j + 1\n if k < len( self.l ) and self.l[ i ] > max( self.l[ j ], self.l[ k ] ):\n if self.l[ j ] == min( self.l[ j ], self.l[ k ] ):\n self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ]\n i = j\n else:\n self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ]\n i = k\n elif k < len( self.l ) and self.l[ i ] > self.l[ k ]:\n self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ]\n i = k\n elif j < len( self.l ) and self.l[ i ] > self.l[ j ]:\n self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ]\n i = j\n else:\n break\n return r\n\nt = int( I() )\nfor _ in range( t ):\n n = int( I() )\n voter = [ list( map( int, I().split() ) ) for _ in range( n ) ]\n h = Heap()\n d = {}\n for m, p in voter:\n if m not in d:\n d[ m ] = []\n d[ m ].append( p )\n need = {}\n c = 0\n sk = sorted( d.keys() )\n for m in sk:\n need[ m ] = max( 0, m - c )\n c += len( d[ m ] )\n c = 0\n ans = 0\n for m in sk[::-1]:\n for p in d[ m ]:\n h.ins( p )\n while c < need[ m ]:\n c += 1\n ans += h.pop()\n print( ans )\n", "import heapq\nimport sys\ninput = sys.stdin.readline\n\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n info = [list(map(int, input().split())) for i in range(n)]\n info = sorted(info)\n cnt = [0] * n\n for i in range(n):\n ind = info[i][0]\n cnt[ind] += 1\n ruiseki_cnt = [0] * (n+1)\n for i in range(n):\n ruiseki_cnt[i+1] = ruiseki_cnt[i] + cnt[i]\n # print(cnt)\n # print(ruiseki_cnt)\n need = [0] * n\n for i in range(1,n):\n if cnt[i] != 0 and i > ruiseki_cnt[i]:\n need[i] = min(i - ruiseki_cnt[i], i)\n # print(need)\n info = sorted(info, reverse = True)\n #print(info)\n\n num = n - 1\n pos = 0\n q = []\n used_cnt = 0\n ans = 0\n while True:\n if num == -1:\n break\n while True:\n if pos < n and info[pos][0] >= num:\n heapq.heappush(q, info[pos][1])\n pos += 1\n else:\n break\n if need[num] - used_cnt > 0:\n tmp = need[num] - used_cnt\n for _ in range(tmp):\n ans += heapq.heappop(q)\n used_cnt += tmp\n num -= 1\n print(ans)", "import sys\ninput = sys.stdin.readline\n\nimport heapq\nfrom itertools import accumulate\n\nt=int(input())\n\nfor test in range(t):\n n=int(input())\n M=[[] for i in range(n)]\n MCOUNT=[0]*(n)\n\n for i in range(n):\n m,p=list(map(int,input().split()))\n M[m].append(p)\n MCOUNT[m]+=1\n\n #print(M)\n #print(MCOUNT)\n\n ACC=list(accumulate(MCOUNT))\n\n #print(ACC)\n HQ=[]\n ANS=0\n use=0\n\n for i in range(n-1,-1,-1):\n for j in M[i]:\n heapq.heappush(HQ,j)\n\n #print(HQ)\n \n while ACC[i-1]+use<i:\n x=heapq.heappop(HQ)\n ANS+=x\n use+=1\n\n\n\n print(ANS)\n \n \n \n \n \n\n \n\n \n", "import sys\nfrom heapq import heappop, heappush\n\nreader = (line.rstrip() for line in sys.stdin)\ninput = reader.__next__\n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n mp = []\n for i in range(n):\n mi, pi = list(map(int, input().split()))\n mp.append((mi, pi))\n mp.sort()\n \n prices = []\n cost = 0\n bribed = 0\n i = n - 1\n while i >= 0:\n currM = mp[i][0]\n heappush(prices, mp[i][1])\n while i >= 1 and mp[i-1][0] == currM:\n i -= 1\n heappush(prices, mp[i][1])\n already = i + bribed\n for k in range(max(0, currM - already)):\n cost += heappop(prices)\n bribed += 1\n i -= 1\n \n print(cost)\n", "import sys\ninput = sys.stdin.readline\nimport heapq as hq\nt = int(input())\nfor _ in range(t):\n n = int(input())\n vt = [list(map(int,input().split())) for i in range(n)]\n vt.sort(reverse=True)\n q = []\n hq.heapify(q)\n ans = 0\n cnt = 0\n for i in range(n):\n hq.heappush(q,vt[i][1])\n if vt[i][0] >= n-i+cnt:\n ans += hq.heappop(q)\n cnt += 1\n print(ans)", "import sys\nimport heapq as hq\n\nreadline = sys.stdin.readline\nread = sys.stdin.read\nns = lambda: readline().rstrip()\nni = lambda: int(readline().rstrip())\nnm = lambda: map(int, readline().split())\nnl = lambda: list(map(int, readline().split()))\nprn = lambda x: print(*x, sep='\\n')\n\ndef solve():\n n = ni()\n vot = [tuple(nm()) for _ in range(n)]\n vot.sort(key = lambda x: (-x[0], x[1]))\n q = list()\n c = 0\n cost = 0\n for i in range(n):\n hq.heappush(q, vot[i][1])\n while n - i - 1 + c < vot[i][0]:\n cost += hq.heappop(q)\n c += 1\n print(cost)\n return\n\n\n# solve()\n\nT = ni()\nfor _ in range(T):\n solve()\n", "import sys\nimport heapq as hp\n#sys.stdin = open('in', 'r')\nt = int(sys.stdin.readline())\nfor ti in range(t):\n n = int(sys.stdin.readline())\n a = [tuple(map(int, sys.stdin.readline().split())) for i in range(n)]\n a.sort(key = lambda x: (x[0], -x[1]))\n c = 0\n h = []\n res = 0\n for i in range(n-1,-1,-1):\n hp.heappush(h, a[i][1])\n while c + i < a[i][0]:\n res += hp.heappop(h)\n c += 1\n print(res)\n\n\n#sys.stdout.write('YES\\n')\n#sys.stdout.write(f'{res}\\n')\n#sys.stdout.write(f'{y1} {x1} {y2} {x2}\\n')\n", "import sys\nfrom heapq import *\n#sys.stdin = open('in', 'r')\nt = int(sys.stdin.readline())\nfor ti in range(t):\n n = int(sys.stdin.readline())\n a = [tuple(map(int, sys.stdin.readline().split())) for i in range(n)]\n a.sort(key = lambda x: (x[0], -x[1]))\n c = 0\n h = []\n res = 0\n for i in range(n-1,-1,-1):\n heappush(h, a[i][1])\n while c + i < a[i][0]:\n res += heappop(h)\n c += 1\n print(res)\n\n\n#sys.stdout.write('YES\\n')\n#sys.stdout.write(f'{res}\\n')\n#sys.stdout.write(f'{y1} {x1} {y2} {x2}\\n')\n"]
{ "inputs": [ "3\n3\n1 5\n2 10\n2 8\n7\n0 1\n3 1\n1 1\n6 1\n1 1\n4 1\n4 1\n6\n2 6\n2 3\n2 8\n2 7\n4 4\n5 5\n" ], "outputs": [ "8\n0\n7\n" ] }
interview
https://codeforces.com/problemset/problem/1251/E2
8
You like playing chess tournaments online. In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game"). The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game. After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug. Compute the maximum score you can get by cheating in the optimal way. -----Input----- Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) – the number of games played and the number of outcomes that you can change. The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L. It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$. -----Output----- For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way. -----Example----- Input 8 5 2 WLWLL 6 5 LLLWWL 7 1 LWLWLWL 15 5 WWWLLLWWWLLLWWW 40 7 LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL 1 0 L 1 1 L 6 1 WLLWLW Output 7 11 6 26 46 0 1 6 -----Note----- Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game). An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game. Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game). An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
["import sys\ninput = sys.stdin.readline\n\ndef main():\n n, k = map(int, input().split())\n string = input().strip()\n if \"W\" not in string:\n ans = min(n, k) * 2 - 1\n print(max(ans, 0))\n return\n \n L_s = []\n cnt = 0\n bef = string[0]\n ans = 0\n for s in string:\n if s == bef:\n cnt += 1\n else:\n if bef == \"L\":\n L_s.append(cnt)\n else:\n ans += cnt * 2 - 1\n cnt = 1\n bef = s\n if bef == \"W\":\n ans += cnt * 2 - 1\n cnt = 0\n \n if string[0] == \"L\" and L_s:\n cnt += L_s[0]\n L_s = L_s[1:]\n L_s.sort()\n for l in L_s:\n if k >= l:\n ans += l * 2 + 1\n k -= l\n else:\n ans += k * 2\n k = 0\n \n ans += 2 * min(k, cnt)\n print(ans)\n \n \n \nfor _ in range(int(input())):\n main()", "import sys\n\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n n,k = map(int,input().split())\n s = input()\n s = [s[i] for i in range(n)]\n\n base = s.count(\"W\")\n if base == 0:\n if k:\n print(2*k-1)\n else:\n print(0)\n elif base+k>=n:\n print(2*n-1)\n else:\n interval = []\n while s and s[-1]==\"L\":\n s.pop()\n s = s[::-1]\n while s and s[-1]==\"L\":\n s.pop()\n\n while s:\n if s[-1]==\"W\":\n while s and s[-1]==\"W\":\n s.pop()\n else:\n tmp = 0\n while s and s[-1]==\"L\":\n s.pop()\n tmp += 1\n interval.append(tmp)\n interval.sort(reverse=True)\n K = k\n while interval and k:\n if k>=interval[-1]:\n k -= interval.pop()\n else:\n break\n print(2*(base+K)-1-len(interval))", "import sys\ninput = sys.stdin.readline\n\n\ndef compress(string):\n string = string + \"#\"\n n = len(string)\n begin, end, cnt = 0, 1, 1\n ans = []\n while end < n:\n if string[begin] == string[end]:\n end, cnt = end + 1, cnt + 1\n else:\n ans.append((string[begin], cnt))\n begin, end, cnt = end, end + 1, 1\n return ans\n\n\nt = int(input())\nfor _ in range(t):\n n, k = map(int, input().split())\n s = input()[:-1]\n \n s = compress(s)\n\n \n w_groups = 0\n w_cnt = 0\n l_cnt = 0\n li = []\n for i, (char, cnt) in enumerate(s):\n if char == \"W\":\n w_groups += 1\n w_cnt += cnt\n if char == \"L\":\n l_cnt += cnt\n if 1 <= i < len(s) - 1:\n li.append(cnt)\n\n if w_cnt == 0:\n print(max(min(k, l_cnt) * 2 - 1, 0))\n continue\n \n ans = w_cnt * 2 - w_groups\n ans += min(k, l_cnt) * 2\n\n li.sort()\n for val in li:\n if k >= val:\n ans += 1\n k -= val\n print(ans)", "for _ in range(int(input())):\n n, k = list(map(int, input().split()))\n s = input()\n k = min(k, s.count(\"L\"))\n arr = []\n cur = 0\n sc = 0\n se = False\n if s[0] == \"W\":\n sc += 1\n for e in s:\n if e == \"L\":\n cur += 1\n else:\n if cur > 0 and se:\n arr.append(cur)\n se = True\n cur = 0\n for i in range(1, n):\n if s[i] == \"W\":\n if s[i-1] == \"W\":\n sc += 2\n else:\n sc += 1 \n arr.sort() \n arr.reverse()\n #print(arr, sc)\n while len(arr) > 0 and arr[-1] <= k:\n k -= arr[-1]\n sc += arr[-1]*2+1\n arr.pop()\n #print(k)\n sc += k*2\n if k > 0 and s.count(\"W\") == 0:\n sc -= 1\n print(sc)\n", "from sys import stdin\n\nt = int(stdin.readline())\nfor i in range(t):\n n, k = tuple(int(x) for x in stdin.readline().split())\n line = 'L' * (k+1) + stdin.readline()[:-1] + 'L' * (k+1)\n score = 0\n flag = False\n for char in line:\n if char == 'W':\n if flag:\n score += 2\n else:\n score += 1\n flag = True\n else:\n flag = False\n \n seq = sorted(len(x) for x in line.split('W'))\n\n if len(seq) == 1:\n if k == 0:\n print(0)\n else:\n print(2*k-1)\n continue\n for item in seq:\n if item == 0:\n continue\n if k - item >= 0:\n k -= item\n score += 2 * (item-1) + 3\n elif k > 0:\n score += 2 * k\n break\n else:\n break\n print(min(score, 2*n-1))\n \n", "from sys import stdin\n\"\"\"\nn=int(stdin.readline().strip())\nn,m=map(int,stdin.readline().strip().split())\ns=list(map(int,stdin.readline().strip().split()))\ns=stdin.readline().strip()\n\"\"\"\nT=int(stdin.readline().strip())\nfor caso in range(T):\n n,k=list(map(int,stdin.readline().strip().split()))\n s=list(stdin.readline().strip())\n aux=[]\n last=-1\n for i in range(n):\n if i>0 and s[i]=='L' and s[i-1]=='W':\n last=i\n if i<n-1 and s[i]=='L' and s[i+1]=='W' and last!=-1:\n aux.append([i-last,last,i])\n aux.sort()\n for i in aux:\n for j in range(i[1],i[2]+1):\n if k>0:\n s[j]='W'\n k-=1\n ini=-1\n fin=n\n for i in range(n):\n if s[i]=='W':\n ini=i-1\n break\n for i in range(n-1,-1,-1):\n if s[i]=='W':\n fin=i+1\n break\n for i in range(ini,-1,-1):\n if k>0:\n s[i]='W'\n k-=1\n for i in range(fin,n):\n if k>0:\n s[i]='W'\n k-=1\n ans=0\n if ini==-1 and fin==n:\n for i in range(n):\n if k>0:\n s[i]='W'\n k-=1\n for i in range(n):\n if s[i]=='W':\n if i>0 and s[i-1]=='W':\n ans+=2\n else:\n ans+=1\n print(ans)\n \n \n \n\n", "for _ in range(int(input())):\n n, k = list(map(int, input().split()))\n inp = input().lower()\n k = min(k, inp.count('l'))\n ans = inp.count('w') + tuple(zip(inp, 'l' + inp)).count('ww') + k * 2\n if 'w' in inp:\n inp2 = []\n cur = -1\n for c in inp:\n if cur != -1:\n if c == 'l':\n cur += 1\n else:\n inp2.append(cur)\n if c == 'w':\n cur = 0\n inp2.sort()\n for inp2i in inp2:\n if inp2i > k:\n break\n k -= inp2i\n ans += 1\n else:\n ans = max(ans - 1, 0)\n print(ans)\n", "import sys\nreadline = sys.stdin.readline\n\nT = int(readline())\nAns = [None]*T\n\nfor qu in range(T):\n N, K = list(map(int, readline().split()))\n S = [1 if s == 'W' else 0 for s in readline().strip()]\n if all(s == 0 for s in S):\n Ans[qu] = max(0, 2*K-1)\n continue\n \n ans = 0\n ctr = 0\n st = []\n L = []\n res = 0\n hh = False\n for i in range(N):\n s = S[i]\n if s == 1:\n if i == 0 or S[i-1] == 0:\n ans += 1\n else:\n ans += 2\n if ctr:\n st.append(ctr)\n ctr = 0\n hh = True\n else:\n if hh: \n ctr += 1\n else:\n res += 1\n res += ctr\n st.sort()\n J = []\n for s in st:\n J.extend([2]*(s-1) + [3])\n J.extend([2]*res)\n Ans[qu] = ans + sum(J[:min(len(J), K)])\nprint('\\n'.join(map(str, Ans)))\n", "def solve():\n n, k = list(map(int, input().split()))\n s = input()\n ans = 0\n prev = False\n c = []\n cc = 0\n for i in range(n):\n if s[i] == 'W':\n if cc:\n if cc != i:\n c.append(cc)\n cc = 0\n if prev:\n ans += 2\n else:\n ans += 1\n prev = True\n else:\n prev = False\n cc += 1\n c.sort()\n for i in range(len(c)):\n if c[i] <= k:\n k -= c[i]\n ans += c[i] * 2 + 1\n if 'W' in s:\n ans += k * 2\n else:\n ans += max(k * 2 - 1, 0)\n ans = min(ans, n * 2 - 1)\n print(ans)\nt = int(input())\nfor _ in range(t):\n solve()\n"]
{ "inputs": [ "8\n5 2\nWLWLL\n6 5\nLLLWWL\n7 1\nLWLWLWL\n15 5\nWWWLLLWWWLLLWWW\n40 7\nLLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL\n1 0\nL\n1 1\nL\n6 1\nWLLWLW\n" ], "outputs": [ "7\n11\n6\n26\n46\n0\n1\n6\n" ] }
interview
https://codeforces.com/problemset/problem/1427/B
9
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them. For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$. The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them. Each player wants to maximize their score. Calculate the resulting score of Alice. -----Input----- The first line contains one integer $T$ ($1 \le T \le 500$) — the number of test cases. Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$). -----Output----- For each test case, print one integer — the resulting score of Alice (the number of $1$-characters deleted by her). -----Example----- Input 5 01111001 0000 111111 101010101 011011110111 Output 4 0 6 3 6 -----Note----- Questions about the optimal strategy will be ignored.
["for _ in range(int(input())):\n s = input()\n p = [i for i in s.split(\"0\") if i!=\"\"]\n p.sort(reverse=True)\n ans = 0\n for i in range(0,len(p),2):\n ans+=len(p[i])\n print(ans)\n\n", "for _ in range(int(input())):\n s=[len(i)for i in input().split('0')]\n s.sort()\n print(sum(s[-1::-2]))", "for _ in range(int(input())):\n s = input()\n t = [i for i in s.split(\"0\") if i!=\"\"]\n t.sort(reverse=True)\n cnt=0\n for i in range(0,len(t),2):\n cnt+=len(t[i])\n print(cnt)", "for _ in range(int(input())):\n s = input()\n ar = []\n cur = 0\n for c in s:\n if c == \"1\":\n cur += 1\n else:\n ar.append(cur)\n cur = 0\n if cur != 0:\n ar.append(cur)\n ar.sort()\n ar.reverse()\n print(sum(ar[::2]))\n", "for nt in range(int(input())):\n\ts = input()\n\tn = len(s)\n\tif s[0]==\"1\":\n\t\tcount = 1\n\telse:\n\t\tcount = 0\n\tgroups = []\n\tfor i in range(1,n):\n\t\tif s[i]==\"1\":\n\t\t\tcount += 1\n\t\telse:\n\t\t\tif count:\n\t\t\t\tgroups.append(count)\n\t\t\tcount = 0\n\tif count:\n\t\tgroups.append(count)\n\tgroups.sort(reverse=True)\n\tans = 0\n\tfor i in range(0,len(groups),2):\n\t\tans += groups[i]\n\tprint (ans)\n", "def solv():\n\ts=list(map(int,input()))\n\tv=[]\n\tsm=0\n\tfor n in s:\n\t\tif n:\n\t\t\tsm+=1\n\t\telse:\n\t\t\tv.append(sm)\n\t\t\tsm=0\n\tif sm:v.append(sm)\n\tv.sort(reverse=True)\n\n\tres=0\n\n\tfor n in range(0,len(v),2):res+=v[n]\n\tprint(res)\n\nfor _ in range(int(input())):solv()", "import math\nt=int(input())\nfor w in range(t):\n s=sorted(input().split('0'),reverse=True)\n c=0\n for i in range(0,len(s),2):\n c+=len(s[i])\n print(c)", "from itertools import groupby\n\nt = int(input())\n\nfor _ in range(t):\n s = input()\n l = []\n for k, v in groupby(s):\n if k == '1':\n l.append(len(list(v)))\n l.sort(reverse=True)\n n = len(l)\n res = 0\n for i in range(0, n, 2):\n res += l[i]\n print(res)\n", "for _ in range(int(input())):\n s = input()\n x = sorted(len(i) for i in s.split('0') if len(i) > 0)\n\n print(max(sum(x[::2]), sum(x[1::2])))", "from sys import stdin,stdout\nfrom math import sqrt,gcd,ceil,floor,log2,log10,factorial,cos,acos,tan,atan,atan2,sin,asin,radians,degrees,hypot\nfrom bisect import insort, insort_left, insort_right, bisect_left, bisect_right, bisect\nfrom array import array\nfrom functools import reduce\nfrom itertools import combinations, combinations_with_replacement, permutations\nfrom fractions import Fraction\nfrom random import choice,getrandbits,randint,random,randrange,shuffle\nfrom re import compile,findall,escape\nfrom statistics import mean,median,mode\nfrom heapq import heapify,heappop,heappush,heappushpop,heapreplace,merge,nlargest,nsmallest\n\nfor test in range(int(stdin.readline())):\n s=input()\n l=findall(r'1+',s)\n lengths=[len(i) for i in l]\n lengths.sort(reverse=True)\n alice=0\n for i in range(0,len(lengths),2):\n alice+=lengths[i]\n print(alice)", "import sys\ninput = sys.stdin.readline\nT = int(input())\n\nfor t in range(T):\n s = input()[:-1]\n\n counts = []\n current = 0\n for c in s:\n if c == '1':\n current += 1\n else:\n counts.append(current)\n current = 0\n if current:\n counts.append(current)\n\n res = 0\n counts = sorted(counts, reverse=True)\n for i in range(len(counts)):\n if 2*i >= len(counts):\n break\n res += counts[2*i]\n print(res)\n", "import sys\nimport math\ndef II():\n\treturn int(sys.stdin.readline())\n\ndef LI():\n\treturn list(map(int, sys.stdin.readline().split()))\n\ndef MI():\n\treturn map(int, sys.stdin.readline().split())\n\ndef SI():\n\treturn sys.stdin.readline().strip()\nt = II()\nfor q in range(t):\n\ts = SI()\n\ta = []\n\tcount = 0\n\tfor i in range(len(s)):\n\t\tif s[i] == \"1\":\n\t\t\tcount+=1\n\t\telse:\n\t\t\ta.append(count)\n\t\t\tcount = 0\n\ta.append(count)\n\ta.sort(reverse=True)\n\tprint(sum(a[0:len(a):2]))", "from math import *\nfrom collections import *\nfrom random import *\nfrom decimal import Decimal\nfrom heapq import *\nfrom bisect import *\nimport sys\ninput=sys.stdin.readline\nsys.setrecursionlimit(10**5)\ndef lis():\n return list(map(int,input().split()))\ndef ma():\n return list(map(int,input().split()))\ndef inp():\n return int(input())\ndef st1():\n return input().rstrip('\\n')\nt=inp()\nwhile(t):\n t-=1\n #n=inp()\n a=st1()\n oe=[]\n c=0\n for i in a:\n if(i=='1'):\n c+=1\n else:\n if(c!=0):\n oe.append(c)\n c=0\n if(c):\n oe.append(c)\n s=0\n oe.sort(reverse=True)\n for i in range(len(oe)):\n if(i%2==0):\n s+=oe[i]\n print(s)\n \n", "for _ in range(int(input())):\n s = input() + '0'\n A = []\n tr = False\n x = 0\n for i in range(len(s)):\n if s[i] == '1':\n if tr:\n x += 1\n else:\n tr = True\n x = 1\n else:\n if tr:\n tr = False\n A.append(x)\n A.sort(reverse=True)\n Ans = 0\n for i in range(len(A)):\n if i % 2 == 0:\n Ans += A[i]\n print(Ans)", "t = int(input())\nwhile t:\n s = input()\n arr = []\n k = 0\n for i in s:\n if i == '1':\n k += 1\n else:\n arr.append(k)\n k = 0\n if k:\n arr.append(k)\n arr.sort(reverse=True)\n ans = 0\n for i in range(0, len(arr), 2):\n ans += arr[i]\n print(ans)\n t -= 1\n", "import sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n x = input().rstrip()\n \n arr = []\n \n c = 0\n for char in x:\n if char=='1':\n c+=1\n else:\n arr.append(c)\n c = 0\n \n arr.append(c)\n arr.sort()\n arr.reverse()\n \n ans = 0\n for i in range(0,len(arr),2):\n ans += arr[i]\n \n print(ans)", "import sys\ninput = sys.stdin.readline\n\nt=int(input())\nfor tests in range(t):\n S=input().strip()+\"0\"\n\n L=[]\n\n NOW=0\n for s in S:\n if s==\"0\":\n L.append(NOW)\n NOW=0\n else:\n NOW+=1\n\n L.sort(reverse=True)\n\n ANS=0\n\n for i in range(0,len(L),2):\n ANS+=L[i]\n\n print(ANS)\n \n", "for _ in range (int(input())):\n s=input()\n a = []\n flag = 0\n count = 0\n for i in range (len(s)):\n if s[i]=='1':\n count+=1\n else:\n a.append(count)\n count=0\n if i==len(s)-1 and count!=0:\n a.append(count)\n a.sort(reverse=True)\n ans = 0\n for i in range(len(a)):\n if i%2==0:\n ans+=a[i]\n print(ans)", "for t in range(int(input())):\n\ts = input()\n\tlast = -1\n\tnum = []\n\tn = len(s)\n\tfor i in range(n):\n\t\tif (s[i] == \"0\"):\n\t\t\tif (i - last - 1 > 0):\n\t\t\t\tnum.append(i - last - 1)\n\t\t\tlast = i\n\tif (n - last - 1 > 0):\n\t\tnum.append(n - last - 1)\n\tnum = sorted(num)[::-1]\n\tans = 0\n\tfor i in range(0, len(num), 2):\n\t\tans += num[i]\n\tprint(ans)", "for test in range(int(input())):\n s = input()\n a = []\n now = 0\n n = len(s)\n for i in range(n):\n if s[i] == \"0\":\n if now > 0:\n a.append(now)\n now = 0\n else:\n now += 1\n if now > 0:\n a.append(now)\n a.sort(reverse=True)\n ans = 0\n for i in range(0, len(a), 2):\n ans += a[i]\n print(ans)", "for _ in range(int(input())):\n s = input()\n\n ones = []\n cnt = 0\n for i in s:\n if i == '1':\n cnt += 1\n else:\n if cnt != 0:\n ones.append(cnt)\n cnt = 0\n if cnt != 0:\n ones.append(cnt)\n\n ones.sort(reverse=True)\n print(sum(ones[::2]))\n", "from collections import defaultdict as dd\nimport math\nimport sys\ninput=sys.stdin.readline\ndef nn():\n\treturn int(input())\n\ndef li():\n\treturn list(input())\n\ndef mi():\n\treturn list(map(int, input().split()))\n\ndef lm():\n\treturn list(map(int, input().split()))\n\ndef solve():\n\ts = input()\n\n\tsets = []\n\tstreak = 0\n\tfor i in range(len(s)):\n\t\tif s[i]=='1':\n\t\t\tstreak+=1\n\t\telse:\n\t\t\tif streak>0:\n\t\t\t\tsets.append(streak)\n\t\t\t\tstreak=0\n\tif streak>0:\n\t\tsets.append(streak)\n\t\tstreak=0\n\n\tsets.sort(reverse=True)\n\n\tprint(sum(sets[::2]))\n\n\nq=nn()\nfor _ in range(q):\n\tsolve()\n", "t = int(input())\n\nfor _ in range(t):\n s = [int(i) for i in input().strip()]\n n = len(s)\n bckt = []\n ct = 0\n \n for i in range(n):\n if s[i]:\n ct += 1\n else:\n if ct:\n bckt.append(ct)\n ct = 0\n \n if ct:\n bckt.append(ct)\n \n bckt.sort(reverse=True)\n print(sum(bckt[::2]))", "for i in range(int(input())):\n\tip=list(map(int,input()))\n\tones=[]\n\ttot=0\n\tfor i in ip:\n\t\tif i==1:\n\t\t\ttot+=1\n\t\telse:\n\t\t\tones.append(tot)\n\t\t\ttot=0\n\tif tot:ones.append(tot)\n\tones.sort(reverse=True)\n\tans=0\n\tfor i in range(0,len(ones),2):\n\t\tans+=ones[i]\n\tprint(ans)", "#BINOD\nimport math\ntest = int(input())\nfor t in range(test):\n s = input()\n n = len(s)\n A = []\n o=0\n for i in range(n):\n if(s[i]=='1'):\n o+=1\n else:\n A.append(o)\n o=0\n if(s[n-1]=='1'):\n A.append(o)\n A.sort(reverse = True)\n ans = 0\n for i in range(0,len(A),2):\n ans += A[i]\n print(ans)\n\n\n\n\n#Binod\n", "for _ in range(int(input())):\n data = list(map(int,list(input())))\n fl = False\n data.append(\"&\")\n l = 0\n st = []\n for i in range(len(data)):\n if fl and data[i] == 1:\n l+=1\n continue\n if fl and data[i]!=1:\n st.append(l)\n l = 0\n fl = False\n continue\n if not fl and data[i] == 1:\n l = 1\n fl = True\n st.sort(reverse=True)\n c1 = 0\n for i in range(0,len(st),2):\n c1+=st[i]\n print(c1)", "import math\nfrom collections import deque\nfrom sys import stdin, stdout\nfrom string import ascii_letters\ninput = stdin.readline\n#print = stdout.write\nletters = ascii_letters[:26]\n \nfor _ in range(int(input())):\n arr = list(map(int, input().strip()))\n lens = []\n count = 0\n for i in arr:\n if i == 0:\n if count > 0:\n lens.append(count)\n count = 0\n else:\n count += 1\n if count > 0:\n lens.append(count)\n lens.sort(reverse=True)\n res = 0\n for i in range(0, len(lens), 2):\n res += lens[i]\n print(res)\n"]
{ "inputs": [ "5\n01111001\n0000\n111111\n101010101\n011011110111\n" ], "outputs": [ "4\n0\n6\n3\n6\n" ] }
interview
https://codeforces.com/problemset/problem/1398/B
10
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them. A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements. A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once. -----Input----- The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$) — the length of the permutation $p$. The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct) — the elements of the permutation $p$. The sum of $n$ across the test cases doesn't exceed $10^5$. -----Output----- For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$ — its elements. If multiple subsequences satisfy these conditions, you are allowed to find any of them. -----Example----- Input 2 3 3 2 1 4 1 3 4 2 Output 2 3 1 3 1 4 2 -----Note----- In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$. So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
["for _ in range(int(input())):\n # n, x = map(int, input().split())\n n = int(input())\n arr = list(map(int, input().split()))\n ans = [arr[0]]\n for i in range(1, n - 1):\n if arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:\n ans.append(arr[i])\n elif arr[i - 1] > arr[i] and arr[i] < arr[i + 1]:\n ans.append(arr[i])\n ans.append(arr[-1])\n print(len(ans))\n print(*ans)", "\nt = int(input())\n\nfor loop in range(t):\n\n n = int(input())\n p = list(map(int,input().split()))\n a = p\n\n ans = []\n \n\n for i in range(n):\n\n if i == 0 or i == n-1:\n ans.append(p[i])\n\n elif a[i-1] <= a[i] <= a[i+1]:\n continue\n elif a[i-1] >= a[i] >= a[i+1]:\n continue\n else:\n ans.append(p[i])\n\n print(len(ans))\n print(*ans)\n", "for t in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n b = [a[0]] + [a[i] for i in range(1, n - 1) if not(a[i - 1] < a[i] < a[i + 1] or \n a[i - 1] > a[i] > a[i + 1])] + [a[-1]]\n print(len(b))\n print(*b)", "for _ in range(int(input())):\n n = int(input())\n p = list(map(int, input().split()))\n ans = [str(p[0])]\n for i in range(1,n-1):\n if p[i-1] < p[i] < p[i+1]:\n continue\n if p[i-1] > p[i] > p[i+1]:\n continue\n ans.append(str(p[i]))\n ans.append(str(p[-1]))\n print(len(ans))\n print(\" \".join(ans))\n", "for _ in range(int(input())):\n n = int(input())\n p = tuple(map(int, input().split()))\n ans = [p[i] for i in range(n) if i in (0, n - 1) or p[i] != sorted(p[i - 1:i + 2])[1]]\n print(len(ans))\n print(*ans)\n", "t = int(input())\nfor test in range(t):\n n = int(input())\n l = list(map(int, input().rstrip().split()))\n i = 0\n arr = list()\n arr.append(str(l[0]))\n while i+1 < n:\n if i+1 == n-1 or (l[i] < l[i+1] and l[i+1] > l[i+2]) or (l[i] > l[i+1] and l[i+1] < l[i+2]):\n arr.append(str(l[i+1]))\n i += 1\n print(len(arr))\n print(\" \".join(arr))", "from collections import *\nfrom sys import stdin,stderr\ndef rl():\n return [int(w) for w in stdin.readline().split()]\n\nt, = rl()\nfor _ in range(t):\n n, = rl()\n p = rl()\n s = [p[0]]\n for i in range(1, n-1):\n if p[i-1] < p[i] > p[i+1] or p[i-1] > p[i] < p[i+1]:\n s.append(p[i])\n s.append(p[-1])\n print(len(s))\n print(*s)\n", "import sys\ninput = sys.stdin.readline\n\nfor nt in range(int(input())):\n\tn = int(input())\n\ta = list(map(int,input().split()))\n\tif n==2:\n\t\tprint (2)\n\t\tprint (*a)\n\t\tcontinue\n\tans = [a[0]]\n\tif a[1]>a[0]:\n\t\tturn = 1\n\telse:\n\t\tturn = 0\n\ts = abs(a[1]-a[0])\n\tfor i in range(2,n):\n\t\tif turn:\n\t\t\tif a[i]>a[i-1]:\n\t\t\t\tcontinue\n\t\t\tans.append(a[i-1])\n\t\t\tturn = 0\n\t\telse:\n\t\t\tif a[i]<a[i-1]:\n\t\t\t\tcontinue\n\t\t\tans.append(a[i-1])\n\t\t\tturn = 1\n\tans.append(a[-1])\n\tprint (len(ans))\n\tprint (*ans)", "from collections import defaultdict as dd\nimport math\nimport sys\ninput=sys.stdin.readline\ndef nn():\n\treturn int(input())\n\ndef li():\n\treturn list(input())\n\ndef mi():\n\treturn list(map(int, input().split()))\n\ndef lm():\n\treturn list(map(int, input().split()))\n\n\n\nq=nn()\n\nfor _ in range(q):\n\tn = nn()\n\n\tper = lm()\n\n\tbest =[per[0]]\n\n\tfor i in range(len(per)-2):\n\t\tminper = min(per[i], per[i+1], per[i+2])\n\t\tmaxper = max(per[i], per[i+1], per[i+2])\n\t\tif minper==per[i+1] or maxper==per[i+1]:\n\t\t\tbest.append(per[i+1])\n\tbest.append(per[-1])\n\tprint(len(best))\n\tprint(*best)\n", "import sys\n\ndef ii():\n return sys.stdin.readline().strip()\n\ndef idata():\n return [int(x) for x in ii().split()]\n\ndef solve_of_problem():\n n = int(ii())\n data = idata()\n ans = [data[0]]\n for i in range(1, n - 1):\n if data[i - 1] < data[i] > data[i + 1] or data[i - 1] > data[i] < data[i + 1]:\n ans += [data[i]]\n print(len(ans) + 1)\n print(*ans, data[-1])\n return\n\nfor ______ in range(int(ii())):\n solve_of_problem()", "def main():\n n = int(input())\n lst = list(map(int, input().split()))\n take = [lst[0]]\n sign = 0\n for i in range(1, n):\n if i == n - 1:\n take.append(lst[i])\n else:\n if lst[i] > take[-1]:\n if lst[i + 1] < lst[i]:\n take.append(lst[i])\n elif lst[i] < take[-1]:\n if lst[i + 1] > lst[i]:\n take.append(lst[i])\n line = str(len(take)) + '\\n'\n for i in take:\n line += str(i) + ' '\n print(line)\n\ndef __starting_point():\n t = int(input())\n for i in range(t):\n main()\n\n__starting_point()", "import sys\ninput = sys.stdin.readline\nt = int(input())\nfor _ in range(t):\n n = int(input())\n p = list(map(int, input().split()))\n ans = [p[0]]\n for i in range(n-2):\n if (p[i]-p[i+1])*(p[i+1]-p[i+2])<0:\n ans.append(p[i+1])\n ans.append(p[-1])\n print(len(ans))\n print(*ans)", "T = int(input())\n\nfor t in range(T):\n N = int(input())\n\n P = [int(_) for _ in input().split()]\n up = P[1] > P[0]\n res = [P[0]]\n\n for i in range(1, N-1):\n if up and P[i+1] < P[i]:\n res.append(P[i])\n up = False\n elif not up and P[i+1] > P[i]:\n res.append(P[i])\n up = True\n\n if P[N-1] != P[N-2]:\n res.append(P[N-1])\n\n print(len(res))\n print(' '.join(map(str, res)))\n", "def f(n,l):\n output = [l[0]]\n for i in range(1,n-1):\n if (l[i]-l[i-1])*(l[i+1]-l[i]) < 0:\n output.append(l[i])\n output.append(l[-1])\n return str(len(output))+'\\n'+' '.join([str(x) for x in output])\n\nnumberofcases = int(input())\nfor _ in range(numberofcases):\n n = int(input())\n l = [int(t) for t in input().split()]\n print(f(n,l))", "def help():\n\tn = int(input())\n\tarr = list(map(int,input().split(\" \")))\n\n\tpeak = [False]*n\n\tdown = [False]*n\n\tfor i in range(n):\n\t\tif(i==0):\n\t\t\tif(arr[0]<arr[1]):\n\t\t\t\tdown[0]=True\n\t\t\tif(arr[0]>arr[1]):\n\t\t\t\tpeak[i]=True\n\t\telif(i==n-1):\n\t\t\tif(arr[n-1]<arr[n-2]):\n\t\t\t\tdown[i]=True\n\t\t\tif(arr[n-1]>arr[n-2]):\n\t\t\t\tpeak[i]=True\n\t\telse:\n\t\t\tif(arr[i-1]<arr[i] and arr[i]>arr[i+1]):\n\t\t\t\tpeak[i]=True\n\t\t\telif(arr[i-1]>arr[i] and arr[i]<arr[i+1]):\n\t\t\t\tdown[i]=True\n\tseries = []\n\tfor i in range(n):\n\t\tif(peak[i]==True or down[i]==True):\n\t\t\tseries.append(i)\n\tans = 0\n\tfor i in range(len(series)-1):\n\t\tans += abs(series[i]-series[i+1])\n\tprint(len(series))\n\tfor i in range(len(series)):\n\t\tprint(arr[series[i]],end=\" \")\n\tprint()\n\nfor _ in range(int(input())):\n\thelp()\n", "import sys\n\nT = int(sys.stdin.readline().strip())\nfor t in range (0, T):\n n = int(sys.stdin.readline().strip())\n p = list(map(int, sys.stdin.readline().strip().split()))\n ans = [p[0]]\n for i in range(1, n):\n if p[i] != ans[-1]:\n if len(ans) == 1:\n ans.append(p[i])\n else:\n if (ans[-2] - ans[-1]) * (ans[-1] - p[i]) > 0:\n ans.pop()\n ans.append(p[i])\n print(len(ans))\n print(\" \".join(list(map(str, ans))))\n\n \n \n"]
{ "inputs": [ "2\n3\n3 2 1\n4\n1 3 4 2\n" ], "outputs": [ "2\n3 1 \n3\n1 4 2 \n" ] }
interview
https://codeforces.com/problemset/problem/1364/B
11
You have a string $s$ — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' — move one cell up; 'S' — move one cell down; 'A' — move one cell left; 'D' — move one cell right. Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image] You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$. What is the minimum area of $Grid(s)$ you can achieve? -----Input----- The first line contains one integer $T$ ($1 \le T \le 1000$) — the number of queries. Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) — the sequence of commands. It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$. -----Output----- Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve. -----Example----- Input 3 DSAWWAW D WA Output 8 2 4 -----Note----- In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$. In second and third queries you can not decrease the area of $Grid(s)$.
["n = int(input())\n\ndef area(width, height) :\n return (width+1) * (height+1)\n\ndef calcul(s1, c, s2) :\n maxx, maxy, minx, miny = 0, 0, 0, 0\n x, y = 0, 0\n for k in range(len(s1)) :\n if s1[k] == \"W\" :\n y += 1\n if s1[k] == \"S\" :\n y -= 1\n if s1[k] == \"A\" :\n x -= 1\n if s1[k] == \"D\" :\n x += 1\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n\n\n\n if c == \"W\" :\n y += 1\n elif c == \"S\" :\n y -= 1\n elif c == \"A\" :\n x -= 1\n elif c == \"D\" :\n x += 1\n else :\n print(c, \"ok\")\n\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n for k in range(len(s2)) :\n if s2[k] == \"W\" :\n y += 1\n if s2[k] == \"S\" :\n y -= 1\n if s2[k] == \"A\" :\n x -= 1\n if s2[k] == \"D\" :\n x += 1\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n\n\n diffx = maxx - minx\n diffy = maxy - miny\n tmp = area(diffx, diffy)\n\n\n return tmp\n\ndef pre_calcul(s, moment, pre_avant, date_debut) :\n x, y, maxx, minx, maxy, miny = pre_avant\n for k in range(date_debut, moment) :\n if s[k] == \"W\" :\n y += 1\n if s[k] == \"S\" :\n y -= 1\n if s[k] == \"A\" :\n x -= 1\n if s[k] == \"D\" :\n x += 1\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n return (x, y, maxx, minx, maxy, miny)\n\ndef calcul2(s, c, moment, precalcul) :\n x, y, maxx, minx, maxy, miny = precalcul\n\n\n\n if c == \"W\" :\n y += 1\n elif c == \"S\" :\n y -= 1\n elif c == \"A\" :\n x -= 1\n elif c == \"D\" :\n x += 1\n else :\n print(c, \"ok\")\n\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n for k in range(moment, len(s)) :\n if s[k] == \"W\" :\n y += 1\n if s[k] == \"S\" :\n y -= 1\n if s[k] == \"A\" :\n x -= 1\n if s[k] == \"D\" :\n x += 1\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n\n\n\n diffx = maxx - minx\n diffy = maxy - miny\n tmp = area(diffx, diffy)\n\n\n return tmp\n\nfor _ in range(n) :\n s = input()\n maxx, maxy, minx, miny = 0, 0, 0, 0\n x, y = 0, 0\n momentminx, momentmaxx, momentminy, momentmaxy = -1, -1, -1, -1\n for k in range(len(s)) :\n if s[k] == \"W\" :\n y += 1\n if s[k] == \"S\" :\n y -= 1\n if s[k] == \"A\" :\n x -= 1\n if s[k] == \"D\" :\n x += 1\n\n if x > maxx :\n momentmaxx = k\n if y > maxy :\n momentmaxy = k\n if x < minx :\n momentminx = k\n if y < miny :\n momentminy = k\n maxx = max(maxx, x)\n minx = min(minx, x)\n\n maxy = max(maxy, y)\n miny = min(miny, y)\n diffx = maxx - minx\n diffy = maxy - miny\n\n\n tmp = 999999999999999999999999999999999999\n l = [momentmaxx, momentmaxy, momentminx, momentminy]\n l = list(set(l))\n l = [i for i in l if i != -1]\n l.sort()\n if l != [] :\n precalcul = pre_calcul(s, l[0], (0, 0, 0, 0, 0, 0), 0)\n avant = l[0]\n for moment in l :\n precalcul = pre_calcul(s, moment, precalcul, avant)\n avant = moment\n tmp = min(tmp, calcul2(s, 'W', moment, precalcul))\n tmp = min(tmp, calcul2(s, 'S', moment, precalcul))\n tmp = min(tmp, calcul2(s, 'A', moment, precalcul))\n tmp = min(tmp, calcul2(s, 'D', moment, precalcul))\n print(tmp)\n", "import sys\ninput = sys.stdin.readline\n \nQ=int(input())\n\nfor testcases in range(Q):\n S=input().strip()\n\n X=Y=0\n MAXX=MINX=MAXY=MINY=0\n\n for s in S:\n if s==\"D\":\n X+=1\n MAXX=max(MAXX,X)\n\n elif s==\"A\":\n X-=1\n MINX=min(MINX,X)\n\n elif s==\"W\":\n Y+=1\n MAXY=max(MAXY,Y)\n\n else:\n Y-=1\n MINY=min(MINY,Y)\n\n #print(MAXX,MINX,MAXY,MINY)\n\n MAXXLIST=[]\n MINXLIST=[]\n MAXYLIST=[]\n MINYLIST=[]\n\n if MAXX==0:\n MAXXLIST.append(0)\n\n if MAXY==0:\n MAXYLIST.append(0)\n\n if MINX==0:\n MINXLIST.append(0)\n\n if MINY==0:\n MINYLIST.append(0)\n\n X=Y=0\n \n\n for i in range(len(S)):\n s=S[i]\n if s==\"D\":\n X+=1\n if X==MAXX:\n MAXXLIST.append(i+1)\n \n elif s==\"A\":\n X-=1\n if X==MINX:\n MINXLIST.append(i+1)\n\n elif s==\"W\":\n Y+=1\n if Y==MAXY:\n MAXYLIST.append(i+1)\n\n else:\n Y-=1\n if Y==MINY:\n MINYLIST.append(i+1)\n\n #print(MAXXLIST)\n #print(MAXYLIST)\n #print(MINXLIST)\n #print(MINYLIST)\n\n ANS=(MAXX-MINX+1)*(MAXY-MINY+1)\n\n #print(ANS)\n\n\n if MAXX-MINX>1:\n if MAXXLIST[0]>MINXLIST[-1] or MINXLIST[0]>MAXXLIST[-1]:\n ANS=min(ANS,(MAXX-MINX)*(MAXY-MINY+1))\n\n if MAXY-MINY>1:\n if MAXYLIST[0]>MINYLIST[-1] or MINYLIST[0]>MAXYLIST[-1]:\n ANS=min(ANS,(MAXX-MINX+1)*(MAXY-MINY))\n\n print(ANS)\n \n", "T = int(input())\n\nfor _ in range(T):\n\ts = input()\n\n\tcleft=cup=cdown=cright=0\n\tleft=up=down=right=0\n\tfleft=lleft=0\n\tfright=lright=0\n\tfup=lup=0\n\tfdown=ldown=0\n\n\tx=y=0\n\tfor i, c in enumerate(s):\n\t\tif c==\"W\":\n\t\t\ty -= 1\n\t\t\tcup += 1\n\t\telif c==\"S\":\n\t\t\ty += 1\n\t\t\tcdown += 1\n\t\telif c==\"A\":\n\t\t\tx -= 1\n\t\t\tcleft += 1\n\t\telif c==\"D\":\n\t\t\tx += 1\n\t\t\tcright += 1\n\n\t\tif x == left:\n\t\t\tlleft = i\n\t\tif x == right:\n\t\t\tlright = i\n\t\tif y == down:\n\t\t\tldown = i\n\t\tif y == up:\n\t\t\tlup = i\n\n\t\tif x < left:\n\t\t\tleft = x\n\t\t\tfleft=i\n\t\t\tlleft=i\n\n\t\tif x > right:\n\t\t\tright = x\n\t\t\tfright=i\n\t\t\tlright=i\n\n\n\t\tif y < up:\n\t\t\tup = y\n\t\t\tfup=i\n\t\t\tlup=i\n\n\n\t\tif y > down:\n\t\t\tdown = y\n\t\t\tfdown=i\n\t\t\tldown=i\n\n\twidth = right - left + 1\n\theight = down - up + 1\n\n\tbest = width * height\n\n\tif height > 2:\n\t\tif ldown < fup or lup < fdown:\n\t\t\tbest = min(best, width * (height-1))\n\tif width > 2:\n\t\tif lleft < fright or lright < fleft:\n\t\t\tbest = min(best, (width-1) * height)\n\tprint(best)", "t = int(input())\nfor _ in range(t):\n\ts = input()\n\tn = len(s)\n\tfa, fd, fs, fw = [0], [0], [0], [0]\n\tba, bd, bs, bw = [0], [0], [0], [0]\n\tcur = [0, 0]\n\tfor i in range(n):\n\t\tif s[i] == \"A\":\n\t\t\tcur[0] -= 1\n\t\t\t\n\t\telif s[i] == \"D\":\n\t\t\tcur[0] += 1\n\t\t\t\n\t\telif s[i] == \"S\":\n\t\t\tcur[1] -= 1\n\t\t\t\n\t\telif s[i] == \"W\":\n\t\t\tcur[1] += 1\n\t\t\t\n\t\tfa.append(min(fa[-1], cur[0]))\n\t\tfd.append(max(fd[-1], cur[0]))\n\t\tfs.append(min(fs[-1], cur[1]))\n\t\tfw.append(max(fw[-1], cur[1]))\n\n\th = fd[-1]-fa[-1]\n\tv = fw[-1]-fs[-1]\n\tarea = (h+1)*(v+1)\n\n\tcur = [0, 0]\n\tfor i in range(n-1, -1, -1):\n\t\tif s[i] == \"D\":\n\t\t\tcur[0] -= 1\n\t\telif s[i] == \"A\":\n\t\t\tcur[0] += 1\n\t\telif s[i] == \"W\":\n\t\t\tcur[1] -= 1\n\t\telif s[i] == \"S\":\n\t\t\tcur[1] += 1\n\n\t\tba.append(min(ba[-1], cur[0]))\n\t\tbd.append(max(bd[-1], cur[0]))\n\t\tbs.append(min(bs[-1], cur[1]))\n\t\tbw.append(max(bw[-1], cur[1]))\n\n\tba.reverse()\n\tbd.reverse()\n\tbs.reverse()\n\tbw.reverse()\n\n\t#print(fa, fd, fs, fw)\n\t#print(ba, bd, bs, bw)\n\n\thok, vok = False, False\n\tfor i in range(1, n):\n\t\t#print(n, i)\n\t\tif fd[i]-fa[i] < h and abs(bd[i]-ba[i]) < h:\n\t\t\thok = True\n\t\tif fw[i]-fs[i] < v and abs(bw[i]-bs[i]) < v:\n\t\t\tvok = True\n\n\tif hok:\n\t\tarea = min(area, h*(v+1))\n\tif vok:\n\t\tarea = min(area, v*(h+1))\n\tprint(area)\n", "for q in range(int(input())):\n\n data = input()\n # if data in [\"WW\", \"AA\", \"SS\", \"DD\"]:\n # print(2)\n # continue\n mx = [0,0,0,0]\n x = 0\n y = 0\n pos = [[-1],[-1],[-1],[-1]]\n for i in range(len(data)):\n # print(x,y)\n d = data[i]\n if d == \"W\":\n y += 1\n if y > mx[0]:\n \n mx[0] = y\n pos[0] = []\n elif d == \"S\":\n y -= 1\n if y < mx[2]:\n \n mx[2] = y\n pos[2] = []\n elif d == \"A\":\n x -= 1\n if x < mx[1]:\n \n mx[1] = x\n pos[1] = []\n else:\n x += 1\n if x > mx[3]:\n \n mx[3] = x\n pos[3] = []\n if x == mx[3]:\n pos[3].append(i)\n if x == mx[1]:\n pos[1].append(i)\n if y == mx[0]:\n pos[0].append(i)\n if y == mx[2]:\n pos[2].append(i)\n\n # print(mx)\n # print(pos)\n wid = mx[3] - mx[1] + 1\n hei = mx[0] - mx[2] + 1\n ans = wid * hei\n\n \n \n if pos[3][0] > pos[1][-1] + 1 or pos[1][0] > pos[3][-1] + 1:\n ans -= hei\n if pos[0][0] > pos[2][-1] + 1 or pos[2][0] > pos[0][-1] + 1:\n ans = min((hei-1)*(wid), ans)\n print(ans)", "T = int(input())\n\nw = [[-1, 0], [1, 0], [0, 1], [0, -1]]\nmp = {'A':0, 'D':1, 'W':2, 'S':3}\nwhile T > 0:\n\tT-=1\n\ts = input()\n\tl = [0]; r = [0];\n\tu = [0]; d = [0];\n\n\tfor dir in s[::-1]:\n\t\tl.append(l[-1])\n\t\tr.append(r[-1])\n\t\tu.append(u[-1])\n\t\td.append(d[-1])\n\t\tif dir == 'A':\n\t\t\tl[-1]+=1\n\t\t\tif r[-1] > 0: r[-1]-=1\n\t\telif dir == 'D':\n\t\t\tr[-1]+=1\n\t\t\tif l[-1] > 0: l[-1]-=1\n\t\telif dir == 'S':\n\t\t\td[-1]+=1\n\t\t\tif u[-1] > 0: u[-1]-=1\n\t\telse:\n\t\t\tu[-1]+=1\n\t\t\tif d[-1] > 0: d[-1]-=1\n\n\tl = l[::-1]; r = r[::-1]; u = u[::-1]; d = d[::-1];\n\n\tx = 0; y = 0\n\tml = 0; mr = 0; mu = 0; md = 0;\n\n\tans = (l[0] + r[0] + 1) * (u[0] + d[0] + 1)\n\tfor i in range(len(s)+1):\n\t\tmml=ml;mmr=mr;mmu=mu;mmd=md;\n\t\tfor j in range(4):\n\t\t\txx=x+w[j][0]\n\t\t\tyy=y+w[j][1]\n\n\t\t\tif xx<0: ml=max(ml,-xx)\n\t\t\tif xx>0: mr=max(mr,xx)\n\t\t\tif yy>0: mu=max(mu,yy)\n\t\t\tif yy<0: md=max(md,-yy)\n\n\t\t\txx-=l[i]\n\t\t\tif xx<0: ml=max(ml,-xx)\n\t\t\txx+=r[i]+l[i];\n\t\t\tif xx>0: mr=max(mr,xx)\n\t\t\tyy-=d[i]\n\t\t\tif yy<0: md=max(md,-yy)\n\t\t\tyy+=u[i]+d[i]\n\t\t\tif yy>0: mu=max(mu,yy)\n\n\t\t\tans = min(ans, (ml+mr+1)*(mu+md+1))\n\t\t\tml=mml;mr=mmr;mu=mmu;md=mmd;\n\n\t\tif i < len(s):\n\t\t\tx+=w[mp[s[i]]][0]\n\t\t\ty+=w[mp[s[i]]][1]\n\t\t\tif x<0: ml=max(ml,-x)\n\t\t\tif x>0: mr=max(mr,x)\n\t\t\tif y>0: mu=max(mu,y)\n\t\t\tif y<0: md=max(md,-y)\n\n\tprint(ans)", "import sys\nfrom collections import defaultdict\ninput = sys.stdin.readline\nimport math\n\n\ndef main():\n t = int(input())\n for _ in range(t):\n s = input().rstrip()\n a1 = []\n a2 = []\n ws = {'W': 1, 'S': -1}\n ad = {'A': 1, 'D': -1}\n for c in s:\n if c in ('W', 'S'):\n a1.append(ws[c])\n else:\n a2.append(ad[c])\n pref_a1 = [0] + a1.copy()\n pref_a2 = [0] + a2.copy()\n for i in range(1, len(pref_a1)):\n pref_a1[i] += pref_a1[i-1]\n for i in range(1, len(pref_a2)):\n pref_a2[i] += pref_a2[i-1]\n\n def canDecrease(a):\n _min = min(a)\n _max = max(a)\n\n # decrease max\n _min_rindex = a.index(_min)\n for i in range(_min_rindex, len(a)):\n if a[i] == _min:\n _min_rindex = i\n _max_index = a.index(_max)\n if _max_index > _min_rindex:\n return True\n\n # increase min\n _max_rindex = a.index(_max)\n for i in range(_max_rindex, len(a)):\n if a[i] == _max:\n _max_rindex = i\n _min_index = a.index(_min)\n if _max_rindex < _min_index:\n return True\n\n return False\n\n x = max(pref_a1)-min(pref_a1)\n y = max(pref_a2)-min(pref_a2)\n res = (x+1) * (y+1)\n if x > 1 and canDecrease(pref_a1):\n res = min(res, x * (y+1))\n if y > 1 and canDecrease(pref_a2):\n res = min(res, (x+1) * y)\n\n print(res)\n\n\ndef __starting_point():\n main()\n\n\n__starting_point()", "\nfor i in range(int(input())):\n\ts = input()\n\tlm, rm, um, dm = 0, 0, 0, 0\n\txp, yp = 0, 0\n\tfor ch in s:\n\t\tif ch == 'W':\n\t\t\typ += 1\n\t\telif ch == 'A':\n\t\t\txp -= 1\n\t\telif ch == 'S':\n\t\t\typ -= 1\n\t\telse:\n\t\t\txp += 1\n\t\tlm = min(lm, xp)\n\t\trm = max(rm, xp)\n\t\tum = max(um, yp)\n\t\tdm = min(dm, yp)\n\txp, yp = 0, 0\n\tlmfSet, rmfSet, umfSet, dmfSet = 0, 0, 0, 0\n\tif lm == 0:\n\t\tlml = 0\n\t\tlmf = 0\n\t\tlmfSet = 1\n\tif rm == 0:\n\t\trml = 0\n\t\trmf = 0\n\t\trmfSet = 1\n\tif um == 0:\n\t\tuml = 0\n\t\tumf = 0\n\t\tumfSet = 1\n\tif dm == 0:\n\t\tdml = 0\n\t\tdmf = 0\n\t\tdmfSet = 1\n\tfor i, ch in zip(list(range(1, len(s) + 1)), s):\n\t\tif ch == 'W':\n\t\t\typ += 1\n\t\telif ch == 'A':\n\t\t\txp -= 1\n\t\telif ch == 'S':\n\t\t\typ -= 1\n\t\telse:\n\t\t\txp += 1\n\t\tif xp == lm:\n\t\t\tlml = i\n\t\t\tif not lmfSet:\n\t\t\t\tlmf = i\n\t\t\t\tlmfSet = 1\n\t\tif xp == rm:\n\t\t\trml = i\n\t\t\tif not rmfSet:\n\t\t\t\trmf = i\n\t\t\t\trmfSet = 1\n\t\tif yp == um:\n\t\t\tuml = i\n\t\t\tif not umfSet:\n\t\t\t\tumf = i\n\t\t\t\tumfSet = 1\n\t\tif yp == dm:\n\t\t\tdml = i\n\t\t\tif not dmfSet:\n\t\t\t\tdmf = i\n\t\t\t\tdmfSet = 1\n\tcanx, cany = 0, 0\n\tif dml + 1 < umf or uml + 1 < dmf:\n\t\tcany = 1\n\tif lml + 1 < rmf or rml + 1 < lmf:\n\t\tcanx = 1\n\tif canx:\n\t\tif cany:\n\t\t\tprint(min((um - dm) * (rm - lm + 1), (um - dm + 1) * (rm - lm)))\n\t\telse:\n\t\t\tprint((rm - lm) * (um - dm + 1))\n\telse:\n\t\tif cany:\n\t\t\tprint((um - dm) * (rm - lm + 1))\n\t\telse:\n\t\t\tprint((rm - lm + 1) * (um - dm + 1))\n\n\n", "t=int(input())\ndef possible(presum):\n l=len(presum)\n lastmax=-1\n firstmin=l\n mx=max(presum)\n mn=min(presum)\n for i in range(l):\n if(mx==presum[i]):\n lastmax=max(lastmax,i)\n if(mn==presum[i]):\n firstmin=min(i,firstmin)\n if lastmax<firstmin:\n return True\n return False\nfor i in range(t):\n s=input()\n l1=[0]\n l2=[0]\n for i in s:\n if i=='S':\n l1.append(l1[-1]-1)\n elif i=='W':\n l1.append(l1[-1]+1)\n elif i==\"D\":\n l2.append(l2[-1]+1)\n else:\n l2.append(l2[-1]-1)\n length=max(l1)-min(l1)+1\n breadth=max(l2)-min(l2)+1\n ans=length*breadth\n if length>2 and possible(l1):\n ans=min(ans,(length-1)*breadth)\n for i in range(len(l1)):\n l1[i]*=-1\n if length>2 and possible(l1):\n ans=min(ans,(length-1)*breadth)\n if breadth>2 and possible(l2):\n ans=min(ans,(length)*(breadth-1))\n for i in range(len(l2)):\n l2[i]*=-1\n if breadth>2 and possible(l2):\n ans=min(ans,(length)*(breadth-1))\n print(ans)", "def lim(s):\n now = 0\n up, down = 0, 0\n for i in s:\n now += i\n up = max(up, now)\n down = min(down, now)\n return up, down\ndef f(a):\n return a[0] - a[1] + 1\ndef upg(s):\n t = lim(s)\n up, down = t[0], t[1]\n arr = [1, 1]\n now = 0\n for i in range(len(s) - 1):\n if now == up - 1 and s[i + 1] == 1 and arr[0] == 1:\n arr[0] = 0\n if f(lim(s[:(i + 1)] + [-1] + s[(i + 1):])) < f(t):\n return 1\n if now == down + 1 and s[i + 1] == -1 and arr[1] == 1:\n arr[1] = 0\n if f(lim(s[:(i + 1)] + [1] + s[(i + 1):])) < f(t):\n return 1\n now += s[i + 1]\n return 0\n\n\nfor q in range(int(input())):\n s = input()\n s1, s2 = [0], [0]\n for i in s:\n if i == 'W': s1.append(1)\n if i == 'S': s1.append(-1)\n if i == 'A': s2.append(1)\n if i == 'D': s2.append(-1)\n u1 = upg(s1)\n u2 = upg(s2)\n res1, res2 = f(lim(s1)), f(lim(s2))\n ans = min((res1 - u1) * res2, (res2 - u2) * res1)\n print(ans)", "t= int(input())\n\nfor _ in range(0,t):\n\n a= list(input())\n nowx=0\n nowy=0\n maxx=0\n minx=0\n maxy=0\n miny=0\n tmaxx=0\n tminx=0\n tmaxy=0\n tminy=0\n highw=0\n highs=0\n widthd=0\n widtha=0\n for i in range (0,len(a)):\n \n if a[i] == 'W':\n nowy += 1\n if nowy >= maxy:\n maxy=nowy\n tmaxy=i\n \n elif a[i] == 'S':\n nowy -= 1\n if nowy <=miny:\n miny=nowy\n tminy=i\n elif a[i] == 'D':\n nowx += 1\n if nowx >= maxx:\n maxx=nowx\n tmaxx=i\n elif a[i] == 'A':\n nowx -= 1\n if nowx <=minx:\n minx=nowx\n tminx=i\n\n highw= max(highw,nowy-miny)\n highs= max(highs,maxy-nowy)\n widthd=max(widthd,nowx-minx)\n widtha=max(widtha,maxx-nowx)\n y1= max(highw,highs)\n y2= max(highw!=0 or highs!=0, y1- ((highw!=highs)))\n x1= max(widthd,widtha)\n x2= max(widthd!=0 or widtha!=0, x1-((widthd!=widtha)))\n print(min((y1+1)*(x2+1),(1+y2)*(x1+1)))\n \n \n \n \n\n \n\n \n \n", "t = int(input())\nfor _ in range(t):\n ss = input()\n minx=0\n fminxpos = -1\n lminxpos = -1\n maxx=0\n fmaxxpos = -1\n lmaxxpos = -1\n miny=0\n fminypos = -1\n lminypos = -1\n maxy=0\n fmaxypos = -1\n lmaxypos = -1\n x = 0\n y = 0\n for i,s in enumerate(ss):\n if s == 'W':\n y +=1\n if y > maxy:\n maxy=y\n fmaxypos=i\n if y == maxy:\n lmaxypos=i\n elif s == 'S':\n y -= 1\n if y < miny:\n miny = y\n fminypos = i\n if y == miny:\n lminypos = i\n elif s == 'D':\n lastd = i\n x += 1\n if x > maxx:\n maxx = x\n fmaxxpos = i\n if x == maxx:\n lmaxxpos = i\n elif s == 'A':\n lasta = i\n x -= 1\n if x < minx:\n minx = x\n fminxpos = i\n if x == minx:\n lminxpos = i\n xsize = maxx - minx + 1\n ysize = maxy - miny + 1\n if xsize > 2 and (fmaxxpos > lminxpos or fminxpos > lmaxxpos):\n xmin = xsize - 1\n else:\n xmin = xsize\n if ysize > 2 and (fmaxypos > lminypos or fminypos > lmaxypos):\n ymin = ysize - 1\n else:\n ymin = ysize\n print(min(xmin*ysize, xsize*ymin))", "T = int(input())\n\nfor _ in range(T):\n cmd = input()\n\n mostL, mostR, mostB, mostT = 0, 0, 0, 0\n mostLs, mostRs, mostBs, mostTs = [0],[0],[0],[0]\n x,y=0,0\n i = 0\n for c in cmd:\n i += 1\n if c == \"W\":\n y += 1\n if y>mostT:\n mostT = y\n mostTs = [i]\n elif y == mostT:\n mostTs.append(i)\n elif c == \"S\":\n y -= 1\n if y<mostB:\n mostB = y\n mostBs = [i]\n elif y == mostB:\n mostBs.append(i)\n elif c == \"A\":\n x -= 1\n if x < mostL:\n mostL = x\n mostLs = [i]\n elif x == mostL:\n mostLs.append(i)\n elif c == \"D\":\n x += 1\n if x > mostR:\n mostR = x\n mostRs = [i]\n elif x == mostR:\n mostRs.append(i)\n\n LR = mostR - mostL + 1\n if LR >= 3:\n firstL, lastL = mostLs[0], mostLs[-1]\n firstR, lastR = mostRs[0], mostRs[-1]\n\n cross = lastR > firstL and lastL > firstR\n LR_extra = not cross\n else:\n LR_extra = False\n\n BT = mostT - mostB + 1\n if BT >= 3:\n firstB, lastB = mostBs[0], mostBs[-1]\n firstT, lastT = mostTs[0], mostTs[-1]\n\n cross = lastB > firstT and lastT > firstB\n BT_extra = not cross\n else:\n BT_extra = False\n\n if LR_extra and BT_extra:\n area = min((LR-1)*BT,LR*(BT-1))\n elif LR_extra:\n area = (LR-1)*BT\n elif BT_extra:\n area = LR*(BT-1)\n else:\n area = LR*BT\n print(area)", "def main():\n hh, vv, r = [0], [0], []\n f = {'W': (vv, -1), 'S': (vv, 1), 'A': (hh, -1), 'D': (hh, 1)}.get\n for _ in range(int(input())):\n del vv[1:], hh[1:], r[:]\n for l, d in map(f, input()):\n l.append(l[-1] + d)\n for l in hh, vv:\n mi, ma = min(l), max(l)\n a, tmp = mi - 1, []\n for b in filter((mi, ma).__contains__, l):\n if a != b:\n a = b\n tmp.append(a)\n ma -= mi - 1\n r.append(ma)\n if len(tmp) < 3 <= ma:\n ma -= 1\n r.append(ma)\n print(min((r[0] * r[3], r[1] * r[2])))\n\n\ndef __starting_point():\n main()\n\n__starting_point()", "def main():\n h, v = hv = ([0], [0])\n f = {'W': (v, -1), 'S': (v, 1), 'A': (h, -1), 'D': (h, 1)}.get\n for _ in range(int(input())):\n del h[1:], v[1:]\n for l, d in map(f, input()):\n l.append(l[-1] + d)\n x = y = 1\n for l in hv:\n lh, a, n = (min(l), max(l)), 200001, 0\n for b in filter(lh.__contains__, l):\n if a != b:\n a = b\n n += 1\n le = lh[1] - lh[0] + 1\n x, y = y * le, x * (le - (n < 3 <= le))\n print(x if x < y else y)\n\n\ndef __starting_point():\n main()\n\n__starting_point()", "t = int(input())\nfor c in range(t):\n s = input()\n up_max = down_max = right_max = left_max = 0\n first_up = last_up = first_down = last_down = first_left = last_left = first_right = last_right = 0\n current_x = current_y = 0\n horizontal_count = vertical_count = 0\n for i in range(len(s)):\n if s[i] == 'W':\n current_y += 1\n vertical_count += 1\n if current_y > up_max:\n up_max = current_y\n first_up = last_up = i + 1\n elif current_y == up_max:\n last_up = i + 1\n elif s[i] == 'S':\n current_y -= 1\n vertical_count += 1\n if current_y < down_max:\n down_max = current_y\n first_down = last_down = i + 1\n elif current_y == down_max:\n last_down = i + 1\n elif s[i] == 'D':\n current_x += 1\n horizontal_count += 1\n if current_x > right_max:\n right_max = current_x\n first_right = last_right = i + 1\n elif current_x == right_max:\n last_right = i + 1\n else:\n current_x -= 1\n horizontal_count += 1\n if current_x < left_max:\n left_max = current_x\n first_left = last_left = i + 1\n elif current_x == left_max:\n last_left = i + 1\n\n h = up_max - down_max + 1\n w = right_max - left_max + 1\n ans = h * w\n if vertical_count > 1 and last_up < first_down:\n ans = min(ans, (h - 1) * w)\n if vertical_count > 1 and last_down < first_up:\n ans = min(ans, (h - 1) * w)\n if horizontal_count > 1 and last_right < first_left:\n ans = min(ans, h * (w - 1))\n if horizontal_count > 1 and last_left < first_right:\n ans = min(ans, h * (w - 1))\n\n print(ans)", "q = int(input())\nfor _ in range(q):\n d = [x for x in list(input())]\n x, y = 0, 0\n minX, maxX, minY, maxY = 0, 0 ,0 ,0\n allowW, allowS, allowA, allowD = True, True, True, True\n for v in d:\n if v == 'W':\n y += 1\n if y > maxY:\n maxY = y\n allowS = True\n allowW = False\n elif y == maxY:\n allowW = False\n elif v == 'S':\n y -= 1\n if y < minY:\n minY = y\n allowW = True\n allowS = False\n elif y == minY:\n allowS = False\n elif v == 'A':\n x -= 1\n if x < minX:\n minX = x\n allowA = False\n allowD = True\n elif x == minX:\n allowA = False\n else:#if v == 'D':\n x += 1\n if x > maxX:\n maxX = x\n allowA = True\n allowD = False\n elif x == maxX:\n allowD = False\n val = (maxX-minX+1)*(maxY-minY+1)\n if (maxX-minX) > 1 and (allowD or allowA):\n val = min(val, (maxX-minX)*(maxY-minY+1))\n if (maxY-minY) > 1 and (allowW or allowS):\n val = min(val, (maxX-minX+1)*(maxY-minY))\n print(val)", "# coding=utf-8\nINF = 1e11\n\n# move = {'W': (0, 0), 'A': (0, 0), 'S': (0, 0), 'D': (0, 0)}\nmove = {'W': (0, 1), 'A': (-1, 0), 'S': (0, -1), 'D': (1, 0)}\n\n\ndef getExtremes(positions):\n minX, minY, maxX, maxY = [positions[0][0]], [positions[0][1]], [positions[0][0]], [positions[0][1]]\n for p in positions[1:]:\n minX.append(min(minX[-1], p[0]))\n minY.append(min(minY[-1], p[1]))\n maxX.append(max(maxX[-1], p[0]))\n maxY.append(max(maxY[-1], p[1]))\n return minX, minY, maxX, maxY\n\n\nt = int(input())\n\nwhile t > 0:\n t -= 1\n s = input()\n x, y = 0, 0\n positions = [(0, 0)]\n for c in s:\n x, y = x + move[c][0], y + move[c][1]\n positions.append((x, y))\n # print(positions)\n # print()\n minXBeg, minYBeg, maxXBeg, maxYBeg = getExtremes(positions)\n # print(minXBeg, minYBeg, maxXBeg, maxYBeg, sep=\"\\n\")\n # print()\n positions.reverse()\n minXEnd, minYEnd, maxXEnd, maxYEnd = getExtremes(positions)\n minXEnd.reverse()\n minYEnd.reverse()\n maxXEnd.reverse()\n maxYEnd.reverse()\n # print(minXEnd, minYEnd, maxXEnd, maxYEnd, sep=\"\\n\")\n # print()\n positions.reverse()\n ans = INF\n for i in range(len(s)):\n for c in move:\n minX = min(minXBeg[i], positions[i][0] + move[c][0], minXEnd[i + 1] + move[c][0])\n maxX = max(maxXBeg[i], positions[i][0] + move[c][0], maxXEnd[i + 1] + move[c][0])\n minY = min(minYBeg[i], positions[i][1] + move[c][1], minYEnd[i + 1] + move[c][1])\n maxY = max(maxYBeg[i], positions[i][1] + move[c][1], maxYEnd[i + 1] + move[c][1])\n area = (maxX - minX + 1) * (maxY - minY + 1)\n # print(i, c, minX, maxX, minY, maxY, area)\n ans = min(ans, area)\n print(ans)\n", "def solve():\n i = 0\n j = 0\n imax = imin = 0\n jmax = jmin = 0\n fjmin = ljmin = fjmax = ljmax = fimax = limax = fimin = limin = -1\n for ind, e in enumerate(input()):\n if e == 'W':\n i += 1\n if i > imax:\n imax = i\n fimax = ind\n limax = ind\n elif e == 'S':\n i -= 1\n if i < imin:\n imin = i\n fimin = ind\n limin = ind\n elif e == \"A\":\n j -= 1\n if j < jmin:\n jmin = j\n fjmin = ind\n ljmin = ind\n elif e == 'D':\n j += 1\n if j > jmax:\n jmax = j\n fjmax = ind\n ljmax = ind\n if j == jmin:\n ljmin = ind\n if j == jmax:\n ljmax = ind\n if i == imin:\n limin = ind\n if i == imax:\n limax = ind\n ans = 0\n if fjmax > ljmin + 1 or fjmin > ljmax + 1:\n ans = imax - imin + 1\n if fimax > limin + 1 or fimin > limax + 1:\n ans = max(ans, jmax - jmin + 1)\n print((imax - imin + 1) * (jmax - jmin + 1) - ans)\n\n\nfor _ in range(int(input())):\n solve()\n", "import sys\ninput = sys.stdin.readline\n\n\nQ = int(input())\nQuery = [list(input().rstrip()) for _ in range(Q)]\n\nfor S in Query:\n L = len(S)\n T = [(0, 0)]\n for s in S:\n x, y = T[-1]\n if s == \"W\":\n T.append((x, y+1))\n elif s == \"S\":\n T.append((x, y-1))\n elif s == \"A\":\n T.append((x-1, y))\n else:\n T.append((x+1, y))\n \n # up, down, left, right\n dp1 = [[0, 0, 0, 0] for _ in range(L+1)]\n for i, (x, y) in enumerate(T):\n if i == 0: continue\n dp1[i][0] = max(y, dp1[i-1][0])\n dp1[i][1] = min(y, dp1[i-1][1])\n dp1[i][2] = min(x, dp1[i-1][2])\n dp1[i][3] = max(x, dp1[i-1][3])\n \n\n lx, ly = T[-1]\n dp2 = [[ly, ly, lx, lx] for _ in range(L+1)]\n for i in reversed(range(L)):\n x, y = T[i]\n dp2[i][0] = max(y, dp2[i+1][0])\n dp2[i][1] = min(y, dp2[i+1][1])\n dp2[i][2] = min(x, dp2[i+1][2])\n dp2[i][3] = max(x, dp2[i+1][3])\n \n Y, X = dp1[L][0]-dp1[L][1]+1, dp1[L][3]-dp1[L][2]+1\n ans = 0\n for i in range(L):\n if dp1[i][0] < dp2[i][0] and dp1[i][1] < dp2[i][1]:\n ans = max(ans, X)\n if dp1[i][0] > dp2[i][0] and dp1[i][1] > dp2[i][1]:\n ans = max(ans, X)\n if dp1[i][2] < dp2[i][2] and dp1[i][3] < dp2[i][3]:\n ans = max(ans, Y)\n if dp1[i][2] > dp2[i][2] and dp1[i][3] > dp2[i][3]:\n ans = max(ans, Y)\n print(X*Y-ans)", "def read_int():\n return int(input())\n\n\ndef read_ints():\n return list(map(int, input().split(' ')))\n\n\nt = read_int()\nINF = int(1e7)\nfor case_num in range(t):\n s = input()\n x = 0\n y = 0\n xlist = [0]\n ylist = [0]\n for c in s:\n if c == 'W':\n y += 1\n elif c == 'S':\n y -= 1\n elif c == 'A':\n x -= 1\n else:\n x += 1\n xlist.append(x)\n ylist.append(y)\n n = len(s)\n l = [0]\n r = [0]\n u = [0]\n d = [0]\n for i in range(1, n + 1):\n l.append(min(l[-1], xlist[i]))\n r.append(max(r[-1], xlist[i]))\n u.append(max(u[-1], ylist[i]))\n d.append(min(d[-1], ylist[i]))\n lr = [xlist[n]]\n rr = [xlist[n]]\n ur = [ylist[n]]\n dr = [ylist[n]]\n for i in range(1, n + 1):\n lr.append(min(lr[-1], xlist[n - i]))\n rr.append(max(rr[-1], xlist[n - i]))\n ur.append(max(ur[-1], ylist[n - i]))\n dr.append(min(dr[-1], ylist[n - i]))\n ans = INF * INF\n coeff = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n for k in range(4):\n for i in range(n):\n nl = min(l[i], lr[n - i] + coeff[k][0])\n nr = max(r[i], rr[n - i] + coeff[k][0])\n nu = max(u[i], ur[n - i] + coeff[k][1])\n nd = min(d[i], dr[n - i] + coeff[k][1])\n area = (nr - nl + 1) * (nu - nd + 1)\n ans = min(ans, area)\n print(ans)\n", "import sys\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n s = input()\n l, r, u, d, fl, fr, fu, fd, x, y = [0] * 10\n for i in range(len(s)):\n if s[i] == 'W':\n y += 1\n if y > u:\n u = y\n fd = 0\n fu = 1\n if y == u:\n fu = 1\n elif s[i] == 'A':\n x -= 1\n if x < l:\n l = x\n fl = 1\n fr = 0\n if x == l:\n fl = 1\n elif s[i] == 'S':\n y -= 1\n if y < d:\n d = y\n fd = 1\n fu = 0\n if y == d:\n fd = 1\n elif s[i] == 'D':\n x += 1\n if x > r:\n r = x\n fr = 1\n fl = 0\n if x == r:\n fr = 1\n #bless Ctrl+C Ctrl+V\n x, y = r - l + 1, u - d + 1\n s, k = x * y, x * y\n if x > 2 and not fl * fr:\n s = k - y\n if y > 2 and not fu * fd and k - x < s:\n s = k - x\n print(s)", "import sys\ndef work(c,c1, s):\n maxlast, maxfirst,minlast,minfirst = 0,0,0,0\n max = 0\n min = 0\n y = 0\n for i in range(len(s)):\n if s[i] == c:\n y += 1\n elif s[i] == c1:\n y -=1\n\n if max < y:\n maxfirst,maxlast = i,i\n max = y\n elif max ==y :\n maxlast = i\n\n if y < min:\n minlast,minfirst =i,i\n min = y\n elif min == y:\n minlast = i\n flag = 0\n if (maxlast<minfirst or maxfirst>minlast) and max-min > 1:\n flag = 1\n return max-min+1,flag\n\ncount = 0\nfor line in sys.stdin:\n if count == 0:\n n = int(line.strip().split(' ')[0])\n #k = int(line.strip().split(' ')[1])\n #m = int(line.strip().split(' ')[2])\n count += 1\n continue\n s = line.strip()\n flag,flag1 =0,0\n n,flag = work('W','S', s)\n m,flag1 = work('A', 'D', s)\n\n res = n * m\n if flag1 and flag:\n res = min(n*(m-1),m*(n-1))\n elif flag:\n res = m*(n-1)\n elif flag1:\n res = (m-1)*n\n print(res)"]
{ "inputs": [ "3\nDSAWWAW\nD\nWA\n" ], "outputs": [ "8\n2\n4\n" ] }
interview
https://codeforces.com/problemset/problem/1202/C
12
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$. Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$. For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation. Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$)  — the length of arrays. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$)  — elements of array $a$. There can be duplicates among elements. The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$)  — elements of array $b$. There can be duplicates among elements. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible. You can print each letter in any case (upper or lower). -----Example----- Input 5 3 1 -1 0 1 1 -2 3 0 1 1 0 2 2 2 1 0 1 41 2 -1 0 -1 -41 5 0 1 -1 1 -1 1 1 -1 1 -1 Output YES NO YES YES NO -----Note----- In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$ In the second test case we can't make equal numbers on the second position. In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case. In the last lest case, it is impossible to make array $a$ equal to the array $b$.
["from math import *\n\nmod = 1000000007\n\nfor zz in range(int(input())):\n n = int(input())\n a = [ int(i) for i in input().split()]\n b = [int(i) for i in input().split()]\n ha = True\n hp = False\n hm = False\n for i in range(n):\n if b[i] != a[i]:\n if b[i] > a[i]:\n if (hp):\n pass\n else:\n ha = False\n break\n else:\n if (hm):\n pass\n else:\n ha = False\n break\n if a[i] > 0:\n hp = True\n elif a[i] < 0:\n hm = True\n\n if ha:\n print('YES')\n else:\n print('NO')\n", "t = int(input())\nfor i in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n d1 = False\n d2 = False\n ans = True\n for j in range(n):\n if a[j] > b[j]:\n if not d1:\n ans = False\n if a[j] < b[j]:\n if not d2:\n ans = False\n if a[j] == -1:\n d1 = True\n elif a[j] == 1:\n d2 = True\n if ans:\n print(\"YES\")\n else:\n print(\"NO\")", "import sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n pos = neg = False\n ok = True\n for i in range(n):\n if a[i] > b[i] and not neg:\n ok = False\n break\n if a[i] < b[i] and not pos:\n ok = False\n break\n if a[i] == -1:\n neg = True\n if a[i] == 1:\n pos = True\n print('YES' if ok else 'NO')", "from math import *\n\n\n\nfor t in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n cnt1 = 0\n cnt0 = 0\n cntotr = 0\n f = True\n for i in range(n):\n if a[i] > b[i]:\n if cntotr == 0:\n f = False\n break\n if a[i] < b[i]:\n if cnt1 == 0:\n f = False\n break\n if a[i] == 0:\n cnt0 += 1\n elif a[i] == 1:\n cnt1 += 1\n else:\n cntotr += 1\n if f:\n print(\"YES\")\n else:\n print(\"NO\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "t = int(input())\nfor _ in range(t):\n n = int(input())\n A = map(int, input().split())\n B = map(int, input().split())\n \n seen_pos = seen_neg = False\n for a, b in zip(A, B):\n if (b > a and not seen_pos) or (b < a and not seen_neg):\n print('NO')\n break\n \n if a > 0:\n seen_pos = True\n elif a < 0:\n seen_neg = True \n else:\n print('YES')", "import math\nfrom collections import defaultdict\nml=lambda:map(int,input().split())\nll=lambda:list(map(int,input().split()))\nii=lambda:int(input())\nip=lambda:input()\n\n\"\"\"========main code===============\"\"\"\n\nt=ii()\nfor _ in range(t):\n x=ii()\n a=ll()\n b=ll()\n one=-1\n minus=-1\n f=0\n for i in range(x):\n if(b[i]>a[i]):\n if(one==-1):\n f=1\n break\n elif (b[i]<a[i]):\n if(minus==-1):\n f=1\n break\n if(a[i]==1):\n one=1\n elif(a[i]==-1):\n minus=1\n if(f):\n print(\"NO\")\n else:\n print(\"YES\")", "t=int(input())\nfor _ in range(t):\n n=int(input())\n a=list(map(int, input().split()))\n b=list(map(int, input().split()))\n grow = shrink = False\n for ai, bi in zip(a,b):\n if bi < ai:\n if not shrink:\n print('NO')\n break\n elif bi > ai and not grow:\n print('NO')\n break\n if ai == 1:\n grow = True\n elif ai == -1:\n shrink = True\n else:\n print('YES')\n", "t = int(input())\nfor case_num in range(t):\n n = int(input())\n a = list(map(int, input().split(' ')))\n b = list(map(int, input().split(' ')))\n pos = False\n neg = False\n ok = True\n for i in range(n):\n if (not pos) and (not neg) and (a[i] != b[i]):\n ok = False\n break\n if (not pos) and (a[i] < b[i]):\n ok = False\n break\n if (not neg) and (a[i] > b[i]):\n ok = False\n break\n if a[i] < 0:\n neg = True\n if a[i] > 0:\n pos = True\n print('YES' if ok else 'NO')\n", "import math\n\n\ndef main():\n was = set()\n n = int(input())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n for i in range(n):\n if a[i] - b[i] > 0:\n if not -1 in was:\n print(\"NO\")\n return\n elif a[i] - b[i] < 0:\n if not 1 in was:\n print(\"NO\")\n return\n was.add(a[i])\n print(\"YES\")\n\ndef __starting_point():\n t = int(input())\n for i in range(t):\n main()\n\n__starting_point()", "from bisect import *\nfrom collections import *\nfrom itertools import *\nimport functools\nimport sys\nimport math\nfrom decimal import *\nfrom copy import *\nfrom heapq import *\nfrom fractions import *\ngetcontext().prec = 30\nMAX = sys.maxsize\nMAXN = 300010\nMOD = 10**9+7\nspf = [i for i in range(MAXN)]\nspf[0]=spf[1] = -1\ndef sieve():\n for i in range(2,MAXN,2):\n spf[i] = 2\n for i in range(3,int(MAXN**0.5)+1):\n if spf[i]==i:\n for j in range(i*i,MAXN,i):\n if spf[j]==j:\n spf[j]=i\ndef fib(n,m):\n if n == 0:\n return [0, 1]\n else:\n a, b = fib(n // 2)\n c = ((a%m) * ((b%m) * 2 - (a%m)))%m\n d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m\n if n % 2 == 0:\n return [c, d]\n else:\n return [d, c + d]\n\ndef charIN(x= ' '):\n return(sys.stdin.readline().strip().split(x))\n\ndef arrIN(x = ' '):\n return list(map(int,sys.stdin.readline().strip().split(x)))\n\ndef ncr(n,r):\n num=den=1\n for i in range(r):\n num = (num*(n-i))%MOD\n den = (den*(i+1))%MOD\n\n return (num*(pow(den,MOD-2,MOD)))%MOD\n\ndef flush():\n return sys.stdout.flush()\n\n'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''\ndef solve():\n n = int(input())\n a = arrIN()\n b = arrIN()\n x = [[0,0,0] for i in range(n)]\n for i in range(n):\n x[i][0] = int(a[i]==-1)\n x[i][1] = int(a[i]==0)\n x[i][2] = int(a[i]==1)\n x[i][0]|=x[i-1][0]\n x[i][1]|=x[i-1][1]\n x[i][2]|=x[i-1][2]\n if a[0]!=b[0]:\n print('NO')\n else:\n for i in range(1,n):\n if a[i]!=b[i]:\n if a[i]>b[i]:\n if not x[i-1][0]:\n print('NO')\n break\n else:\n if not x[i-1][2]:\n print('NO')\n break\n else:\n print('YES')\n\n\nt = int(input())\nfor i in range(t):\n solve()\n\n"]
{ "inputs": [ "5\n3\n1 -1 0\n1 1 -2\n3\n0 1 1\n0 2 2\n2\n1 0\n1 41\n2\n-1 0\n-1 -41\n5\n0 1 -1 1 -1\n1 1 -1 1 -1\n" ], "outputs": [ "YES\nNO\nYES\nYES\nNO\n" ] }
interview
https://codeforces.com/problemset/problem/1333/B
13
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on. You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good. You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality. What is the minimum number of days is needed to finish the repair of the whole highway? -----Input----- The first line contains a single integer $T$ ($1 \le T \le 10^4$) — the number of test cases. Next $T$ lines contain test cases — one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) — the length of the highway and the number of good and bad days respectively. -----Output----- Print $T$ integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality. -----Example----- Input 3 5 1 1 8 10 10 1000000 1 1000000 Output 5 8 499999500000 -----Note----- In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good. In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
["for i in range(int(input())):\n n,g,b=map(int,input().split())\n nn=(n+1)//2\n print(max(nn+(nn-1)//g*b,n))", "for _ in range(int(input())):\n n, g, b = list(map(int, input().split()))\n half = (n - 1) // 2 + 1\n\n ans = (g + b) * (half // g) - b # + (half % g)\n if half % g != 0:\n ans += b + half % g\n print(max(ans, n))\n", "# import sys\n#\n# input = lambda: sys.stdin.readline().strip()\nfor i in range(int(input())):\n n,g, b = list(map(int, input().split()))\n n1 = n\n n = (n+1)//2\n k = n//g\n if n%g:\n print(max(n1,k*(g+b)+n%g))\n else:\n print(max(n1,g*k+b*(k-1)))\n", "def iinput():\n return [int(x) for x in input().split()]\n\n\ndef main():\n n, g, b = iinput()\n z = (n + 1) // 2\n d = (z - 1) // g\n return max(d * b + z, n)\n\n\nfor i in range(int(input())):\n print(main())\n", "import sys\ninput = sys.stdin.readline\n\nt=int(input())\nfor tests in range(t):\n n,g,b=list(map(int,input().split()))\n ALL=(n+1)//2\n\n ANS=n\n\n week=-(-ALL//g)-1\n ANS=max(ANS,week*(g+b)+(ALL-week*g))\n\n print(ANS)\n", "t = int(input())\nfor q in range(t):\n n, g, b = [int(i) for i in input().split()]\n num = n\n n = n // 2 + n % 2\n val = n // g\n d = 0\n if n % g == 0:\n d = (val - 1) * (b + g) + g\n else:\n d = val * (b + g) + n % g\n if d < num:\n print(num)\n else:\n print(d)\n \n", "t = int(input())\n\ndef check(n, h, g, b, m):\n if m < n:\n return False\n loop, rest = divmod(m, g + b)\n ok = min(rest, g) + loop * g\n return ok >= h\n\nfor _ in range(t):\n n,g,b = list(map(int,input().split()))\n high = (n + 1) // 2\n ok, ng = 10 ** 20, 0\n while ok - ng > 1:\n mid = (ok + ng) // 2\n if check(n, high, g, b, mid):\n ok = mid\n else:\n ng = mid\n print(ok)\n", "def solve():\n n, g, b = [int(x) for x in input().split()]\n l = 0\n r = int(1e30)\n\n while r-l > 1:\n m = (l+r)//2\n\n blk = m // (g + b)\n cnt = blk * g + min(g, m % (g + b))\n\n if cnt >= (n+1)//2:\n r = m\n else:\n l = m\n \n print(max(r, n))\n\nt = int(input())\nfor _ in range(t):\n solve()", "import sys\nimport math\nfrom collections import defaultdict\nfrom collections import deque\nfrom itertools import combinations\nfrom itertools import permutations\ninput = lambda : sys.stdin.readline().rstrip()\nread = lambda : list(map(int, input().split()))\ngo = lambda : 1/0\ndef write(*args, sep=\"\\n\"):\n for i in args:\n sys.stdout.write(\"{}{}\".format(i, sep))\nINF = float('inf')\nMOD = int(1e9 + 7)\nYES = \"YES\"\nNO = \"NO\"\n\nfor _ in range(int(input())):\n try:\n n, g, b = read()\n\n total = math.ceil(n / 2) \n\n s = 0\n e = 1 << 63\n while s <= e:\n m = (s + e) // 2\n good = 0\n bad = 0 \n\n x = m // (g + b)\n good += x * g\n bad += x * b \n\n y = m - (m // (g + b)) * (g + b)\n good += min(y, g)\n bad += max(0, y - g)\n\n if good + bad >= n and good >= total:\n e = m - 1\n else:\n s = m + 1\n \n print(s)\n\n\n\n \n\n except ZeroDivisionError:\n continue\n\n except Exception as e:\n print(e)\n continue", "for _ in range(int(input())):\n\tn,g,b = map(int,input().split())\n\torign = n\n\tn = (n+1)//2\n\tcom = ((n-1)//g)\n\tans = com*(g+b)\n\tn -= com*g\n\tans += n\n\tprint(max(ans,orign))"]
{ "inputs": [ "3\n5 1 1\n8 10 10\n1000000 1 1000000\n" ], "outputs": [ "5\n8\n499999500000\n" ] }
interview
https://codeforces.com/problemset/problem/1303/B

APPS Dataset

Dataset Description

APPS is a benchmark for code generation with 10000 problems. It can be used to evaluate the ability of language models to generate code from natural language specifications. You can also find APPS metric in the hub here codeparrot/apps_metric.

Languages

The dataset contains questions in English and code solutions in Python.

Dataset Structure

from datasets import load_dataset
load_dataset("codeparrot/apps")

DatasetDict({
    train: Dataset({
        features: ['problem_id', 'question', 'solutions', 'input_output', 'difficulty', 'url', 'starter_code'],
        num_rows: 5000
    })
    test: Dataset({
        features: ['problem_id', 'question', 'solutions', 'input_output', 'difficulty', 'url', 'starter_code'],
        num_rows: 5000
    })
})

How to use it

You can load and iterate through the dataset with the following two lines of code for the train split:

from datasets import load_dataset
import json

ds = load_dataset("codeparrot/apps", split="train")
sample = next(iter(ds))
# non-empty solutions and input_output features can be parsed from text format this way:
sample["solutions"] = json.loads(sample["solutions"])
sample["input_output"] = json.loads(sample["input_output"])
print(sample)

#OUTPUT:
{
 'problem_id': 0,
 'question': 'Polycarp has $n$ different binary words. A word called binary if it contains only characters \'0\' and \'1\'. For example...',
 'solutions': ["for _ in range(int(input())):\n    n = int(input())\n    mass = []\n    zo = 0\n    oz = 0\n    zz = 0\n    oo = 0\n...",...],
 'input_output': {'inputs': ['4\n4\n0001\n1000\n0011\n0111\n3\n010\n101\n0\n2\n00000\n00001\n4\n01\n001\n0001\n00001\n'], 
                  'outputs': ['1\n3 \n-1\n0\n\n2\n1 2 \n']},
 'difficulty': 'interview',
 'url': 'https://codeforces.com/problemset/problem/1259/D',
 'starter_code': ''}
}

Each sample consists of a programming problem formulation in English, some ground truth Python solutions, test cases that are defined by their inputs and outputs and function name if provided, as well as some metadata regarding the difficulty level of the problem and its source.

If a sample has non empty input_output feature, you can read it as a dictionary with keys inputs and outputs and fn_name if it exists, and similarily you can parse the solutions into a list of solutions as shown in the code above.

You can also filter the dataset for the difficulty level: Introductory, Interview and Competition. Just pass the list of difficulties as a list. E.g. if you want the most challenging problems, you need to select the competition level:

ds = load_dataset("codeparrot/apps", split="train", difficulties=["competition"])
print(next(iter(ds))["question"])

#OUTPUT:
"""\
Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by
...

For each settlement $p = 1, 2, \dots, n$, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement $p$) after some roads are abandoned?

-----Input-----

The first line of the input contains four integers $n$, $m$, $a$ and $b$ 
...

-----Output-----

Output a single line containing $n$ integers
...

-----Examples-----
Input
5 5 20 25
1 2 25
...

Output
0 25 60 40 20
...

Data Fields

Field Type Description
problem_id int problem id
question string problem description
solutions string some python solutions
input_output string Json string with "inputs" and "outputs" of the test cases, might also include "fn_name" the name of the function
difficulty string difficulty level of the problem
url string url of the source of the problem
starter_code string starter code to include in prompts

we mention that only few samples have fn_name and starter_code specified

Data Splits

The dataset contains a train and test splits with 5000 samples each.

Dataset Statistics

  • 10000 coding problems
  • 131777 test cases
  • all problems have a least one test case except 195 samples in the train split
  • for tests split, the average number of test cases is 21.2
  • average length of a problem is 293.2 words
  • all files have ground-truth solutions except 1235 samples in the test split

Dataset Creation

To create the APPS dataset, the authors manually curated problems from open-access sites where programmers share problems with each other, including Codewars, AtCoder, Kattis, and Codeforces. For more details please refer to the original paper.

Considerations for Using the Data

In AlphaCode the authors found that this dataset can generate many false positives during evaluation, where incorrect submissions are marked as correct due to lack of test coverage.

Citation Information

@article{hendrycksapps2021,
  title={Measuring Coding Challenge Competence With APPS},
  author={Dan Hendrycks and Steven Basart and Saurav Kadavath and Mantas Mazeika and Akul Arora and Ethan Guo and Collin Burns and Samir Puranik and Horace He and Dawn Song and Jacob Steinhardt},
  journal={NeurIPS},
  year={2021}
}
Downloads last month
22,722
Edit dataset card

Models trained or fine-tuned on codeparrot/apps

Spaces using codeparrot/apps 5