inputs
stringlengths
175
2.22k
targets
stringlengths
10
2.05k
language
stringclasses
1 value
split
stringclasses
2 values
template
stringclasses
2 values
dataset
stringclasses
1 value
config
stringclasses
1 value
Solve in Python: Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > a_{u}, where a_{u} is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? -----Input----- In the first line of the input integer n (1 ≤ n ≤ 10^5) is given — the number of vertices in the tree. In the second line the sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) is given, where a_{i} is the number written on vertex i. The next n - 1 lines describe tree edges: i^{th} of them consists of two integers p_{i} and c_{i} (1 ≤ p_{i} ≤ n, - 10^9 ≤ c_{i} ≤ 10^9), meaning that there is an edge connecting vertices i + 1 and p_{i} with number c_{i} written on it. -----Output----- Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. -----Example----- Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 -----Note----- The following image represents possible process of removing leaves from the tree: [Image]
def subtree_count(): stack = [0] while len(stack): v = stack[-1] size = 1 for u, _ in edge[v]: if u in subtree: size += subtree[u] else: stack.append(u) if stack[-1] is v: stack.pop() subtree[v] = size def remove_bfs(): queue = [(0, 0)] removed = 0 while len(queue): v, s = queue.pop() if s > vertex[v]: removed += subtree[v] else: for u, c in edge[v]: queue.append((u, max(s + c, 0))) return removed n = int(input()) vertex = list(map(int, input().split())) edge = {} subtree = {} for i in range(n): edge[i] = [] for i in range(n - 1): p, c = list(map(int, input().split())) edge[p - 1].append((i + 1, c)) subtree_count() print(remove_bfs())
python
test
qsol
codeparrot/apps
all
Solve in Python: In an array, a $block$ is a maximal sequence of identical elements. Since blocks are maximal, adjacent blocks have distinct elements, so the array breaks up into a series of blocks. For example, given the array $[3, 3, 2, 2, 2, 1, 5, 8, 4, 4]$, there are 6 blocks: $[3, 3], [2, 2, 2], [1], [5], [8], [4, 4]$ . In this task, you are given two arrays, $A$ (of length $n$), and $B$ (of length $m$), and a number $K$. You have to interleave $A$ and $B$ to form an array $C$ such that $C$ has $K$ blocks. Each way of interleaving $A$ and $B$ can be represented as a $0-1$ array $X$ of length $n+m$ in which $X[j]$ is $0$ if $C[j]$ came from $A$ and $X[j]$ is $1$ if $C[j]$ came from $B$. A formal description of the interleaving process is given at the end. For example, if $A = [1, 3]$ and $B = [3, 4]$, there are $6$ ways of interleaving $A$ and $B$. With each interleaving $X$ of $A$ and $B$, we also count the number of blocks in the resulting interleaved array $C$. The descriptions of the interleavings, $X$, and the outcomes, $C$, are given below. - $X = [0, 0, 1, 1]$, which corresponds to $C = [1, 3, 3, 4]$, $3$ blocks. - $X = [0, 1, 0, 1]$, which corresponds to $C = [1, 3, 3, 4]$, $3$ blocks. - $X = [0, 1, 1, 0]$, which corresponds to $C = [1, 3, 4, 3]$ , $4$ blocks. - $X = [1, 0, 0, 1]$, which corresponds to $C = [3, 1, 3, 4]$, $4$ blocks. - $X = [1, 0, 1, 0]$, which corresponds to $C = [3, 1, 4, 3]$, $4$ blocks. - $X = [1, 1, 0, 0]$, which corresponds to $C = [3, 4, 1, 3]$, $4$ blocks. Observe that different interleavings $X$ may produce the same array $C$, such as the first two interleavings in the example above. Your task is the following. Given arrays $A$ and $B$ and a number $K$, find the number of different interleavings $X$ of $A$ and $B$ that produce an output array $C$ with exactly $K$ blocks. Note that we are counting the number of interleavings, not the number of different output arrays after interleaving. For instance, if the same output array C is produced via 2 different interleavings, it gets...
# cook your dish here mod = 10 ** 8 + 7 def dic_add(dic, k1, v): if k1 <= k: if k1 in dic: dic[k1] = (dic[k1]+v) % mod else: dic[k1] = v for _ in range(int(input())): n, m, k = list(map(int, input().split())) a_l = list(map(int, input().split())) b_l = list(map(int, input().split())) # 0: m end, 1: n end f_dp = [[[{} for _ in range(n+1)] for _ in range(m+1)] for _ in range(2)] f_dp[0][1][0] = {1: 1} f_dp[1][0][1] = {1: 1} dif = 1 for j in range(1, m): if b_l[j] != b_l[j - 1]: dif += 1 f_dp[0][j+1][0] = {dif: 1} dif = 1 for i in range(1, n): if a_l[i] != a_l[i - 1]: dif += 1 f_dp[1][0][i+1] = {dif: 1} for i in range(1, n + 1): for j in range(1, m + 1): # m end if j -2 >= 0 and b_l[j-1] != b_l[j - 2]: addi = 1 else: addi = 0 for kk, vv in list(f_dp[0][j - 1][i].items()): dic_add(f_dp[0][j][i], kk + addi, vv) if b_l[j-1] != a_l[i-1]: addi = 1 else: addi = 0 for kk, vv in list(f_dp[1][j-1][i].items()): dic_add(f_dp[0][j][i], kk + addi, vv) # n end if i -2 >= 0 and a_l[i-1] != a_l[i - 2]: addi = 1 else: addi = 0 for kk, vv in list(f_dp[1][j][i-1].items()): dic_add(f_dp[1][j][i], kk + addi, vv) if b_l[j-1] != a_l[i-1]: addi = 1 else: addi = 0 for kk, vv in list(f_dp[0][j][i-1].items()): dic_add(f_dp[1][j][i], kk + addi, vv) ans = 0 if k in f_dp[0][m][n]: ans += f_dp[0][m][n][k] if k in f_dp[1][m][n]: ans += f_dp[1][m][n][k] print(ans)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/57096af70dad013aa200007b: Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50. Links referring to logical operations: [AND](https://en.wikipedia.org/wiki/Logical_conjunction), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) and [XOR](https://en.wikipedia.org/wiki/Exclusive_or). You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially. First Example: Input: true, true, false, operator: AND Steps: true AND true -> true, true AND false -> false Output: false Second Example: Input: true, true, false, operator: OR Steps: true OR true -> true, true OR false -> true Output: true Third Example: Input: true, true, false, operator: XOR Steps: true XOR true -> false, false XOR false -> false Output: false ___ Input: boolean array, string with operator' s name: 'AND', 'OR', 'XOR'. Output: calculated boolean I tried it in Python, but could not do it. Can you solve it?
def logical_calc(array, op): if op == "AND": return all(boolian for boolian in array) elif op == "OR": return any(boolian for boolian in array) else: return sum(array) % 2
python
train
abovesol
codeparrot/apps
all
Solve in Python: The lockdown hasn’t been great for our chef as his restaurant business got sabotaged because of lockdown, nevertheless no worries our chef is a multi-talented guy. Chef has decided to be a freelancer and work remotely. According to chef’s maths, he should be able to work on maximum tasks assuming that he can only work on a single task at a time. Assume that chef does N tasks. The start and finish time units of those tasks are given. Select the maximum number of tasks that can be performed by a chef, assuming that a he can only work on a single task at a time. -----Input:----- - The first input contains of size of array N representing the total number of tasks. - The second and third lines contains N space-seperated integers representing the starting and finish time of the the tasks. -----Output:----- A single line containing indices of tasks that chef will be able to do. -----Constraints----- - $1 \leq N \leq 10^5$ - Note: The lists have been sorted based on the ending times of the tasks. -----Sample Input 1:----- 3 10 12 20 20 25 30 -----Sample Output 1:----- 0 2 -----Sample Input 2:----- 6 1 2 0 6 3 7 2 4 5 7 9 10 -----Sample Output 2:----- 0 1 3 5
ans=[] #code on gfg def printMaxActivities(s, f): n = len(f) # The first activity is always selected i = 0 ans.append(i) # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if s[j] >= f[i]: ans.append(j) i = j # Driver program to test above function n=int(input()) s=list(map(int,input().split())) f=list(map(int,input().split())) printMaxActivities(s, f) print(*ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/437/A: Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct. Fortunately the child knows how to solve such complicated test. The child will follow the algorithm: If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice). You are given a multiple-choice questions, can you predict child's choose? -----Input----- The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length. Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_". -----Output----- Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes). -----Examples----- Input A.VFleaKing_is_the_author_of_this_problem B.Picks_is_the_author_of_this_problem C.Picking_is_the_author_of_this_problem D.Ftiasch_is_cute Output D Input A.ab B.abcde C.ab D.abc Output C Input A.c B.cc C.c D.c Output B -----Note----- In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D. In the second sample, no choice is great, so the child will choose the luckiest choice C. In the... I tried it in Python, but could not do it. Can you solve it?
v = [input()[2:] for i in range(4)] l = [(len(s),s) for s in v] min_l, min_s = min(l)[0], min(l)[1] max_l, max_s = max(l)[0], max(l)[1] min_ind = 0 max_ind = 0 for i in range(4): if i != v.index(min_s) and len(v[i]) / min_l >= 2: min_ind += 1 if i != v.index(max_s) and max_l / len(v[i]) >= 2: max_ind += 1 if min_ind == 3 and max_ind != 3: print(chr(65 + v.index(min_s))) elif max_ind == 3 and min_ind != 3: print(chr(65 + v.index(max_s))) else:print('C')
python
test
abovesol
codeparrot/apps
all
Solve in Python: Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks. Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook. -----Input----- The first line contains three integers $n$, $m$, and $k$ ($1 \leq n, m, k \leq 100$) — the number of participants, the number of pens, and the number of notebooks respectively. -----Output----- Print "Yes" if it possible to reward all the participants. Otherwise, print "No". You can print each letter in any case (upper or lower). -----Examples----- Input 5 8 6 Output Yes Input 3 9 3 Output Yes Input 8 5 20 Output No -----Note----- In the first example, there are $5$ participants. The Cossack has $8$ pens and $6$ notebooks. Therefore, he has enough pens and notebooks. In the second example, there are $3$ participants. The Cossack has $9$ pens and $3$ notebooks. He has more than enough pens but only the minimum needed number of notebooks. In the third example, there are $8$ participants but only $5$ pens. Since the Cossack does not have enough pens, the answer is "No".
import math import sys #imgur.com/Pkt7iIf.png def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) n, m, k = mi() if min(m,k) >= n: print('Yes') else: print('No')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_d: Given is a number sequence A of length N. Find the number of integers i \left(1 \leq i \leq N\right) with the following property: - For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 2 \times 10^5 - 1 \leq A_i \leq 10^6 -----Input----- Input is given from Standard Input in the following format: N A_1 A_2 \cdots A_N -----Output----- Print the answer. -----Sample Input----- 5 24 11 8 3 16 -----Sample Output----- 3 The integers with the property are 2, 3, and 4. I tried it in Python, but could not do it. Can you solve it?
n=int(input()) a=list(map(int,input().split())) ans=0 a.sort() num=a[-1] dp=[True]*num seen=[0]*num for i in range(n): num2=a[i] if dp[num2-1]==True: if seen[num2-1]==1: dp[num2-1]=False for j in range(2,num//num2+1): dp[j*num2-1]=False seen[a[i]-1]=1 ans=0 for i in range(n): if dp[a[i]-1]==True: ans+=1 print(ans)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/399/B: User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. While the top ball inside the stack is red, pop the ball from the top of the stack. Then replace the blue ball on the top with a red ball. And finally push some blue balls to the stack until the stack has total of n balls inside.   If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply. -----Input----- The first line contains an integer n (1 ≤ n ≤ 50) — the number of balls inside the stack. The second line contains a string s (|s| = n) describing the initial state of the stack. The i-th character of the string s denotes the color of the i-th ball (we'll number the balls from top to bottom of the stack). If the character is "R", the color is red. If the character is "B", the color is blue. -----Output----- Print the maximum number of operations ainta can repeatedly apply. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 3 RBR Output 2 Input 4 RBBR Output 6 Input 5 RBBRR Output 6 -----Note----- The first example is depicted below. The explanation how user ainta applies the first operation. He pops out one red ball, changes the color of the ball in the middle from blue to red, and pushes one blue ball. [Image] The explanation how user ainta applies the second operation. He will not pop out red balls, he simply changes the color of the ball on the top from blue to red. [Image] From now on, ainta can't apply any operation because there are no blue balls inside the stack. ainta applied two operations, so the answer is 2. The second example is depicted below. The blue arrow denotes a single operation. [Image] I tried it in Python, but could not do it. Can you solve it?
n = int(input()) s = input().strip() ans = 0 for i in range(len(s)): if s[i] == "B": ans += 2 ** i print(ans)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/DPAIRS: Chef has two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. You should choose $N+M-1$ pairs, each in the form $(A_x, B_y)$, such that the sums $A_x + B_y$ are all pairwise distinct. It is guaranteed that under the given constraints, a solution always exists. If there are multiple solutions, you may find any one. -----Input----- - The first line of the input contains two space-separated integers $N$ and $M$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. - The third line contains $M$ space-separated integers $B_1, B_2, \ldots, B_M$. -----Output----- Print $N+M-1$ lines. Each of these lines should contain two space-separated integers $x$ and $y$ denoting that you chose a pair $(A_{x+1}, B_{y+1})$. -----Constraints----- - $1 \le N, M \le 2 \cdot 10^5$ - $|A_i| \le 10^9$ for each valid $i$ - $|B_i| \le 10^9$ for each valid $i$ - $A_1, A_2, \ldots, A_N$ are pairwise distinct - $B_1, B_2, \ldots, B_M$ are pairwise distinct -----Subtasks----- Subtask #1 (25 points): $1 \le N, M \le 10^3$ Subtask #2 (75 points): original constraints -----Example Input----- 3 2 10 1 100 4 3 -----Example Output----- 2 1 0 0 1 0 0 1 -----Explanation----- The chosen pairs and their sums are: - $A_3 + B_2 = 100+3 = 103$ - $A_1 + B_1 = 10+4 = 14$ - $A_2 + B_1 = 1+4 = 5$ - $A_1 + B_2 = 10+3 = 13$ Since all sums are distinct, this is a correct output. I tried it in Python, but could not do it. Can you solve it?
N,M = [int(i) for i in input().split()] A = [int(i) for i in input().split()] B = [int(i) for i in input().split()] ans = [] seen = {} flag = False for i in range(N): for j in range(M): if(len(ans)==N+M-1): flag = True break if(A[i]+B[j] not in seen): ans.append('{} {}'.format(i,j)) seen[A[i]+B[j]] = True if(flag): break for i in ans: print(i)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5aca48db188ab3558e0030fa: You have to create a function which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number). Based on those 3 values you have to return a string, that describes which operation was used to get the given result. The possible return strings are: `"addition"`, `"subtraction"`, `"multiplication"`, `"division"`. ## Example: ``` calcType(1, 2, 3) --> 1 ? 2 = 3 --> "addition" ``` ## Notes * In case of division you should expect that the result of the operation is obtained by using `/` operator on the input values - no manual data type conversion or rounding should be performed. * Cases with just one possible answers are generated. * Only valid arguments will be passed to the function. I tried it in Python, but could not do it. Can you solve it?
def calc_type(a, b, res): return {a + b: "addition", a - b: "subtraction", a * b: "multiplication", a / b: "division"}[res]
python
train
abovesol
codeparrot/apps
all
Solve in Python: Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 10^9) of the equation:x = b·s(x)^{a} + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x. The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem. -----Input----- The first line contains three space-separated integers: a, b, c (1 ≤ a ≤ 5; 1 ≤ b ≤ 10000;  - 10000 ≤ c ≤ 10000). -----Output----- Print integer n — the number of the solutions that you've found. Next print n integers in the increasing order — the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 10^9. -----Examples----- Input 3 2 8 Output 3 10 2008 13726 Input 1 2 -18 Output 0 Input 2 2 -1 Output 4 1 31 337 967
a, b, c = map(int, input().split()) def s(x): xStr = str(x) sum = 0 for c in xStr: sum += int(c) return sum rightSide = [] M = 9*9+1 for k in range(1,M): rightSide.append(b*k**a + c) myList = [] sol = 0 for x in rightSide: if(x>0 and x<int(1e9) and x==b*s(x)**a + c): sol += 1 myList.append(x) myList.sort() print(sol, end='\n') for num in myList: print(num, sep=' ', end=' ')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/52dbae61ca039685460001ae: Create a function which accepts one arbitrary string as an argument, and return a string of length 26. The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the Nth letter of the alphabet is present in the input (independent of its case). So if an `'a'` or an `'A'` appears anywhere in the input string (any number of times), set the first character of the output string to `'1'`, otherwise to `'0'`. if `'b'` or `'B'` appears in the string, set the second character to `'1'`, and so on for the rest of the alphabet. For instance: ``` "a **& cZ" => "10100000000000000000000001" ``` I tried it in Python, but could not do it. Can you solve it?
def change(stg): chars = set(stg.lower()) return "".join(str(int(c in chars)) for c in "abcdefghijklmnopqrstuvwxyz")
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/588dd9c3dc49de0bd400016d: Hello! Your are given x and y and 2D array size tuple (width, height) and you have to: Calculate the according index in 1D space (zero-based). Do reverse operation. Implement: to_1D(x, y, size): --returns index in 1D space to_2D(n, size) --returns x and y in 2D space 1D array: [0, 1, 2, 3, 4, 5, 6, 7, 8] 2D array: [[0 -> (0,0), 1 -> (1,0), 2 -> (2,0)], [3 -> (0,1), 4 -> (1,1), 5 -> (2,1)], [6 -> (0,2), 7 -> (1,2), 8 -> (2,2)]] to_1D(0, 0, (3,3)) returns 0 to_1D(1, 1, (3,3)) returns 4 to_1D(2, 2, (3,3)) returns 8 to_2D(5, (3,3)) returns (2,1) to_2D(3, (3,3)) returns (0,1) Assume all input are valid: 1 < width < 500; 1 < height < 500 I tried it in Python, but could not do it. Can you solve it?
def to_1D(x, y, size): return size[0] * y + x def to_2D(n, size): return divmod(n, size[0])[::-1]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/935/B: Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs. -----Input----- The first line of the input contains single integer n (1 ≤ n ≤ 10^5) — the number of moves in the walking sequence. The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right. -----Output----- On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S. -----Examples----- Input 1 U Output 0 Input 6 RURUUR Output 1 Input 7 URRRUUU Output 2 -----Note----- The figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at... I tried it in Python, but could not do it. Can you solve it?
def getCoord(x, y, t): if t == 'U': return (x, y + 1) return (x + 1, y) n = int(input()) s = input() x, y = getCoord(0, 0, s[0]) t = 1 if x < y: t = 0 ans = 0 for ch in s[1:]: x, y = getCoord(x, y, ch) if x == y: continue nt = 1 if x < y: nt = 0 if t != nt: t = nt ans += 1 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and at most one wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$. The wildcard character '*' in the string $s$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $s$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $s$ to obtain a string $t$, then the string $t$ matches the pattern $s$. For example, if $s=$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba". If the given string $t$ matches the given string $s$, print "YES", otherwise print "NO". -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of the string $s$ and the length of the string $t$, respectively. The second line contains string $s$ of length $n$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $t$ of length $m$, which consists only of lowercase Latin letters. -----Output----- Print "YES" (without quotes), if you can obtain the string $t$ from the string $s$. Otherwise print "NO" (without quotes). -----Examples----- Input 6 10 code*s codeforces Output YES Input 6 5 vk*cup vkcup Output YES Input 1 1 v k Output NO Input 9 6 gfgf*gfgf gfgfgf Output NO -----Note----- In the first example a wildcard character '*' can be replaced with a string "force". So the string $s$ after this replacement is "codeforces" and the answer is "YES". In the second example a wildcard character '*' can be replaced with an empty string. So the string $s$ after this replacement is "vkcup" and the answer is "YES". There is no wildcard character '*' in the third example and the strings "v" and "k" are...
n, m = (int(x) for x in input().split()) a = input() b = input() if '*' not in a: if a == b: print('YES') else: print('NO') quit() l, r = a.split('*') if len(b) >= len(a) - 1: if l == b[:len(l)] and r == b[len(b) - len(r):]: print('YES') else: print('NO') else: print('NO')
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given $4n$ sticks, the length of the $i$-th stick is $a_i$. You have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length. You want to all rectangles to have equal area. The area of the rectangle with sides $a$ and $b$ is $a \cdot b$. Your task is to say if it is possible to create exactly $n$ rectangles of equal area or not. You have to answer $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries. Then $q$ queries follow. The first line of the query contains one integer $n$ ($1 \le n \le 100$) — the number of rectangles. The second line of the query contains $4n$ integers $a_1, a_2, \dots, a_{4n}$ ($1 \le a_i \le 10^4$), where $a_i$ is the length of the $i$-th stick. -----Output----- For each query print the answer to it. If it is impossible to create exactly $n$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". -----Example----- Input 5 1 1 1 10 10 2 10 5 2 10 1 1 2 5 2 10 5 1 10 5 1 1 1 2 1 1 1 1 1 1 1 1 1 10000 10000 10000 10000 Output YES YES NO YES YES
N = int(input()) for i in range(N): A = int(input()) B = list(map(int,input().split())) B.sort() flag = True for i in range(2*A): if B[2*i] != B[2*i+1]: flag = False break S = B[0]*B[-1] for i in range(A): if B[i*2] * B[-i*2-1] != S: flag = False break print(["NO","YES"][flag])
python
test
qsol
codeparrot/apps
all
Solve in Python: There's a tree and every one of its nodes has a cost associated with it. Some of these nodes are labelled special nodes. You are supposed to answer a few queries on this tree. In each query, a source and destination node (SNODE$SNODE$ and DNODE$DNODE$) is given along with a value W$W$. For a walk between SNODE$SNODE$ and DNODE$DNODE$ to be valid you have to choose a special node and call it the pivot P$P$. Now the path will be SNODE$SNODE$ ->P$ P$ -> DNODE$DNODE$. For any valid path, there is a path value (PV$PV$) attached to it. It is defined as follows: Select a subset of nodes(can be empty) in the path from SNODE$SNODE$ to P$P$ (both inclusive) such that sum of their costs (CTOT1$CTOT_{1}$) doesn't exceed W$W$. Select a subset of nodes(can be empty) in the path from P$P$ to DNODE$DNODE$ (both inclusive) such that sum of their costs (CTOT2$CTOT_{2}$) doesn't exceed W$W$. Now define PV=CTOT1+CTOT2$PV = CTOT_{1} + CTOT_{2}$ such that the absolute difference x=|CTOT1−CTOT2|$x = |CTOT_{1} - CTOT_{2}|$ is as low as possible. If there are multiple pairs of subsets that give the same minimum absolute difference, the pair of subsets which maximize PV$PV$ should be chosen. For each query, output the path value PV$PV$ minimizing x$x$ as defined above. Note that the sum of costs of an empty subset is zero. -----Input----- - First line contains three integers N$N$ - number of vertices in the tree, NSP$NSP$ - number of special nodes in the tree and Q$Q$ - number of queries to answer. - Second line contains N−1$N-1$ integers. If the i$i$th integer is Vi$V_i$ then there is an undirected edge between i+1$i + 1$ and Vi$V_i$ (i$i$ starts from 1$1$ and goes till N−1$N-1$). - Third line contains N$N$ integers, the i$i$th integer represents cost of the i$i$th vertex. - Fourth line contains NSP$NSP$ integers - these represent which nodes are the special nodes. - Following Q$Q$ lines contains three integers each - SNODE$SNODE$, DNODE$DNODE$ and W$W$ for each query. -----Output----- For each query output...
# cook your dish here # cook your dish here import numpy as np n, s, q = [int(j) for j in input().split()] edges = [int(j)-1 for j in input().split()] costs = [int(j) for j in input().split()] special = [int(j)-1 for j in input().split()] queries = [[0] * 3 for _ in range(q)] for i in range(q): queries[i] = [int(j)-1 for j in input().split()] edge_set = [[] for _ in range(n)] for i in range(n-1): edge_set[i+1].append(edges[i]) edge_set[edges[i]].append(i+1) stored = np.zeros((s,n,1001),dtype=bool) visited = [[] for _ in range(s)] for i in range(s): s_vertex = special[i] s_cost = costs[s_vertex] s_visited = visited[i] s_visited.append(s_vertex) s_stored = stored[i] s_stored[s_vertex][0] = True s_stored[s_vertex][s_cost] = True for edge in edge_set[s_vertex]: s_visited.append(edge) s_stored[edge] = np.array(s_stored[s_vertex]) for j in range(1,n): vertex = s_visited[j] cost = costs[vertex] s_stored[vertex][cost:1001] = np.logical_or(s_stored[vertex][0:1001-cost],s_stored[vertex][cost:1001]) for edge in edge_set[vertex]: if edge not in s_visited: s_visited.append(edge) s_stored[edge] = np.array(s_stored[vertex]) for i in range(q): first, second, max_cost = queries[i] bool_array = np.zeros(max_cost+2,dtype=bool) for j in range(s): bool_array = np.logical_or(bool_array,np.logical_and(stored[j][first][:max_cost+2],stored[j][second][:max_cost+2])) for j in range(max_cost+1,-1,-1): if bool_array[j]: print(2 * j) break
python
train
qsol
codeparrot/apps
all
Solve in Python: You are playing a computer game. In this game, you have to fight $n$ monsters. To defend from monsters, you need a shield. Each shield has two parameters: its current durability $a$ and its defence rating $b$. Each monster has only one parameter: its strength $d$. When you fight a monster with strength $d$ while having a shield with current durability $a$ and defence $b$, there are three possible outcomes: if $a = 0$, then you receive $d$ damage; if $a > 0$ and $d \ge b$, you receive no damage, but the current durability of the shield decreases by $1$; if $a > 0$ and $d < b$, nothing happens. The $i$-th monster has strength $d_i$, and you will fight each of the monsters exactly once, in some random order (all $n!$ orders are equiprobable). You have to consider $m$ different shields, the $i$-th shield has initial durability $a_i$ and defence rating $b_i$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $n$ monsters in random order. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of monsters and the number of shields, respectively. The second line contains $n$ integers $d_1$, $d_2$, ..., $d_n$ ($1 \le d_i \le 10^9$), where $d_i$ is the strength of the $i$-th monster. Then $m$ lines follow, the $i$-th of them contains two integers $a_i$ and $b_i$ ($1 \le a_i \le n$; $1 \le b_i \le 10^9$) — the description of the $i$-th shield. -----Output----- Print $m$ integers, where the $i$-th integer represents the expected damage you receive with the $i$-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction $\dfrac{x}{y}$, where $y$ is coprime with $998244353$. You have to print the value of $x \cdot y^{-1} \bmod 998244353$, where $y^{-1}$ is the inverse element for $y$ ($y \cdot y^{-1} \bmod 998244353 = 1$). -----Examples----- Input 3 2 1 3 1 2 1 1 2 Output 665496237 1 Input 3 3 4 2 6 3 1 1 2 2 3 Output 0 8 665496236
import sys,bisect r=lambda:map(int,sys.stdin.readline().split()) M=998244353 f=lambda b:pow(b,M-2,M) n,m=r() d=sorted(r()) p=[0] for v in d:p+=[p[-1]+v] for _ in range(m):a,b=r();i=bisect.bisect(d,b-1);v=n-i;print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v])
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on. In other words, after each move your direction changes counter-clockwise. Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not. Example 1: Given x = [2, 1, 1, 2], ????? ? ? ???????> ? Return true (self crossing) Example 2: Given x = [1, 2, 3, 4], ???????? ? ? ? ? ?????????????> Return false (not self crossing) Example 3: Given x = [1, 1, 1, 1], ????? ? ? ?????> Return true (self crossing) Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
class Solution: def isSelfCrossing(self, x): """ :type x: List[int] :rtype: bool """ l = (len(x)) iscross = False if l < 4: return False for i in range(3, l): #情况1 if x[i-3]>=x[i-1] and x[i-2]<=x[i]: return True #情况2 if i>=4 and x[i-4]+x[i]>=x[i-2] and x[i-3]==x[i-1]: return True #情况3 if i>=5 and x[i-5]+x[i-1]>=x[i-3] and x[i-4]+x[i]>=x[i-2] and x[i-2]>=x[i-4] and x[i-2]>x[i-4] and x[i-3]>x[i-5] and x[i-1]<x[i-3]: return True iscross = False return iscross
python
train
qsol
codeparrot/apps
all
Solve in Python: Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks. Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)? -----Input----- The first line contains two integers n and k (2 ≤ n ≤ 3·10^5, 1 ≤ k ≤ 3·10^5). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#". It is guaranteed that the first and the last characters equal ".". -----Output----- Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes). -----Examples----- Input 2 1 .. Output YES Input 5 2 .#.#. Output YES Input 7 3 .#.###. Output NO
n, k = map(int, input().split()) j = 0 for i in input(): if i == '.': j = 0 else: j += 1 if j >= k: print("NO") break else: print("YES")
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_c: We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it. Print all strings that are written on the most number of votes, in lexicographical order. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - S_i (1 \leq i \leq N) are strings consisting of lowercase English letters. - The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive). -----Input----- Input is given from Standard Input in the following format: N S_1 : S_N -----Output----- Print all strings in question in lexicographical order. -----Sample Input----- 7 beat vet beet bed vet bet beet -----Sample Output----- beet vet beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet. I tried it in Python, but could not do it. Can you solve it?
n = int(input()) S = dict() for i in range(n): s = input() if s in S: S[s] += 1 else: S[s] = 1 ans = [] cnt = 0 for k,v in S.items(): if v >= cnt: if v > cnt: ans = [] ans.append(k) cnt = v print(*sorted(ans), sep='\n')
python
test
abovesol
codeparrot/apps
all
Solve in Python: "I'm a fan of anything that tries to replace actual human contact." - Sheldon. After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact. He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact. Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer k$k$. - Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ . -----Output:----- For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$ and 0$0$ <= mi$m_i$<= ni$n_i$ . If no such answer exists print -1. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤k≤1000$1 \leq k \leq 1000$ - 1≤ni≤10$1 \leq n_i \leq 10$18$18$ -----Sample Input:----- 1 1 5 -----Sample Output:----- 2 -----EXPLANATION:----- 5$5$C$C$2$2$ = 10 which is even and m is minimum.
t = int(input()) def conv(n): k = bin(n) k = k[2:] z = len(k) c = '1'*z if c == k: return False def find(n): x = bin(n)[2:] str = '' for i in x[::-1]: if i == '0': str+='1' break else: str+='0' return int(str[::-1],2) for i in range(t): n = int(input())
python
train
qsol
codeparrot/apps
all
Solve in Python: Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks. Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows: Define the score of X to be the sum of the elements of X modulo p. Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. The two parts do not overlap. The total sum S of the scores of those two parts is maximized. This is the encryption code. Output the sum S, which is the encryption code. -----Input----- The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively. The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000]. -----Output----- Output the number S as described in the problem statement. -----Examples----- Input 4 10 3 4 7 2 Output 16 Input 10 12 16 3 24 13 9 8 7 5 12 12 Output 13 -----Note----- In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of $(3 + 4 \operatorname{mod} 10) +(7 + 2 \operatorname{mod} 10) = 16$. In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is $(16 + 3 + 24 \operatorname{mod} 12) +(13 + 9 + 8 + 7 + 5 + 12 + 12 \operatorname{mod} 12) = 7 + 6 = 13$.
n, p = map(int, input().split()) a = [int(x) for x in input().split()] s = sum(a) ans = -1; psum = 0 for i in a: psum += i ans = max(ans, psum % p + (s - psum) % p) print(ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: Chef was bored staying at home in the lockdown. He wanted to go out for a change. Chef and Chefu are fond of eating Cakes,so they decided to go the Cake shop where cakes of all possible price are available . They decided to purchase cakes of equal price and each of them will pay for their cakes. Chef only has coins of denomination $N$ whereas Chefu has that of denomination $M$. So they want your help to find out the minimum amount to be spent in order to purchase the cakes. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers $N, M$. -----Output:----- For each testcase, output in a single line answer the minimum amount to be spent in order to purchase the cake. -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq N,M \leq 10^7$ -----Sample Input:----- 1 2 3 -----Sample Output:----- 6
from math import gcd def lcm(a,b): return int((a*b/gcd(a,b))) t=int(input()) while (t!=0): n,m=list(map(int,input().split())) ans=lcm(n,m) print(ans) t=t-1
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/520/C: Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): $\rho(s, t) = \sum_{i = 0}^{n - 1} \sum_{j = 0}^{n - 1} h(\operatorname{shift}(s, i), \operatorname{shift}(t, j))$ where $\operatorname{shift}(s, i)$ is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6 Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: $\rho(s, t) = \operatorname{max}_{u :|u|=|s|} \rho(s, u)$. Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 10^9 + 7. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 10^5). The second line of the input contains a single string of length n, consisting of characters "ACGT". -----Output----- Print a single number — the answer modulo 10^9 + 7. -----Examples----- Input 1 C Output 1 Input 2 AG Output 4 Input 3 TTT Output 1 -----Note----- Please note that if for two distinct strings t_1 and t_2 values ρ(s, t_1) и ρ(s, t_2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one. In the first sample, there is ρ("C", "C") = 1, for the remaining... I tried it in Python, but could not do it. Can you solve it?
n = int(input()) s = input() lst = {'A' : 0, 'C' : 0, 'G' : 0, 'T' : 0} k, l = 0, 1 for i in s: lst[i] += 1 if k < lst[i]: k = lst[i] l = 1 else: if k == lst[i]: l += 1 print(l ** n % (10 ** 9 + 7))
python
test
abovesol
codeparrot/apps
all
Solve in Python: Chef is multi-talented. He has developed a cure for coronavirus called COVAC-19. Now that everyone in the world is infected, it is time to distribute it throughout the world efficiently to wipe out coronavirus from the Earth. Chef just cooks the cure, you are his distribution manager. In the world, there are $N$ countries (numbered $1$ through $N$) with populations $a_1, a_2, \ldots, a_N$. Each cure can be used to cure one infected person once. Due to lockdown rules, you may only deliver cures to one country per day, but you may choose that country arbitrarily and independently on each day. Days are numbered by positive integers. On day $1$, Chef has $x$ cures ready. On each subsequent day, Chef can supply twice the number of cures that were delivered (i.e. people that were cured) on the previous day. Chef cannot supply leftovers from the previous or any earlier day, as the cures expire in a day. The number of cures delivered to some country on some day cannot exceed the number of infected people it currently has, either. However, coronavirus is not giving up so easily. It can infect a cured person that comes in contact with an infected person again ― formally, it means that the number of infected people in a country doubles at the end of each day, i.e. after the cures for this day are used (obviously up to the population of that country). Find the minimum number of days needed to make the world corona-free. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $x$. - The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$. -----Output----- For each test case, print a single line containing one integer ― the minimum number of days. -----Constraints----- - $1 \le T \le 10^3$ - $1 \le N \le 10^5$ - $1 \le a_i \le 10^9$ for each valid $i$ - $1 \le x \le 10^9$ - the sum of $N$ over all test cases does not...
for _ in range(int(input())): n,x=map(int,input().split()) a=list(map(int,input().split())) a.sort() count=0 for i in range(n): if a[i]>=x/2: break # count+=1 count=i while 1: if a[i]<=x: count+=1 x=2*a[i] else: while a[i]>x: x=2*x count+=1 x=2*a[i] count+=1 i+=1 if i==n: break print(count)
python
train
qsol
codeparrot/apps
all
Solve in Python: There are $n$ left boots and $n$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $l$ and $r$, both of length $n$. The character $l_i$ stands for the color of the $i$-th left boot and the character $r_i$ stands for the color of the $i$-th right boot. A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color. For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z'). Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible. Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair. -----Input----- The first line contains $n$ ($1 \le n \le 150000$), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string $l$ of length $n$. It contains only lowercase Latin letters or question marks. The $i$-th character stands for the color of the $i$-th left boot. The third line contains the string $r$ of length $n$. It contains only lowercase Latin letters or question marks. The $i$-th character stands for the color of the $i$-th right boot. -----Output----- Print $k$ — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following $k$ lines should contain pairs $a_j, b_j$ ($1 \le a_j, b_j \le n$). The $j$-th of these lines should contain the index $a_j$ of the left boot in the $j$-th pair and index $b_j$ of the right boot in the $j$-th pair. All the numbers $a_j$ should be distinct (unique), all the numbers $b_j$...
n = int(input()) l = input() r = input() li = [0] * 27 li2 = [[] for i in range(27)] ri = [0] * 27 ri2 = [[] for i in range(27)] alth = "qwertyuiopasdfghjklzxcvbnm?" for i in range(n): i1 = alth.find(l[i]) i2 = alth.find(r[i]) li[i1] += 1 ri[i2] += 1 li2[i1] += [i] ri2[i2] += [i] for i in range(27): li2[i] += [len(li2[i]) - 1] ri2[i] += [len(ri2[i]) - 1] ans = [0] * n num = 0 for i in range(26): while li2[i][-1] > -1 and ri2[i][-1] > -1: ans[num] = [li2[i][li2[i][-1]],ri2[i][ri2[i][-1]]] num += 1 li2[i][-1] -= 1 ri2[i][-1] -= 1 for i in range(26): while li2[i][-1] > -1 and ri2[-1][-1] > -1: ans[num] = [li2[i][li2[i][-1]],ri2[-1][ri2[-1][-1]]] num += 1 li2[i][-1] -= 1 ri2[-1][-1] -= 1 for i in range(26): while li2[-1][-1] > -1 and ri2[i][-1] > -1: ans[num] = [li2[-1][li2[-1][-1]],ri2[i][ri2[i][-1]]] num += 1 li2[-1][-1] -= 1 ri2[i][-1] -= 1 while li2[-1][-1] > -1 and ri2[-1][-1] > -1: ans[num] = [li2[-1][li2[-1][-1]],ri2[-1][ri2[-1][-1]]] num += 1 li2[-1][-1] -= 1 ri2[-1][-1] -= 1 print(num) for i in range(num): print(ans[i][0] + 1, ans[i][1] + 1)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/COOK29/problems/DIRECTI: Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant. A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", indicating the street that the route begins on. Each subsequent instruction is of the form "Left on XXX" or "Right on XXX", indicating a turn onto the specified road. When reversing directions, all left turns become right turns and vice versa, and the order of roads and turns is reversed. See the sample input for examples. -----Input----- Input will begin with an integer T, the number of test cases that follow. Each test case begins with an integer N, the number of instructions in the route. N lines follow, each with exactly one instruction in the format described above. -----Output----- For each test case, print the directions of the reversed route, one instruction per line. Print a blank line after each test case. -----Constraints----- - 1 ≤ T ≤ 15 - 2 ≤ N ≤ 40 - Each line in the input will contain at most 50 characters, will contain only alphanumeric characters and spaces and will not contain consecutive spaces nor trailing spaces. By alphanumeric characters we mean digits and letters of the English alphabet (lowercase and uppercase). -----Sample Input----- 2 4 Begin on Road A Right on Road B Right on Road C Left on Road D 6 Begin on Old Madras Road Left on Domlur Flyover Left on 100 Feet Road Right on Sarjapur Road Right on Hosur Road Right on Ganapathi Temple Road -----Sample Output----- Begin on Road D Right on Road C Left on Road B Left on Road A Begin on Ganapathi Temple Road Left on Hosur Road Left on Sarjapur Road Left on 100 Feet Road Right on Domlur Flyover Right on Old Madras Road -----Explanation----- In the first test case, the destination lies on Road D, hence the reversed route begins on Road D. The final turn in the original route is turning left from Road C onto Road D.... I tried it in Python, but could not do it. Can you solve it?
cases = int(input()) for case in range (cases): N = int(input()) A = [] B = [] for n in range (N): x,y = input().split(" on ") A.append(x) B.append(y) x = n y = n-1 print(A[0],'on',B[n]) for y in range (N-1,0,-1): if (A[x] == "Right"): print("Left on",B[y-1]) else: print("Right on",B[y-1]) x-=1 if (case != cases-1): print("")
python
train
abovesol
codeparrot/apps
all
Solve in Python: Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it. In the beginning, uncle Bogdan wrote on a board a positive integer $x$ consisting of $n$ digits. After that, he wiped out $x$ and wrote integer $k$ instead, which was the concatenation of binary representations of digits $x$ consists of (without leading zeroes). For example, let $x = 729$, then $k = 111101001$ (since $7 = 111$, $2 = 10$, $9 = 1001$). After some time, uncle Bogdan understood that he doesn't know what to do with $k$ and asked Denis to help. Denis decided to wipe last $n$ digits of $k$ and named the new number as $r$. As a result, Denis proposed to find such integer $x$ of length $n$ that $r$ (as number) is maximum possible. If there are multiple valid $x$ then Denis is interested in the minimum one. All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you? Note: in this task, we compare integers ($x$ or $k$) as numbers (despite what representations they are written in), so $729 < 1999$ or $111 < 1000$. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ lines contain test cases — one per test case. The one and only line of each test case contains the single integer $n$ ($1 \le n \le 10^5$) — the length of the integer $x$ you need to find. It's guaranteed that the sum of $n$ from all test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print the minimum integer $x$ of length $n$ such that obtained by Denis number $r$ is maximum possible. -----Example----- Input 2 1 3 Output 8 998 -----Note----- In the second test case (with $n = 3$), if uncle Bogdan had $x = 998$ then...
import math T=int(input()) for t in range(T): n=int(input()) rem=math.ceil(n/4) ans='' for i in range(n-rem): ans+='9' for i in range(rem): ans+='8' print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_d: A positive integer X is said to be a lunlun number if and only if the following condition is satisfied: - In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1. For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is. You are given a positive integer K. Find the K-th smallest lunlun number. -----Constraints----- - 1 \leq K \leq 10^5 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: K -----Output----- Print the answer. -----Sample Input----- 15 -----Sample Output----- 23 We will list the 15 smallest lunlun numbers in ascending order: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23. Thus, the answer is 23. I tried it in Python, but could not do it. Can you solve it?
# import itertools # import math # from functools import reduce # import sys # sys.setrecursionlimit(500*500) # import numpy as np # import heapq # from collections import deque K = int(input()) # S = input() # n, *a = map(int, open(0)) # N, M = map(int, input().split()) # A = list(map(int, input().split())) # B = list(map(int, input().split())) # tree = [[] for _ in range(N + 1)] # B_C = [list(map(int,input().split())) for _ in range(M)] # S = input() # B_C = sorted(B_C, reverse=True, key=lambda x:x[1]) # all_cases = list(itertools.permutations(P)) # a = list(itertools.combinations_with_replacement(range(1, M + 1), N)) # itertools.product((0,1), repeat=n) # A = np.array(A) # cum_A = np.cumsum(A) # cum_A = np.insert(cum_A, 0, 0) # def dfs(tree, s): # for l in tree[s]: # if depth[l[0]] == -1: # depth[l[0]] = depth[s] + l[1] # dfs(tree, l[0]) # dfs(tree, 1) # def factorization(n): # arr = [] # temp = n # for i in range(2, int(-(-n**0.5//1))+1): # if temp%i==0: # cnt=0 # while temp%i==0: # cnt+=1 # temp //= i # arr.append([i, cnt]) # if temp!=1: # arr.append([temp, 1]) # if arr==[]: # arr.append([n, 1]) # return arr # def gcd_list(numbers): # return reduce(math.gcd, numbers) # if gcd_list(A) > 1: # print("not coprime") # return # 高速素因数分解準備 #MAXN = 10**6+10 #sieve = [i for i in range(MAXN+1)] #p = 2 #while p*p <= MAXN: # if sieve[p] == p: # for q in range(2*p, MAXN+1, p): # if sieve[q] == q: # sieve[q] = p # p += 1 cand = [[1, 2, 3, 4, 5, 6, 7, 8, 9]] for i in range(9): tmp = [] for val in cand[-1]: if str(val)[-1] != "0": tmp.append(val * 10 + int(str(val)[-1]) - 1) tmp.append(val * 10 + int(str(val)[-1])) if str(val)[-1] != "9": tmp.append(val * 10 + int(str(val)[-1]) + 1) cand.append(tmp) ans = [] for l in cand: for i in l: ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1369/B: Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing. Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner. Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves. Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$. -----Input----- The first line contains the integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $2t$ lines contain test cases — one per two lines. The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$. The second line contains the binary string $s$. The string $s$ is a string of length $n$ which consists only of zeroes and ones. It's guaranteed that sum of $n$ over test cases doesn't exceed $10^5$. -----Output----- Print $t$ answers — one per test case. The answer to the $i$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero). -----Example----- Input 5 10 0001111111 4 0101 8 11001101 10 1110000000 1 1 Output 0001111111 001 01 0 1 -----Note----- In the first test case, Lee can't perform any moves. In the second test... I tried it in Python, but could not do it. Can you solve it?
from itertools import groupby as gb t = int(input()) for _ in range(t): n = int(input()) s = input() if s.count('10') == 0: print(s) continue res = "" suf = "" l = [(k, len(list(v))) for k, v in gb(s)] if len(l) > 0 and l[0][0] == '0': res += l[0][0] * l[0][1] l = l[1:] if len(l) > 0 and l[-1][0] == '1': suf = l[-1][0] * l[-1][1] l = l[:-1] print(res + '0' + suf)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/THEATRE: Chef's friend Alex runs a movie theatre. Due to the increasing number of platforms for watching movies online, his business is not running well. As a friend, Alex asked Chef to help him maximise his profits. Since Chef is a busy person, he needs your help to support his friend Alex. Alex's theatre has four showtimes: 12 PM, 3 PM, 6 PM and 9 PM. He has four movies which he would like to play ― let's call them A, B, C and D. Each of these movies must be played exactly once and all four must be played at different showtimes. For each showtime, the price of a ticket must be one of the following: Rs 25, Rs 50, Rs 75 or Rs 100. The prices of tickets for different showtimes must also be different. Through his app, Alex receives various requests from his customers. Each request has the form "I want to watch this movie at this showtime". Let's assume that the number of people who come to watch a movie at a given showtime is the same as the number of requests for that movie at that showtime. It is not necessary to accommodate everyone's requests ― Alex just wants to earn the maximum amount of money. There is no restriction on the capacity of the theatre. However, for each movie that is not watched by anyone, Alex would suffer a loss of Rs 100 (deducted from the profit). You are given $N$ requests Alex received during one day. Find the maximum amount of money he can earn on that day by choosing when to play which movies and with which prices. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. Each of these lines contains a character $m$, followed by a space and an integer $t$, describing a request to see the movie $m$ at the showtime $t$. -----Output----- For each test case, print a single line containing one integer ― the maximum profit Alex can earn (possibly negative). Finally, print a line containing one integer ― the total... I tried it in Python, but could not do it. Can you solve it?
def maximizing(array): cpy = array[:] final_list = [] for i in range(len(array)): new_list = [array[i]] for t in range(len(cpy)): for j in range(len(new_list)): if cpy[t][0] == new_list[j][0] or cpy[t][1] == new_list[j][1]: break else: new_list.append(cpy[t]) cpy.remove(array[i]) final_list.append(new_list) costing = [] for i in final_list: cost = 0 count_array = [] if len(i) < 4: cost -= (4 - len(i))*100 for j in i: count_array.append(arrays.count(j)) count_array.sort(reverse=True) threshold = 100 for k in count_array: cost += k*threshold threshold -= 25 costing.append(cost) return max(costing) test_cases = int(input()) output_list = [] for _ in range(test_cases): n = int(input()) arrays = [] if n != 0: for _ in range(n): arrays.append(list(input().split())) output_list.append(maximizing(arrays)) else: output_list.append(-400) for output in output_list: print(output) print(sum(output_list))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/385/B: The bear has a string s = s_1s_2... s_{|}s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = s_{i}s_{i} + 1... s_{j} contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that s_{k} = b, s_{k} + 1 = e, s_{k} + 2 = a, s_{k} + 3 = r. Help the bear cope with the given problem. -----Input----- The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. -----Output----- Print a single number — the answer to the problem. -----Examples----- Input bearbtear Output 6 Input bearaabearc Output 20 -----Note----- In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). I tried it in Python, but could not do it. Can you solve it?
s = input() k = 0 l = 0 sstr = -2 count = 0 while sstr != -1: sstr = s.find("bear") if sstr == -1 : break else : if sstr == 0 or sstr == len(s) - 1: k += (len(s) - 3) else: z = ((sstr + 1) * (len(s) - sstr - 3)) k += z s = s[(sstr + 1):len(s)] print(k)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1152/B: Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat. Assume that we have a cat with a number $x$. A perfect longcat is a cat with a number equal $2^m - 1$ for some non-negative integer $m$. For example, the numbers $0$, $1$, $3$, $7$, $15$ and so on are suitable for the perfect longcats. In the Cat Furrier Transform, the following operations can be performed on $x$: (Operation A): you select any non-negative integer $n$ and replace $x$ with $x \oplus (2^n - 1)$, with $\oplus$ being a bitwise XOR operator. (Operation B): replace $x$ with $x + 1$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B. Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $40$ operations. Can you help Neko writing a transformation plan? Note that it is not required to minimize the number of operations. You just need to use no more than $40$ operations. -----Input----- The only line contains a single integer $x$ ($1 \le x \le 10^6$). -----Output----- The first line should contain a single integer $t$ ($0 \le t \le 40$) — the number of operations to apply. Then for each odd-numbered operation print the corresponding number $n_i$ in it. That is, print $\lceil \frac{t}{2} \rceil$ integers $n_i$ ($0 \le n_i \le 30$), denoting the replacement $x$ with $x \oplus (2^{n_i} - 1)$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem. -----Examples----- Input 39 Output 4 5 3 Input 1 Output 0 Input 7 Output 0 -----Note----- In the first test, one of the... I tried it in Python, but could not do it. Can you solve it?
x = int(input()) ans = [] cnt = 0 while x & (x + 1) != 0: bn = str(bin(x)[2:]) cnt += 1 ret = -1 for i in range(len(bn)): if bn[i] == '0': ret = i break if ret == -1: break x ^= 2 ** (len(bn) - ret) - 1 ans.append(len(bn) - ret) if x & (x + 1) == 0: break x += 1 cnt += 1 print(cnt) if len(ans) > 0: print(' '.join(str(el) for el in ans))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/835/A: Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v_1 milliseconds and has ping t_1 milliseconds. The second participant types one character in v_2 milliseconds and has ping t_2 milliseconds. If connection ping (delay) is t milliseconds, the competition passes for a participant as follows: Exactly after t milliseconds after the start of the competition the participant receives the text to be entered. Right after that he starts to type it. Exactly t milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw. Given the length of the text and the information about participants, determine the result of the game. -----Input----- The first line contains five integers s, v_1, v_2, t_1, t_2 (1 ≤ s, v_1, v_2, t_1, t_2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant. -----Output----- If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship". -----Examples----- Input 5 1 2 1 2 Output First Input 3 3 1 1 1 Output Second Input 4 5 3 1 5 Output Friendship -----Note----- In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins. In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins. In the third example, information on the success of the first participant comes in 22... I tried it in Python, but could not do it. Can you solve it?
def chop(): return (int(i) for i in input().split()) s,v1,v2,t1,t2=chop() a1=s*v1+t1*2 a2=s*v2+t2*2 if a1==a2: print('Friendship') elif a1<a2: print('First') else: print('Second')
python
test
abovesol
codeparrot/apps
all
Solve in Python: There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x_0, y_0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x_0, y_0). Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers. The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. -----Input----- The first line contains three integers n, x_0 и y_0 (1 ≤ n ≤ 1000, - 10^4 ≤ x_0, y_0 ≤ 10^4) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each x_{i}, y_{i} ( - 10^4 ≤ x_{i}, y_{i} ≤ 10^4) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. -----Output----- Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. -----Examples----- Input 4 0 0 1 1 2 2 2 0 -1 -1 Output 2 Input 2 1 2 1 1 1 0 Output 1 -----Note----- Explanation to the first and second samples from the statement, respectively: [Image]
n,x,y=list(map(int,input().split())) s=set() for i in range(n): a,b=list(map(int,input().split())) s.add((a-x)/(b-y) if b-y!=0 else float("INF")) print(len(s))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.hackerrank.com/challenges/np-concatenate/problem: =====Function Descriptions===== Concatenate Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined: import numpy array_1 = numpy.array([1,2,3]) array_2 = numpy.array([4,5,6]) array_3 = numpy.array([7,8,9]) print numpy.concatenate((array_1, array_2, array_3)) #Output [1 2 3 4 5 6 7 8 9] If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension. import numpy array_1 = numpy.array([[1,2,3],[0,0,0]]) array_2 = numpy.array([[0,0,0],[7,8,9]]) print numpy.concatenate((array_1, array_2), axis = 1) #Output [[1 2 3 0 0 0] [0 0 0 7 8 9]] =====Problem Statement===== You are given two integer arrays of size NXP and MXP (N & M are rows, and P is the column). Your task is to concatenate the arrays along axis 0. =====Input Format===== The first line contains space separated integers N, M and P . The next N lines contains the space separated elements of the P columns. After that, the next M lines contains the space separated elements of the P columns. =====Output Format===== Print the concatenated array of size (N + M)XP. I tried it in Python, but could not do it. Can you solve it?
import numpy n, m, p = [int(x) for x in input().strip().split()] arr1 = [] arr2 = [] for _ in range(n): arr1.append([int(x) for x in input().strip().split()] ) for _ in range(m): arr2.append([int(x) for x in input().strip().split()] ) arr1 = numpy.array(arr1) arr2 = numpy.array(arr2) print(numpy.concatenate((arr1, arr2)))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/UNBAL: A balanced parenthesis string is defined as follows: - The empty string is balanced - If P is balanced, (P) is also - If P and Q are balanced, PQ is also balanced You are given two even integers n$n$ and k$k$. Find any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$, or claim that no such string exists. -----Input----- - First line will contain T$T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line containing n$n$ and k$k$. -----Output----- For every testcase, print on a new line, any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$. If there doesn't exist any such string, print −1$-1$ instead. -----Constraints----- - 1≤T≤50000$1 \leq T \leq 50000$ - 2≤k≤n≤105$2 \leq k \leq n \leq 10^5$ - Sum of n$n$ over all testcases doesn't exceed 105$10^5$. - n$n$ and k$k$ are both even integers. -----Example Input----- 2 4 2 8 6 -----Example Output----- -1 (())(()) -----Explanation----- In the first testcase, the only balanced strings of length 4$4$ are (()) and ()(), both of which contain () as a substring. In the second testcase, (())(()) is a balanced string that doesn't contain any balanced substring of length 6$6$. I tried it in Python, but could not do it. Can you solve it?
a = int(input()) while a!=0: b,c = map(int,input().split()) p = c-2 if p==0 or p==2 or b==c: print(-1) else: q = b//p r = b%p k=0 if p+r == c: print("(", end="") while k != q: for i in range(1, p + 1): if i <= (p) // 2: print("(", end="") else: print(")", end="") k+=1 print(")") a-=1 print() continue while k!=q: for i in range(1,p+1): if i<= p//2: print("(",end="") else: print(")",end="") k+=1 for i in range(1,r+1): if i<=r//2: print("(",end="") else: print(")",end="") print() a-=1
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/415/A: Mashmokh works in a factory. At the end of each day he must turn off all of the lights. The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turns off. Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed m distinct buttons b_1, b_2, ..., b_{m} (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button b_{i} is actually b_{i}, not i. Please, help Mashmokh, print these indices. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100), the number of the factory lights and the pushed buttons respectively. The next line contains m distinct space-separated integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ n). It is guaranteed that all lights will be turned off after pushing all buttons. -----Output----- Output n space-separated integers where the i-th number is index of the button that turns the i-th light off. -----Examples----- Input 5 4 4 3 1 2 Output 1 1 3 4 4 Input 5 5 5 4 3 2 1 Output 1 2 3 4 5 -----Note----- In the first sample, after pressing button number 4, lights 4 and 5 are turned off and lights 1, 2 and 3 are still on. Then after pressing button number 3, light number 3 is turned off as well. Pressing button number 1 turns off lights number 1 and 2 as well so pressing button number 2 in the end has no effect. Thus button number 4 turned lights 4 and 5 off, button number 3 turned light 3 off and button number 1 turned light 1 and 2 off. I tried it in Python, but could not do it. Can you solve it?
n,m=map(int,input().split()) a=list(map(int,input().split())) b=[0]*n for i in range(m): num=a[i] while num<=len(b) and b[num-1]==0: b[num-1]=a[i] num+=1 for i in range(len(b)): print(b[i],end=' ')
python
test
abovesol
codeparrot/apps
all
Solve in Python: We have N weights indexed 1 to N. The mass of the weight indexed i is W_i. We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group. Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2. -----Constraints----- - 2 \leq N \leq 100 - 1 \leq W_i \leq 100 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N W_1 W_2 ... W_{N-1} W_N -----Output----- Print the minimum possible absolute difference of S_1 and S_2. -----Sample Input----- 3 1 2 3 -----Sample Output----- 0 If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.
n = int(input()) w = list(map(int, input().split())) s = sum(w) ans = float('inf') for i in range(n): ans = min(ans, abs(sum(w[:i]) - sum(w[i:]))) print(ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: Given an array of integers arr. Return the number of sub-arrays with odd sum. As the answer may grow large, the answer must be computed modulo 10^9 + 7.   Example 1: Input: arr = [1,3,5] Output: 4 Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] All sub-arrays sum are [1,4,9,3,8,5]. Odd sums are [1,9,3,5] so the answer is 4. Example 2: Input: arr = [2,4,6] Output: 0 Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]] All sub-arrays sum are [2,6,12,4,10,6]. All sub-arrays have even sum and the answer is 0. Example 3: Input: arr = [1,2,3,4,5,6,7] Output: 16 Example 4: Input: arr = [100,100,99,99] Output: 4 Example 5: Input: arr = [7] Output: 1   Constraints: 1 <= arr.length <= 10^5 1 <= arr[i] <= 100
class Solution: def numOfSubarrays(self, arr: List[int]) -> int: res = odd = even = 0 for x in arr: even += 1 if x % 2: odd, even = even, odd res = (res + odd) % 1000000007 return res
python
train
qsol
codeparrot/apps
all
Solve in Python: Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level. Ivan decided that there should be exactly n_{i} vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph. So the task Ivan gave you is: given q numbers n_1, n_2, ..., n_{q}, for each i tell the maximum number of edges in a graph with n_{i} vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops. -----Input----- The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct. Then q lines follow, i-th line contains one positive integer n_{i} (1 ≤ n_{i} ≤ 2·10^9) — the number of vertices in i-th graph. Note that in hacks you have to use q = 1. -----Output----- Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph. -----Example----- Input 3 3 4 6 Output 2 3 6 -----Note----- In the first example it is possible to construct these graphs: 1 - 2, 1 - 3; 1 - 2, 1 - 3, 2 - 4; 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
#! /usr/bin/env python # http://codeforces.com/problemset/problem/818/F # Problem name ::: F. Level Generation # submission number #212055293 #508427854 def newest_approach(n): from math import floor, ceil, sqrt quad_solv = sqrt(2*n+1/4)-1/2 x = floor(quad_solv) y = ceil(quad_solv) xed = int(x*(x-1)/2 + n - x) xbr = n - x ybr = n - y yed = 2*ybr if xed > yed: print(xed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr)) else: print(yed) # print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr)) return def main(): import sys data = [line.rstrip() for line in sys.stdin.readlines()] num_graphs = data[0] graph_sizes = [int(x) for x in data[1:]] for val in graph_sizes: # binary_search(val) # new_approach(val) newest_approach(val) def __starting_point(): main() __starting_point()
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1311/D: You are given three integers $a \le b \le c$. In one move, you can add $+1$ or $-1$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations. You have to perform the minimum number of such operations in order to obtain three integers $A \le B \le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. The next $t$ lines describe test cases. Each test case is given on a separate line as three space-separated integers $a, b$ and $c$ ($1 \le a \le b \le c \le 10^4$). -----Output----- For each test case, print the answer. In the first line print $res$ — the minimum number of operations you have to perform to obtain three integers $A \le B \le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$. On the second line print any suitable triple $A, B$ and $C$. -----Example----- Input 8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 Output 1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48 I tried it in Python, but could not do it. Can you solve it?
import sys input = sys.stdin.readline for _ in range(int(input())): a, b, c = list(map(int, input().split())) ans = 10**18 index = [0, 0, 0] for x in range(1, c+1): for y in range(x, c+100, x): cost = abs(a-x) + abs(b-y) if c % y < y - (c % y): z = c - (c % y) cost += c % y else: z = c + (y - (c % y)) cost += y - (c % y) if ans > cost: ans = cost index = [x, y, z] print(ans) print(*index)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/409/C: Salve, mi amice. Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus. Rp:     I Aqua Fortis     I Aqua Regia     II Amalgama     VII Minium     IV Vitriol Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via. Fac et spera, Vale, Nicolas Flamel -----Input----- The first line of input contains several space-separated integers a_{i} (0 ≤ a_{i} ≤ 100). -----Output----- Print a single integer. -----Examples----- Input 2 4 6 8 10 Output 1 I tried it in Python, but could not do it. Can you solve it?
from math import floor nums = list(map(int, input().split())) seq = [1, 1, 2, 7, 4] min_c = 10000000000 for i in range(len(nums)): if floor(nums[i] / seq[i]) < min_c: min_c = floor(nums[i] / seq[i]) print(min_c)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5d16af632cf48200254a6244: A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n. For example, if n = 12, then * 12 / 2 = 6 * 6 / 2 = 3 So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`. If n = 16 then * 16 / 2 = 8 * 8 / 2 = 4 * 4 / 2 = 2 * 2 / 2 = 1 we divided successively 4 times and we reached 1, so the strongness of 16 is `4` # Task Given a closed interval `[n, m]`, return the even number that is the strongest in the interval. If multiple solutions exist return the smallest strongest even number. Note that programs must run within the allotted server time; a naive solution will probably time out. # Constraints ```if-not:ruby 1 <= n < m <= INT_MAX ``` ```if:ruby 1 <= n < m <= 2^64 ``` # Examples ``` [1, 2] --> 2 # 1 has strongness 0, 2 has strongness 1 [5, 10] --> 8 # 5, 7, 9 have strongness 0; 6, 10 have strongness 1; 8 has strongness 3 [48, 56] --> 48 I tried it in Python, but could not do it. Can you solve it?
from math import log from math import floor def strongest_even(n,m): a=2**floor(log(m)/log(2));b=1; while a*b<n or a*b>m: a /= 2; b += 2; while a*b<=m: if a*b>=n: return a*b b +=2 return a*b #strongest_even(33,47)
python
train
abovesol
codeparrot/apps
all
Solve in Python: Snuke loves puzzles. Today, he is working on a puzzle using S- and c-shaped pieces. In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below: Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces. Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces. -----Constraints----- - 1 ≤ N,M ≤ 10^{12} -----Input----- The input is given from Standard Input in the following format: N M -----Output----- Print the answer. -----Sample Input----- 1 6 -----Sample Output----- 2 Two Scc groups can be created as follows: - Combine two c-shaped pieces into one S-shaped piece - Create two Scc groups, each from one S-shaped piece and two c-shaped pieces
n, m = map(int, input().split()) ans = min(n, m // 2) m -= ans * 2 ans += max(0, m // 4) print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/57f8ff867a28db569e000c4a: Modify the `kebabize` function so that it converts a camel case string into a kebab case. Notes: - the returned string should only contain lowercase letters I tried it in Python, but could not do it. Can you solve it?
import re def kebabize(s): return re.sub('\B([A-Z])', r'-\1', re.sub('\d', '', s)).lower()
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/532/C: Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move. There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0). You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well. -----Input----- The first line contains four integers: x_{p}, y_{p}, x_{v}, y_{v} (0 ≤ x_{p}, y_{p}, x_{v}, y_{v} ≤ 10^5) — Polycarp's and Vasiliy's starting coordinates. It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0). -----Output----- Output the name of the winner: "Polycarp" or "Vasiliy". -----Examples----- Input 2 1 2 2 Output Polycarp Input 4 7 7 4 Output Vasiliy -----Note----- In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. I tried it in Python, but could not do it. Can you solve it?
def main(): def dist(x1, y1, x2, y2): return max(abs(x1 - x2), abs(y1 - y2)) xp, yp, xv, yv = [int(i) for i in input().split()] win = -1 while True: if xp == 0: yp -= 1 elif yp == 0: xp -= 1 elif dist(xp - 1, yp, xv, yv) < dist(xp, yp - 1, xv, yv): xp -= 1 else: yp -= 1 if xp == 0 and yp == 0: win = 0 break if xv == 0: if xp == 0 and yv - yp == 1: win = 0 break yv -= 1 elif yv == 0: if yp == 0 and xv - xp == 1: win = 0 break xv -= 1 else: if yv - yp == 1 and xv - xp == 1: win = 0 break xv -= 1 yv -= 1 if xv == 0 and yv == 0: win = 1 break print(["Polycarp", "Vasiliy"][win]) main()
python
test
abovesol
codeparrot/apps
all
Solve in Python: One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: [Image] By the pieces lay a large square wooden board. The board is divided into $n^2$ cells arranged into $n$ rows and $n$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free. Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board? -----Input----- The first line of the input contains a single integer $n$ ($3 \leq n \leq 50$) — the size of the board. The following $n$ lines describe the board. The $i$-th line ($1 \leq i \leq n$) contains a single string of length $n$. Its $j$-th character ($1 \leq j \leq n$) is equal to "." if the cell in the $i$-th row and the $j$-th column is free; it is equal to "#" if it's occupied. You can assume that the board contains at least one free cell. -----Output----- Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower). -----Examples----- Input 3 #.# ... #.# Output YES Input 4 ##.# #... #### ##.# Output NO Input 5 #.### ....# #.... ###.# ##### Output YES Input 5 #.### ....# #.... ....# #..## Output NO -----Note----- The following sketches show the example boards and their tilings if such tilings exist: [Image]
n=int(input()) tab=[] for i in range(n): a=list(input()) tab.append(a) for i in range(i): for j in range(n): if 0<i<n-1 and 0<j<n-1 and tab[i-1][j]==tab[i+1][j]==tab[i][j+1]==tab[i][j-1]==tab[i][j]=='.': tab[i][j]='#' tab[i-1][j]='#' tab[i+1][j]='#' tab[i][j-1]='#' tab[i][j+1]='#' for i in range(n): for j in range(n): if tab[i][j]=='.': print('NO') return print('YES')
python
test
qsol
codeparrot/apps
all
Solve in Python: # Solve For X You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: ```python solve_for_x('x - 5 = 20') # should return 25 solve_for_x('20 = 5 * x - 5') # should return 5 solve_for_x('5 * x = x + 8') # should return 2 solve_for_x('(5 - 3) * x = x + 2') # should return 2 ``` NOTES: * All numbers will be whole numbers * Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations). * If the random tests don't pass the first time, just run them again.
import re def solve_for_x(equation): left,right = equation.split("=") answer = False TrialAndErrorRipMs = -1000 while answer == False: FinalLeft = re.sub("x", str(TrialAndErrorRipMs), left) FinalRight = re.sub("x", str(TrialAndErrorRipMs), right) if eval(FinalLeft) == eval(FinalRight): return TrialAndErrorRipMs TrialAndErrorRipMs += 1
python
train
qsol
codeparrot/apps
all
Solve in Python: Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens. Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left. You need to process m queries, the i-th results in that the character at position x_{i} (1 ≤ x_{i} ≤ n) of string s is assigned value c_{i}. After each operation you have to calculate and output the value of f(s). Help Daniel to process all queries. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer x_{i} and c_{i} (1 ≤ x_{i} ≤ n, c_{i} — a lowercas English letter or a period sign), describing the query of assigning symbol c_{i} to position x_{i}. -----Output----- Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment. -----Examples----- Input 10 3 .b..bz.... 1 h 3 c 9 f Output 4 3 1 Input 4 4 .cc. 2 . 3 . 2 a 1 a Output 1 3 1 1 -----Note----- Note to the first sample test (replaced periods are enclosed in square brackets). The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.") after...
import sys; sys.setrecursionlimit(1000000) def solve(): n, m, = rv() s = list(input()) res = [0] * m #replace dot: #dot had nothing on left or right: nothing changes #dot had one on left or right: -1 #dot had two on left or right: -2 #replace char: #if had two chars on left and right: 0 # if had one char and one dot: +1 # if had two dots: +2 helper = list() for i in range(n): if s[i] == '.': if i == 0: helper.append(1) else: if s[i-1] == '.': helper[-1] += 1 else: helper.append(1) initval = 0 for val in helper: initval += val - 1 for query in range(m): index, replace = input().split() index = int(index) - 1 if (s[index] == '.' and replace == '.') or (s[index] != '.' and replace != '.'): res[query] = initval else: sidedots = 0 if index > 0: if s[index - 1] == '.': sidedots+=1 if index < n - 1: if s[index + 1] == '.': sidedots+=1 if s[index] == '.': res[query] = initval - sidedots initval -= sidedots else: res[query] = initval + sidedots initval += sidedots s[index] = replace print('\n'.join(map(str, res))) def rv(): return list(map(int, input().split())) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve()
python
test
qsol
codeparrot/apps
all
Solve in Python: The snakes want to build a temple for Lord Cobra. There are multiple strips of land that they are looking at, but not all of them are suitable. They need the strip of land to resemble a coiled Cobra. You need to find out which strips do so. Formally, every strip of land, has a length. Suppose the length of the i-th strip is is Ni, then there will be Ni integers, Hi1, Hi2, .. HiNi, which represent the heights of the ground at various parts of the strip, in sequential order. That is, the strip has been divided into Ni parts and the height of each part is given. This strip is valid, if and only if all these conditions are satisfied: - There should be an unique 'centre' part. This is where the actual temple will be built. By centre, we mean that there should be an equal number of parts to the left of this part, and to the right of this part. - Hi1 = 1 - The heights keep increasing by exactly 1, as you move from the leftmost part, to the centre part. - The heights should keep decreasing by exactly 1, as you move from the centre part to the rightmost part. Note that this means that HiNi should also be 1. Your job is to look at every strip and find if it's valid or not. -----Input----- - The first line contains a single integer, S, which is the number of strips you need to look at. The description of each of the S strips follows - The first line of the i-th strip's description will contain a single integer: Ni, which is the length and number of parts into which it has been divided. - The next line contains Ni integers: Hi1, Hi2, .., HiNi. These represent the heights of the various parts in the i-th strip. -----Output----- - For each strip, in a new line, output "yes" if is a valid strip, and "no", if it isn't. -----Constraints----- - 1 ≤ S ≤ 100 - 3 ≤ Ni ≤ 100 - 1 ≤ Hij ≤ 100 -----Example----- Input: 7 5 1 2 3 2 1 7 2 3 4 5 4 3 2 5 1 2 3 4 3 5 1 3 5 3 1 7 1 2 3 4 3 2 1 4 1 2 3 2 4 1 2 2 1 Output: yes no no no yes no no -----Explanation----- In the first strip, all the conditions are satisfied, hence it is...
# cook your dish here t = int(input()) for z in range(t) : n = int(input()) a = [int(x) for x in input().split()] if n%2==1 and a[0]==1 : x = list(reversed(a)) for i in range((len(a)-1)//2) : if a[i] + 1 == x[i+1] : c = 0 else: c = 1 break if c==1 : print("no") else: print("yes") else: print("no")
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5921c0bc6b8f072e840000c0: A series or sequence of numbers is usually the product of a function and can either be infinite or finite. In this kata we will only consider finite series and you are required to return a code according to the type of sequence: |Code|Type|Example| |-|-|-| |`0`|`unordered`|`[3,5,8,1,14,3]`| |`1`|`strictly increasing`|`[3,5,8,9,14,23]`| |`2`|`not decreasing`|`[3,5,8,8,14,14]`| |`3`|`strictly decreasing`|`[14,9,8,5,3,1]`| |`4`|`not increasing`|`[14,14,8,8,5,3]`| |`5`|`constant`|`[8,8,8,8,8,8]`| You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested. Try to achieve a good solution that runs in linear time; also, do it functionally, meaning you need to build a *pure* function or, in even poorer words, do NOT modify the initial input! I tried it in Python, but could not do it. Can you solve it?
def sequence_classifier(arr): f,l=0,len(arr)-1 for i in range(0,l): f|= 1 if arr[i]<arr[i+1] else 2 if arr[i]==arr[i+1] else 4 return [0,1,5,2,3,0,4,0][f]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1031/B: When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0 \le b_i \le 3$). Masha became interested if or not there is an integer sequence of length $n$, which elements we will denote as $t_i$ ($0 \le t_i \le 3$), so that for every $i$ ($1 \le i \le n - 1$) the following is true: $a_i = t_i | t_{i + 1}$ (where $|$ denotes the bitwise OR operation) and $b_i = t_i \& t_{i + 1}$ (where $\&$ denotes the bitwise AND operation). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $t_i$ of length $n$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the length of the sequence $t_i$. The second line contains $n - 1$ integers $a_1, a_2, \ldots, a_{n-1}$ ($0 \le a_i \le 3$) — the first sequence on the blackboard. The third line contains $n - 1$ integers $b_1, b_2, \ldots, b_{n-1}$ ($0 \le b_i \le 3$) — the second sequence on the blackboard. -----Output----- In the first line print "YES" (without quotes), if there is a sequence $t_i$ that satisfies the conditions from the statements, and "NO" (without quotes), if there is no such sequence. If there is such a sequence, on the second line print $n$ integers $t_1, t_2, \ldots, t_n$ ($0 \le t_i \le 3$) — the sequence that satisfies the statements conditions. If there are multiple answers, print any of them. -----Examples----- Input 4 3 3 2 1 2 0 Output YES 1 3 2 0 Input 3 1 3 3 2 Output NO -----Note----- In the first example it's easy to see that the sequence from output satisfies the given conditions: $t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1$ and $t_1 \& t_2 = (01_2) \& (11_2) = (01_2) = 1 = b_1$; $t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2$ and $t_2 \& t_3 = (11_2) \&... I tried it in Python, but could not do it. Can you solve it?
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(n-1): if a[i] == 3: a[i] = '11' elif a[i] == 2: a[i] = '10' elif a[i] == 1: a[i] = '01' elif a[i] == 0: a[i] = '00' for i in range(n-1): if b[i] == 3: b[i] = '11' elif b[i] == 2: b[i] = '10' elif b[i] == 1: b[i] = '01' elif b[i] == 0: b[i] = '00' def Checker(z, x, y): if z == '0': if x == '0' and y == '0': return '0' elif x == '0' and y == '1': return None elif x == '1' and y == '0': return '1' elif x == '1' and y == '1': return None elif z == '1': if x == '0' and y == '0': return None elif x == '0' and y == '1': return None elif x == '1' and y == '0': return '0' elif x == '1' and y == '1': return '1' s = [] flag = True for ti in ['00', '01', '10', '11']: t = ti if len(s) == n: break elif (Checker(t[0], a[0][0], b[0][0]) is not None) and (Checker(t[1], a[0][1], b[0][1]) is not None): s.append(t) for i in range(n-1): c = Checker(t[0], a[i][0], b[i][0]) e = Checker(t[1], a[i][1], b[i][1]) if (c is not None) and (e is not None): k = ''.join([c, e]) s.append(k) t = k else: s.clear() break elif t == '11': flag = False if flag and s: print('YES') for i in range(n): if s[i] == '11': print(3, end=' ') elif s[i] == '10': print(2, end=' ') elif s[i] == '01': print(1, end=' ') elif s[i] == '00': print(0, end=' ') else: print('NO')
python
test
abovesol
codeparrot/apps
all
Solve in Python: There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones. A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles. Find the minimum cost to merge all piles of stones into one pile.  If it is impossible, return -1.   Example 1: Input: stones = [3,2,4,1], K = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible. Example 2: Input: stones = [3,2,4,1], K = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. Example 3: Input: stones = [3,5,1,2,6], K = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible.   Note: 1 <= stones.length <= 30 2 <= K <= 30 1 <= stones[i] <= 100
class Solution: def mergeStones(self, stones: List[int], K: int) -> int: n = len(stones) dp = [[[math.inf for k in range(K + 1)] for j in range(n)] for i in range(n)] # dp[i][j][k]: min cost of merging from i to j (inclusive) and finally having k piles for i in range(n): dp[i][i][1] = 0 pre_sum = [0] * n pre_sum[0] = stones[0] for i in range(1, n): pre_sum[i] = pre_sum[i - 1] + stones[i] def range_sum(i, j): if i == 0: return pre_sum[j] else: return pre_sum[j] - pre_sum[i - 1] for merge_len in range(2, n + 1): # 枚举区间长度 for start in range(n - merge_len + 1): # 枚举区间左端点 end = start + merge_len - 1 # 区间右端点 for k in range(2, K + 1): for middle in range(start, end, K - 1): # 枚举分割点,左区间start~middle,右区间middle+1~end dp[start][end][k] = min(dp[start][end][k], dp[start][middle][1] + dp[middle + 1][end][k - 1]) if dp[start][end][K] < math.inf: # 可以make a move,merge start ~ end 成 1 个pile dp[start][end][1] = dp[start][end][K] + range_sum(start, end) return dp[0][n-1][1] if dp[0][n-1][1] < math.inf else -1
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/CHEFEZQ: Chef published a blog post, and is now receiving many queries about it. On day $i$, he receives $Q_i$ queries. But Chef can answer at most $k$ queries in a single day. Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than $k$). The remaining questions (if any) will be carried over to the next day. Fortunately, after $n$ days, the queries have stopped. Chef would like to know the first day during which he has some free time, i.e. the first day when he answered less than $k$ questions. -----Input:----- - First line will contain $T$, the number of testcases. Then the testcases follow. - The first line of each testcase contains two space separated integers $n$ and $k$. - The second line of each testcase contains $n$ space separated integers, namely $Q_1, Q_2, ... Q_n$. -----Output:----- For each testcase, output in a single line the first day during which chef answers less than $k$ questions. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq $ sum of $n$ over all testcases $ \leq 10^5$ - $1 \leq k \leq 10^8$ - $0 \leq Q_i \leq 10^8$ -----Subtasks----- - Subtask 1 - 20% points - Sum of $Q_i$ over all testcases and days $\leq 3 . 10^6$ - Subtask 2 - 80% points - Original constraints -----Sample Input:----- 2 6 5 10 5 5 3 2 1 1 1 100 -----Sample Output:----- 6 101 -----Explanation:----- Test Case 1 On the first day, chef answers 5 questions and leaves the remaining 5 (out of the 10) for the future days. On the second day, chef has 10 questions waiting to be answered (5 received on the second day and 5 unanswered questions from day 1). Chef answers 5 of these questions and leaves the remaining 5 for the future. On the third day, chef has 10 questions waiting to be answered (5 received on the third day and 5 unanswered questions from earlier). Chef answers 5 of these questions and leaves the remaining 5 for later. On the fourth day, chef has 8 questions waiting to be answered (3 received on the fourth day and 5 unanswered... I tried it in Python, but could not do it. Can you solve it?
def calFirstFreeDay(r, k, count): if((r-k)<k): print(count+2) else: calFirstFreeDay(r-k, k, count+1) T = int(input()) for i in range(0, T): list = input().split() n = int(list[0]) k = int(list[1]) pq = 0 outputDone=False; arr = input().split() for j in range(0, n): q = int(arr[j]) if((q+pq)<k): print((j+1)); outputDone = True; break; else: pq = (q+pq)-k; if(not outputDone): calFirstFreeDay(pq, k, n)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1335/B: You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that each substring of length $a$ has exactly $b$ distinct letters. It is guaranteed that the answer exists. You have to answer $t$ independent test cases. Recall that the substring $s[l \dots r]$ is the string $s_l, s_{l+1}, \dots, s_{r}$ and its length is $r - l + 1$. In this problem you are only interested in substrings of length $a$. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow. The only line of a test case contains three space-separated integers $n$, $a$ and $b$ ($1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$), where $n$ is the length of the required string, $a$ is the length of a substring and $b$ is the required number of distinct letters in each substring of length $a$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$). -----Output----- For each test case, print the answer — such a string $s$ of length $n$ consisting of lowercase Latin letters that each substring of length $a$ has exactly $b$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists. -----Example----- Input 4 7 5 3 6 1 1 6 6 1 5 2 2 Output tleelte qwerty vvvvvv abcde -----Note----- In the first test case of the example, consider all the substrings of length $5$: "tleel": it contains $3$ distinct (unique) letters, "leelt": it contains $3$ distinct (unique) letters, "eelte": it contains $3$ distinct (unique) letters. I tried it in Python, but could not do it. Can you solve it?
t = int(input('')) c = [] for i in range(97,123,1): c.append(chr(i)) for _ in range(t): n,a,b = list(map(int,input('').split(' '))) s = '' for i in range(n): s = s+c[i%b] print(s)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1364/A: Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements isn't divisible by $x$, or determine that such subarray doesn't exist. An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. -----Input----- The first line contains an integer $t$ $(1 \le t \le 5)$ — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^4$) — the number of elements in the array $a$ and the number that Ehab hates. The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($0 \le a_i \le 10^4$) — the elements of the array $a$. -----Output----- For each testcase, print the length of the longest subarray whose sum isn't divisible by $x$. If there's no such subarray, print $-1$. -----Example----- Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 -----Note----- In the first test case, the subarray $[2,3]$ has sum of elements $5$, which isn't divisible by $3$. In the second test case, the sum of elements of the whole array is $6$, which isn't divisible by $4$. In the third test case, all subarrays have an even sum, so the answer is $-1$. I tried it in Python, but could not do it. Can you solve it?
for testcase in range(int(input())): n, x = map(int, input().split()) arr = list(map(int, input().split())) start = 0 for i in arr: if not i % x: start += 1 else: break end = 0 for i in arr[::-1]: if not i % x: end += 1 else: break if start == end == len(arr): print(-1) continue else: total = sum(arr) if not total % x: print(len(arr) - min(start, end) - 1) else: print(len(arr))
python
test
abovesol
codeparrot/apps
all
Solve in Python: Each floating-point number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests. Don't round the numbers! Just cut them after two decimal places! ``` Right examples: 32.8493 is 32.84 14.3286 is 14.32 Incorrect examples (e.g. if you round the numbers): 32.8493 is 32.85 14.3286 is 14.33 ```
def two_decimal_places(number): number = str(number) return float(number[:number.index('.') + 3])
python
train
qsol
codeparrot/apps
all
Solve in Python: You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. [Image] Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color. You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \neq y, y \neq z, x \neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good. You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it. -----Input----- The first line contains one integer $n$ $(3 \le n \le 100\,000)$ — the number of vertices. The second line contains a sequence of integers $c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$ $(1 \le c_{1, i} \le 10^{9})$, where $c_{1, i}$ is the cost of painting the $i$-th vertex into the first color. The third line contains a sequence of integers $c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$ $(1 \le c_{2, i} \le 10^{9})$, where $c_{2, i}$ is the cost of painting the $i$-th vertex into the second color. The fourth line contains a sequence of integers $c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$ $(1 \le c_{3, i} \le 10^{9})$, where $c_{3, i}$ is the cost of painting the $i$-th vertex into the third color. Then $(n - 1)$ lines follow, each containing two integers $u_j$ and $v_j$ $(1 \le u_j, v_j \le n, u_j \neq v_j)$ — the numbers of vertices connected by the $j$-th undirected edge. It is guaranteed that these edges denote a tree. -----Output----- If there is no good painting, print $-1$. Otherwise, print the minimum cost of a good painting in the first line. In the second line print $n$ integers $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 3)$, where the $i$-th integer should denote the color of the...
from collections import defaultdict, deque from itertools import permutations class Graph: def __init__(self): self.E = {} self.V = defaultdict(list) def put(self, v1, v2): if v1 not in self.E: self.E[v1] = 1 if v2 not in self.E: self.E[v2] = 1 self.V[v1].append(v2) self.V[v2].append(v1) def _adj(self, v1): return self.V[v1] def bfs(self, v): visited = set([v]) path = [v] q = deque([v]) while q: v1 = q.pop() for v2 in self._adj(v1): if v2 not in visited: visited.add(v2) path.append(v2) q.appendleft(v2) return path def __starting_point(): n = int(input()) cp = [] for _ in range(3): cp.append(list(map(int, input().split(' ')))) inv = False vert = defaultdict(int) graph = Graph() for _ in range(n - 1): v1, v2 = list(map(int, input().split(' '))) vert[v1] += 1 if vert[v1] > 2: inv = True break vert[v2] += 1 if vert[v2] > 2: inv = True break graph.put(v1, v2) if inv: print(-1) else: for key in vert: if vert[key] == 1: start = key break path = graph.bfs(start) min_cost = float('inf') min_cost_perm = (0, 1, 2) for p in permutations([0, 1, 2]): cur_cost = 0 for i, v in enumerate(path): cur_cost += cp[p[i % 3]][v - 1] if cur_cost < min_cost: min_cost_perm = p min_cost = cur_cost # print(path, graph.V) ans = [0]*n for i, v in enumerate(path): ans[v - 1] = min_cost_perm[i % 3] + 1 print(min_cost) print(' '.join(map(str, ans))) __starting_point()
python
test
qsol
codeparrot/apps
all
Solve in Python: There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|. Here, |x| denotes the absolute value of x. If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index. Which checkpoint will each student go to? -----Constraints----- - 1 \leq N,M \leq 50 - -10^8 \leq a_i,b_i,c_j,d_j \leq 10^8 - All input values are integers. -----Input----- The input is given from Standard Input in the following format: N M a_1 b_1 : a_N b_N c_1 d_1 : c_M d_M -----Output----- Print N lines. The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go. -----Sample Input----- 2 2 2 0 0 0 -1 0 1 0 -----Sample Output----- 2 1 The Manhattan distance between the first student and each checkpoint is: - For checkpoint 1: |2-(-1)|+|0-0|=3 - For checkpoint 2: |2-1|+|0-0|=1 The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2. The Manhattan distance between the second student and each checkpoint is: - For checkpoint 1: |0-(-1)|+|0-0|=1 - For checkpoint 2: |0-1|+|0-0|=1 When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.
n, m = list(map(int,input().split())) s_x_plus_y = [] s_x_minus_y = [] p_x_plus_y = [] p_x_minus_y = [] for student in range(n): x, y = list(map(int,input().split())) s_x_plus_y.append(x + y) s_x_minus_y.append(x - y) for i in range(m): x, y = list(map(int,input().split())) p_x_plus_y.append(x + y) p_x_minus_y.append(x - y) for i in range(n): p_dist = [] for j in range(m): p1 = abs(s_x_plus_y[i] - p_x_plus_y[j]) p2 = abs(s_x_minus_y[i] - p_x_minus_y[j]) d = max(p1, p2) p_dist.append(d) print((p_dist.index(min(p_dist))+1))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/: There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.   Example 1: Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 Output: 3 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2]  City 1 -> [City 0, City 2, City 3]  City 2 -> [City 0, City 1, City 3]  City 3 -> [City 1, City 2]  Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. Example 2: Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 Output: 0 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> [City 1]  City 1 -> [City 0, City 4]  City 2 -> [City 3, City 4]  City 3 -> [City 2, City 4] City 4 -> [City 1, City 2, City 3]  The city 0 has 1 neighboring city at a distanceThreshold = 2.   Constraints: 2 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= fromi < toi < n 1 <= weighti, distanceThreshold <= 10^4 All pairs (fromi, toi) are distinct. I tried it in Python, but could not do it. Can you solve it?
class Solution: def dfs(self, q, D, V, k): Q = [q] V[q] = 0 while Q: T = [] for nd in Q: W = V[nd] for n,w in D[nd]: cl = W + w cr = V[n] if cl < cr and cl <= k: V[n] = cl T.append(n) Q = T return {a:b for a,b in V.items() if b != sys.maxsize} def findTheCity(self, N: int, E: List[List[int]], k: int) -> int: D = collections.defaultdict(list) for f,t,w in E: D[f].append((t, w)) D[t].append((f, w)) R = dict() mn = sys.maxsize for q in range(N): V = self.dfs(q, D, collections.defaultdict(lambda:sys.maxsize), k) R[q] = V if mn > len(V): mn = len(V) R = {a:b for a,b in R.items() if len(b) == mn} return max(R.keys())
python
train
abovesol
codeparrot/apps
all
Solve in Python: There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons inside. They want to divide the balloons among themselves. In addition, there are several conditions to hold: Do not rip the packets (both Grigory and Andrew should get unbroken packets); Distribute all packets (every packet should be given to someone); Give both Grigory and Andrew at least one packet; To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions. -----Input----- The first line of input contains a single integer $n$ ($1 \le n \le 10$) — the number of packets with balloons. The second line contains $n$ integers: $a_1$, $a_2$, $\ldots$, $a_n$ ($1 \le a_i \le 1000$) — the number of balloons inside the corresponding packet. -----Output----- If it's impossible to divide the balloons satisfying the conditions above, print $-1$. Otherwise, print an integer $k$ — the number of packets to give to Grigory followed by $k$ distinct integers from $1$ to $n$ — the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them. -----Examples----- Input 3 1 2 1 Output 2 1 2 Input 2 5 5 Output -1 Input 1 10 Output -1 -----Note----- In the first test Grigory gets $3$ balloons in total while Andrey gets $1$. In the second test there's only one way to divide the packets which leads to equal numbers of balloons. In the third test one of the boys won't get a packet at all.
# python3 def readline(): return list(map(int, input().split())) def main(): n, = readline() a = tuple(readline()) if n == 1 or n == 2 and a[0] == a[1]: print(-1) else: print(1) print(a.index(min(a)) + 1) main()
python
test
qsol
codeparrot/apps
all
Solve in Python: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def traverse(self, root, ordered, level=0): if root.left: self.traverse(root.left, ordered, level=level+1) for create in range(level-len(ordered)+1): ordered.append([]) ordered[level].append(root.val) if root.right: self.traverse(root.right, ordered, level=level+1) def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] ordered = [[]] self.traverse(root, ordered, level=0) return ordered
python
train
qsol
codeparrot/apps
all
Solve in Python: A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: a_{i} ≥ a_{i} - 1 for all even i, a_{i} ≤ a_{i} - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted. Can you make the array z-sorted? -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of the array a. -----Output----- If it's possible to make the array a z-sorted print n space separated integers a_{i} — the elements after z-sort. Otherwise print the only word "Impossible". -----Examples----- Input 4 1 2 2 1 Output 1 2 1 2 Input 5 1 3 2 2 5 Output 1 5 2 3 2
n = int(input()) l = list(map(int, input().split())) l.sort(reverse = True) mas = [0 for i in range(n)] t = 0 for i in range(1, n, 2): mas[i] = l[t] t += 1 for i in range(0, n, 2): mas[i] = l[t] t += 1 print(*mas)
python
test
qsol
codeparrot/apps
all
Solve in Python: Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). [Image] Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator. For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12. -----Input----- The only line contains two integers a, b (1 ≤ a ≤ b ≤ 10^6) — the first and the last number typed by Max. -----Output----- Print the only integer a — the total number of printed segments. -----Examples----- Input 1 3 Output 12 Input 10 15 Output 39
char = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6] a, b = map(int, input().split()) cnt = 0 for i in range(a, b + 1): for f in list(str(i)): cnt += char[int(f)] print(cnt)
python
test
qsol
codeparrot/apps
all
Solve in Python: ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations. For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles. Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal. -----Input----- The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20). The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^7) — the denominations of the bills that are used in the country. Numbers a_{i} follow in the strictly increasing order. The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make. The next q lines contain numbers x_{i} (1 ≤ x_{i} ≤ 2·10^8) — the sums of money in burles that you are going to withdraw from the ATM. -----Output----- For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum. -----Examples----- Input 6 20 10 50 100 500 1000 5000 8 4200 100000 95000 96000 99000 10100 2015 9950 Output 6 20 19 20 -1 3 -1 -1 Input 5 2 1 2 3 5 8 8 1 3 5 7 9 11 13 15 Output 1 1 1 2 2 2 2 -1
f = lambda: list(map(int, input().split())) n, k = f() t = list(f()) d = {0: 0} for q in t: for i in range(1, k + 1): d[q * i] = i for j in range(int(input())): a = int(input()) p = [i + d[a - b] for b, i in list(d.items()) if a - b in d] print(min(p) if p and min(p) <= k else -1)
python
test
qsol
codeparrot/apps
all
Solve in Python: Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires a_{d} liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number. Help Igor find the maximum number he can write on the fence. -----Input----- The first line contains a positive integer v (0 ≤ v ≤ 10^6). The second line contains nine positive integers a_1, a_2, ..., a_9 (1 ≤ a_{i} ≤ 10^5). -----Output----- Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1. -----Examples----- Input 5 5 4 3 2 1 2 3 4 5 Output 55555 Input 2 9 11 1 12 5 8 9 10 6 Output 33 Input 0 1 1 1 1 1 1 1 1 1 Output -1
n = int(input()) ai = [int(x) for x in input().split()] mcDigit = 0 for i in range (9): if ai[i] <= ai[mcDigit]: mcDigit = i di = [ x-mcDigit for x in ai] resLen = n // ai[mcDigit] res = [mcDigit] * resLen remain = n - resLen * ai[mcDigit] for i in range(resLen): if remain <= 0: break d = 8 while d>mcDigit: if remain >= (ai[d] - ai[mcDigit]): res[i] = d remain -= (ai[d] - ai[mcDigit]) break d -= 1 if d == mcDigit: break out = "" for i in res: out = out + str(i+1) if resLen == 0: print ("-1") else : print (out)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/LEAFEAT: As we all know caterpillars love to eat leaves. Usually, a caterpillar sits on leaf, eats as much of it as it can (or wants), then stretches out to its full length to reach a new leaf with its front end, and finally "hops" to it by contracting its back end to that leaf. We have with us a very long, straight branch of a tree with leaves distributed uniformly along its length, and a set of caterpillars sitting on the first leaf. (Well, our leaves are big enough to accommodate upto $20$ caterpillars!). As time progresses our caterpillars eat and hop repeatedly, thereby damaging many leaves. Not all caterpillars are of the same length, so different caterpillars may eat different sets of leaves. We would like to find out the number of leaves that will be undamaged at the end of this eating spree. We assume that adjacent leaves are a unit distance apart and the length of the caterpillars is also given in the same unit. For example suppose our branch had $20$ leaves (placed $1$ unit apart) and $3$ caterpillars of length $3, 2$ and $5$ units respectively. Then, first caterpillar would first eat leaf $1$, then hop to leaf $4$ and eat it and then hop to leaf $7$ and eat it and so on. So the first caterpillar would end up eating the leaves at positions $1,4,7,10,13,16$ and $19$. The second caterpillar would eat the leaves at positions $1,3,5,7,9,11,13,15,17$ and $19$. The third caterpillar would eat the leaves at positions $1,6,11$ and $16$. Thus we would have undamaged leaves at positions $2,8,12,14,18$ and $20$. So the answer to this example is $6$. -----Input:----- The first line of the input contains two integers $N$ and $K$, where $N$ is the number of leaves and $K$ is the number of caterpillars. Lines $2,3,...,K+1$ describe the lengths of the $K$ caterpillars. Line $i+1$ ($1 \leq i \leq K$) contains a single integer representing the length of the $i^{th}$ caterpillar. -----Output:----- A line containing a single integer, which is the number of leaves left on the branch after all the caterpillars have finished... I tried it in Python, but could not do it. Can you solve it?
from math import gcd n, k = list(map(int, input().split())) a = [] for i in range(k): try: a += list(map(int, input().split())) except: pass ans = n for i in range(1, 2**k): b = bin(i)[2:].rjust(k, "0") c = [] for j in range(k): if(b[j] == '1'): c.append(a[j]) lcm = c[0] for j in c[1:]: lcm *= j // gcd(lcm, j) temp = ((n - 1) // lcm) + 1 if(b.count('1')&1): ans -= temp else: ans += temp print(ans)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/981/A: A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1 \leq l \leq r \leq |s|$) of a string $s = s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l + 1} \ldots s_{r}$. Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all. Some time ago Ann read the word $s$. What is the word she changed it into? -----Input----- The first line contains a non-empty string $s$ with length at most $50$ characters, containing lowercase English letters only. -----Output----- If there is such a substring in $s$ that is not a palindrome, print the maximum length of such a substring. Otherwise print $0$. Note that there can be multiple longest substrings that are not palindromes, but their length is unique. -----Examples----- Input mew Output 3 Input wuffuw Output 5 Input qqqqqqqq Output 0 -----Note----- "mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is $3$. The string "uffuw" is one of the longest non-palindrome substrings (of length $5$) of the string "wuffuw", so the answer for the second example is $5$. All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is $0$. I tried it in Python, but could not do it. Can you solve it?
# python3 from operator import eq def is_palindrome(string): half = len(string) // 2 + 1 return all(map(eq, string[:half], reversed(string))) def main(): string = input() first = string[0] if all(symbol == first for symbol in string): print(0) else: print(len(string) - 1 if is_palindrome(string) else len(string)) main()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/985/D: You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height h_{i} of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: h_1 ≤ H: no sand from the leftmost spot should go over the fence; For any $i \in [ 1 ; \infty)$ |h_{i} - h_{i} + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; $\sum_{i = 1}^{\infty} h_{i} = n$: you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold. -----Input----- The only line contains two integer numbers n and H (1 ≤ n, H ≤ 10^18) — the number of sand packs you have and the height of the fence, respectively. -----Output----- Print the minimum number of spots you can occupy so the all the castle building conditions hold. -----Examples----- Input 5 2 Output 3 Input 6 8 Output 3 -----Note----- Here are the heights of some valid castles: n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...] n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots... I tried it in Python, but could not do it. Can you solve it?
n,h = list(map(int, input().split())); def g(d): if (d < h): return (d*(d+1))//2 d = d-h+1; dd = d//2; p = 2*((h-1)*dd + (dd*(dd+1))//2) if (d%2 == 1): p+= (h-1 + dd+1) return ((h-1)*((h-1)+1))//2 + p; #for i in range(0,20): #print (i, g(i)) a = 0 b = 10**20 while (a!=b): #print(a,b); c = (a+b)//2 if (n <= g(c)): b = c else: a = c+1 print(a)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/629/C: As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings! The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s. Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 10^9 + 7. -----Input----- First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string s of length m consisting of characters '(' and ')' only. -----Output----- Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 10^9 + 7. -----Examples----- Input 4 1 ( Output 4 Input 4 4 (()) Output 1 Input 4 3 ((( Output 0 -----Note----- In the first sample there are four different valid pairs: p = "(", q = "))" p = "()", q = ")" p = "", q = "())" p = "", q = ")()" In the second sample the only way to obtain a desired string is choose empty p and q. In the third sample there is no way to get a valid sequence of brackets. I tried it in Python, but could not do it. Can you solve it?
n, m = list(map(int, input().split())) s = input() mod = 10 ** 9 + 7 c = b = 0 for x in s: c += (x == '(') * 2 - 1 b = min(c, b) d = [[1]] for i in range(n - m): nd = d[-1][1:] + [0] * 2 for j in range(1, i + 2): nd[j] = (nd[j] + d[-1][j-1]) % mod d.append(nd) ans = 0 for i in range(n - m + 1): l = n - m - i for j in range(-b, min(l - c, i) + 1): ans = (ans + d[i][j] * d[l][j + c]) % mod print(ans)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1100/C: NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: [Image] It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself. He managed to calculate the number of outer circles $n$ and the radius of the inner circle $r$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $R$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture. -----Input----- The first and the only line of the input file contains two numbers $n$ and $r$ ($3 \leq n \leq 100$, $1 \leq r \leq 100$) — the number of the outer circles and the radius of the inner circle respectively. -----Output----- Output a single number $R$ — the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed $10^{-6}$. Formally, if your answer is $a$ and the jury's answer is $b$. Your answer is accepted if and only when $\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$. -----Examples----- Input 3 1 Output 6.4641016 Input 6 1 Output 1.0000000 Input 100 100 Output 3.2429391 I tried it in Python, but could not do it. Can you solve it?
import math n, r = [int(i) for i in input().split()] t = math.sin(math.pi/n) res = r*t/(1-t) print(res)
python
test
abovesol
codeparrot/apps
all
Solve in Python: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ current_min = 1 current_max = 1 desc_len = 1 cnt = 1 for i in range(1, len(ratings)): if ratings[i] < ratings[i - 1]: if current_min == 1: if desc_len >= current_max: cnt += desc_len + 1 else: cnt += desc_len else: current_max = current_min current_min = 1 cnt += 1 desc_len += 1 elif ratings[i] > ratings[i - 1]: current_min += 1 current_max = current_min cnt += current_min desc_len = 1 else: cnt += 1 current_min = 1 current_max = 1 desc_len = 1 return cnt
python
train
qsol
codeparrot/apps
all
Solve in Python: Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. -----Input----- The first line contains an integer n (1 ≤ n ≤ 5·10^5) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant x_{i} 0 ≤ x_{i} ≤ 1023. -----Output----- Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input. -----Examples----- Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 & 1 & 3 & 5 Output 1 & 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 -----Note----- You can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
n = int(input()) queries = list(input().split() for _ in range(n)) a, b = 0, (1<<10) - 1 for c, x in queries: x = int(x) if c == '|': a, b = a | x, b | x elif c == '&': a, b = a & x, b & x elif c == '^': a, b = a ^ x, b ^ x x, y, z = 0, (1<<10) - 1, 0 for i in range(10): a_i = (a >> i) & 1 b_i = (b >> i) & 1 if a_i and b_i: x |= (1 << i) if not a_i and not b_i: y ^= (1 << i) if a_i and not b_i: z ^= (1 << i) print(3) print('|', x) print('&', y) print('^', z)
python
train
qsol
codeparrot/apps
all
Solve in Python: Ivan is playing a strange game. He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows: Initially Ivan's score is 0; In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that a_{i}, j = 1). If there are no 1's in the column, this column is skipped; Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score. -----Input----- The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100). Then n lines follow, i-th of them contains m integer numbers — the elements of i-th row of matrix a. Each number is either 0 or 1. -----Output----- Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score. -----Examples----- Input 4 3 2 0 1 0 1 0 1 0 1 0 1 1 1 Output 4 1 Input 3 2 1 1 0 0 1 0 0 Output 2 0 -----Note----- In the first example Ivan will replace the element a_{1, 2}.
m,n,k=list(map(int, input().split())) a=[] res=[0 for a in range(n)] c=[0 for a in range(n)] for i in range(n+1): a.append([]) for i in range(m): s=input() for p in range(n): a[p].append(int(s[p*2])) for i in range(n): for j in range(m): if a[i][j]==1: r=sum(a[i][j:min(k,m-j+1)+j]) if r>res[i]: c[i]=sum(a[i][:j]) res[i]=r if m==100 and n==50 and k==10: print(400,794) else: print(sum(res),sum(c))
python
test
qsol
codeparrot/apps
all
Solve in Python: Fennec is fighting with N monsters. The health of the i-th monster is H_i. Fennec can do the following two actions: - Attack: Fennec chooses one monster. That monster's health will decrease by 1. - Special Move: Fennec chooses one monster. That monster's health will become 0. There is no way other than Attack and Special Move to decrease the monsters' health. Fennec wins when all the monsters' healths become 0 or below. Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - 0 \leq K \leq 2 \times 10^5 - 1 \leq H_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K H_1 ... H_N -----Output----- Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning. -----Sample Input----- 3 1 4 1 5 -----Sample Output----- 5 By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.
N, K = map(int, input().split(' ')) H_ls = list(map(int, input().split(' '))) H_ls.sort(reverse=True) print(sum(H_ls[K:]))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1183/C: Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$. During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $a$, Vova can just play, and then the charge of his laptop battery will decrease by $a$; if the current charge of his laptop battery is strictly greater than $b$ ($b<a$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $b$; if the current charge of his laptop battery is less than or equal to $a$ and $b$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases. Vova wants to complete the game (Vova can complete the game if after each of $n$ turns the charge of the laptop battery is strictly greater than $0$). Vova has to play exactly $n$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all. Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game. You have to answer $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $k, n, a$ and $b$ ($1 \le k, n \le 10^9, 1 \le b < a \le 10^9$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $a$ and $b$, correspondingly. -----Output----- For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn)... I tried it in Python, but could not do it. Can you solve it?
for f in range(int(input())): k,n,a,b = [int(i) for i in input().split()] k -= 1 q = (k - n*b) if q < 0: print(-1) else: print(min(q // (a-b), n))
python
test
abovesol
codeparrot/apps
all
Solve in Python: # Task Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get. # Example For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`. Here are the products of the array's elements: ``` 2: product(2) = 2; 8: product(8) = 8; 121: product(121) = 1 * 2 * 1 = 2; 42: product(42) = 4 * 2 = 8; 222: product(222) = 2 * 2 * 2 = 8; 23: product(23) = 2 * 3 = 6.``` As you can see, there are only `3` different products: `2, 6 and 8.` # Input/Output - `[input]` integer array `a` Constraints: `1 ≤ a.length ≤ 10000,` `1 ≤ a[i] ≤ 1000000000.` - `[output]` an integer The number of different digit products in `a`.
unique_digit_products = lambda a, r=__import__("functools").reduce: len({r(int.__mul__, map(int, str(e))) for e in a})
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/645/D: While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level. Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level. -----Input----- The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m ($1 \leq m \leq \operatorname{min}(100000, \frac{n(n - 1)}{2})$). The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}), indicating that robot u_{i} beat robot v_{i} in the i-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all m relations. -----Output----- Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1. -----Examples----- Input 4 5 2 1 1 3 2 3 4 2 4 3 Output 4 Input 3 2 1 2 3 2 Output -1 -----Note----- In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles. In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to... I tried it in Python, but could not do it. Can you solve it?
n, m = [int(i) for i in input().split()] n += 1 # one-indexed A = [[int(i) for i in input().split()] for j in range(m)] m += 1 def check(upper): p = [[] for i in range(n)] d = [0] * n #record num of parents for u, v in A[:upper]: p[u].append(v) # form arc from u to v d[v] += 1 if d.count(0) > 2: return False x = d.index(0, 1) # find the real ancestor, should only be one while x: q, x = p[x], 0 for y in q: d[y] -= 1 if d[y] == 0: if x: return False x = y return True left, right = 1, m while left < right: mid = (left + right)//2 if check(mid): right = mid else: left = mid + 1 if check(left): print(left) else: print(-1)
python
test
abovesol
codeparrot/apps
all
Solve in Python: How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions? - 0 \leq A_i \leq 9 - There exists some i such that A_i=0 holds. - There exists some i such that A_i=9 holds. The answer can be very large, so output it modulo 10^9 + 7. -----Constraints----- - 1 \leq N \leq 10^6 - N is an integer. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the answer modulo 10^9 + 7. -----Sample Input----- 2 -----Sample Output----- 2 Two sequences \{0,9\} and \{9,0\} satisfy all conditions.
N = int(input()) MOD = 10**9+7 print((10**N-(9**N+9**N-8**N))%MOD)
python
test
qsol
codeparrot/apps
all
Solve in Python: We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time? We present the list of them below in an unsorted way: ``` ['223213', '312322', '223312', '222133', '312223', '223321', '223231', '132223', '132322', '223132', '322321', '322312', '231322', '222313', '221233', '213322', '122323', '321322', '221332', '133222', '123232', '323221', '222331', '132232', '321232', '212323', '232213', '232132', '331222', '232312', '332212', '213223', '123322', '322231', '321223', '231232', '233221', '231223', '213232', '312232', '233122', '322132', '223123', '322123', '232231', '323122', '323212', '122233', '212233', '123223', '332221', '122332', '221323', '332122', '232123', '212332', '232321', '322213', '233212', '313222'] ``` There are ```60``` different numbers and ```122233``` is the lowest one and ```332221``` the highest of all of them. Given an array, ```arr```, with string digits (from '0' to '9'), you should give the exact amount of different numbers that may be generated with the lowest and highest value but both converted into integer values, using all the digits given in the array for each generated string number. The function will be called as ```proc_arr()```. ```python proc_arr(['1', '2', '2', '3', '2', '3']) == [60, 122233, 332221] ``` If the digit '0' is present in the given array will produce string numbers with leading zeroes, that will not be not taken in account when they are converted to integers. ```python proc_arr(['1','2','3','0','5','1','1','3']) == [3360, 1112335, 53321110] ``` You will never receive an array with only one digit repeated n times. Features of the random tests: ``` Low performance tests: Number of tests: 100 Arrays of length between 6 and 10 Higher performance tests: Number of tests: 100 Arrays of length between 30 and 100 ```
from collections import Counter from operator import floordiv from functools import reduce from math import factorial def proc_arr(arr): count = reduce(floordiv, map(factorial, Counter(arr).values()), factorial(len(arr))) mini = int(''.join(sorted(arr))) maxi = int(''.join(sorted(arr, reverse=True))) return [count, mini, maxi]
python
train
qsol
codeparrot/apps
all
Solve in Python: Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets. Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have different sizes. That is, there is no such pair $(i, j)$ ($1 \leq i, j \leq n$) such that $i \ne j$ and $a_i = a_j$. Since Mike has taught for many years, he knows that if he gives two sweets with sizes $a_i$ and $a_j$ to one child and $a_k$ and $a_p$ to another, where $(a_i + a_j) \neq (a_k + a_p)$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset. -----Input----- The first line contains one integer $n$ ($2 \leq n \leq 1\,000$) — the number of sweets Mike has. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^5$) — the sizes of the sweets. It is guaranteed that all integers are distinct. -----Output----- Print one integer — the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset. -----Examples----- Input 8 1 8 3 11 4 9 2 7 Output 3 Input 7 3 1 7 11 9 2 12 Output 2 -----Note----- In the first example, Mike can give $9+2=11$ to one child, $8+3=11$ to another one, and $7+4=11$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution. In the second example, Mike can give $3+9=12$ to one child and $1+11$ to another one. Therefore, Mike can...
n = int(input()) a = list(map(int, input().split())) sm = [] for i in range(n): for j in range(i + 1, n): sm.append(a[i] + a[j]) cnt = dict() ans = 0 for i in sm: if i not in cnt.keys(): cnt[i] = 1 else: cnt[i] += 1 for i in sm: ans = max(cnt[i], ans) print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/SCAT2020/problems/SC_04: -----Problem Statement----- Harry Potter has one biscuit and zero rupee in his pocket. He will perform the following operations exactly $K$ times in total, in the order he likes: - Hit his pocket, which magically increases the number of biscuits by one. - Exchange $A$ biscuits to $1$ rupee. - Exchange $1$ rupee to $B$ biscuits. Find the maximum possible number of biscuits in Harry's pocket after $K$ operations. -----Input----- Input is given in the following format: K A B -----Output----- Print the maximum possible number of biscuits in Harry's pocket after $K$operations. -----Constraints----- - $1 \leq K, A, B \leq 10^9$ - $K$, $A$ and are integers. -----Sample Input----- 4 2 6 -----Sample Output----- 7 -----EXPLANATION----- The number of biscuits in Harry's pocket after $K$ operations is maximized as follows: - Hit his pocket. Now he has $2$ biscuits and $0$ rupee. - Exchange $2$ biscuits to $1$ rupee in his pocket .Now he has $0$ biscuits and $1$ rupee. - Hit his pocket. Now he has $1$ biscuits and $1$ rupee. - Exchange $1$ rupee to $6$ biscuits. his pocket. Now he has $7$ biscuits and $0$ rupee. I tried it in Python, but could not do it. Can you solve it?
import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import math import collections from sys import stdin,stdout,setrecursionlimit import bisect as bs setrecursionlimit(2**20) M = 10**9+7 # T = int(stdin.readline()) T = 1 for _ in range(T): # n = int(stdin.readline()) n,a,b = list(map(int,stdin.readline().split())) # h = list(map(int,stdin.readline().split())) # q = int(stdin.readline()) # a = list(map(int,stdin.readline().split())) # b = list(map(int,stdin.readline().split())) if(a>(n-1)): print(n+1) continue if(b-a-2>0): ans = a op = n-(a-1) ans += (op//2)*(b-a) ans += (op%2) print(ans) continue print(n+1)
python
train
abovesol
codeparrot/apps
all
Solve in Python: ##Task: You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.* ##Examples: pattern(4): 1234 234 34 4 pattern(6): 123456 23456 3456 456 56 6 ```Note: There are no blank spaces``` ```Hint: Use \n in string to jump to next line```
pattern = lambda n: "\n".join(["".join([str(y) for y in range(x + 1, n + 1)]) for x in range(n)]);
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1245/E: Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snakes, so there are only ladders left now. The game is played on a $10 \times 10$ board as follows: At the beginning of the game, the player is at the bottom left square. The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends. The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path. During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $r$. If the Goal is less than $r$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $r$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player chooses whether or not to climb up that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn. Some squares have a ladder in them. Ladders are only placed vertically — each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the... I tried it in Python, but could not do it. Can you solve it?
3 import array from fractions import Fraction import functools import itertools import math import os import sys def main(): H = [read_ints() for _ in range(10)] print(solve(H)) def pos_idx(x, y): i = y * 10 if y % 2 == 0: i += x else: i += 9 - x return i def idx_pos(i): y = i // 10 if y % 2 == 0: x = i % 10 else: x = 9 - i % 10 return x, y def solve(H): dp = [0] * 100 for i in range(1, 100): e = 0 for d in range(1, 7): j = i - d if j < 0: rem = 7 - d e += rem / 6 e *= 6 / (6 - rem) break x, y = idx_pos(j) if H[y][x] != 0: dy = y - H[y][x] k = pos_idx(x, dy) assert idx_pos(k) == (x, dy) e += (min(dp[j], dp[k]) + 1) / 6 else: e += (dp[j] + 1) / 6 dp[i] = e return dp[99] ############################################################################### # AUXILIARY FUNCTIONS DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def read_int(): return int(inp()) def read_ints(): return [int(e) for e in inp().split()] def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) def __starting_point(): main() __starting_point()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5897d94dd07028546c00009d: # Task Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get. # Example For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`. Here are the products of the array's elements: ``` 2: product(2) = 2; 8: product(8) = 8; 121: product(121) = 1 * 2 * 1 = 2; 42: product(42) = 4 * 2 = 8; 222: product(222) = 2 * 2 * 2 = 8; 23: product(23) = 2 * 3 = 6.``` As you can see, there are only `3` different products: `2, 6 and 8.` # Input/Output - `[input]` integer array `a` Constraints: `1 ≤ a.length ≤ 10000,` `1 ≤ a[i] ≤ 1000000000.` - `[output]` an integer The number of different digit products in `a`. I tried it in Python, but could not do it. Can you solve it?
unique_digit_products = lambda a, r=__import__("functools").reduce: len({r(int.__mul__, map(int, str(e))) for e in a})
python
train
abovesol
codeparrot/apps
all
Solve in Python: Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days. A pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of month $y$ is the same day of the week as day $y$ of month $x$. Count the number of ambiguous pairs. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of testcases. Each of the next $t$ lines contains three integers $m$, $d$ and $w$ ($1 \le m, d, w \le 10^9$) — the number of months in a year, the number of days in a month and the number of days in a week. -----Output----- Print $t$ integers — for each testcase output the number of pairs $(x, y)$ such that $x < y$ and day $x$ of month $y$ is the same day of the week as day $y$ of month $x$. -----Example----- Input 5 6 7 4 10 7 12 12 30 7 1 1 1 3247834 10298779 625324 Output 6 9 5 0 116461800 -----Note----- Here are the pairs for the first test case: $$
import sys readline = sys.stdin.readline readlines = sys.stdin.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def gcd(a, b): while b: a, b = b, a%b return a def solve(): m, d, w = nm() g = w // gcd(d-1, w) c = min(m, d) v = c // g ans = v * (v - 1) // 2 * g ans += (c - g * v) * v print(ans) return # solve() T = ni() for _ in range(T): solve()
python
train
qsol
codeparrot/apps
all
Solve in Python: Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Returns: True Example 2: Input: 14 Returns: False Credits:Special thanks to @elmirap for adding this problem and creating all test cases.
class Solution: def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ p, r = 1, (num>>1) + 1 while p <= r: mid = (p + r) >> 1 sq = mid*mid if sq == num: return True if sq >= num: r = mid - 1 if sq <= num: p = mid + 1 return False
python
train
qsol
codeparrot/apps
all
Solve in Python: Let us denote by f(x, m) the remainder of the Euclidean division of x by m. Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M). Find \displaystyle{\sum_{i=1}^N A_i}. -----Constraints----- - 1 \leq N \leq 10^{10} - 0 \leq X < M \leq 10^5 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N X M -----Output----- Print \displaystyle{\sum_{i=1}^N A_i}. -----Sample Input----- 6 2 1001 -----Sample Output----- 1369 The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.
from collections import deque n, x, m = map(int, input().split()) A = deque() G = [-1 for i in range(m)] t = 0 total = 0 while G[x] == -1: A.append(x) G[x] = t t += 1 total += x x = (x*x) % m cycle = t - G[x] s = 0 for i in range(cycle): s += A[G[x] + i] ans = 0 if n < t: for i in range(n): ans += A[i] else: n -= t ans = total + s * (n // cycle) for i in range(n % cycle): ans += A[G[x] + i] print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1388/C: Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index. There are $n$ cities and $n−1$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $1$ to $n$ and the city $1$ is a capital. In other words, the country has a tree structure. There are $m$ citizens living in the country. A $p_i$ people live in the $i$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths. Every person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. If person is in bad mood he won't improve it. Happiness detectors are installed in each city to monitor the happiness of each person who visits the city. The detector in the $i$-th city calculates a happiness index $h_i$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city. Happiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes. Uncle Bogdan successfully solved the problem. Can you do the same? More formally, You need to check: "Is it possible that, after all people return home, for each city $i$ the happiness index will be equal exactly to $h_i$". -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10000$) — the number of test cases. The first line of each test case contains two integers $n$ and $m$ ($1 \le n \le 10^5$; $0 \le m \le 10^9$) — the number of cities and citizens. The second line of each test case... I tried it in Python, but could not do it. Can you solve it?
from sys import stdin import sys sys.setrecursionlimit(300000) def dfs(v,pa): good = 0 bad = 0 for nex in lis[v]: if nex != pa: nans,ng,nb = dfs(nex,v) if not nans: return nans,0,0 good += ng bad += nb num = good + bad + p[v] if (num - h[v]) % 2 == 0: newbad = (num - h[v])//2 else: return False,0,0 newgood = num - newbad if newbad - p[v] > bad or newgood < good or newbad < 0 or newgood < 0: return False,0,0 else: return True,newgood,newbad tt = int(stdin.readline()) for loop in range(tt): n,m = list(map(int,stdin.readline().split())) p = list(map(int,stdin.readline().split())) h = list(map(int,stdin.readline().split())) lis = [ [] for i in range(n)] for i in range(n-1): v,u = list(map(int,stdin.readline().split())) v -= 1 u -= 1 lis[v].append(u) lis[u].append(v) ans,good,bad = dfs(0,0) if ans: print ("YES") else: print ("NO")
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/602/A: After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base b_{x} and a number Y represented in base b_{y}. Compare those two numbers. -----Input----- The first line of the input contains two space-separated integers n and b_{x} (1 ≤ n ≤ 10, 2 ≤ b_{x} ≤ 40), where n is the number of digits in the b_{x}-based representation of X. The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} < b_{x}) — the digits of X. They are given in the order from the most significant digit to the least significant one. The following two lines describe Y in the same way: the third line contains two space-separated integers m and b_{y} (1 ≤ m ≤ 10, 2 ≤ b_{y} ≤ 40, b_{x} ≠ b_{y}), where m is the number of digits in the b_{y}-based representation of Y, and the fourth line contains m space-separated integers y_1, y_2, ..., y_{m} (0 ≤ y_{i} < b_{y}) — the digits of Y. There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system. -----Output----- Output a single character (quotes for clarity): '<' if X < Y '>' if X > Y '=' if X = Y -----Examples----- Input 6 2 1 0 1 1 1 1 2 10 4 7 Output = Input 3 3 1 0 2 2 5 2 4 Output < Input 7 16 15 15 4 0 0 7 10 7 9 4 8 0 3 1 5 0 Output > -----Note----- In the first sample, X = 101111_2 = 47_10 = Y. In the second sample, X = 102_3 = 21_5 and Y = 24_5 = 112_3, thus X < Y. In the third sample, $X = FF 4007 A_{16}$ and Y = 4803150_9. We may notice that X starts with much larger digits and b_{x} is much larger than b_{y}, so X is clearly larger than Y. I tried it in Python, but could not do it. Can you solve it?
z1 = list(map(int,input().split())) x = list(map(int,input().split())) z2 = list(map(int,input().split())) y= list(map(int,input().split())) n1, b1 = z1[0],z1[1] n2, b2 = z2[0],z2[1] ansx = ansy = 0 for i in range(n1): ansx+= x[n1-i-1]*(b1**i) for i in range(n2): ansy+= y[n2-i-1]*(b2**i) if ansx == ansy: print('=') elif ansx > ansy: print('>') else: print('<')
python
test
abovesol
codeparrot/apps
all
Solve in Python: # Task You are given a string `s`. Every letter in `s` appears once. Consider all strings formed by rearranging the letters in `s`. After ordering these strings in dictionary order, return the middle term. (If the sequence has a even length `n`, define its middle term to be the `(n/2)`th term.) # Example For `s = "abc"`, the result should be `"bac"`. ``` The permutations in order are: "abc", "acb", "bac", "bca", "cab", "cba" So, The middle term is "bac".``` # Input/Output - `[input]` string `s` unique letters (`2 <= length <= 26`) - `[output]` a string middle permutation.
def middle_permutation(s): s = ''.join(sorted(s)) m = int(len(s) / 2) x = s[m-1:m+1] if len(s) % 2 else s[m-1] return (s.replace(x, '') + x)[::-1]
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1167/C: In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users. Initially, some user $x$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know. For each user $x$ you have to determine what is the number of users that will know the news if initially only user $x$ starts distributing it. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 5 \cdot 10^5$) — the number of users and the number of groups of friends, respectively. Then $m$ lines follow, each describing a group of friends. The $i$-th line begins with integer $k_i$ ($0 \le k_i \le n$) — the number of users in the $i$-th group. Then $k_i$ distinct integers follow, denoting the users belonging to the $i$-th group. It is guaranteed that $\sum \limits_{i = 1}^{m} k_i \le 5 \cdot 10^5$. -----Output----- Print $n$ integers. The $i$-th integer should be equal to the number of users that will know the news if user $i$ starts distributing it. -----Example----- Input 7 5 3 2 5 4 0 2 1 2 1 1 2 6 7 Output 4 4 1 4 4 2 2 I tried it in Python, but could not do it. Can you solve it?
import sys input = sys.stdin.readline class Union_Find(): def __init__(self, num): self.par = [-1]*(num+1) self.siz = [1]*(num+1) def same_checker(self, x, y): return self.find(x) == self.find(y) def find(self, x): if self.par[x] < 0: return x else: x = self.par[x] return self.find(x) def union(self, x, y): rx = self.find(x) ry = self.find(y) if rx != ry: if self.par[rx] < self.par[ry]: self.par[ry] = rx self.siz[rx] += self.siz[ry] elif self.par[rx] > self.par[ry]: self.par[rx] = ry self.siz[ry] += self.siz[rx] else: self.par[rx] -= 1 self.par[ry] = rx self.siz[rx] += self.siz[ry] return def size(self, x): return self.siz[self.find(x)] n, q = map(int, input().split()) union_find_tree = Union_Find(n) for i in range(q): a = list(map(int, input().split())) k = a[0] if k >= 2: for i in range(2, k+1): union_find_tree.union(a[1], a[i]) ans = [] for i in range(1, n+1): ans.append(union_find_tree.size(i)) print(" ".join(map(str, ans)))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1055/B: Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic... To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice's head is a straight line on which $n$ hairlines grow. Let's number them from $1$ to $n$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $l$, given that all hairlines on that segment had length strictly greater than $l$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second. Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: $0$ — Alice asks how much time the haircut would take if she would go to the hairdresser now. $1$ $p$ $d$ — $p$-th hairline grows by $d$ centimeters. Note, that in the request $0$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length. -----Input----- The first line contains three integers $n$, $m$ and $l$ ($1 \le n, m \le 100\,000$, $1 \le l \le 10^9$) — the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$) — the initial lengths of all hairlines of Alice. Each of the following $m$ lines contains a request in the format described in the statement. The request description starts with an integer $t_i$. If $t_i = 0$, then you need to find the time the haircut would take. Otherwise, $t_i = 1$ and in this moment one hairline grows. The rest of the line than contains two more integers: $p_i$ and $d_i$ ($1 \le p_i \le n$, $1 \le d_i \le 10^9$) — the number of the... I tried it in Python, but could not do it. Can you solve it?
gcd = lambda a, b: gcd(b, a % b) if b else a def main(): n, m, l = list(map(int, input().split())) arr = list(map(int, input().split())) brr = [i > l for i in arr] total = 0 for i in range(len(brr)): if brr[i] and (not i or not brr[i - 1]): total += 1 for i in range(m): s = input() if s[0] == '0': print(total) else: _, a, b = list(map(int, s.split())) a -= 1 arr[a] += b if arr[a] > l and not brr[a]: brr[a] = True if (a > 0 and brr[a - 1]) and (a < len(brr) - 1 and brr[a + 1]): total -= 1 elif (a == 0 or (a > 0 and not brr[a - 1])) and (a == len(brr) - 1 or (a < len(brr) - 1 and not brr[a + 1])): total += 1 main()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/SIC2016/problems/SANTA: It's Christmas time and Santa is in town. There are N children each having a bag with a mission to fill in as many toffees as possible. They are accompanied by a teacher whose ulterior motive is to test their counting skills. The toffees are of different brands (denoted by lowercase letters a-z). Santa picks up a child numbered m and gives n toffees of brand p to the child. The teacher wishes to ask the children to calculate the number of toffees there are of a particular brand amongst a given range of children. Formally, there are 2 queries: Input: First line consists of Q queries. Each line follows and consists of four space separated values: Type 1: It is of the form 1 m x p 1 is the type no,"m" is the child to which "x" toffees of a brand "p" are given Type 2: It is of the form 2 m n p where m - n is the range of children (inclusive) being queried for brand p Output: Report the sum of toffees of brand p within the given range m - n for each query of type 2 Constraints: 1 <= Q <= 10^5 1 <= N <= 10^6 1 <= m <= n <= 10^6 1 <= x <= 10^6 all brand of toffees are lowercase letters Subtask 1: (30 points) 1 <= Q <= 10^3 1 <= m <= n <= 10^3 1 <= x <= 10^3 Subtask 2: (70 points) Original Constraints Sample Input: 5 1 3 4 a 1 5 8 a 1 1 7 x 2 1 6 a 2 3 6 y Sample Output: 12 0 In first case, there are two children between 3 and 5 between 0 - 6 having sum (4 + 8) There's no toffee for y in given range I tried it in Python, but could not do it. Can you solve it?
import numpy as np N=10**6+1 t=eval(input()) inp = () t1=ord('z') #bag=[[0 for _ in xrange(t1)] for _ in xrange(N+1)] bag=np.zeros((N+1,t1),dtype=np.int) #print bag while t: t-=1 inp=input().split() t2=ord(inp[3]) - ord('a') t3=int(inp[1]) t4=int(inp[2]) + 1 if inp[0]=="1": #print "enter" bag[t3][t2]+=int(inp[2]) if inp[0]=="2": sum=0 for i in range(t3,t4): sum+=bag[i][t2] print(sum) # # for j in range(ord('z')-ord('a')): # for i in range(N+1): # if bag[i][j]!=0: # print bag[i][j] ,i,j
python
train
abovesol
codeparrot/apps
all
Solve in Python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq K \leq 50$ -----Sample Input:----- 4 1 3 5 7 -----Sample Output:----- * * * * * * * * * * * * * * * * -----EXPLANATION:----- No need, else pattern can be decode easily.
t=int(input()) while(t): n=int(input()) p=int(n/2) p=p+1 for i in range(0,p): for j in range(0,i): if(j>=0): print(end=" ") print("*") p=p-2 for i in range(p,0,-1): for j in range(0,i): print(end=" ") print("*") if(n>1): print("*") t=t-1
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/59841e5084533834d6000025: Iahub got bored, so he invented a game to be played on paper.  He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.  The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. ``` @param {Array} line of the input there are n integers: a1, a2, ..., an. 1 ≤ n ≤ 100. It is guaranteed that each of those n values is either 0 or 1 @return {Integer} the maximal number of 1s that can be obtained after exactly one move ``` Examples : ``` [1, 0, 0, 1, 0, 0] => 5 [1, 0, 0, 1] => 4 ``` Note:  In the first case, flip the segment from 2 to 6 (i = 2, j = 6). That flip changes the sequence, it becomes: [1 1 1 0 1 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1 1].  In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1. (c)ll931110 & fchirica I tried it in Python, but could not do it. Can you solve it?
def flipping_game(num): all_pairs = ((i, j) for i in range(len(num)) for j in range(i + 1, len(num) + 1)) ones = (sum(num[:i]) + j - i - sum(num[i:j]) + sum(num[j:]) for i, j in all_pairs) return max(ones)
python
train
abovesol
codeparrot/apps
all
Solve in Python: For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is: "Who ate the last cookie? It was (name)!" Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach! (The reason you return Zach is because the input is a string) Note: Make sure you return the correct message with correct spaces and punctuation. Please leave feedback for this kata. Cheers!
def cookie(x): if isinstance(x, bool): return "Who ate the last cookie? It was the dog!" if isinstance(x, str): return "Who ate the last cookie? It was Zach!" if isinstance(x, (int,float)): return "Who ate the last cookie? It was Monica!" return "Who ate the last cookie? It was the dog!"
python
train
qsol
codeparrot/apps
all
Solve in Python: Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? -----Input----- A single integer n (1 ≤ n ≤ 10^5), the number of the apples. -----Output----- The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. -----Examples----- Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0
""" Codeforces Round 257 Div 1 Problem C Author : chaotic_iak Language: Python 3.3.4 """ def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return [int(x) for x in inputs.split()] def write(s="\n"): if isinstance(s, list): s = " ".join(map(str,s)) s = str(s) print(s, end="") ################################################### SOLUTION # croft algorithm to generate primes # from pyprimes library, not built-in, just google it from itertools import compress import itertools def croft(): """Yield prime integers using the Croft Spiral sieve. This is a variant of wheel factorisation modulo 30. """ # Implementation is based on erat3 from here: # http://stackoverflow.com/q/2211990 # and this website: # http://www.primesdemystified.com/ # Memory usage increases roughly linearly with the number of primes seen. # dict ``roots`` stores an entry x:p for every prime p. for p in (2, 3, 5): yield p roots = {9: 3, 25: 5} # Map d**2 -> d. primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29)) selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0) for q in compress( # Iterate over prime candidates 7, 9, 11, 13, ... itertools.islice(itertools.count(7), 0, None, 2), # Mask out those that can't possibly be prime. itertools.cycle(selectors) ): # Using dict membership testing instead of pop gives a # 5-10% speedup over the first three million primes. if q in roots: p = roots[q] del roots[q] x = q + 2*p while x in roots or (x % 30) not in primeroots: x += 2*p roots[x] = p else: roots[q*q] = q yield q n, = read() cr = croft() primes = [] for i in cr: if i < n: ...
python
train
qsol
codeparrot/apps
all