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: The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this: There are space-separated non-empty words of lowercase and uppercase Latin letters. There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding. The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it. You should write a program that will find minimal width of the ad. -----Input----- The first line contains number k (1 ≤ k ≤ 10^5). The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 10^6 characters. -----Output----- Output minimal width of the ad. -----Examples----- Input 4 garage for sa-le Output 7 Input 4 Edu-ca-tion-al Ro-unds are so fun Output 10 -----Note----- Here all spaces are replaced with dots. In the first example one of possible results after all word wraps looks like this: garage. for. sa- le The second example: Edu-ca- tion-al. Ro-unds. are.so.fun
n = int(input()) s = input() s += ' ' def ok(w): wordcnt = 0 lettercnt = 0 linecnt = 0 for j in range(len(s)): if not (s[j]==' ' or s[j]=='-'): lettercnt += 1; else: lettercnt += 1 if j==len(s)-1: lettercnt -= 1 if (wordcnt+lettercnt)>w: linecnt += 1 wordcnt = lettercnt else: wordcnt += lettercnt lettercnt = 0 if wordcnt>w: return False if wordcnt: linecnt += 1 if linecnt>n: return False else: return True l = 1 r = 1000000 while l<r: mid = l + (r-l)//2 if ok(mid): r = mid else: l = mid + 1 print(l)
python
test
qsol
codeparrot/apps
all
Solve in Python: There is a grid of squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Each square is black or white. The color of the square is given as an H-by-W matrix (a_{i, j}). If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black. Snuke is compressing this grid. He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares: - Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns. It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation. Find the final state of the grid. -----Constraints----- - 1 \leq H, W \leq 100 - a_{i, j} is . or #. - There is at least one black square in the whole grid. -----Input----- Input is given from Standard Input in the following format: H W a_{1, 1}...a_{1, W} : a_{H, 1}...a_{H, W} -----Output----- Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity. -----Sample Input----- 4 4 ##.# .... ##.# .#.# -----Sample Output----- ### ### .## The second row and the third column in the original grid will be removed.
import sys input = sys.stdin.readline H, W = map(int, input().split()) grid = [] for _ in range(H): grid.append(list(input().strip())) h_set = set() for i in range(H): flag = True for j in range(W): if grid[i][j] == "#": flag = False break if flag: h_set.add(i) w_set = set() for j in range(W): flag = True for i in range(H): if grid[i][j] == "#": flag = False break if flag: w_set.add(j) for i in range(H): if i in h_set: continue for j in range(W): if j in w_set: continue print(grid[i][j], end="") print("")
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5840946ea3d4c78e90000068: It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team. You will be given two arrays with two values. The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team caught the golden snitch! The team who catches the snitch wins their team an extra 150 points - but doesn't always win them the game. If the score is a tie return "It's a draw!"" ** The game only ends when someone catches the golden snitch, so one array will always include 'yes' or 'no.' Points scored by Chasers can be any positive integer. I tried it in Python, but could not do it. Can you solve it?
def game_winners(gryffindor, slytherin): g = gryffindor[0] + 150 * (gryffindor[1] == "yes") s = slytherin[0] + 150 * (slytherin[1] == "yes") return "Gryffindor wins!" if g > s else "Slytherin wins!" if s > g else "It's a draw!"
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/554a44516729e4d80b000012: Let us begin with an example: A man has a rather old car being worth $2000. He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one. He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore this percent of loss increases of `0.5` percent at the end of every two months. Our man finds it difficult to make all these calculations. **Can you help him?** How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over? **Parameters and return of function:** ``` parameter (positive int or float, guaranteed) startPriceOld (Old car price) parameter (positive int or float, guaranteed) startPriceNew (New car price) parameter (positive int or float, guaranteed) savingperMonth parameter (positive float or int, guaranteed) percentLossByMonth nbMonths(2000, 8000, 1000, 1.5) should return [6, 766] or (6, 766) ``` ### Detail of the above example: ``` end month 1: percentLoss 1.5 available -4910.0 end month 2: percentLoss 2.0 available -3791.7999... end month 3: percentLoss 2.0 available -2675.964 end month 4: percentLoss 2.5 available -1534.06489... end month 5: percentLoss 2.5 available -395.71327... end month 6: percentLoss 3.0 available 766.158120825... return [6, 766] or (6, 766) ``` where `6` is the number of months at **the end of which** he can buy the new car and `766` is the nearest integer to `766.158...` (rounding `766.158` gives `766`). **Note:** Selling, buying and saving are normally done at end of month. Calculations are processed at the end of each considered month but if, by chance from the start, the value of the old car is bigger than the value of the new one or equal there is no saving to be made, no need to wait so he can at the beginning of the month buy the new car: ``` nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000] nbMonths(8000, 8000, 1000, 1.5) should return [0, 0] ``` We don't take care... I tried it in Python, but could not do it. Can you solve it?
def nbMonths(oldCarPrice, newCarPrice, saving, loss): months = 0 budget = oldCarPrice while budget < newCarPrice: months += 1 if months % 2 == 0: loss += 0.5 oldCarPrice *= (100 - loss) / 100 newCarPrice *= (100 - loss) / 100 budget = saving * months + oldCarPrice return [months, round(budget - newCarPrice)]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/MAY16/problems/CHBLLS: Chef has bought ten balls of five colours. There are two balls of each colour. Balls of same colour have same weight. Let us enumerate colours by numbers from 1 to 5. Chef knows that all balls, except two (of same colour), weigh exactly one kilogram. He also knows that each of these two balls is exactly 1 kg heavier than other balls. You need to find the colour which balls are heavier than others. To do that, you can use mechanical scales with two weighing pans. As your scales are very accurate, you can know the exact difference of weights of objects from first and second pans. Formally, the scales will give you the difference (signed difference) of weights of the objects put into the first pan and the second pan. See the following examples for details. - If you put two balls of the same colour on your scales, each ball to one pan, the scales will tell you that difference is "0". - But if you put into the first pan some balls of total weight 3 kg, and into the second pan of 5 kg, then scales will tell you "-2" because the second pan is 2 kg heavier than first. - Similarly, if you put 5 kg weight in first pan and 3 kg in the second pan, then scale will tell you "2" as first pan is 2 kg heavier than second. -----Input & Output----- - The interaction process have two phases. At first phase you perform sequence of weighings on the mechanical scales. At the second phase you should output the colour of the heavier balls. - To use the mechanical scales, you should print "1"(without quotes) and then print two lines, the first line will describe the enumeration of colours of balls on the first pan and second line should that of second pan. - To describe some pan, you need to print one integer n - the number of balls you put in this pan, followed by n space-separated integers - colours of the balls you put in this pan. - Once you have printed required data, you can read from the standard input one integer - the difference of weights of the first and the second pans. - To output the colour of the heavier balls,... I tried it in Python, but could not do it. Can you solve it?
print("1") print("3 1 2 2") print("3 3 4 4") import sys d = {1:1, 2:2, -1:3, -2:4, 0:5 } sys.stdout.flush() v = eval(input()) print("2") print(d[v])
python
test
abovesol
codeparrot/apps
all
Solve in Python: # Our Setup Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days! # This Game Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out. # Their Words Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories. The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least. # The Rules * a valid response word must contain four different letters * `1` letter is replaced while the other `3` stay in position * it must be the lowest indexed valid word in their memory * this word cannot have already been used during the game * the final player to provide a valid word will win the game * if 1st player fails 1st turn, 2nd can win with a valid word * when both players fail the initial word, there is no winner # Your Task To determine the winner! # Some Examples `alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore` `bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap` 1) In the case of `word = "send"` and `first = 0`: * Alice responds to `send` with `rend` * Bob responds to `rend` with `lend` * Alice has no valid response to `lend` * Bob wins the game. 2) In the case of `word = "flip"` and `first = 1`: * Bob has no valid response to `flip` * Alice responds to `flip` with `flap` * Alice wins the game. 3) In the case of `word = "maze"` and `first = 0`: * Alice responds to `maze` with `mare` * Bob ...
import re def genMask(w): x = list(w) for i in range(len(w)): x[i] = '.' yield ''.join(x) x[i] = w[i] def mutations(alice, bob, word, first): players, seen = [alice,bob], {word} win, failed, i = -1, -1, first^1 while 1: i ^= 1 lst = players[i] reg = re.compile('|'.join(genMask(word))) found = next((w for w in lst if reg.match(w) and w not in seen and len(set(w))==4), None) if found is None: if failed==i^1: break failed = i else: seen.add(found) word, win = found, i if failed!=-1: break return win
python
train
qsol
codeparrot/apps
all
Solve in Python: Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja. -----Input----- The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence. Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in...
n=int(input()) a=[] for i in range(n): a.append(list(map(int,input().split()))) m=int(input()) b=list([int(x)-1 for x in input().split()]) c=[] now=0 k=0 ans=[] for i in range(n): t=a[i] if t[0]==1: now+=1 if len(c)<100000: c.append(t[1]) if k<m and b[k]==now-1: ans.append(t[1]) k+=1 else: last=now now+=t[1]*t[2] while t[2]: if len(c)<100000: c.extend(c[:t[1]]) else: break t[2]-=1 while k<m and last<=b[k]<now: ans.append(c[(b[k]-last)%t[1]]) k+=1 print(' '.join(map(str,ans)))
python
train
qsol
codeparrot/apps
all
Solve in Python: We have a string S of length N consisting of uppercase English letters. How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)? -----Constraints----- - 3 \leq N \leq 50 - S consists of uppercase English letters. -----Input----- Input is given from Standard Input in the following format: N S -----Output----- Print number of occurrences of ABC in S as contiguous subsequences. -----Sample Input----- 10 ZABCDBABCQ -----Sample Output----- 2 Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.
n = int(input()) s = list(input()) cnt = 0 for i in range(n-2): if s[i]+s[i+1]+s[i+2] == "ABC": cnt += 1 print(cnt)
python
test
qsol
codeparrot/apps
all
Solve in Python: Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. [Image] So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer. -----Input----- The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display. -----Output----- Print the maximum integer which can be shown on the display of Stepan's newest device. -----Examples----- Input 2 Output 1 Input 3 Output 7
n = 0 one = 0 seven = 0 i = 0 j = 0 n = int(input()) if n % 2 == 0: for i in range(1, n // 2 + 1): print('1', end="") else: print('7', end="") n = n - 3 while n > 1: print('1', end="") n = n - 2
python
test
qsol
codeparrot/apps
all
Solve in Python: There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not. Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind. How many honest persons can be among those N people at most? -----Constraints----- - All values in input are integers. - 1 \leq N \leq 15 - 0 \leq A_i \leq N - 1 - 1 \leq x_{ij} \leq N - x_{ij} \neq i - x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2) - y_{ij} = 0, 1 -----Input----- Input is given from Standard Input in the following format: N A_1 x_{11} y_{11} x_{12} y_{12} : x_{1A_1} y_{1A_1} A_2 x_{21} y_{21} x_{22} y_{22} : x_{2A_2} y_{2A_2} : A_N x_{N1} y_{N1} x_{N2} y_{N2} : x_{NA_N} y_{NA_N} -----Output----- Print the maximum possible number of honest persons among the N people. -----Sample Input----- 3 1 2 1 1 1 1 1 2 0 -----Sample Output----- 2 If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.
n=int(input()) a=[] l=[] for i in range(n): A=int(input()) L=[list(map(int,input().split())) for _ in range(A)] a.append(A) l.append(L) ans=0 for i in range(2**n): b=[0]*n for j in range(n): if (i>>j)&1: b[j]=1 for k in range(n): for h in range(a[k]): hito=l[k][h][0]-1 singi=l[k][h][1] if b[k]==1 and b[hito]!=singi: break else: continue break else: ans=max(ans,sum(b)) print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/411/B: The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor. At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked. The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked. -----Input----- The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: x_{i}1, x_{i}2, ..., x_{im} (0 ≤ x_{ij} ≤ k), where x_{ij} is the instruction that must be executed by the i-th core at the j-th cycle. If x_{ij} equals 0, then the corresponding instruction is «do nothing». But if x_{ij} is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number x_{ij}». We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from... I tried it in Python, but could not do it. Can you solve it?
n, m, k = map(int, input().split()) a = [[0 for i in range(m)] for j in range(n)] inf = [0 for i in range(k + 1)] stat = [True for i in range(n + 1)] time = [0 for i in range(n + 1)] for i in range(n): a[i] = list(map(int, input().split())) for i in range(m): for j in range(1, n + 1): if stat[j]: current_core = inf[a[j - 1][i]] if current_core == 0 and a[j - 1][i] != 0: inf[a[j - 1][i]] = j elif current_core == -1: stat[j], time[j] = False, i + 1 elif a[j - 1][i] != 0: stat[current_core], time[current_core] = False, i + 1 stat[j], time[j] = False, i + 1 inf[a[j - 1][i]] = -1 for p in range(len(inf)): if inf[p] != -1: inf[p] = 0 for i in range(1, n + 1): print(time[i])
python
test
abovesol
codeparrot/apps
all
Solve in Python: Takahashi is meeting up with Aoki. They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now. Takahashi will leave his house now and go straight to the place at a speed of S meters per minute. Will he arrive in time? -----Constraints----- - 1 \leq D \leq 10000 - 1 \leq T \leq 10000 - 1 \leq S \leq 10000 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: D T S -----Output----- If Takahashi will reach the place in time, print Yes; otherwise, print No. -----Sample Input----- 1000 15 80 -----Sample Output----- Yes It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.
d,t,s = input().strip().split() d,t,s = [int(d), int(t), int(s)] sum = d / s if t >= sum : print('Yes') else: print('No')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_c: Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ). Consider a sequence A satisfying the following conditions: - A is a sequence of N positive integers. - 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M. Let us define a score of this sequence as follows: - The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.) Find the maximum possible score of A. -----Constraints----- - All values in input are integers. - 2 ≤ N ≤ 10 - 1 \leq M \leq 10 - 1 \leq Q \leq 50 - 1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q ) - 0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q ) - (a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j) - 1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q ) -----Input----- Input is given from Standard Input in the following format: N M Q a_1 b_1 c_1 d_1 : a_Q b_Q c_Q d_Q -----Output----- Print the maximum possible score of A. -----Sample Input----- 3 4 3 1 3 3 100 1 2 2 10 2 3 2 10 -----Sample Output----- 110 When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110. I tried it in Python, but could not do it. Can you solve it?
from itertools import combinations_with_replacement N, M, Q = map(int, input().split()) T = [] for q in range(Q): T.append(list(map(int, input().split()))) A = list(combinations_with_replacement(list(range(1, M+1)), N)) Alist = [list(a) for a in A] #print(Alist) Max = 0 for a in Alist: cost = 0 for t in T: if a[t[1]-1] - a[t[0]-1] == t[2]: cost += t[3] if cost > Max: Max = cost print(Max)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1375/G: You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$. For every vertex $d$ other than $b$ that is adjacent to $a$, remove the edge connecting $d$ and $a$ and add the edge connecting $d$ and $c$. Delete the edge connecting $a$ and $b$ and add the edge connecting $a$ and $c$. As an example, consider the following tree: [Image] The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $2$, $4$, and $5$: [Image] It can be proven that after each operation, the resulting graph is still a tree. Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $n - 1$, called its center, and $n - 1$ vertices of degree $1$. -----Input----- The first line contains an integer $n$ ($3 \le n \le 2 \cdot 10^5$)  — the number of vertices in the tree. The $i$-th of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$, $u_i \neq v_i$) denoting that there exists an edge connecting vertices $u_i$ and $v_i$. It is guaranteed that the given edges form a tree. -----Output----- Print a single integer  — the minimum number of operations needed to transform the tree into a star. It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most $10^{18}$ operations. -----Examples----- Input 6 4 5 2 6 3 2 1 2 2 4 Output 1 Input 4 2 4 4 1 3 4 Output 0 -----Note----- The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex $5$ by applying a single operation to vertices $2$, $4$, and $5$. In the second test case, the given tree is already a star with the center at vertex $4$, so no operations have to be performed. I tried it in Python, but could not do it. Can you solve it?
from collections import defaultdict n = int(input()) graph = defaultdict(list) for i in range(n - 1): l = list(map(int, input().split())) graph[l[0]].append(l[1]) graph[l[1]].append(l[0]) color_v = [-1]*(n + 1) color_v[1] = 0 q = [1] while q: x = q.pop() for i in graph[x]: if color_v[i] == -1: color_v[i] = 1 - color_v[x] q.append(i) print(min(color_v.count(1), color_v.count(0)) - 1)
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem. You are also given two integers $0 \le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$. -----Input----- The first line of the input contains three integers $n, x, y$ ($0 \le y < x < n \le 2 \cdot 10^5$) — the length of the number and the integers $x$ and $y$, respectively. The second line of the input contains one decimal number consisting of $n$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1. -----Output----- Print one integer — the minimum number of operations you should perform to obtain the number having remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$. -----Examples----- Input 11 5 2 11010100101 Output 1 Input 11 5 1 11010100101 Output 3 -----Note----- In the first example the number will be $11010100100$ after performing one operation. It has remainder $100$ modulo $100000$. In the second example the number will be $11010100010$ after performing three operations. It has remainder $10$ modulo $100000$.
n,x,y=[int(x) for x in input().split()] a=[int(x) for x in list(input())] counter=0 for i in range(n-x,n): if i==n-y-1: if a[i]==0: counter+=1 else: if a[i]==1: counter+=1 print(counter)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/254/B: In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by p_{i} people for t_{i} days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it. For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd. In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time. -----Input----- The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers m_{i}, d_{i}, p_{i} and t_{i} — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ m_{i} ≤ 12, d_{i} ≥ 1, 1 ≤ p_{i}, t_{i} ≤ 100), d_{i} doesn't exceed the number of days in month m_{i}. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all... I tried it in Python, but could not do it. Can you solve it?
import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nsmallest from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction sys.setrecursionlimit(pow(10, 6)) sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return list(map(int, data().split())) def ssp(): return list(map(str, data().split())) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def jury_size(a): date = start[a] dp[' '.join(map(str, end[a]))] += jury[a] while date != end[a]: dp[' '.join(map(str, date))] += jury[a] if date[0] in tone and date[1] == 31: date[0] += 1 date[1] = 1 elif date[0] == 2 and date[1] == 28: date[0] += 1 date[1] = 1 elif date[0] not in tone and date[1] == 30: date[0] += 1 date[1] = 1 else: date[1] += 1 start, end, jury = [], [], [] dp = dd(int) tone = [1, 3, 5, 7, 8, 10, 12, 0, -2] n = int(data()) for i in range(n): m, d, p, t = sp() if d > 1: end.append([m, d - 1]) else: temp = d if (m - 1) in tone: temp = 31 elif m == 3: temp = 28 else: temp = 30 end.append([m-1, temp]) temp = d while t >= temp: m -= 1 if m in tone: temp += 31 elif m == 2: temp += 28 else: temp += 30 ed = temp - t start.append([m,...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58de819eb76cf778fe00005c: A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For this kata, single digit numbers will not be considered numerical palindromes. For a given number ```num```, write a function to test if the number contains a numerical palindrome or not and return a boolean (true if it does and false if does not). Return "Not valid" if the input is not an integer or is less than 0. Note: Palindromes should be found without permutating ```num```. ``` palindrome(5) => false palindrome(1221) => true palindrome(141221001) => true palindrome(1215) => true palindrome(1294) => false palindrome("109982") => "Not valid" ``` I tried it in Python, but could not do it. Can you solve it?
import re def palindrome(num): if not (isinstance(num, int) and num > 0): return 'Not valid' return bool(re.search(r'(.)\1|(.).\2', str(num)))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/59f04228e63f8ceb92000038: The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```). The next one is ```3375```. In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]``` Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive) Examples: ``` python odd_dig_cubic(-5000, 5000) == [-3375,-1331, -1, 1, 1331, 3375] # the output should be sorted. odd_dig_cubic(0, 5000) == [1, 1331, 3375] odd_dig_cubic(-1, 5000) == [-1, 1, 1331, 3375] odd_dig_cubic(-5000, -2) == [-3375,-1331] ``` Features of the random tests for python: ``` number of Tests = 94 minimum value for a = -1e17 maximum value for b = 1e17 ``` You do not have to check the entries, ```a``` and ```b``` always integers and ```a < b``` Working well in Python 2 and Python 3. Translation into Ruby is coming soon. I tried it in Python, but could not do it. Can you solve it?
def get_podpc(): r=[] x=1 while (x*x*x<=1e17): y=x*x*x if all(int(d)%2==1 for d in str(y)): r.append(y) x+=2 return sorted([-1*x for x in r]+r) arr=get_podpc() def odd_dig_cubic(a, b): return [x for x in arr if a<=x<=b]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/547/B: Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly a_{i} feet high. [Image] A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group. Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x. -----Input----- The first line of input contains integer n (1 ≤ n ≤ 2 × 10^5), the number of bears. The second line contains n integers separated by space, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), heights of bears. -----Output----- Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x. -----Examples----- Input 10 1 2 3 4 5 4 3 2 1 6 Output 6 4 4 3 3 2 2 1 1 1 I tried it in Python, but could not do it. Can you solve it?
n = int(input()) a = [0] + list(map(int,input().split())) + [0] r = [0] * (n + 1) st = [(0, 0)] for i in range(1, n + 2): while a[i] < st[-1][0]: r[i - st[-2][1] - 1] = max(st[-1][0], r[i - st[-2][1] - 1]) st.pop() st.append((a[i], i)) for i in range(n): r[-i - 2] = max(r[-i - 2], r[-i - 1]) print(*r[1:])
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1006/A: Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: Replace each occurrence of $1$ in the array $a$ with $2$; Replace each occurrence of $2$ in the array $a$ with $1$; Replace each occurrence of $3$ in the array $a$ with $4$; Replace each occurrence of $4$ in the array $a$ with $3$; Replace each occurrence of $5$ in the array $a$ with $6$; Replace each occurrence of $6$ in the array $a$ with $5$; $\dots$ Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$; Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above. For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm: $[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array. Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it. -----Input----- The... I tried it in Python, but could not do it. Can you solve it?
n = int(input()) lst = [int(x) for x in input().split()] for i in range(len(lst)): if lst[i]%2==0: lst[i]-=1 lst = [str(x) for x in lst] print(' '.join(lst))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_c: You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries: - Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring? -----Notes----- A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T. For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq Q \leq 10^5 - S is a string of length N. - Each character in S is A, C, G or T. - 1 \leq l_i < r_i \leq N -----Input----- Input is given from Standard Input in the following format: N Q S l_1 r_1 : l_Q r_Q -----Output----- Print Q lines. The i-th line should contain the answer to the i-th query. -----Sample Input----- 8 3 ACACTACG 3 7 2 3 1 8 -----Sample Output----- 2 0 3 - Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring. - Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring. - Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring. I tried it in Python, but could not do it. Can you solve it?
N,Q=list(map(int,input().split())) S=input() cnt=[0,0] for i in range(1,N): cnt.append(cnt[-1]+S[i-1:i+1].count("AC")) for _ in range(Q): l,r=list(map(int,input().split())) print((cnt[r]-cnt[l]))
python
test
abovesol
codeparrot/apps
all
Solve in Python: Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k. -----Input----- The only line of input contains integers n and k (1 ≤ k ≤ n ≤ 10^12). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- Print the number that will stand at the position number k after Volodya's manipulations. -----Examples----- Input 10 3 Output 5 Input 7 7 Output 6 -----Note----- In the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 5.
a,b=list(map(int,input().split())) c=b-(a+1)//2 print(2*c if c>0 else 2*b-1)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1437/E: You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$. In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$. Calculate the minimum number of operations you should perform so the array $a$ is increasing (that is, $a_1 < a_2 < a_3 < \dots < a_n$), or report that it is impossible. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n \le 5 \cdot 10^5$, $0 \le k \le n$) — the size of the array $a$ and the set $b$, respectively. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$). Then, if $k \ne 0$, the third line follows, containing $k$ integers $b_1$, $b_2$, ..., $b_k$ ($1 \le b_1 < b_2 < \dots < b_k \le n$). If $k = 0$, this line is skipped. -----Output----- If it is impossible to make the array $a$ increasing using the given operations, print $-1$. Otherwise, print one integer — the minimum number of operations you have to perform. -----Examples----- Input 7 2 1 2 1 1 3 5 1 3 5 Output 4 Input 3 3 1 3 2 1 2 3 Output -1 Input 5 0 4 3 1 2 3 Output 2 Input 10 3 1 3 5 6 12 9 8 10 13 15 2 4 9 Output 3 I tried it in Python, but could not do it. Can you solve it?
import sys input=sys.stdin.readline n,k = map(int,input().split()) a = list(map(int,input().split())) b = [] if k: b = list(map(int,input().split())) for i in range(n): a[i] -= i prev = -1 ans = 0 for j in range(k + 1): if j < k: val = b[j] - 1 if j and a[prev] > a[val]: print(-1) quit() else: val = n if val - prev > 1: path = [0] * (val - prev - 1) arr = [0] * (val - prev) found = 0 for i in range(val - prev - 1): if val < n and a[i + prev + 1] > a[val]: continue elif prev + 1 and a[prev] > a[i + prev + 1]: continue l = 1 h = found while h >= l: m = (l + h + 1) // 2 if a[arr[m] + prev + 1] <= a[i + prev + 1]: l = m + 1 else: h = m - 1 path[i] = arr[l - 1] arr[l] = i if l > found: found = l ans += found prev = val print(n - k - ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L. She will concatenate all of the strings in some order, to produce a long string. Among all strings that she can produce in this way, find the lexicographically smallest one. Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds: - There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i. - s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m. -----Constraints----- - 1 ≦ N, L ≦ 100 - For each i, the length of S_i equals L. - For each i, S_i consists of lowercase letters. -----Input----- The input is given from Standard Input in the following format: N L S_1 S_2 : S_N -----Output----- Print the lexicographically smallest string that Iroha can produce. -----Sample Input----- 3 3 dxx axx cxx -----Sample Output----- axxcxxdxx The following order should be used: axx, cxx, dxx.
N,L = map(int,input().split()) S = [] for i in range(N): S.append(str(input())) S.sort() print(''.join(S))
python
train
qsol
codeparrot/apps
all
Solve in Python: The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression. To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum. Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression. -----Input----- The single line contains integer n (2 ≤ n ≤ 10^3) — the number of students. The second line contains n space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 10^4. -----Output----- In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative. If there are multiple possible answers, you can print any of them. -----Examples----- Input 5 -3 -4 -2 -3 3 Output 2 -3 1 Input 5 2 -3 -1 -4 3 Output 1 -4 2 -----Note----- Lets look at the first sample. We can proceed in the following manner: don't feed the 1-st student, his height will stay equal to -3; give two buns of the first type to the 2-nd student, his height become equal to -2; give two buns of the first type...
q = 10001 n, a = int(input()), list(map(int, input().split())) a.sort() for i in range(40000 // (n - 1) + 1): b = [a[j] - j * i for j in range(n)] u, v = max(b), min(b) p = (u - v + 1) // 2 if p < q: q, s, d = p, v + p, i print(q) print(s, d)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/443/B: Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. -----Input----- The first line contains s (1 ≤ |s| ≤ 200). This string contains only small English letters. The second line contains number k (1 ≤ k ≤ 200) — the number of the added characters. -----Output----- Print a single number — the maximum length of the tandem repeat that could have occurred in the new string. -----Examples----- Input aaba 2 Output 6 Input aaabbbb 2 Output 6 Input abracadabra 10 Output 20 -----Note----- A tandem repeat of length 2n is string s, where for any position i (1 ≤ i ≤ n) the following condition fulfills: s_{i} = s_{i} + n. In the first sample Kolya could obtain a string aabaab, in the second — aaabbbbbb, in the third — abracadabrabracadabra. I tried it in Python, but could not do it. Can you solve it?
s = input().rstrip() k = int(input()) if k > len(s): print((len(s) + k) - ((len(s) + k) % 2 == 1)) else: aux = [] for j in range(1, len(s)): i = len(s) - 1 cnt = 0 while i - j >= 0 and s[i] == s[i - j]: i -= 1 cnt += 1 if cnt == j: break diff = i - (len(s) - j - 1) if diff <= k: aux.append(2 * j) aux.append(2 * k) for i in range(len(s)): for j in range((len(s) - i) // 2): if s[i:i + j] == s[i + j:i + 2 * j]: aux.append(2 * j) print(max(aux))
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given an array $a_1, a_2, \dots , a_n$ consisting of integers from $0$ to $9$. A subarray $a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$ is good if the sum of elements of this subarray is equal to the length of this subarray ($\sum\limits_{i=l}^{r} a_i = r - l + 1$). For example, if $a = [1, 2, 0]$, then there are $3$ good subarrays: $a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$ and $a_{1 \dots 3} = [1, 2, 0]$. Calculate the number of good subarrays of the array $a$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$) — the length of the array $a$. The second line of each test case contains a string consisting of $n$ decimal digits, where the $i$-th digit is equal to the value of $a_i$. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case print one integer — the number of good subarrays of the array $a$. -----Example----- Input 3 3 120 5 11011 6 600005 Output 3 6 1 -----Note----- The first test case is considered in the statement. In the second test case, there are $6$ good subarrays: $a_{1 \dots 1}$, $a_{2 \dots 2}$, $a_{1 \dots 2}$, $a_{4 \dots 4}$, $a_{5 \dots 5}$ and $a_{4 \dots 5}$. In the third test case there is only one good subarray: $a_{2 \dots 6}$.
T, = list(map(int, input().split())) for t in range(T): N, = list(map(int, input().split())) X = [0]*(N+1) for i, c in enumerate(input().strip()): X[i+1] = X[i]+int(c) d = dict() for i in range( N+1): x = X[i] - i if x not in d: d[x] = 0 d[x] += 1 R = 0 for k in d: R += d[k]*(d[k]-1)//2 print(R)
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it. Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex). -----Input----- The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively. Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v). -----Output----- If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO. -----Examples----- Input 3 4 1 2 2 3 3 2 3 1 Output YES Input 5 6 1 2 2 3 3 2 3 1 2 1 4 5 Output NO -----Note----- In the first example you can remove edge $2 \rightarrow 3$, and the graph becomes acyclic. In the second example you have to remove at least two edges (for example, $2 \rightarrow 1$ and $2 \rightarrow 3$) in order to make the graph acyclic.
n, m = [int(x) for x in input().split()] a = [[] for i in range(n)] for i in range(m): u, v = [int(x) for x in input().split()] a[u - 1].append(v - 1) color = [0] * n # 0 - white, 1 - grey, 2 - black cycle = [] blocked_u, blocked_v = -1, -1 def dfs(u): nonlocal color nonlocal cycle if color[u]: return color[u] = 1 for v in a[u]: if u == blocked_u and v == blocked_v: continue if color[v] == 0: dfs(v) if color[v] == 1 or cycle: if not(cycle): cycle.append(v) cycle.append(u) return True color[u] = 2 return False def find_cycle(): nonlocal color nonlocal cycle color = [0] * n # 0 - white, 1 - grey, 2 - black cycle = [] for u in range(n): if dfs(u): break result = cycle[::-1] return {(result[i], result[(i + 1) % len(result)]) for i in range(len(result))} cur = find_cycle() if not(cur): print('YES') return for bu, bv in cur: blocked_u = bu blocked_v = bv new = find_cycle() if not(new): print('YES') return print('NO')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/COOK17/problems/CIELAB: In Ciel's restaurant, a waiter is training. Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change. Ciel gives him a simple problem. What is A-B (A minus B) ? Surprisingly, his answer is wrong. To be more precise, his answer has exactly one wrong digit. Can you imagine this? Can you make the same mistake in this problem? -----Input----- An input contains 2 integers A and B. -----Output----- Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not allowed. If there are multiple answers satisfying the above conditions, anyone will do. -----Constraints----- 1 ≤ B < A ≤ 10000 -----Sample Input----- 5858 1234 -----Sample Output----- 1624 -----Output details----- The correct answer of 5858-1234 is 4624. So, for instance, 2624, 4324, 4623, 4604 and 4629 will be accepted, but 0624, 624, 5858, 4624 and 04624 will be rejected. -----Notes----- The problem setter is also not good at arithmetic. I tried it in Python, but could not do it. Can you solve it?
a, b = [int(x) for x in input().split()] r = list(str(a-b)) if r[0] == "1": r[0] = "2" else: r[0]="1" print("".join(r))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/53689951c8a5ca91ac000566: Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters. Each element of the given array can be: * a single string, * a single string array, * an array of two strings In the last case (array of two strings) the first string should have a `"--"` prefix if it is more than one character long; or a `"-"` prefix otherwise; e.g.: * `["foo", "bar"]` becomes `"--foo bar"` * `["f", "bar"]` becomes `"-f bar"` You may assume that all strings are non-empty and have no spaces. ## Examples ```python ["foo", "bar"] # "foo bar" [["foo", "bar"]] # "--foo bar" [["f", "bar"]] # "-f bar" [["foo", "bar"], "baz"] # "--foo bar baz" [["foo"], ["bar", "baz"], "qux"] # "foo --bar baz qux" ``` I tried it in Python, but could not do it. Can you solve it?
def args_to_string(args): return ' '.join('-'*(len(a)>1 and 1+(len(a[0])>1))+' '.join(a) if type(a)==list else a for a in args)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/978/D: Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not. It follows from the definition that any sequence of length one or two is an arithmetic progression. Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged. Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible. It is possible that the resulting sequence contains element equals $0$. -----Input----- The first line contains a single integer $n$ $(1 \le n \le 100\,000)$ — the number of elements in $b$. The second line contains a sequence $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 10^{9})$. -----Output----- If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position). -----Examples----- Input 4 24 21 14 10 Output 3 Input 2 500 500 Output 0 Input 3 14 5 1 Output -1 Input 5 1 3 6 9 12 Output 1 -----Note----- In the first example Polycarp should increase the first number on $1$, decrease the second number on $1$, increase the third number on $1$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $[25, 20, 15, 10]$,... I tried it in Python, but could not do it. Can you solve it?
def solve(n, a): if n <= 2: return 0 d = [v - u for u, v in zip(a, a[1:])] max_d = max(d) min_d = min(d) if max_d - min_d > 4: return -1 min_cnt = -1 for d in range(min_d, max_d + 1): for d0 in range(-1, 2): y = a[0] + d0 valid = True cnt = 0 if d0 == 0 else 1 for x in a[1:]: dx = abs(y + d - x) if dx > 1: valid = False break cnt += dx y += d if valid: # print(d) if cnt < min_cnt or min_cnt < 0: min_cnt = cnt return min_cnt def main(): n = int(input()) a = [int(_) for _ in input().split()] ans = solve(n, a) print(ans) def __starting_point(): main() __starting_point()
python
test
abovesol
codeparrot/apps
all
Solve in Python: One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers. If there are exactly $K$ distinct values in the array, then we need $k = \lceil \log_{2} K \rceil$ bits to store each value. It then takes $nk$ bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $l \le r$, and after that all intensity values are changed in the following way: if the intensity value is within the range $[l;r]$, we don't change it. If it is less than $l$, we change it to $l$; if it is greater than $r$, we change it to $r$. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size $I$ bytes, and the number of changed elements in the array is minimal possible. We remind you that $1$ byte contains $8$ bits. $k = \lceil log_{2} K \rceil$ is the smallest integer such that $K \le 2^{k}$. In particular, if $K = 1$, then $k = 0$. -----Input----- The first line contains two integers $n$ and $I$ ($1 \le n \le 4 \cdot 10^{5}$, $1 \le I \le 10^{8}$) — the length of the array and the size of the disk in bytes, respectively. The next line contains $n$ integers $a_{i}$ ($0 \le a_{i} \le 10^{9}$) — the array denoting the sound file. -----Output----- Print a single integer — the minimal possible number of changed elements. -----Examples----- Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 -----Note----- In the first example we can choose $l=2, r=3$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $K=2$, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are...
n,i=list(map(int,input().split())) k=2**(8*i//n) if 8*i//n < 20 else n a=[int(x) for x in input().split()] a.sort() freq = [1] for i in range(1, len(a)): if a[i-1] == a[i]: freq[-1] += 1 else: freq.append(1) window = sum(freq[:k]) ans = window for i in range(k, len(freq)): window += freq[i] window -= freq[i-k] ans = max(ans, window) print(n-ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most k swaps. -----Input----- The single line contains two integers a and k (1 ≤ a ≤ 10^18; 0 ≤ k ≤ 100). -----Output----- Print the maximum number that Pasha can get if he makes at most k swaps. -----Examples----- Input 1990 1 Output 9190 Input 300 0 Output 300 Input 1034 2 Output 3104 Input 9090000078001234 6 Output 9907000008001234
def yoba(a, k): if not a: return [] elif not k: return a else: m = max(a[:k + 1]) mi = a.index(m) if m > a[0]: a[1:mi + 1] = a[:mi] a[0] = m k -= mi return [a[0]] + yoba(a[1:], k) a, k = str.split(input()) k = int(k) print(str.join("", yoba(list(a), k)))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/486/E: The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson. Nam created a sequence a consisting of n (1 ≤ n ≤ 10^5) elements a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). A subsequence a_{i}_1, a_{i}_2, ..., a_{i}_{k} where 1 ≤ i_1 < i_2 < ... < i_{k} ≤ n is called increasing if a_{i}_1 < a_{i}_2 < a_{i}_3 < ... < a_{i}_{k}. An increasing subsequence is called longest if it has maximum length among all increasing subsequences. Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 ≤ i ≤ n), into three groups: group of all i such that a_{i} belongs to no longest increasing subsequences. group of all i such that a_{i} belongs to at least one but not every longest increasing subsequence. group of all i such that a_{i} belongs to every longest increasing subsequence. Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job. -----Input----- The first line contains the single integer n (1 ≤ n ≤ 10^5) denoting the number of elements of sequence a. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). -----Output----- Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to. -----Examples----- Input 1 4 Output 3 Input 4 1 3 2 5 Output 3223 Input 4 1 5 2 3 Output 3133 -----Note----- In the second sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a_1, a_2, a_4} = {1, 3, 5} and {a_1, a_3, a_4} = {1, 2, 5}. In the third sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3,... I tried it in Python, but could not do it. Can you solve it?
N = int( input() ) A = list( map( int, input().split() ) ) maxa = max( A ) def upd( ftree, x, v ): while x <= maxa: ftree[ x ] = max( ftree[ x ], v ) x += x & -x def qry( ftree, x ): res = 0 while x: res = max( res, ftree[ x ] ) x -= x & -x return res st_len = [ 0 for i in range( N ) ] ftree = [ 0 for i in range( maxa + 1 ) ] for i in range( N - 1, -1, -1 ): st_len[ i ] = qry( ftree, maxa + 1 - A[ i ] - 1 ) + 1 upd( ftree, maxa + 1 - A[ i ], st_len[ i ] ) ed_len = [ 0 for i in range( N ) ] ftree = [ 0 for i in range( maxa + 1 ) ] for i in range( N ): ed_len[ i ] = qry( ftree, A[ i ] - 1 ) + 1 upd( ftree, A[ i ], ed_len[ i ] ) max_len = max( st_len ) st_cnt_len = [ 0 for i in range( N + 1 ) ] for i in range( N ): if ed_len[ i ] + st_len[ i ] - 1 == max_len: st_cnt_len[ st_len[ i ] ] += 1 for i in range( N ): if ed_len[ i ] + st_len[ i ] - 1 != max_len: print( 1, end = "" ) elif st_cnt_len[ st_len[ i ] ] > 1: print( 2, end = "" ) else: print( 3, end = "" ) print()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/EAREA: You are given a convex polygon $P$ with vertices $P_0, P_1, \ldots, P_{n-1}$, each having integer coordinates. On each edge $P_{i} P_{(i+1) \% n}$ of the polygon, choose a point $R_i$ uniformly at random. What is the expected area of the convex hull of these $n$ chosen points $R_0, R_1, \ldots R_{n-1}$ ? -----Note----- - Consider the area of the convex hull as zero if it contains less than 3 vertices. - All the points $R_i$ are chosen independently of each other. - Your answer is considered correct if and only if its absolute or relative error doesn't exceed $10^{-6}$. -----Input----- - The first line contains $n$, the number of vertices in the convex polygon. - The next $n$ lines contain the coordinates of the vertices of the polygon in anti-clockwise order. -----Output----- For each testcase, print the expected area of the convex hull of the $n$ randomly chosen points. -----Constraints----- - $3 \leq n \leq 10^5$ - The absolute values of all the coordinates $\leq 10^7$. - All the points in the input are distinct. - The described polygon $P$ is convex and the vertices of the polygon are given in anti-clockwise order. Also, no three vertices of the polygon are collinear. -----Example Input----- 3 0 0 1 0 0 1 -----Example Output----- 0.1250000000 I tried it in Python, but could not do it. Can you solve it?
# cook your dish here def func(a,n): if n < 3: return 0 res_arr = [] for i in range(n): x = (a[i][0] + a[(i + 1) % n][0]) / 2 y = (a[i][1] + a[(i + 1) % n][1]) / 2 res_arr.append((x, y)) l = len(res_arr) s = 0 for i in range(n): u = res_arr[i][0]*res_arr[(i+1) % l][1] v = res_arr[i][1]*res_arr[(i+1) % l][0] s += (u-v) return abs(s)/2 def __starting_point(): n = int(input()) arr = [] for i in range(n): x, y = map(int, input().split()) arr.append((x,y)) res = func(arr, n) print(res) __starting_point()
python
train
abovesol
codeparrot/apps
all
Solve in Python: Create a function that differentiates a polynomial for a given value of `x`. Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer. ## Assumptions: * There will be a coefficient near each `x`, unless the coefficient equals `1` or `-1`. * There will be an exponent near each `x`, unless the exponent equals `0` or `1`. * All exponents will be greater or equal to zero ## Examples: ```python differenatiate("12x+2", 3) ==> returns 12 differenatiate("x^2+3x+2", 3) ==> returns 9 ```
def parse_monom(monom): if 'x' not in monom: monom = monom + 'x^0' if monom.startswith('x'): monom = '1' + monom if monom.startswith('-x'): monom = '-1' + monom[1:] if monom.endswith('x'): monom = monom + '^1' coefficient, degree = map(int, monom.replace('x', '').split('^')) return degree, coefficient def differentiate(equation, point): monoms = equation.replace('-', '+-').lstrip('+').split('+') polynom = dict(map(parse_monom, monoms)) return sum(coefficient * degree * point ** (degree - 1) for degree, coefficient in polynom.items() if degree)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/520/B: Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n. Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result? -----Input----- The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 10^4), separated by a space . -----Output----- Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n. -----Examples----- Input 4 6 Output 2 Input 10 1 Output 9 -----Note----- In the first example you need to push the blue button once, and then push the red button once. In the second example, doubling the number is unnecessary, so we need to push the blue button nine times. I tried it in Python, but could not do it. Can you solve it?
def main() -> object: """ :rtype : Integer :return: The answer which the problem is required. """ n, m = [int(i) for i in input().split()] count = 0 while n < m: if m % 2 == 0: m >>= 1 else: m += 1 count += 1 count += n - m return count def __starting_point(): print(main()) __starting_point()
python
test
abovesol
codeparrot/apps
all
Solve in Python: A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.) Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits. -----Constraints----- - 1 \leq K \leq N \leq 1000 - 1 \leq p_i \leq 1000 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K p_1 p_2 \ldots p_N -----Output----- Print an integer representing the minimum possible total price of fruits. -----Sample Input----- 5 3 50 100 80 120 80 -----Sample Output----- 210 This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively. The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.
N,K = list(map(int,input().split())) P = sorted((list(map(int,input().split())))) print((sum(P[:K])))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/largest-values-from-labels/: We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length I tried it in Python, but could not do it. Can you solve it?
import heapq class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: maxHeap = [] for value, label in zip(values, labels): print((value, label)) heappush(maxHeap, (-value, label)) labelFrequencies = {} maxSum = 0 numChosen = 0 while maxHeap and numChosen < num_wanted: value, label = heappop(maxHeap) value = -value #when you can't use that value if label in labelFrequencies and labelFrequencies[label] >= use_limit: continue if label not in labelFrequencies: labelFrequencies[label] = 0 labelFrequencies[label] += 1 numChosen += 1 maxSum += value return maxSum
python
train
abovesol
codeparrot/apps
all
Solve in Python: Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word. The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, case-insensitive. example: ```javascript function sortIt('bid, zag', 2) //=> 'zag, bid' ``` ```ruby function sortIt('bid, zag', 2) //=> 'zag, bid' ``` ```python function sortIt('bid, zag', 2) #=> 'zag, bid' ``` The length of all words provided in the list will be >= n. The format will be "x, x, x". In Haskell you'll get a list of `String`s instead.
from operator import itemgetter def sort_it(list_, n): return ', '.join(sorted(list_.split(', '), key=itemgetter(n - 1)))
python
train
qsol
codeparrot/apps
all
Solve in Python: Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder). He is dividing the problems into two categories by choosing an integer K, as follows: - A problem with difficulty K or higher will be for ARCs. - A problem with difficulty lower than K will be for ABCs. How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same? -----Problem Statement----- - 2 \leq N \leq 10^5 - N is an even number. - 1 \leq d_i \leq 10^5 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N d_1 d_2 ... d_N -----Output----- Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same. -----Sample Input----- 6 9 1 4 4 6 7 -----Sample Output----- 2 If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved. Thus, the answer is 2.
N = int(input()) d = list(map(int, input().split())) d.sort() print(d[N//2] - d[N//2-1])
python
test
qsol
codeparrot/apps
all
Solve in Python: There is a game that involves three variables, denoted A, B, and C. As the game progresses, there will be N events where you are asked to make a choice. Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other. After each choice, none of A, B, and C should be negative. Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices. -----Constraints----- - 1 \leq N \leq 10^5 - 0 \leq A,B,C \leq 10^9 - N, A, B, C are integers. - s_i is AB, AC, or BC. -----Input----- Input is given from Standard Input in the following format: N A B C s_1 s_2 : s_N -----Output----- If it is possible to make N choices under the condition, print Yes; otherwise, print No. Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice. -----Sample Input----- 2 1 3 0 AB AC -----Sample Output----- Yes A C You can successfully make two choices, as follows: - In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2. - In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.
N, A, B, C = map(int, input().split()) S = [input() for _ in range(N)] ans = [] for i, s in enumerate(S): if s == "AB": if A == 0: A += 1 B -= 1 ans.append("A") elif B == 0: A -= 1 B += 1 ans.append("B") else: if i + 1 == N or S[i + 1] == "AB": A += 1 B -= 1 ans.append("A") else: if S[i + 1] == "BC": A -= 1 B += 1 ans.append("B") else: A += 1 B -= 1 ans.append("A") if A < 0 or B < 0: print("No") return elif s == "BC": if B == 0: B += 1 C -= 1 ans.append("B") elif C == 0: B -= 1 C += 1 ans.append("C") else: if i + 1 == N or S[i + 1] == "BC": B += 1 C -= 1 ans.append("B") else: if S[i + 1] == "AB": B += 1 C -= 1 ans.append("B") else: B -= 1 C += 1 ans.append("C") if B < 0 or C < 0: print("No") return else: if C == 0: C += 1 A -= 1 ans.append("C") elif A == 0: C -= 1 A += 1 ans.append("A") else: if i + 1 == N or S[i + 1] == "AC": A += 1 C -= 1 ans.append("A") else: if S[i + 1] == "AB": A += 1 C -= 1 ans.append("A") else: A -= 1 C += 1 ans.append("C") if A < 0 or C < 0: ...
python
test
qsol
codeparrot/apps
all
Solve in Python: $n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy presented to some girl is equal to $b_i$ and for all $1 \leq j \leq m$ the maximal number of sweets, which $j$-th girl received from some boy is equal to $g_j$. More formally, let $a_{i,j}$ be the number of sweets which the $i$-th boy give to the $j$-th girl. Then $b_i$ is equal exactly to the minimum among values $a_{i,1}, a_{i,2}, \ldots, a_{i,m}$ and $g_j$ is equal exactly to the maximum among values $b_{1,j}, b_{2,j}, \ldots, b_{n,j}$. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $a_{i,j}$ for all $(i,j)$ such that $1 \leq i \leq n$ and $1 \leq j \leq m$. You are given the numbers $b_1, \ldots, b_n$ and $g_1, \ldots, g_m$, determine this number. -----Input----- The first line contains two integers $n$ and $m$, separated with space — the number of boys and girls, respectively ($2 \leq n, m \leq 100\,000$). The second line contains $n$ integers $b_1, \ldots, b_n$, separated by spaces — $b_i$ is equal to the minimal number of sweets, which $i$-th boy presented to some girl ($0 \leq b_i \leq 10^8$). The third line contains $m$ integers $g_1, \ldots, g_m$, separated by spaces — $g_j$ is equal to the maximal number of sweets, which $j$-th girl received from some boy ($0 \leq g_j \leq 10^8$). -----Output----- If the described situation is impossible, print $-1$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. -----Examples----- Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 -----Note----- In the first test, the minimal total number of sweets, which boys could have presented is equal to $12$. This can be...
n, m = list(map(int, input().split())) b = list(map(int, input().split())) g = list(map(int, input().split())) x = max(b) y = min(g) if x > y: print(-1) elif x == y: print(sum(b) * m + sum(g) - x * m) else: m1, m2 = 0, 0 for c in b: if c >= m1: m1, m2 = c, m1 elif c >= m2: m2 = c #print(m1, m2) print(sum(b) * m + sum(g) - x * (m - 1) - m2)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/arc068/tasks/arc068_a: Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7. Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation: - Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward. For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure. If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward. Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back. Find the minimum number of operation Snuke needs to perform in order to score at least x points in total. -----Constraints----- - 1 ≦ x ≦ 10^{15} - x is an integer. -----Input----- The input is given from Standard Input in the following format: x -----Output----- Print the answer. -----Sample Input----- 7 -----Sample Output----- 2 I tried it in Python, but could not do it. Can you solve it?
import sys sys.setrecursionlimit(10**7) def I(): return int(sys.stdin.readline().rstrip()) def MI(): return list(map(int,sys.stdin.readline().rstrip().split())) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり def LI2(): return list(map(int,sys.stdin.readline().rstrip())) #空白なし def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) #空白あり def LS2(): return list(sys.stdin.readline().rstrip()) #空白なし x = I() q,r = x//11,x % 11 ans = 2*q if 1 <= r <= 6: ans += 1 elif r >= 7: ans += 2 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). -----Input----- The only line of input contains a string s of length between 1 and 10^5 consisting of uppercase Latin letters. -----Output----- Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. -----Examples----- Input ABA Output NO Input BACFAB Output YES Input AXBYBXA Output NO -----Note----- In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO". In the second sample test there are the following occurrences of the substrings: BACFAB. In the third sample test there is no substring "AB" nor substring "BA".
def __starting_point(): s = input() a = None b = None for i in range(len(s) - 1): if s[i] == 'A' and s[i + 1] == 'B': if a is None: a = i if b is not None and abs(i - b) > 1: print('YES') return if s[i] == 'B' and s[i + 1] == 'A': if b is None: b = i if a is not None and abs(a - i) > 1: print('YES') return print('NO') __starting_point()
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/56314d3c326bbcf386000007: Write a function to calculate compound tax using the following table: For $10 and under, the tax rate should be 10%. For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%. For $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%. Tack on an additional 3% for the portion of the total above $30. Return 0 for invalid input(anything that's not a positive real number). Examples: An input of 10, should return 1 (1 is 10% of 10) An input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1) * Note that the returned value should be rounded to the nearest penny. I tried it in Python, but could not do it. Can you solve it?
def tax_calculator(total): if not isinstance(total, (int, float)) or total < 0: return 0 tax = 0 if total > 30: tax = 2.2 + (total - 30) * 0.03 elif total > 20: tax = 1.7 + (total - 20) * 0.05 elif total > 10: tax = 1 + (total-10) * 0.07 elif total > 0: tax = total / 10.0 return round(tax, 2)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/max-consecutive-ones-iii/: Given an array A of 0s and 1s, we may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1s.    Example 1: Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.   Note: 1 <= A.length <= 20000 0 <= K <= A.length A[i] is 0 or 1 I tried it in Python, but could not do it. Can you solve it?
class Solution: def longestOnes(self, A: List[int], K: int) -> int: i = 0 j = 0 numZeros = 0 bestSize = 0 while j < len(A): if A[j] == 1: pass elif A[j] == 0: numZeros += 1 while numZeros > K: if i >= 0 and A[i] == 0: numZeros -= 1 i += 1 bestSize = max(bestSize, j - i + 1) j += 1 return bestSize
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc092/tasks/arc093_a: There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis. You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0. However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned. For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled. -----Constraints----- - 2 \leq N \leq 10^5 - -5000 \leq A_i \leq 5000 (1 \leq i \leq N) - All input values are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 A_2 ... A_N -----Output----- Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled. -----Sample Input----- 3 3 5 -1 -----Sample Output----- 12 8 10 Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively. For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows: - For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen. - For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen. - For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen. I tried it in Python, but could not do it. Can you solve it?
def main(): n = int(input()) a = list(map(int, input().split())) a.append(0) base = abs(a[0]) for i in range(n): base += abs(a[i+1] - a[i]) ans = [] for i in range(n): if (a[i] - a[i-1]) * (a[i+1] - a[i]) >= 0: ans.append(base) else: ans.append(base - 2 * min(abs(a[i] - a[i-1]), abs(a[i+1] - a[i]))) for i in ans: print(i) main()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/XOMMON: Given an array of n$n$ integers : A1,A2,...,An$ A_1, A_2,... , A_n$, find the longest size subsequence which satisfies the following property: The xor of adjacent integers in the subsequence must be non-decreasing. -----Input:----- - First line contains an integer n$n$, denoting the length of the array. - Second line will contain n$n$ space separated integers, denoting the elements of the array. -----Output:----- Output a single integer denoting the longest size of subsequence with the given property. -----Constraints----- - 1≤n≤103$1 \leq n \leq 10^3$ - 0≤Ai≤1018$0 \leq A_i \leq 10^{18}$ -----Sample Input:----- 8 1 200 3 0 400 4 1 7 -----Sample Output:----- 6 -----EXPLANATION:----- The subsequence of maximum length is {1, 3, 0, 4, 1, 7} with Xor of adjacent indexes as {2,3,4,5,6} (non-decreasing) I tried it in Python, but could not do it. Can you solve it?
# cook your dish here n=int(input()) l=list(map(int,input().split())) a=[] for i in range(0,n): for j in range(i+1,n): a.append((l[i]^l[j],(i,j))) a.sort() dp=[0]*n for i in range(0,len(a)): x=a[i][0] left,right=a[i][1][0],a[i][1][1] dp[right]=max(dp[left]+1,dp[right]) print(max(dp)+1)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/remove-comments/: Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n. In C++, there are two types of comments, line comments, and block comments. The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored. The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning. The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.) It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format. Example 1: Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] The line by line code is visualized as below: /*Test program */ int main() { //... I tried it in Python, but could not do it. Can you solve it?
S1 = 1 S2 = 2 S3 = 3 S4 = 4 S5 = 5 class Solution(object): def __init__(self): self.state = S1 def removeComments(self, source): """ :type source: List[str] :rtype: List[str] """ ret = [] buf = [] for s in source: for c in s: if self.state in [S1, S2]: buf.append(c) elif self.state == S4: if len(buf) >= 2 and buf[len(buf) - 2: len(buf)] == ['/','*']: buf.pop() buf.pop() elif self.state == S3: if len(buf) >= 2 and buf[len(buf) - 2: len(buf)] == ['/', '/']: buf.pop() buf.pop() self._transite(c) self._transite('\n') if len(buf) != 0 and self.state in [S1, S2]: ret.append(''.join(buf)) buf = [] return ret def _transite(self, char): if self.state == S1: if char == '/': self.state = S2 else: self.state = S1 elif self.state == S2: if char == '/': self.state = S3 elif char == '*': self.state = S4 else: self.state = S1 elif self.state == S3: if char == '\n': self.state = S1 else: self.state = S3 elif self.state == S4: if char == '*': self.state = S5 else: self.state = S4 elif self.state == S5: if char == '/': self.state = S1 elif char == '*': self.state = S5 else: self.state = S4 return self.state
python
train
abovesol
codeparrot/apps
all
Solve in Python: A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes). A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string. The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap. String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 10^5. -----Output----- Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings. -----Examples----- Input 4 mail ai lru cf Output cfmailru Input 3 kek preceq cheburek Output NO -----Note----- One can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.
n=int(input()) m=[] sc=[] for i in range(n): m.append(input()) sc.append(set(m[i])) if len(sc[i])!=len(m[i]): print('NO') break else: i=0 pX=False while i<len(m): j=i+1 p=False while j<len(m): #print(m) z=len(sc[i].intersection(sc[j])) #a=len(sc[i]) #b=len(sc[j]) if m[i] in m[j]: m[i]=m[j] sc[i]=sc[j] sc.pop(j) m.pop(j) p=True break elif m[j] in m[i]: sc.pop(j) m.pop(j) j-=1 elif z>0: if m[i][-z:]==m[j][:z]: m[i]+=m[j][z:] elif m[j][-z:]==m[i][:z]: m[i]=m[j]+m[i][z:] else: pX=True break sc[i]=set(m[i]) m.pop(j) sc.pop(j) j-=1 p=True j+=1 if not p: i+=1 if pX: print('NO') break if not pX: print(''.join(sorted(m)))
python
test
qsol
codeparrot/apps
all
Solve in Python: The only difference between easy and hard versions is the constraints. Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$. Vova wants to repost exactly $x$ pictures in such a way that: each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them. Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions. -----Input----- The first line of the input contains three integers $n, k$ and $x$ ($1 \le k, x \le n \le 200$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the beauty of the $i$-th picture. -----Output----- Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement. -----Examples----- Input 5 2 3 5 1 3 10 1 Output 18 Input 6 1 5 10 30 30 70 10 10 Output -1 Input 4 3 1 1 100 1 1 Output 100
n, k, x = map(int, input().split()) a = [None] + list(map(int, input().split())) dp = [[-1] * (n + 1) for i in range(x + 1)] dp[0][0] = 0 for i in range(1, x + 1): for j in range(1, n + 1): dp[i][j] = max(dp[i - 1][max(0, j - k):j]) if dp[i][j] != -1: dp[i][j] += a[j] ans = max(dp[x][n - k + 1:n + 1]) print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/779/B: Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10^{k}. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10^{k}. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 10^3 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10^{k}. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. -----Input----- The only line of the input contains two integer numbers n and k (0 ≤ n ≤ 2 000 000 000, 1 ≤ k ≤ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. -----Output----- Print w — the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10^{k}. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). -----Examples----- Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 -----Note----- In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. I tried it in Python, but could not do it. Can you solve it?
l = input().split() k = int(l[1]) ; n = l[0] n = n[::-1] def compute() : j = 0 ; i = 0 ; ans = 0 if len(n) <= k : return len(n)-1 while j < k and i < len(n) : if n[i] != '0' : ans += 1 else: j+= 1 i += 1 if i == len(n) and j < k : return len(n)-1 else: return ans print(compute())
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are going to eat X red apples and Y green apples. You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C. Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively. From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible. Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples. -----Constraints----- - 1 \leq X \leq A \leq 10^5 - 1 \leq Y \leq B \leq 10^5 - 1 \leq C \leq 10^5 - 1 \leq p_i \leq 10^9 - 1 \leq q_i \leq 10^9 - 1 \leq r_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: X Y A B C p_1 p_2 ... p_A q_1 q_2 ... q_B r_1 r_2 ... r_C -----Output----- Print the maximum possible sum of the deliciousness of the eaten apples. -----Sample Input----- 1 2 2 2 1 2 4 5 1 3 -----Sample Output----- 12 The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows: - Eat the 2-nd red apple. - Eat the 1-st green apple. - Paint the 1-st colorless apple green and eat it.
X, Y, A, B, C = list(map(int, input().split())) Ps = list(map(int, input().split())) Qs = list(map(int, input().split())) Rs = list(map(int, input().split())) Ps.sort(reverse=True) Qs.sort(reverse=True) Rs += Ps[:X] + Qs[:Y] Rs.sort(reverse=True) ans = sum(Rs[:X+Y]) print(ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"... The game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_i$ (which are determined and are known before the game begins, $s_i$ and $e_i$ may differ from round to round). The integer $s_i$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $a$) and will choose to write either $2 \cdot a$ or $a + 1$ instead. Whoever writes a number strictly greater than $e_i$ loses that round and the other one wins that round. Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $s_i$ and $e_i$ in advance. Lee will start the first round, the loser of each round will start the next round. The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game. Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not. -----Input----- The first line contains the integer $t$ ($1 \le t \le 10^5$) — the number of rounds the game has. Then $t$ lines follow, each contains two integers $s_i$ and $e_i$ ($1 \le s_i \le e_i \le 10^{18}$) — the $i$-th round's information. The rounds are played in the same order as given in input, $s_i$ and $e_i$ for all rounds are known to everyone before the game starts. -----Output----- Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise. -----Examples----- Input 3 5 8 1 4 3 10 Output 1 1 Input 4 1 2 2 3 3 4 4 5 Output 0 0 Input 1 1 1 Output 0 1 Input 2 1 9 4 5 Output 0 0 Input 2 1 2 2...
import sys input = sys.stdin.readline def win(s, e): if e == s: return False elif e == s + 1: return True elif e & 1: return s & 1 == 0 elif e // 2 < s: return s & 1 == 1 elif e // 4 < s: return True else: return win(s, e // 4) def lose(s, e): if e // 2 < s: return True else: return win(s, e // 2) def main(): res = [False, True] for _ in range(int(input())): s, e = [int(x) for x in input().split()] if res == [True, True]: continue if res == [False, False]: continue cur = [win(s, e), lose(s, e)] if res[0]: cur = [not x for x in cur] res = cur print(*[int(x) for x in res]) main()
python
test
qsol
codeparrot/apps
all
Solve in Python: # Task: Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers** ## Examples: ```python sum_fib(2) = 2 # 0! + 1! = 2 sum_fib(3) = 3 # 0! + 1! + 1! = 3 sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5 sum_fib(10) = 295232799039604140898709551821456501251 ``` ### Constraints: * #### **2 ≤ N ≤ 22** ### sum_fib(20) This number is so huge I need to make a separate area for it. Imagine 13327...
from math import factorial def sum_fib(n): fibo_num = 1 fibo_num_prev = 0 sum_factorial = 0 for num in range(0,n): sum_factorial = sum_factorial + factorial(fibo_num_prev) fibo_num_prev, fibo_num = fibo_num, fibo_num + fibo_num_prev return sum_factorial
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/630/E: Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit. More formally, if a game designer selected cells having coordinates (x_1, y_1) and (x_2, y_2), where x_1 ≤ x_2 and y_1 ≤ y_2, then all cells having center coordinates (x, y) such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x_2 - x_1 is divisible by 2. Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map. Help him implement counting of these units before painting. [Image] -----Input----- The only line of input contains four integers x_1, y_1, x_2, y_2 ( - 10^9 ≤ x_1 ≤ x_2 ≤ 10^9, - 10^9 ≤ y_1 ≤ y_2 ≤ 10^9) — the coordinates of the centers of two cells. -----Output----- Output one integer — the number of cells to be filled. -----Examples----- Input 1 1 5 5 Output 13 I tried it in Python, but could not do it. Can you solve it?
ch=input() d=ch.split(" ") x1=int(d[0]) y1=int(d[1]) x2=int(d[2]) y2=int(d[3]) nby=(y2-y1)//2+1 nbx=(x2-x1)//2+1 print(nby*nbx+(nby-1)*(nbx-1))
python
test
abovesol
codeparrot/apps
all
Solve in Python: We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you. For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be: $[2, 5, 6]$ $[4, 6]$ $[1, 3, 4]$ $[1, 3]$ $[1, 2, 4, 6]$ Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). 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. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($2 \le n \le 200$) — the length of the permutation. The next $n-1$ lines describe given segments. The $i$-th line contains the description of the $i$-th segment. The line starts with the integer $k_i$ ($2 \le k_i \le n$) — the length of the $i$-th segment. Then $k_i$ integers follow. All integers in a line are distinct, sorted in ascending order, between $1$ and $n$, inclusive. It is guaranteed that the required $p$ exists for each test case. It is also guaranteed that the sum of $n$ over all test cases does not exceed $200$ ($\sum n \le 200$). -----Output----- For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test...
from collections import Counter from itertools import chain def dfs(n, r, hint_sets, count, removed, result): # print(n, r, hint_sets, count, removed, result) if len(result) == n - 1: last = (set(range(1, n + 1)) - set(result)).pop() result.append(last) return True i, including_r = 0, None for i, including_r in enumerate(hint_sets): if i in removed: continue if r in including_r: break removed.add(i) next_r = [] for q in including_r: count[q] -= 1 if count[q] == 1: next_r.append(q) if not next_r: return False # print(r, next_r, result) if len(next_r) == 2: nr = -1 can1, can2 = next_r for h in hint_sets: if can1 in h and can2 not in h and not h.isdisjoint(result): nr = can1 break if can1 not in h and can2 in h and not h.isdisjoint(result): nr = can2 break if nr == -1: nr = can1 else: nr = next_r[0] result.append(nr) res = dfs(n, nr, hint_sets, count, removed, result) if res: return True result.pop() for q in including_r: count[q] += 1 return False t = int(input()) buf = [] for l in range(t): n = int(input()) hints = [] for _ in range(n - 1): k, *ppp = list(map(int, input().split())) hints.append(ppp) count = Counter(chain.from_iterable(hints)) most_common = count.most_common() hint_sets = list(map(set, hints)) r = most_common[-1][0] result = [r] if dfs(n, r, hint_sets, dict(count), set(), result): buf.append(' '.join(map(str, result[::-1]))) continue r = most_common[-2][0] result = [r] assert dfs(n, r, hint_sets, dict(count), set(), result) buf.append(' '.join(map(str, result[::-1]))) print('\n'.join(map(str, buf)))
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/CHFPARTY: Tonight, Chef would like to hold a party for his $N$ friends. All friends are invited and they arrive at the party one by one in an arbitrary order. However, they have certain conditions — for each valid $i$, when the $i$-th friend arrives at the party and sees that at that point, strictly less than $A_i$ other people (excluding Chef) have joined the party, this friend leaves the party; otherwise, this friend joins the party. Help Chef estimate how successful the party can be — find the maximum number of his friends who could join the party (for an optimal choice of the order of arrivals). -----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$. - 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 maximum number of Chef's friends who could join the party. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le N \le 10^5$ - the sum of $N$ over all test cases does not exceed $10^6$ -----Example Input----- 3 2 0 0 6 3 1 0 0 5 5 3 1 2 3 -----Example Output----- 2 4 0 -----Explanation----- Example case 1: Chef has two friends. Both of them do not require anyone else to be at the party before they join, so they will both definitely join the party. Example case 2: At the beginning, friends $3$ and $4$ can arrive and join the party, since they do not require anyone else to be at the party before they join. After that, friend $2$ can arrive; this friend would see that there are two people at the party and therefore also join. Then, friend $1$ will also join, so in the end, there would be $4$ people attending the party. Example case 3: No one will attend the party because each of Chef's friends will find zero people at the party and leave, regardless of the order in which they arrive. I tried it in Python, but could not do it. Can you solve it?
# cook your dish here t=0 try: t=int(input()) except: pass for _ in range(t): n = int(input()) a = list(map(int, input().split())) a = sorted(a) already_present = 0 for requirement in a: if already_present>=requirement: already_present+=1 print(already_present)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/COM12020/problems/CODE_00: Give me Biscuit Sunny wants to make slices of biscuit of size c * d into identical pieces. but each piece is a square having maximum possible side length with no left over piece of biscuit. Input Format The first line contains an integer N. N lines follow. Each line contains two space separated integers c and d. which denote length and breadth of the biscuit. Constraints 1 <= N <= 1000 1 <= c,d <= 1000 Output Format N lines, each containing an integer that denotes the number of squares of maximum size, when the biscuit is cut as per the given condition. Sample Input 2 2 2 6 9 Sample Output 1 6 Explanation The 1st testcase has a biscuit whose original dimensions are 2 X 2, the biscuit is uncut and is a square. Hence the answer is 1. The 2nd testcase has a biscuit of size 6 X 9 . We can cut it into 54 squares of size 1 X 1 , 6 of size 3 X 3 . For other sizes we will have leftovers. Hence, the number of squares of maximum size that can be cut is 6. I tried it in Python, but could not do it. Can you solve it?
t = int(input()) for i in range(t): m,n = map(int,input().split()) mul = m*n while(m!=n): if (m>n): m-=n else: n-=m print(mul//(m*n))
python
train
abovesol
codeparrot/apps
all
Solve in Python: Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties: - their digits occur only once - they are odd - they are multiple of three ```python next_numb(12) == 15 next_numb(13) == 15 next_numb(99) == 105 next_numb(999999) == 1023459 next_number(9999999999) == "There is no possible number that fulfills those requirements" ``` Enjoy the kata!!
def next_numb(val): i = val + 1 while i <= 9999999999: if i % 3 == 0 and i % 2 and len(str(i)) == len(set(str(i))): return i i += 1 return 'There is no possible number that fulfills those requirements'
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc100/tasks/abc100_b: Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo. As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times. Find the N-th smallest integer that would make Ringo happy. -----Constraints----- - D is 0, 1 or 2. - N is an integer between 1 and 100 (inclusive). -----Input----- Input is given from Standard Input in the following format: D N -----Output----- Print the N-th smallest integer that can be divided by 100 exactly D times. -----Sample Input----- 0 5 -----Sample Output----- 5 The integers that can be divided by 100 exactly 0 times (that is, not divisible by 100) are as follows: 1, 2, 3, 4, 5, 6, 7, ... Thus, the 5-th smallest integer that would make Ringo happy is 5. I tried it in Python, but could not do it. Can you solve it?
d, n = list(map(int, input().split())) start = 100 ** d counter = 0 while True: if start % (100 ** d) == 0 and start % (100 ** (d + 1)) != 0: counter += 1 if counter == n: print(start) break start += 100 ** d
python
test
abovesol
codeparrot/apps
all
Solve in Python: Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller. Return an list of non-empty reports in order of X coordinate.  Every report will have a list of values of nodes.   Example 1: Input: [3,9,20,null,null,15,7] Output: [[9],[3,15],[20],[7]] Explanation: Without loss of generality, we can assume the root node is at position (0, 0): Then, the node with value 9 occurs at position (-1, -1); The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2); The node with value 20 occurs at position (1, -1); The node with value 7 occurs at position (2, -2). Example 2: Input: [1,2,3,4,5,6,7] Output: [[4],[2],[1,5,6],[3],[7]] Explanation: The node with value 5 and the node with value 6 have the same position according to the given scheme. However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.   Note: The tree will have between 1 and 1000 nodes. Each node's value will be between 0 and 1000.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: res = [] frontier = [(root, 0)] h = defaultdict(list) while frontier: next = [] for u, x in frontier: h[x].append(u.val) if u.left: next.append((u.left, x-1)) if u.right: next.append((u.right, x+1)) next.sort(key = lambda x: (x[1], x[0].val)) frontier = next for k in sorted(h): res.append(h[k]) return res
python
train
qsol
codeparrot/apps
all
Solve in Python: You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.) Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise. -----Constraints----- - S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise. -----Sample Input----- 2019/04/30 -----Sample Output----- Heisei
s=input() if int(s[5]+s[6])>=5: print('TBD') else: print('Heisei')
python
test
qsol
codeparrot/apps
all
Solve in Python: Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is. You are to determine the total number of times Vasily takes the top card from the deck. -----Input----- The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the number written on the i-th from top card in the deck. -----Output----- Print the total number of times Vasily takes the top card from the deck. -----Examples----- Input 4 6 3 1 2 Output 7 Input 1 1000 Output 1 Input 7 3 3 3 3 3 3 3 Output 7 -----Note----- In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.
n = int(input()) s = list(map(int,input().split(' '))) a = [] for i in range(max(s)): a.append([]) for i in range(len(s)): a[s[i]-1].append(i) a = list([x for x in a if x != []]) if len(a) > 1: for i in range(1,len(a)): if len(a[i]) > 1: s = a[i-1][-1] if s > a[i][0] and s < a[i][-1]: for j in range(1,len(a[i])): if s < a[i][j]: a[i] = a[i][j:] + a[i][:j] break t = [] for i in a: t += i c = 0 x = t[0] + 1 i = n-1 while i > 0: if t[i] < t[i-1]: k = t[i] - t[i-1] + n else: k = t[i] - t[i-1] c += k x -= c//n i -= 1 print(c+x)
python
train
qsol
codeparrot/apps
all
Solve in Python: One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b". Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get? -----Input----- The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b". -----Output----- Print a single integer — the maximum possible size of beautiful string Nikita can get. -----Examples----- Input abba Output 4 Input bab Output 2 -----Note----- It the first sample the string is already beautiful. In the second sample he needs to delete one of "b" to make it beautiful.
# python3 # utf-8 string = input() prefix___a_nr = [0] prefix___b_nr = [0] for sym in string: curr_a_nr = prefix___a_nr[-1] curr_b_nr = prefix___b_nr[-1] if sym == 'a': curr_a_nr += 1 elif sym == 'b': curr_b_nr += 1 prefix___a_nr.append(curr_a_nr) prefix___b_nr.append(curr_b_nr) ans = 5000 for sep1 in range(len(string) + 1): for sep2 in range(sep1, len(string) + 1): curr_ans = 0 curr_ans += prefix___b_nr[sep1] curr_ans += prefix___a_nr[sep2] - prefix___a_nr[sep1] curr_ans += prefix___b_nr[-1] - prefix___b_nr[sep2] ans = min(ans, curr_ans) print(len(string) - ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58cda88814e65627c5000045: # Write Number in Expanded Form - Part 2 This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form). You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writing-a-decimal-in-expanded-form). For example: ```python expanded_form(1.24) # Should return '1 + 2/10 + 4/100' expanded_form(7.304) # Should return '7 + 3/10 + 4/1000' expanded_form(0.04) # Should return '4/100' ``` I tried it in Python, but could not do it. Can you solve it?
def expanded_form1(num): a = len(str(num)) b = [] for i,j in enumerate(str(num)): if j != '0': b.append(j+'0'*(a-i-1)) return ' + '.join(b) def expanded_form(num): a = str(num).index('.') m = int(str(num)[:a]) n = '0' + str(num)[a+1:] b = [] for i,j in enumerate(n[1:]): if j != '0': b.append(j+'/1'+'0'*(i+1)) b = ' + '.join(b) if len(expanded_form1(m)) > 0: return expanded_form1(m)+' + '+b else: return b
python
train
abovesol
codeparrot/apps
all
Solve in Python: The ZCO scholarship contest offers scholarships to first time ZCO participants. You are participating in it for the first time. So you want to know the number of participants who'll get the scholarship. You know that the maximum number of scholarships offered is $R$ and there are a total of $N$ participants numbered from $1$ to $N$. Out of these, you know the set of people (denoted by $X$) who you know, had participated in previous year ZCOs and hence, they shall not get the scholarship. Further, as the world isn't free from plagiarism, so is the case with the scholarship contest. And from your secret sources, you also know the set of people (denoted by set $Y$) who were involved in plagiarism and therefore aren't eligible for scholarship either. Find out the number of participants who shall get the scholarship. PS: Don't ask how so many scholarships are being offered when you see the constraints on $R$. You never questioned it when in mathematics classes, some person bought $80$ watermelons twice just to compare them and save $₹1$. -----Input:----- - The first line will contain a single integer, $T$, the number of testcases. Then the testcases follow. - The first line of each test case contains four integers; $N$, $R$, $|X|$ and $|Y|$ denoting the number of participants, maximum number of scholarships offered, number of old participants, and the number of participants involved in plagiarism, respectively. - The second line of each test case contains $|X|$ space separated integers $x_1, x_2 \ldots x_{|X|}$ denoting the indices of people who participated in previous years. If $X$ is empty, this line is skipped and no empty line is in the input. - The third line of each test case contains $|Y|$ space separated integers $y_1, y_2 \ldots y_{|Y|}$ denoting the indices of people who are involved in plagiarism. If $Y$ is empty, this line is skipped and no empty line is in input. -----Output:----- For each testcase, print a single integer in a new line, denoting the number of participants who shall get the...
for _ in range(int(input())): n,r,x,y=map(int,input().split()) if x>0: arr=set(list(map(int,input().split()))) if y>0: brr=set(list(map(int,input().split()))) if x>0 and y>0: crr=list(arr.union(brr)) t=n-len(crr) if t>r: print(r) else: print(t) elif x>0 or y>0: s=max(x,y) t=n-s if t>r : print(r) else: print(t) else: if n>r: print(r) else: print(n)
python
train
qsol
codeparrot/apps
all
Solve in Python: Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off. The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms. Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights. Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0. -----Output----- Print a...
def coun(pref): now = 0 for i in range(n): pos = pref[i] if pos == 'l': if i < n - 1 and sum(check[(i + 1):]) > 0: now += 1 if "1" in mat[i]: if pref[i + 1] == "r": now += (m + 1) else: now += (2 * mat[i].rfind("1")) else: if pref[i + 1] == 'r': now += (m + 1) else: if "1" in mat[i]: now += mat[i].rfind("1") else: if i < n - 1 and sum(check[(i + 1):]) > 0: now += 1 if "1" in mat[i]: if pref[i + 1] == "l": now += (m + 1) else: now += (2 * (m + 1 - mat[i].find("1"))) else: if pref[i + 1] == 'l': now += (m + 1) else: if "1" in mat[i]: now += (m + 1 - mat[i].find("1")) return now def gen(pref): nonlocal ans if len(pref) == n: ans = min(ans, coun(pref)) return gen(pref + "l") gen(pref + "r") n, m = map(int, input().split()) mat = [0] * n for i in range(n): mat[i] = input() mat.reverse() check = [0] * n for i in range(n): check[i] = mat[i].count("1") ans = 1000000000 gen("l") print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1105/C: Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: All the integers in the array were between $l$ and $r$ (inclusive). The sum of all the elements was divisible by $3$. Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array. Since the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$. -----Input----- The first and only line contains three integers $n$, $l$ and $r$ ($1 \le n \le 2 \cdot 10^5 , 1 \le l \le r \le 10^9$) — the size of the lost array and the range of numbers in the array. -----Output----- Print the remainder when dividing by $10^9 + 7$ the number of ways to restore the array. -----Examples----- Input 2 1 3 Output 3 Input 3 2 2 Output 1 Input 9 9 99 Output 711426616 -----Note----- In the first example, the possible arrays are : $[1,2], [2,1], [3, 3]$. In the second example, the only possible array is $[2, 2, 2]$. I tried it in Python, but could not do it. Can you solve it?
from sys import stdin, stdout prime = 10**9 + 7 def unitMatrix(size): out = [[0]*size for i in range(size)] for i in range(size): out[i][i] = 1 return out def matrixMult(pre, post): rows = len(pre) mid = len(post) columns = len(post[0]) out = [[0]*columns for i in range(rows)] for i in range(rows): for j in range(columns): for k in range(mid): out[i][j] += pre[i][k]*post[k][j] out[i][j] = out[i][j]%prime return out def matrixExp(base, power): if power == 0: return unitMatrix(len(base)) else: if power%2 == 0: half = matrixExp(base, power/2) return matrixMult(half, half) else: half = matrixExp(base, (power-1)/2) return matrixMult(matrixMult(half, half), base) def main(): n, l, r = [int(i) for i in stdin.readline().split()] vals = [[1], [0], [0]] mods = [(r-l+1)//3 ,(r-l+1)//3 ,(r-l+1)//3] remainder = (r-l+1)%3 if remainder >= 1: mods[l%3] += 1 if remainder == 2: mods[(l+1)%3] += 1 transforms = [[mods[0], mods[2], mods[1]], [mods[1], mods[0], mods[2]], [mods[2], mods[1], mods[0]]] power = matrixExp(transforms, n) out = matrixMult(power, vals) print(out[0][0]) main()
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc067/tasks/arc078_a: Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it. They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card. Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively. They would like to minimize |x-y|. Find the minimum possible value of |x-y|. -----Constraints----- - 2 \leq N \leq 2 \times 10^5 - -10^{9} \leq a_i \leq 10^{9} - a_i is an integer. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 ... a_{N} -----Output----- Print the answer. -----Sample Input----- 6 1 2 3 4 5 6 -----Sample Output----- 1 If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value. I tried it in Python, but could not do it. Can you solve it?
n=int(input()) a=list(map(int,input().split())) ans=2*(10**14)+1 s=sum(a) x=0 y=s for i in range(n-1): x+=a[i] y-=a[i] ans=min(ans,abs(x-y)) print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: There are n students at Berland State University. Every student has two skills, each measured as a number: a_{i} — the programming skill and b_{i} — the sports skill. It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track. There should be exactly p students in the programming team and exactly s students in the sports team. A student can't be a member of both teams. The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all a_{i} and the strength of the sports team is the sum of all b_{i} over corresponding team members. Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad. -----Input----- The first line contains three positive integer numbers n, p and s (2 ≤ n ≤ 3000, p + s ≤ n) — the number of students, the size of the programming team and the size of the sports team. The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3000), where a_{i} is the programming skill of the i-th student. The third line contains n positive integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3000), where b_{i} is the sports skill of the i-th student. -----Output----- In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print p numbers — the members of the programming team. In the third line, print s numbers — the members of the sports team. The students are numbered from 1 to n as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order. If there are multiple solutions, print...
#!/usr/bin/env python3 from itertools import accumulate from heapq import heappop, heappush def top(ppl_indices, vals, start): Q = [] res = [0 for i in range(len(ppl_indices))] for k, idx in enumerate(ppl_indices): heappush(Q, -vals[idx]) if k >= start: res[k] = res[k-1] - heappop(Q) return res n, a_size, b_size = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) conversion_gain = [y - x for x, y in zip(a, b)] ordered_by_a = sorted(zip(a, list(range(n))), reverse=True) prefix_sums_a = list(accumulate([x for x, y in ordered_by_a])) conversions = top([idx for val, idx in ordered_by_a], conversion_gain, a_size) rest_of_bs = list(reversed(top([idx for val, idx in reversed(ordered_by_a[a_size:])], b, n - a_size - b_size))) + [0] sol, top_k = max([(prefix_a + convert + add_bs, idx) for idx, (prefix_a, convert, add_bs) in enumerate(zip(prefix_sums_a[a_size-1:a_size+b_size], conversions[a_size-1:a_size+b_size], rest_of_bs))]) top_k += a_size conversion_ordered_by_a = [(conversion_gain[idx], idx) for val, idx in ordered_by_a] conversion_sorted = sorted(conversion_ordered_by_a[:top_k], reverse=True) converted = [idx for val, idx in conversion_sorted[:top_k-a_size]] team_a = list(set(idx for val, idx in ordered_by_a[:top_k]) - set(converted)) b_ordered_by_a = [(b[idx], idx) for val, idx in ordered_by_a] b_sorted = sorted(b_ordered_by_a[top_k:], reverse=True) team_b = converted + [idx for val, idx in b_sorted[:(a_size+b_size) - top_k]] print(sol) print(" ".join(str(idx+1) for idx in team_a)) print(" ".join(str(idx+1) for idx in team_b))
python
test
qsol
codeparrot/apps
all
Solve in Python: As you know America’s Presidential Elections are about to take place and the most popular leader of the Republican party Donald Trump is famous for throwing allegations against anyone he meets. He goes to a rally and meets n people which he wants to offend. For each person i he can choose an integer between 1 to max[i]. He wants to decide in how many ways he can offend all these persons (N) given the condition that all numbers chosen by him for each person are distinct. So he needs your help to find out the number of ways in which he can do that. If no solution is possible print 0 -----Input----- The first line of the input contains an integer T (1<=T<=100) 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 denoting the number of people Trump wants to offend. The second line contains N space-separated integers maxnumber[0], maxnumber[1], ..., maxnumber[n-1] denoting the maxnumber that trump can choose for each person. -----Output----- For each test case, output a single line containing the number of ways Trump can assign numbers to the people, modulo 1,000,000,007. If it's impossible to assign distinct integers to the people, print 0 -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 50 - 1 ≤ Maxnumber[i] ≤ 3000 -----Example----- Input: 3 1 4 2 10 5 4 2 3 1 3 Output: 4 45 0 -----Explanation----- In case 1, He can choose any number from 1 to 4 In case 2,Out of the total 50 combination he can not take (1,1) ,(2,2) , (3,3) ,(4,4) or (5,5).
for t in range(int(input())): n = int(input()) a = sorted(map(int,input().split())) ans = 1 for i in range(n): ans *= (a[i]-i) ans %= (10**9+7) if (ans == 0): break print(ans)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/960/A: A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes). -----Input----- The first and only line consists of a string $S$ ($ 1 \le |S| \le 5\,000 $). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'. -----Output----- Print "YES" or "NO", according to the condition. -----Examples----- Input aaabccc Output YES Input bbacc Output NO Input aabc Output YES -----Note----- Consider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct. Consider third example: the number of 'c' is equal to the number of 'b'. I tried it in Python, but could not do it. Can you solve it?
s = input() flag = 0 ans = 1 aa = s.count("a") bb = s.count("b") cc = s.count("c") if min(aa,bb) == 0 or (bb != cc and aa != cc): print("NO") else: for i in s: if flag == 0: if i == "b": flag = 1 continue if i != "a": ans = 0 break elif flag == 1: if i == "c": flag = 2 continue if i != "b": ans = 0 break else: if i != "c": ans = 0 break if ans == 1: print("YES") else: print("NO")
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/704/A: Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. -----Input----- The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer type_{i} — type of the i-th event. If type_{i} = 1 or type_{i} = 2 then it is followed by an integer x_{i}. Otherwise it is followed by an integer t_{i} (1 ≤ type_{i} ≤ 3, 1 ≤ x_{i} ≤ n, 1 ≤ t_{i} ≤ q). -----Output----- Print the number of unread notifications after each event. -----Examples----- Input 3 4 1 3 1 1 1 2 2 3 Output 1 2 3 2 Input 4 6 1 2 1 4 1 2 3 3 1 3 1 3 Output 1 2 3 0 1 2 -----Note----- In the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the... I tried it in Python, but could not do it. Can you solve it?
'''input 4 6 1 2 1 4 1 2 3 3 1 3 1 3 ''' n, q = list(map(int, input().split())) count = [0 for i in range(n + 1)] queue = [] read = set() unread = 0 ans = [] last_q_idx = 0 last_app_idx = [1 for i in range(n + 1)] for i in range(q): action, num = list(map(int, input().split())) if action == 1: queue.append((num, count[num] + 1)) count[num] += 1 unread += 1 elif action == 2: for number in range(last_app_idx[num], count[num] + 1): if (num, number) not in read: read.add((num, number)) unread -= 1 last_app_idx[num] = max(last_app_idx[num], count[num]) else: for idx in range(last_q_idx, num): app, number = queue[idx] if (app, number) not in read: read.add((app, number)) last_app_idx[app] = max(last_app_idx[app], number) unread -= 1 last_q_idx = max(last_q_idx, num) # print(action, num, last_q_idx, last_app_idx, queue) ans.append(unread) print("\n".join(map(str, ans)))
python
train
abovesol
codeparrot/apps
all
Solve in Python: You are given strings S and T consisting of lowercase English letters. You can perform the following operation on S any number of times: Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1. Determine if S and T can be made equal by performing the operation zero or more times. -----Constraints----- - 1 \leq |S| \leq 2 \times 10^5 - |S| = |T| - S and T consists of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: S T -----Output----- If S and T can be made equal, print Yes; otherwise, print No. -----Sample Input----- azzel apple -----Sample Output----- Yes azzel can be changed to apple, as follows: - Choose e as c_1 and l as c_2. azzel becomes azzle. - Choose z as c_1 and p as c_2. azzle becomes apple.
import bisect,collections,copy,itertools,math,string import sys def I(): return int(sys.stdin.readline().rstrip()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) def main(): s = S() t = S() dic1 = collections.defaultdict(str) dic2 = collections.defaultdict(str) for i in range(len(s)): if dic1[t[i]] == "": dic1[t[i]] = s[i] else: if dic1[t[i]] != s[i]: print("No") return if dic2[s[i]] == "": dic2[s[i]] = t[i] else: if dic2[s[i]] != t[i]: print("No") return print("Yes") main()
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/802/B: Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences. -----Input----- Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000. -----Output----- Same as the easy version. -----Examples----- Input 4 100 1 2 2 1 Output 2 Input 4 1 1 2 2 1 Output 3 Input 4 2 1 2 3 1 Output 3 I tried it in Python, but could not do it. Can you solve it?
# https://codeforces.com/problemset/problem/802/B import heapq n, k = map(int, input().split()) a = list(map(int, input().split())) d = {} pos = {} Q = [] cnt = 0 for i, x in enumerate(a): if x not in pos: pos[x] = [] pos[x].append(i) for i, x in enumerate(a): if x not in d: cnt += 1 if len(d) == k: pos_, x_ = heapq.heappop(Q) del d[x_] d[x] = 1 pos[x].pop(0) if len(pos[x]) > 0: heapq.heappush(Q, (-pos[x][0], x)) else: heapq.heappush(Q, (-float('inf'), x)) print(cnt)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc107/tasks/abc107_a: There is an N-car train. You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back." -----Constraints----- - 1 \leq N \leq 100 - 1 \leq i \leq N -----Input----- Input is given from Standard Input in the following format: N i -----Output----- Print the answer. -----Sample Input----- 4 2 -----Sample Output----- 3 The second car from the front of a 4-car train is the third car from the back. I tried it in Python, but could not do it. Can you solve it?
n, i = map(int, input().split()) print(n - i + 1)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/rearrange-spaces-between-words/: You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text. Return the string after rearranging the spaces.   Example 1: Input: text = " this is a sentence " Output: "this is a sentence" Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces. Example 2: Input: text = " practice makes perfect" Output: "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string. Example 3: Input: text = "hello world" Output: "hello world" Example 4: Input: text = " walks udp package into bar a" Output: "walks udp package into bar a " Example 5: Input: text = "a" Output: "a"   Constraints: 1 <= text.length <= 100 text consists of lowercase English letters and ' '. text contains at least one word. I tried it in Python, but could not do it. Can you solve it?
class Solution: def reorderSpaces(self, text: str) -> str: # separate words and spaces words = text.split(' ') words = list(filter(lambda x: len(x) > 0, words)) # print(words) # get their counts so we can do some math wordsLen = len(words) spacesLen = text.count(' ') # print(wordsLen, spacesLen) if(wordsLen == 1): return words[0] + ' ' * spacesLen evenDistSpaces = spacesLen // (wordsLen-1) endDistSpaces = spacesLen % (wordsLen-1) # print(evenDistSpaces, endDistSpaces) space = ' ' * evenDistSpaces end = ' ' * endDistSpaces print(len(space), len(end)) resultString = space.join(words) resultString += end return resultString
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5a084a098ba9146690000969: This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`). If the input is `0` or negative value, then you should return `"00:00"` **Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example the remainder of 5 / 2 is 1, so 5 modulo 2 is 1. ## Example If the input is `78`, then you should return `"01:18"`, because 78 minutes converts to 1 hour and 18 minutes. Good luck! :D I tried it in Python, but could not do it. Can you solve it?
def time_convert(num): return '{:02}:{:02}'.format(*divmod(max(0, num), 60))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/ICOD2016/problems/ICODE16G: Abhishek is fond of playing cricket very much. One morning, he is playing cricket with his friends. Abhishek is a right-hand batsman .He has to face all types of balls either good or bad. There are total 26 balls in the game and each ball is represented by one of the following two ways:- 1. "g" denotes a good ball. 2. "b" denotes a bad ball. All 26 balls are represented by lower case letters (a,b,.....z). Balls faced by Abhishek are represented as a string s, all the characters of which are lower case i.e, within 26 above mentioned balls. A substring s[l...r] (1≤l≤r≤|s|) of string s=s1s2...s|s| (where |s| is the length of string s) is string slsl+1...sr. The substring s[l...r] is good, if among the letters slsl+1...sr, there are at most k bad ones (refer sample explanation ). Your task is to find out the number of distinct good substrings for the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their contents are different, i.e. s[x...y]≠s[p...q]. -----Input Format----- First Line contains an integer T, number of test cases. For each test case, first line contains a string - a sequence of balls faced by Abhishek. And, next line contains a string of characters "g" and "b" of length 26 characters. If the ith character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. And, the third line of the test case consists of a single integer k (0≤k≤|s|) — the maximum acceptable number of bad characters in a good substring. -----Output Format ----- For each test case, print a single integer — the number of distinct good substrings of string s. -----Constraints----- - 1<=T<=1000 - 1<=|s|<=2000 - 0<=k<=|s| -----Subtasks----- Subtask 1 : 20 Points - 1<=T<=10 - 1<=|s|<=20 - 0<=k<=|s| Subtask 2 : 80 Points Original Constraints Sample Input 2 ababab bgbbbbbbbbbbbbbbbbbbbbbbbb 1 acbacbacaa bbbbbbbbbbbbbbbbbbbbbbbbbb 2 Sample... I tried it in Python, but could not do it. Can you solve it?
import sys for _ in range(0,eval(input())): d,c,inp,mp,n,q=[],0,list(map(ord,list(sys.stdin.readline().strip()))),sys.stdin.readline().strip(),eval(input()),ord('a') for i in range(0,len(inp)): nn,h=n,0 for j in range(i,len(inp)): if ( (mp[inp[j]-q]=='g') or nn>0 ): if((mp[inp[j]-q]=='g') == False ): nn=nn-1 h=(h*256)^inp[j] d+=[h] else: break print(len(set(d)))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58983deb128a54b530000be6: Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`. **Please note, you need to write this function without using regex!** ## Examples ```python '([[some](){text}here]...)' => True '{([])}' => True '()[]{}()' => True '(...[]...{(..())}[abc]())' => True '1239(df){' => False '[()])' => False ')12[x]34(' => False ``` Don't forget to rate this kata! Thanks :) I tried it in Python, but could not do it. Can you solve it?
def braces_status(string): s = "".join(list(filter(lambda ch: ch in "{[()]}",list(string)))) while '{}' in s or '()' in s or '[]' in s: s=s.replace('{}','') s=s.replace('[]','') s=s.replace('()','') return s==''
python
train
abovesol
codeparrot/apps
all
Solve in Python: You are given a bracket sequence $s$ (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. Your problem is to calculate the number of regular bracket sequences of length $2n$ containing the given bracket sequence $s$ as a substring (consecutive sequence of characters) modulo $10^9+7$ ($1000000007$). -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the half-length of the resulting regular bracket sequences (the resulting sequences must have length equal to $2n$). The second line of the input contains one string $s$ ($1 \le |s| \le 200$) — the string $s$ that should be a substring in each of the resulting regular bracket sequences ($|s|$ is the length of $s$). -----Output----- Print only one integer — the number of regular bracket sequences containing the given bracket sequence $s$ as a substring. Since this number can be huge, print it modulo $10^9+7$ ($1000000007$). -----Examples----- Input 5 ()))() Output 5 Input 3 (() Output 4 Input 2 ((( Output 0 -----Note----- All regular bracket sequences satisfying the conditions above for the first example: "(((()))())"; "((()()))()"; "((()))()()"; "(()(()))()"; "()((()))()". All regular bracket sequences satisfying the conditions above for the second example: "((()))"; "(()())"; "(())()"; "()(())". And there is no regular bracket sequences of length $4$ containing "(((" as a substring in the third example.
MOD=10**9+7 n=int(input()) s=[c=='(' for c in input()] m=len(s) z=[[0,0]] for v in s: a=z[-1][v] z[-1][v]=len(z) z.append(z[a][:]) z[m][0]=z[m][1]=m dp=[[0 for _ in range(m+1)] for _ in range(n+1)] dp[0][0]=1 for _ in range(2*n): ndp=[[0 for _ in range(m+1)] for _ in range(n+1)] for i in range(n+1): for j in range(m+1): if i>0:ndp[i-1][z[j][0]]=(ndp[i-1][z[j][0]]+dp[i][j])%MOD if i<n:ndp[i+1][z[j][1]]=(ndp[i+1][z[j][1]]+dp[i][j])%MOD dp=ndp print(dp[0][m])
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5886faac54a7111c21000072: # Task A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB). # Example For `inputString = "00-1B-63-84-45-E6"`, the output should be `true`; For `inputString = "Z1-1B-63-84-45-E6"`, the output should be `false`; For `inputString = "not a MAC-48 address"`, the output should be `false`. # Input/Output - `[input]` string `inputString` - `[output]` a boolean value `true` if inputString corresponds to MAC-48 address naming rules, `false` otherwise. I tried it in Python, but could not do it. Can you solve it?
is_mac_48_address = lambda address: bool( __import__("re").match('-'.join(['[0-9A-F]{2}']*6) + '$', address) )
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/52ec24228a515e620b0005ef: # How many ways can you make the sum of a number? From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)# >In number theory and combinatorics, a partition of a positive integer *n*, also called an *integer partition*, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways: ``` 4 3 + 1 2 + 2 2 + 1 + 1 1 + 1 + 1 + 1 ``` ## Examples ### Basic ```python exp_sum(1) # 1 exp_sum(2) # 2 -> 1+1 , 2 exp_sum(3) # 3 -> 1+1+1, 1+2, 3 exp_sum(4) # 5 -> 1+1+1+1, 1+1+2, 1+3, 2+2, 4 exp_sum(5) # 7 -> 1+1+1+1+1, 1+1+1+2, 1+1+3, 1+2+2, 1+4, 5, 2+3 exp_sum(10) # 42 ``` ### Explosive ```python exp_sum(50) # 204226 exp_sum(80) # 15796476 exp_sum(100) # 190569292 ``` See [here](http://www.numericana.com/data/partition.htm) for more examples. I tried it in Python, but could not do it. Can you solve it?
import functools @functools.lru_cache(1 << 16) def f(n, m): if n == 0: return 1 return sum(f(n - i, i) for i in range(1, min(n, m)+1)) def exp_sum(n): return f(n, n)
python
train
abovesol
codeparrot/apps
all
Solve in Python: A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. -----Input----- The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n) — the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. -----Output----- Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. -----Examples----- Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 -----Note----- In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). [Image] There are $\frac{n \cdot(n - 1)}{2} = 15$ pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3·1 = 3.
""" #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict as dd, deque as dq,...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc046/tasks/abc046_a: AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive. Since he is forgetful, he might have bought more than one paint can in the same color. Count the number of different kinds of colors of these paint cans and tell him. -----Constraints----- - 1≦a,b,c≦100 -----Input----- The input is given from Standard Input in the following format: a b c -----Output----- Print the number of different kinds of colors of the paint cans. -----Sample Input----- 3 1 4 -----Sample Output----- 3 Three different colors: 1, 3, and 4. I tried it in Python, but could not do it. Can you solve it?
penki=list(map(int,input().split())) ans=len(set(penki)) print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume. There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or decrease the current volume by $1$, $2$, or $5$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $0$. As Bob is so angry, he wants to change the volume to $b$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $a$ and $b$, finds the minimum number of presses to change the TV volume from $a$ to $b$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $T$ ($1 \le T \le 1\,000$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $a$ and $b$ ($0 \le a, b \le 10^{9}$) — the current volume and Bob's desired volume, respectively. -----Output----- For each test case, output a single integer — the minimum number of presses to change the TV volume from $a$ to $b$. If Bob does not need to change the volume (i.e. $a=b$), then print $0$. -----Example----- Input 3 4 0 5 14 3 9 Output 2 3 2 -----Note----- In the first example, Bob can press the $-2$ button twice to reach $0$. Note that Bob can not press $-5$ when the volume is $4$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $+5$ twice, then press $-1$ once. In the last example, Bob can press the $+5$ once, then press $+1$.
T = int(input()) for _ in range(T): a, b = map(int, input().split()) d = abs(a - b) ans = (d // 5) d = d % 5 if d == 1 or d == 2: ans += 1 if d == 3 or d == 4: ans += 2 print(ans)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5993e6f701726f0998000030: # Disclaimer This Kata is an insane step-up from [GiacomoSorbi's Kata](https://www.codewars.com/kata/total-increasing-or-decreasing-numbers-up-to-a-power-of-10/python), so I recommend to solve it first before trying this one. # Problem Description A positive integer `n` is called an *increasing number* if its digits are in increasing order (e.g. 123, 144568, 56799). Similarly, `n` is called a *decreasing number* if its digits are in decreasing order (e.g. 210, 76642, 998500). Note that the numbers whose digits are all the same (e.g. 1111, 22222) are both increasing and decreasing. Given the maximum number of digits (`max_digits`), how many positive integers in the range are either increasing or decreasing (or both)? Since your answer will be very large, please give your answer **modulo 12345787**. Also note that, unlike Giacomo's version, the number zero is excluded from the counts (because it's not positive). # Constraints `1 <= max_digits <= 10 ** 9` **Note the input size!** The input will be always a valid integer. # Examples ```python # Up to two digits, all numbers are either increasing or decreasing insane_inc_or_dec(1) == 9 insane_inc_or_dec(2) == 99 insane_inc_or_dec(3) == 474 insane_inc_or_dec(4) == 1674 insane_inc_or_dec(5) == 4953 insane_inc_or_dec(6) == 12951 ``` # Acknowledgement This problem was inspired by [Project Euler #113: Non-bouncy Numbers](https://projecteuler.net/problem=113). If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)! I tried it in Python, but could not do it. Can you solve it?
from functools import reduce from operator import mul def insane_inc_or_dec(x): return (reduce(mul,[x + i + i * (i == 10) for i in range(1, 11)]) // 3628800 - 10 * x - 2) % 12345787
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/sequential-digits/: An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.   Example 1: Input: low = 100, high = 300 Output: [123,234] Example 2: Input: low = 1000, high = 13000 Output: [1234,2345,3456,4567,5678,6789,12345]   Constraints: 10 <= low <= high <= 10^9 I tried it in Python, but could not do it. Can you solve it?
class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: nums = [] max_digits = 9 for depth in range(2, max_digits + 1): nums += self.genNum(max_digits, depth) return [n for n in nums if n >= low and n <= high] def genNum(self, max_digits, depth): result = [] for startDigit in range(1, max_digits-depth+2): num = startDigit for lvl in range(depth-1): num = num * 10 + num % 10 + 1 result.append(num) return result
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc116/tasks/abc116_d: There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i. You are choosing K among these N pieces to eat. Your "satisfaction" here will be calculated as follows: - The satisfaction is the sum of the "base total deliciousness" and the "variety bonus". - The base total deliciousness is the sum of the deliciousness of the pieces you eat. - The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat. You want to have as much satisfaction as possible. Find this maximum satisfaction. -----Constraints----- - 1 \leq K \leq N \leq 10^5 - 1 \leq t_i \leq N - 1 \leq d_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K t_1 d_1 t_2 d_2 . . . t_N d_N -----Output----- Print the maximum satisfaction that you can obtain. -----Sample Input----- 5 3 1 9 1 7 2 6 2 5 3 1 -----Sample Output----- 26 If you eat Sushi 1,2 and 3: - The base total deliciousness is 9+7+6=22. - The variety bonus is 2*2=4. Thus, your satisfaction will be 26, which is optimal. I tried it in Python, but could not do it. Can you solve it?
n,k=list(map(int,input().split())) td=sorted([list(map(int,input().split())) for i in range(n)],reverse=True,key=lambda x:x[1]) ans=0 kl=dict() for i in range(k): ans+=td[i][1] if td[i][0] in kl: kl[td[i][0]]+=1 else: kl[td[i][0]]=1 l=len(kl) ans+=(l**2) ans_=ans now=k-1 for i in range(k,n): if td[i][0] not in kl: #最小を求めるのをもっと早く while now>=0: if kl[td[now][0]]>1: mi=td[now] kl[mi[0]]-=1 now-=1 break now-=1 if now==-1: break else: ans=ans+2*l+1-mi[1]+td[i][1] kl[td[i][0]]=1 ans_=max(ans,ans_) l+=1 print(ans_)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1191/B: Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $\ldots$, 9m, 1p, 2p, $\ldots$, 9p, 1s, 2s, $\ldots$, 9s. In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand. Do you know the minimum number of extra suited tiles she needs to draw so that she can win? Here are some useful definitions in this game: A mentsu, also known as meld, is formed by a koutsu or a shuntsu; A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu; A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu. Some examples: [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no koutsu or shuntsu, so it includes no mentsu; [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu; [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu. Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite. -----Input----- The only line contains three strings — the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from $1$ to $9$ and the second character is m, p or s. -----Output----- Print a single integer — the minimum... I tried it in Python, but could not do it. Can you solve it?
t = input().split() t.sort() if t.count(t[0]) == 3: print('0') elif t.count(t[0]) == 2 or t.count(t[1]) == 2: print('1') else: num = list(map(int, [t[0][0], t[1][0], t[2][0]])) suit = [t[0][1], t[1][1], t[2][1]] if len(set(suit)) == 3: print('2') elif len(set(suit)) == 1: if num[1] == num[0] + 1 or num[2] == num[1] + 1: if num[2] == num[0] + 2: print('0') else: print('1') elif num[1] == num[0] + 2 or num[2] == num[1] + 2: print('1') else: print('2') else: if suit[0] == suit[1]: if num[1] - num[0] in [1, 2]: print('1') else: print('2') elif suit[1] == suit[2]: if num[2] - num[1] in [1, 2]: print('1') else: print('2') else: if num[2] - num[0] in [1, 2]: print('1') else: print('2')
python
test
abovesol
codeparrot/apps
all
Solve in Python: #### Task: Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner. 1. Start with `n = 213` (as an example). 2. To approximate the square root of n, we will first find the greatest perfect square that is below or equal to `n`. (In this example, that would be 196, or 14 squared.) We will call the square root of this number (which means sqrt 196, or 14) `base`. 3. Then, we will take the lowest perfect square that is greater than or equal to `n`. (In this example, that would be 225, or 15 squared.) 4. Next, subtract 196 (greatest perfect square less than or equal to `n`) from `n`. (213 - 196 = **17**) We will call this value `diff_gn`. 5. Find the difference between the lowest perfect square greater than or equal to `n` and the greatest perfect square less than or equal to `n`. (225 – 196 = **29**) We will call this value `diff_lg`. 6. Your final answer is `base` + (`diff_gn` / `diff_lg`). In this example: 14 + (17 / 29) which is 14.59, rounded to the nearest hundredth. Just to clarify, if the input is a perfect square itself, you should return the exact square of the input. In case you are curious, the approximation (computed like above) for 213 rounded to four decimal places is 14.5862. The actual square root of 213 is 14.5945. Inputs will always be positive whole numbers. If you are having trouble understanding it, let me know with a comment, or take a look at the second group of the example cases. #### Some examples: ```python approx_root(400) #=> 20 approx_root(401) #=> # smallest perfect square above 401 is 441 or 21 squared # greatest perfect square below 401 is 400 or 20 squared # difference between 441 and 400 is 41 # difference between 401 and 400 is 1 # answer is 20 + (1 / 41) which becomes 20.02, rounded to the nearest hundredth #...
def approx_root(n): base = int(n ** 0.5) diff_gn = n - base ** 2 diff_lg = base * 2 + 1 return round(base + diff_gn / diff_lg, 2)
python
train
qsol
codeparrot/apps
all
Solve in Python: Sereja has got an array, consisting of n integers, a_1, a_2, ..., a_{n}. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make v_{i}-th array element equal to x_{i}. In other words, perform the assignment a_{v}_{i} = x_{i}. Increase each array element by y_{i}. In other words, perform n assignments a_{i} = a_{i} + y_{i} (1 ≤ i ≤ n). Take a piece of paper and write out the q_{i}-th array element. That is, the element a_{q}_{i}. Help Sereja, complete all his operations. -----Input----- The first line contains integers n, m (1 ≤ n, m ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 3) that represents the operation type. If t_{i} = 1, then it is followed by two integers v_{i} and x_{i}, (1 ≤ v_{i} ≤ n, 1 ≤ x_{i} ≤ 10^9). If t_{i} = 2, then it is followed by integer y_{i} (1 ≤ y_{i} ≤ 10^4). And if t_{i} = 3, then it is followed by integer q_{i} (1 ≤ q_{i} ≤ n). -----Output----- For each third type operation print value a_{q}_{i}. Print the values in the order, in which the corresponding queries follow in the input. -----Examples----- Input 10 11 1 2 3 4 5 6 7 8 9 10 3 2 3 9 2 10 3 1 3 10 1 1 10 2 10 2 10 3 1 3 10 3 9 Output 2 9 11 20 30 40 39
import sys n,m=list(map(int,sys.stdin.readline().split())) L=list(map(int,sys.stdin.readline().split())) c=0 Ans="" for i in range(m): x=list(map(int,sys.stdin.readline().split())) if(x[0]==1): L[x[1]-1]=x[2]-c elif(x[0]==2): c+=x[1] else: Ans+=str(L[x[1]-1]+c)+"\n" sys.stdout.write(Ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks). The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not. Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university. Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home. Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair. -----Input----- The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university. The second line contains n numbers a_{i} (0 ≤ a_{i} ≤ 1). Number a_{i} equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a_1, a_2, ..., a_{n} are separated by spaces. -----Output----- Print a single number — the number of pairs during which Alena stays at the university. -----Examples----- Input 5 0 1 0 1 1 Output 4 Input 7 1 0 1 0 0 1...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re N = int(input()) S = input() S = S.replace(" ", "") S = S.strip("0") ret = 0 for seg in re.split("00+", S): ret += len(seg) print(ret)
python
test
qsol
codeparrot/apps
all
Solve in Python: -----Problem Statement----- Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following: the number of different objects with rang N = F(N) = A0 + A1 * N + A2 * N2 + A3 * N3. Now Chef wants to know how many different multisets of these objects exist such that sum of rangs of the objects in the multiset equals to S. You are given the coefficients in F(N) and the target sum S. Please, find the number of different multisets modulo 1,000,000,007. You should consider a multiset as an unordered sequence of integers. Two multisets are different if and only if there at least exists one element which occurs X times in the first multiset but Y times in the second one, where (X ≠ Y). -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains four integers A0, A1, A2, A3. The second line contains an integer S. -----Output----- For each test case, output a single line containing a single integer - the answer to the test case modulo 1,000,000,007. -----Constraints----- - 1 ≤ T ≤ 500 - 1 ≤ S ≤ 100 - 0 ≤ Ai ≤ 1000 - Sum of all S for all test cases is not greater than 500. It's guaranteed that at least one Ai is non-zero. -----Example----- Input: 4 1 0 0 0 1 1 0 0 0 3 0 1 0 0 2 2 3 1 4 10 Output: 1 3 3 213986343 -----Explanation----- Example case 2. In the second example function looks as follows F(N) = 1. So for each rang there is a single object of the rang. To get multiset with sum of rangs equal to 3, you can pick: three objects of rang 1, or one object of rang 1 and one of rang 2, or only one object of rang 3. Example case 3. In the third example function looks as follows F(N) = N. So, you have one distinct object of rang 1, two distinct objects of rang 2, three distinct objects of rang 3 and so on. To get multiset with sum of...
# cook your dish here import sys mod_val = 1000000007 rang = [0]*101 pow_cache = [0]*102 multisets = {} def mod_pow(base, pow): result = 1 while pow: if pow&1: result = (result*base) % mod_val base = (base*base) % mod_val pow = pow>>1 return result def precalculate(): for i in range(1, 102): pow_cache[i] = mod_pow(i, mod_val-2) def cal_recurse(i, target_sum): if target_sum == 0: return 1 if i>=target_sum: return 0 if (i, target_sum) in multisets: return multisets[(i, target_sum)] ans = cal_recurse(i+1, target_sum) max_pos = target_sum//(i+1) choose = rang[i+1]%mod_val for j in range(1, max_pos+1): temp = choose*cal_recurse(i+1, target_sum-j*(i+1)) # temp%=mod_val ans += temp ans %= mod_val choose *= rang[i+1]+j # choose %= mod_val choose *= pow_cache[j+1] choose %= mod_val multisets[i, target_sum] = ans return ans def calculate(target_sum, rang_index): populate(target_sum, rang_index) return cal_recurse(0, target_sum) def populate(target_sum, rang_i): for i in range(1, target_sum+1): rang[i] = rang_i[0] + (rang_i[1] + (rang_i[2] + rang_i[3]*i)*i)*i _test_cases = int(input()) precalculate() for _a_case in range(_test_cases): rang = [0]*101 multisets = {} _rang_index = [int(i) for i in input().split(' ')] _target_sum = int(input()) print(calculate(_target_sum, _rang_index))
python
train
qsol
codeparrot/apps
all
Solve in Python: Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 2. If any of the permutations is divisible by 2 then print 1 else print 0. -----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, $N$. -----Output:----- For each test case, output in a single line answer 1 or 0. -----Constraints----- - $1 \leq T \leq 10^6$ - $1 \leq N \leq 10^6$ -----Sample Input:----- 2 19 385 -----Sample Output:----- 0 1
for _ in range(int(input())): r=int(input()) while(r!=0): k=r%10 if(k%2==0): print("1") break r=r//10 else: print("0")
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc059/tasks/arc072_b: Alice and Brown loves games. Today, they will play the following game. In this game, there are two piles initially consisting of X and Y stones, respectively. Alice and Bob alternately perform the following operation, starting from Alice: - Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile. The player who becomes unable to perform the operation, loses the game. Given X and Y, determine the winner of the game, assuming that both players play optimally. -----Constraints----- - 0 ≤ X, Y ≤ 10^{18} -----Input----- Input is given from Standard Input in the following format: X Y -----Output----- Print the winner: either Alice or Brown. -----Sample Input----- 2 1 -----Sample Output----- Brown Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory. I tried it in Python, but could not do it. Can you solve it?
# 解説AC X,Y = map(int, input().split()) print("Alice" if abs(X - Y) > 1 else "Brown")
python
test
abovesol
codeparrot/apps
all
Solve in Python: For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}. Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i. Find the maximum possible value of M_1 + M_2 + \cdots + M_N. -----Constraints----- - N is an integer satisfying 1 \leq N \leq 10^9. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the maximum possible value of M_1 + M_2 + \cdots + M_N. -----Sample Input----- 2 -----Sample Output----- 1 When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.
n=int(input()) print((n*(n-1)//2))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.hackerrank.com/challenges/py-if-else/problem: =====Problem Statement===== Given an integer, n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20, print Weird If n is even and greater than 20, print Not Weird =====Input Format===== A single line containing a positive integer, n. =====Constraints===== 1≤n≤100 =====Output Format===== Print Weird if the number is weird. Otherwise, print Not Weird. I tried it in Python, but could not do it. Can you solve it?
def __starting_point(): n = int(input()) if n % 2 == 1 or 6 <= n <= 20: print("Weird") else: print("Not Weird") __starting_point()
python
test
abovesol
codeparrot/apps
all