source
stringclasses
3 values
instruction
stringlengths
23
3.97k
input
stringclasses
1 value
output
stringlengths
1
3.75k
MatrixStudio/Codeforces-Python-Submissions
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess». This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed...
```python import sys #sys.stdin = open("input.txt") #sys.stdout = open("output.txt", "w") tbl = [] for i in range(8): tbl.append(input()) bestW = 10 bestB = 10 #print(tbl) for i in range(8): for j in range(8): #print(i, j) if tbl[i][j] == 'W': ok = True for k in range(i): if tbl[k][j] != '.': ...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python n = int(input()) array = [] for x in range(0,n): lister = input().split() array.append(lister) sum1=0 sum2=0 sum3=0 for x in range(0,len(array)): sum1 = sum1 + int(array[x][0]) sum2 = sum2 + int(array[x][1]) sum3 = sum3 + int(array[x][2]) if sum1 == 0 and s...
MatrixStudio/Codeforces-Python-Submissions
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are *n* mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For tha...
```python #mounds = int(input()) #m = list(range(1,mounds+1)) #m1 = [1] #m.remove(1) #for i in range(1,len(m)+1): # if i%2==1: # m1.append(max(m)) # m.remove(max(m)) # else: # m1.append(min(m)) # m.remove(min(m)) #print(' '.join(map(str,m1))) # mounds = int(input()) if mo...
MatrixStudio/Codeforces-Python-Submissions
Anton likes to play chess, and so does his friend Danik. Once they have played *n* games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
```python while True: n=int(input()) ch=input() s=0 f=0 for i in range (len(ch)): if ch[i]=="A": s=s+1 if ch[i]=="D": f=f+1 if f+s==n and 1<=n<=100000: break if s>f: print("Anton") elif s<f: print("Danik") else: print("...
MatrixStudio/Codeforces-Python-Submissions
For a given positive integer *n* denote its *k*-rounding as the minimum positive integer *x*, such that *x* ends with *k* or more zeros in base 10 and is divisible by *n*. For example, 4-rounding of 375 is 375·80<==<=30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375. W...
```python from fractions import gcd n, k = map (int, input ().split ()) print (n * (10 ** k) // gcd(n, 10 ** k)) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarpus has an array, consisting of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array *a**i...
```python i=int(input()) l=list(map(int,input().split())) if sum(l)%i==0: print(i) else: print(i-1) ```
MatrixStudio/Codeforces-Python-Submissions
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
```python x = input() c = input() k = len(x) v = len(c) flag = 'YES' if k != v: flag = 'NO' else: for i in range(k): if x[i] != c[k - 1 - i]: flag = 'NO' print(flag) ```
MatrixStudio/Codeforces-Python-Submissions
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1<=\leq<=l<=\leq<=r<=\leq<=|s|$) of a string $s<==<=s_{1}s_{2}...
```python s = input() if s!=s[:: -1]: maximo = len(s) elif len(set(s))<2: maximo = 0 else: maximo = len(s)-1 print(maximo) ```
MatrixStudio/Codeforces-Python-Submissions
You are given a non-empty string *s* consisting of lowercase English letters. You have to pick exactly one non-empty substring of *s* and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'. What is ...
```python str1 = input() str2 = '' for i in range(len(str1)): if str1[i] != 'a': str2 += chr(ord(str1[i]) - 1) else: str2 += 'z' print(str2) ```
MatrixStudio/Codeforces-Python-Submissions
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), *s* and *t*. You need to transform word *s* into word *t*". The task looked simple to the guys because they know th...
```python from collections import Counter s = input() t = input() T = Counter(t) S = Counter(s) yes = True for i in T.items(): key, val = i[0], i[1] if(S[key] < val): yes = False if(yes): # array -> just a permutation ok = True for i in S.items(): key, val = i[0], i[1] ...
MatrixStudio/Codeforces-Python-Submissions
Andrew and Eugene are playing a game. Initially, Andrew has string *s*, consisting of digits. Eugene sends Andrew multiple queries of type "*d**i*<=→<=*t**i*", that means "replace all digits *d**i* in string *s* with substrings equal to *t**i*". For example, if *s*<==<=123123, then query "2<=→<=00" transforms *s* to 10...
```python n = input() k = int(input()) for i in range(k): s = input().split('->') n = n.replace(s[0], s[1]) print(int(n) % 1000000007) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python str = input() up=0 for i in str: if i.isupper(): up += 1 if up>len(str): str=str.upper() else: str=str.lower() print(str) ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string *s* consisting of *n* lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the...
```python t = int(input()) t = input() i = 0 while i < len(t)-2: if t[i] == "o" and t[i+1] == "g" and t[i+2] == "o": j = i+3 t = t[:i] + "***" + t[i+3:] while j < len(t)-1: if t[j] + t[j+1] == "go": t = t[:j] + "**" + t[j+2:] else: break i = j continue else: i = i + 1 print...
MatrixStudio/Codeforces-Python-Submissions
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color...
```python m,n=map(int,input().split()) L=[] for i in range(m): l=list(map(int,input().split())) L.append(l) ans=[0 for i in range(m)] for i in range(n): free=0 for j in range(m): start=max(free,ans[j]) ans[j]=start+L[j][i] free=ans[j] for i in range(m): print(...
MatrixStudio/Codeforces-Python-Submissions
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called *x*. Also, there are two operations: - Operation ++ increases the value of variable *x* by 1. - Operation -- decreases the value of variable *x* by...
```python n = int(input()) cou = 0 for i in range(n): x = input() if '--' in x: cou -= 1 else: cou += 1 print(cou) ```
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ...
```python n=int(input()) if n%2==0: print(n//2,'\n'+'2 '*(n//2)) else: print(n//2) print(3,'2 '*(n//2-1)) ```
MatrixStudio/Codeforces-Python-Submissions
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the *expose* procedure. Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agre...
```python l, r, k = map (int, input().split()) cnt = 0 for i in range (64) : p = pow (k, i) if p >= l and p <= r : cnt += 1 print (p, end = ' '); if p >= r : break; if cnt == 0 : print (-1) ```
MatrixStudio/Codeforces-Python-Submissions
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a *d*1 meter long road between his house and the first shop and a *d*2 meter long road between his house and the second shop. Also, there is a road of len...
```python d1, d2, d3 = map(int, input().split()) first = (d1 * 2) + (d2 * 2) second = d1 + d3 + d2 third = d3 + d2 + d3 + d2 print(min(first, second, third)) ```
MatrixStudio/Codeforces-Python-Submissions
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has *n* instruments, it takes *a**i* days to learn *i*-th instrument. Being busy, Amr dedicated *k* days to learn how to play the maximum possible number of instruments. Amr asked for ...
```python n,k = map(int, input().split()) arr = sorted(list(zip(range(n), (map(int, input().split())))), key = lambda x: x[1]) ans = [] i = 0 while k-arr[i][1] >=0: k-=arr[i][1] ans.append(arr[i][0]+1) i+=1 if i == n: break print(len(ans)) print(*ans) ```
MatrixStudio/Codeforces-Python-Submissions
One day shooshuns found a sequence of *n* integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes *k*-th in the current sequence and add the same number to the end of the sequence; 1. Delete the first number of the current ...
```python #!/usr/bin/python3 def readln(): return tuple(map(int, input().split())) n, k = readln() a = readln() if len(set(a[k - 1:])) == 1: ans = 0 i = k - 1 while i >= 0 and a[i] == a[k - 1]: i -= 1 ans += 1 print(ans) else: print(-1) ```
MatrixStudio/Codeforces-Python-Submissions
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
```python n = int(input()) usernames = {} for _ in range(n): name = input() if name in usernames: prompt_num = usernames[name] + 1 prompt_name = f"{name}{prompt_num}" usernames[name] = prompt_num print(prompt_name) else: usernames[name] = 0 print("OK" ) ...
MatrixStudio/Codeforces-Python-Submissions
There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \le k \le n$) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES"...
```python n,q=list(map(int,input().split())) k=list(map(int,input().split())) p= list(dict.fromkeys(k)) u="" for x in p: for t in k: if x==t: u+=str(k.index(x)) break list=[] j=0 my="" for i in u: j=int(i)+1 list.append(j) if len(p)==q: print("YES") ...
MatrixStudio/Codeforces-Python-Submissions
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)). Max starts to type all the values from *a* to *b*. After typi...
```python def f(x): return 49*int(x)*10**(int(x)-1) def g(y): segs=[6,2,5,5,4,5,6,3,7,6] return sum(segs[1:int(y)]) def h(z): segs=[6,2,5,5,4,5,6,3,7,6] return segs[int(z)] def u(aa,bb): if len(aa)-1==bb: return -1 else: return int(aa[bb+1:len(aa)]) def s...
MatrixStudio/Codeforces-Python-Submissions
One day *n* friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the *i*-th of them occupies the rectangl...
```python n = int(input()) width = [] heigth = [] sumw = 0 h1, h2 = 0, 0 for i in range(n): w, h = map(int, input().split()) width.append(w) heigth.append(h) sumw += w if h > h1: h2 = h1 h1 = h elif h > h2: h2 = h for i in range(n): if heigth[i] != h1:...
MatrixStudio/Codeforces-Python-Submissions
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
```python x=y=z = 0 for x in range(int(input())): x1,y1,z1= map(int,input().split()) x+=x1 y+=y1 z+=z1 if x==y==z ==0: print("YES") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* peopl...
```python t=input() h=0 while int(t)>0: t=int(t)-1 x,y=input().split() if int(y)-int(x)>=2: h=int(h)+1 print(int(h)) ```
MatrixStudio/Codeforces-Python-Submissions
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed *x* in the absolute value. Natasha doesn't like when Vanya spends a long time p...
```python import math m,n=map(int,input().split()) l=list(map(int,input().split())) print(math.ceil(abs(sum(l))/n)) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python str1=str(input()) cap=0 smol=0 for i in str1: if ord(i)>=65 and ord(i)<=96: cap+=1 else: smol+=1 if smol<cap: print(str1.upper()) else: print(str1.lower()) ```
MatrixStudio/Codeforces-Python-Submissions
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
```python t = int(input()) ans = 0 for x in range(1, t+1): u = list(map(int, input().split())) sum = u[0]+u[1]+u[2] if sum >= 2 : ans = ans+1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number *a*, the second player wrote number *b*. How many w...
```python from math import * a,b=[int(x) for x in input().split()] res1,res2,res3=0,0,0 if a==b: print(0,6,0) else: if (a+b)%2==0: res2=1 else: res2=0 for i in range(1,7): if int(fabs(a-i))<int(fabs(b-i)): res1+=1 print(res1,res2,6-res1-res2) ```
MatrixStudio/Codeforces-Python-Submissions
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom...
```python def solution(n,k,g): s = set(g) prefix =[0]*(n) for a in s : for i in range(g.find(a),g.rfind(a)+1): prefix[i]+=1 if max(prefix) > k : return 'YES' else: return "NO" if __name__ == "__main__": n,k = map(int,input().split()) g = input() print(solution(n,k,g)) ``...
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python n, m, a = [input() for _ in range(3)] n += n%a m += m%a n = n // a m = m // a print(n*m) ```
MatrixStudio/Codeforces-Python-Submissions
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
```python # 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) # 3 - Load images player = pygame.image.load("resources/images/dude.png") # 4 - keep looping through while 1: # 5 - clear the s...
MatrixStudio/Codeforces-Python-Submissions
Let's denote a function You are given an array *a* consisting of *n* integers. You have to calculate the sum of *d*(*a**i*,<=*a**j*) over all pairs (*i*,<=*j*) such that 1<=≤<=*i*<=≤<=*j*<=≤<=*n*.
```python n = int(input()) a = list(map(int, input().split())) ans = 0 mm = dict((a[i], 0) for i in range(n)) for i in range(n): ans += a[i] * (i - (n - 1 - i)) mm[a[i]] += 1 ans -= mm.get(a[i] - 1, 0) ans += mm.get(a[i] + 1, 0) print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis...
```python n = int(input()) word = input() numbers = [int(i) for i in input().split()] if word.count("R")==0: print(-1) else: pos = word.find("R") flag = False minimum = 10**9 while pos!=-1: if pos+1>=len(word): break if word[pos+1]!="L": pos = wor...
MatrixStudio/Codeforces-Python-Submissions
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') class BIT_MIN(object): __slots__ = ['nodes', 'size'] def __init__(self, size: int): self.nodes = [10**7]*(size+1) self.size = size+1 def update(self,...
MatrixStudio/Codeforces-Python-Submissions
At regular competition Vladik and Valera won *a* and *b* candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving eac...
```python a = list(map(int, input().split())) d, i = 1, 0 while a[i] >= d: a[i] -= d i = (i + 1) % 2 d += 1 if i == 0: print("Vladik") else: print("Valera") ```
MatrixStudio/Codeforces-Python-Submissions
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers *p*1, *p*2, ..., *p**n*. Lets write down some magic formulas: Here, "mod" means the operation of taking the residue after dividing. The expression means applying ...
```python import math n=int(input('')) P=list(map(int,input('').split())) Q=[] for i in range(n): z=P[i] for j in range(n): z^=((i+1)%(j+1)) if i==0: rez=z; else: rez^=z; print(rez) ``...
MatrixStudio/Codeforces-Python-Submissions
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn ...
```python n = int(input()) x = input() y = input() c = 0 for i in range(n): c+=min(abs(int(x[i])-int(y[i])),abs(10-max(int(x[i]),int(y[i])))+min(int(x[i]),int(y[i]))) print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at t...
```python n, x0 = map(int, input().split()) m = -1 M = float('inf') for i in range(n): a, b = map(int, input().split()) if a > b: a, b = b, a m = max(a, m) M = min(b, M) if m > M: print(-1) exit() if x0 > M: print(x0-M) elif m <= x0 <= M: print(0) else: p...
MatrixStudio/Codeforces-Python-Submissions
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all *n* dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirit...
```python #Coder_1_neel a,s=map(int,input().split()) con=0 for i in range(s): x,y=map(int,input().split()) if(x<=a): con+=1 a+=y else: print("NO") break if con==s: print("YES") ```
MatrixStudio/Codeforces-Python-Submissions
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*. What is the least number of flagstones needed to pave the...
```python while True : n=int(input(" n= ")) if 1<=n<=1000000000: break else: continue while True : m=int(input(" m= ")) if 1<=m<=1000000000: break else: continue while True : a=int(input(" a= ")) if 1<=a<=1000000000: break else:...
MatrixStudio/Codeforces-Python-Submissions
A coordinate line has *n* segments, the *i*-th segment starts at the position *l**i* and ends at the position *r**i*. We will denote such a segment as [*l**i*,<=*r**i*]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all oth...
```python n = int(input()) s = [] for i in range (n): s.append(list(map(int, input().split()))) def big_segment (a): index = -1 lowest = a[0][0] highest = a[0][1] if lowest != highest: index = 1 for i in range (len(a)): if i > 0: if a[i][0]<= lowest and a[i][1] >= highest: ...
MatrixStudio/Codeforces-Python-Submissions
In this problem at each moment you have a set of intervals. You can move from interval (*a*,<=*b*) from our set to interval (*c*,<=*d*) from our set if and only if *c*<=&lt;<=*a*<=&lt;<=*d* or *c*<=&lt;<=*b*<=&lt;<=*d*. Also there is a path from interval *I*1 from our set to interval *I*2 from our set if there is a seq...
```python queries = int(input()) output = [] intervals = [] dic = {} def dfs(cur, target): if not cur or cur not in dic: return False if cur == target: return True temp = dic[cur] for edge in temp: if edge == target: return True dfs(edge, target) return Fa...
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python n=int(input()) arr=[] for i in range(n): word=input() arr.append(word) for item in arr: if len(item)<10: print(item) else: print(item[0],len(item)-2,item[len(item)-1],sep='') ```
MatrixStudio/Codeforces-Python-Submissions
Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible. String *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
```python def main(): line = input() k = int(input()) start_number_dif = len(set(line)) av_for_change = len(line) - start_number_dif if k - start_number_dif > av_for_change: print("impossible") else: print(k - start_number_dif) if __name__ == "__main__": main() ``...
MatrixStudio/Codeforces-Python-Submissions
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius. He has a *n*<=×<=*n* chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by b...
```python n=int(input()) mat=[] for i in range(n): mat.append([int(i) for i in input().split()]) pri=[0]*(2*n) sec=[0]*(2*n) for i in range(n): for j in range(n): pri[i-j+n]+=mat[i][j] sec[i+j]+=mat[i][j] resw=0 resb=0 indw=[] indb=[] for i in range(n): for j in range(n): ...
MatrixStudio/Codeforces-Python-Submissions
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer *n* that for each positive integer *m* number *n*·*m*<=+<=1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is inc...
```python nr = int(input()) m = 1 case = True while case: ourNumber = (nr * m) + 1 for x in range(ourNumber - 1, 1, -1): if ourNumber % x == 0: case = False if case: m += 1 print(m) ```
MatrixStudio/Codeforces-Python-Submissions
Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them wi...
```python bars = int(input()) times = input().split() for i in range(len(times)): times[i] = int(times[i]) a_começou = False b_começou = False a = 0 b = 0 atu_alice = 0 atu_bob = -1 tempo = 0 while atu_alice != len(times)+atu_bob: tempo = tempo + 1 if tempo == times[atu_alice]: atu_a...
MatrixStudio/Codeforces-Python-Submissions
Imagine a city with *n* horizontal streets crossing *m* vertical streets, forming an (*n*<=-<=1)<=×<=(*m*<=-<=1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to wes...
```python n, m = list(map(int, input().split())) h = input() v = input() if '<' in h and '>' in h and 'v' in v and '^' in v: if (h[0] == '<' and v[0] == '^') or (h[-1] == '>' and v[-1] == 'v') or (h[0] == '>' and v[-1] == '^') or (h[-1] == 'v' and v[0] == 'v'): print('NO') else: print('YES') els...
MatrixStudio/Codeforces-Python-Submissions
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of *n* integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly *k* changes of signs of s...
```python n, k = list(map(int, input().split())) arr = list(map(int, input().split())) arr.sort() i = 0 while k > 0: arr[i] = arr[i] * (-1) k -= 1 i += 1 print(sum(arr)) ```
MatrixStudio/Codeforces-Python-Submissions
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are *n* books on sale from one of *m* genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find th...
```python import sys from collections import Counter n, m = map(int, input().split()) cnt = Counter(map(int, input().split())) ans = 0 for k, v in cnt.items(): n -= v ans += v * n print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an *a*1<=×<=*b*1 rectangle, the paintings have shape of a *a*2<=×<=*b*2 and *a*3<=×<=*b*3 rec...
```python def check( x, y, a1, b1, a2, b2): a = a1 + a2 b = max(b1, b2) if((a <= x and b <= y) or (a <= y and b <= x)): return 1 b = b1 + b2 a = max (a1, a2); if((a<=x and b<=y) or (a<=y and b<=x)): return 1 return 0 a = list(map(int, input().split(" "))) ...
MatrixStudio/Codeforces-Python-Submissions
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has *n* lanterns and Big B...
```python n,m=map(int,input().split(' ')) a=list(map(int,input().split(' '))) b=list(map(int,input().split(' '))) cmp=a[0]*b[0] idx=0 for i in range(n): for j in range(m): if(a[i]*b[j]>=cmp): cmp=a[i]*b[j] idx=i ans=int(-1*1e18) for i in range(n): for j in range(m): ...
MatrixStudio/Codeforces-Python-Submissions
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only. Waking up in the ...
```python n,k = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) def f(x): s = 0 for i in range(n): s += max(0,x*a[i]-b[i]) return s ans = 0 lo = 0 hi = 10*18 while lo <= hi: mid = (lo+hi)//2 if f(mid)<=k: ans = mid ...
MatrixStudio/Codeforces-Python-Submissions
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
```python test=True n=input() i=0 while test and i<len(n)-1: if n[i]in["a","o","u","i","e"] and (not(n[i+1]in["a","o","u","i","e","n"])) or (n[i]in["a","o","u","i","e","n"] and (n[i+1]in["a","o","u","i","e","n"])) : print(i) i=i+1 el...
MatrixStudio/Codeforces-Python-Submissions
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
```python n=int(input()) u=[] for i in range(n): a,b=map(int,input().split()) u.append((a,b)) c=0 for i in range(n): for j in range(n): if(i!=j and u[i][0]==u[j][1]): c+=1 print(c) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, ...
```python s=input() j=0 x='hello' for i in range (len(s)-1): if(x[j]==s[i]): j=j+1 if j==5: print('YES') else: print('NO') ```
MatrixStudio/Codeforces-Python-Submissions
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer *k* and a sequence *a*, consisting of *n* integers. He wants to know how many subsequences of length three can be selected from *a*, so that they form a geo...
```python import sys input = sys.stdin.readline n,k = map(int,input().split()) a = list(map(int,input().split())) left = dict() right = dict() for i in range(n): if a[i] in right: right[a[i]]+=1 else: right.update({a[i]:1}) left.update({a[i]:0}) ans = 0 for i in range(n): ...
MatrixStudio/Codeforces-Python-Submissions
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
```python t, s, ans = input(), 1, '' for i in range(1, len(t)): if t[i] == t[i - 1]: s += 1 else: if s % 2: ans += t[i - 1] s = 1 print(ans) ```
MatrixStudio/Codeforces-Python-Submissions
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are *n* schools numerated from 1 to *n*. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools *i* an...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- n=int(input()) print(int(n/2)-1) ```
MatrixStudio/Codeforces-Python-Submissions
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows *n* coffee ...
```python n, k, q = [int(x) for x in input().split()] seg = [0] * 200010 par = [0] * 200010 for i in range(n): li, ri = [int(x) for x in input().split()] seg[li] += 1 seg[ri + 1] -= 1 s = 0 for i in range(1, 200001): s += seg[i] seg[i] = s par[i] = par[i - 1] + (1 if s >= k else 0) f...
MatrixStudio/Codeforces-Python-Submissions
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers ...
```python a,b=map(int,input().split()) #m=list(map(int,input().split())) #k=0 #for i in range(a): # if m[i]>=m[b-1] and m[i]!=0: # k += 1 # else: break if b%2==0: a=(b // 2)*a else: a=(b//2)*a+(a//2) print(a) ```
MatrixStudio/Codeforces-Python-Submissions
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people" Igor just c...
```python # Time complexity: O(1) # Space complexity: O(m) # Rationale: Since there are at most 5 points, we can just use brute force to loop # through relations among three points. If they are the same, then "win". m = int(input()) relation = [[] for _ in range(6)] # Builds the relation graph without duplicates. for ...
MatrixStudio/Codeforces-Python-Submissions
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of *n* painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color...
```python m, n = [int(x) for x in input().split()] t = [[0]*n for _ in range(m)] for i in range(m): t[i] = [int(x) for x in input().split()] dp = [[0]*n for _ in range(m)] for i in range(m): for j in range(n): if i > 0: dp[i][j] = dp[i-1][j] if j > 0: dp[i][...
MatrixStudio/Codeforces-Python-Submissions
Petya recieved a gift of a string *s* with length up to 105 characters for his birthday. He took two more empty strings *t* and *u* and decided to play a game. This game has two possible moves: - Extract the first character of *s* and append *t* with this character. - Extract the last character of *t* and append *u*...
```python def solve(): s=input() t=list(s).sort() print("".join(t)) solve() ```
MatrixStudio/Codeforces-Python-Submissions
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python s=input() if(len(s)<=10): print(s) else: s=list(s) a=s[0] b=s[-1] del s[0] del s[-1] print(a,len(s),b) ```
MatrixStudio/Codeforces-Python-Submissions
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards. Rules of this game are simple: each player bring his favourite *n*-digit credit card. Then both players name the digits written on the...
```python n = int(input()) a = list(map(int, input())) b = list(map(int, input())) a.sort() b.sort() j = n-1 ans1 = 0 ans2 = 0 for i in range(n): if a[i] > b[i]: ans1 += 1 if a[i] < b[j]: ans2 += 1 j -=1 ```
MatrixStudio/Codeforces-Python-Submissions
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom...
```python import sys n,k=map(int,input().split()) s=input() lp={} act=set() for i in range(n): lp[s[i]]=i for i in range(n): act.add(s[i]) if len(act)>k: print("YES") sys.exit() elif lp[s[i]]==i: act.remove(s[i]) print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are *n* jars of honey lined up in front of Winnie...
```python n,k = [int(i) for i in input().split(' ')] T = [int(i) for i in input().split(' ')] func = lambda x: (x>k)*k + (x<=k)*x T1 = map(func,T) print(sum(list(T1))) ```
MatrixStudio/Codeforces-Python-Submissions
A string is called a *k*-string if it can be represented as *k* concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline k = int(input()) cnt = [0] * 26 s = list(input().rstrip()) for i in s: cnt[i - 97] += 1 ok = 1 for i in cnt: if i % k: ok = 0 break if not ok: ans = -1 else: x = [] for i in ra...
MatrixStudio/Codeforces-Python-Submissions
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
```python user_name=input() distinct_chars=set(user_name) if len(distinct_chars)%2==0: print("CHAT WITH HER!") else: print("IGNORE HIM!") ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
```python a = input() b = 1 d = "NO" for i in range(len(a)-1): if a[i] == a[i+1]: b+=1 if b >= 7: d = "YES" print(d) ```
MatrixStudio/Codeforces-Python-Submissions
There are *n* people and *k* keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine th...
```python print("_RANDOM_GUESS_1690486862.7831087")# 1690486862.7831285 ```
MatrixStudio/Codeforces-Python-Submissions
Fafa owns a company that works on huge projects. There are *n* employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best *l* em...
```python from math import ceil def f(val, ret = []): for i in range(2, ceil(val/2)): while val%i == 0: val //= i ret += [i] if len(set(ret))==1: return 2 return len(ret)+1 print(f(int(input()))) ```
MatrixStudio/Codeforces-Python-Submissions
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer ...
```python import collections import math def function(): n = int(input()) res = [] p = 0 if n % 2 == 0: p = n//2 res = ['2' for _ in range(p)] elif n % 3 == 0 or n % 5 == 0: n = n - 3 p = (n//2) res = ['2' for _ in range(p)] res.append...
MatrixStudio/Codeforces-Python-Submissions
Duff is addicted to meat! Malek wants to keep her happy for *n* days. In order to be happy in *i*-th day, she needs to eat exactly *a**i* kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In *i*-th day, they sell meat for *p**i* dollars per kilogram. Malek knows all numbers ...
```python a=int(input()) ans=[] for i in range(a): x,y=map(int,input().split()) ans.append([x,y]) total=0 total+=ans[0][0]*ans[0][1] mini=ans[0][1] for i in range(1,len(ans)): mini=min(mini,ans[i][1]) total+=mini*ans[i][0] print(total) ```
MatrixStudio/Codeforces-Python-Submissions
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choos...
```python row,lie,total = [ int(_) for _ in input().split() ] s = [] def check(x,i): m = 0 if [x[0]-1,x[1]-1] in s and [x[0],x[1]-1] in s and [x[0]-1,x[1]] in s: m += 1 if [x[0]-1,x[1]+1] in s and [x[0],x[1]+1] in s and [x[0]-1,x[1]] in s: m += 1 if [x[0]+1,x[1]+1] in s and [x[...
MatrixStudio/Codeforces-Python-Submissions
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into *a* pieces, and the second one — into *b* pieces. Ivan knows that there will be *n* people at the celebration (including himself), so Ivan has set ...
```python n,a,b=input().split() a=int(a) b=int(b) n=int(n) l=[] for i in range(1,n-1): num=min(a/i,b/(n-i)) l.append(num) l.sort() print(int(l[-1])) ```
MatrixStudio/Codeforces-Python-Submissions
We had a string *s* consisting of *n* lowercase Latin letters. We made *k* copies of this string, thus obtaining *k* identical strings *s*1,<=*s*2,<=...,<=*s**k*. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the s...
```python #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> using namespace std; using ll = long long; const int INF = 1e9; const ll inf = 1LL<<62; template<int MOD> struct ModInt { static const int Mod = MOD; unsigned x; ModInt() : x(0) ...
MatrixStudio/Codeforces-Python-Submissions
Vlad likes to eat in cafes very much. During his life, he has visited cafes *n* times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes...
```python n = int(input()) a = list(map(int,input().split())) for i in range(n): if a.count(a[i])>1: a[i] = - 100000000000000000 else: print(a[i]) exit() ```
MatrixStudio/Codeforces-Python-Submissions
Little Artem is given a graph, constructed as follows: start with some *k*-clique, then add new vertices one by one, connecting them to *k* already existing vertices that form a *k*-clique. Artem wants to count the number of spanning trees in this graph modulo 109<=+<=7.
```python print("_RANDOM_GUESS_1692206826.8607752")# 1692206826.860792 ```
MatrixStudio/Codeforces-Python-Submissions
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
```python n=int(input()) s=input() f1,f2=1,1 for i in range(n): if s[i] in "12356890": f1=0 if f1: if s[:n//2].count("4")==s[n//2:].count("4") and s[:n//2].count("7")==s[n//2:].count("7"): print("YES") else: print("NO") else: print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
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).
```python s = input() ind1 = s.find("AB") ind2 = s.find("BA", ind1+(ind1>=0)*2) if not(ind1 == -1 or ind2 == -1): print("YES") quit() ind1 = s.find("BA") ind2 = s.find("AB", ind1+(ind1>=0)*2) if not(ind1 == -1 or ind2 == -1): print("YES") quit() print("NO") ```
MatrixStudio/Codeforces-Python-Submissions
The Little Elephant has an integer *a*, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number *a* fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number *a* in the binary record. At that a new number appears. It consis...
```python s = input() n = s.index('0') print(s[:n]+s[n+1:]) ```
MatrixStudio/Codeforces-Python-Submissions
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans...
```python # import sys # sys.stdin=open("input1.in","r") # sys.stdout=open("output2.out","w") L=list(input()) for i in range(len(L)-1,0,-1): if L[i]!='?' and L[i]!=' ': if L[i]=='A' or L[i]=='E' or L[i]=='O' or L[i]=='Y' or L[i]=='U' or L[i]=='a' or L[i]=='e' and L[i]=='y' or L[i]=='i' or L[i]=='u': print(...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef has a recipe book. He wishes to read it completely as soon as possible so that he could try to cook the dishes mentioned in the book. The pages of the book are numbered $1$ through $N$. Over a series of days, Chef wants to read each page. O...
```python def ugcd(n): ans = [[1]] if(n==1): return ans elif(n%2==1): ans = [[1, 2, n]] else: ans = [[1, 2]] for k in range(1, int(n//2)): ans.append([k*2+1, k*2+2]) return ans t = int(input()) for i in range(t): n = int(input()) s = (ugcd(n)) print(len(s)) for j in r...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia. The game is played by two people taking turns, where Mr. Cha...
```python from sys import stdin, stdout from collections import defaultdict input = stdin.readline for _ in range(int(input())): n = int(input()) chanek = 0 flag = 1 while n>0: if n%4==0 and n!=4: if flag: chanek += 1 n-=1 flag = 0 else: n-=1 flag = 1 elif n%2: if flag: chanek +...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole n ordered piles of worms such that i-th pile contains a_{i} worms. He labeled all these worms with consecutive integers: worms in first pile ...
```python n=int(input()) a=list(map(int,input().split())) k=[] for i in range(n): for j in range(a[i]): k.append(i+1) m=int(input()) b=list(map(int,input().split())) for i in b: print(k[i-1]) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a_1, a_2, ..., a_{n}. T...
```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = [0] * n stk = [0] for i in range(1, n): while len(stk) > 1 and c[stk[1]] - c[stk[0]] <= a[i] * (b[stk[0]] - b[stk[1]]): del stk[0] c[i] = c[stk[0]] + a[i] * b[stk[0]] while len(stk) > 1...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations: U — move from $(x, y)$ to $(x, y + 1)$; D — move from $(x, y)$ to $(x, y - 1)$; ...
```python # import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try : #raise ModuleNotFoundError import numpy def dprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) dprint('debug mode...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. Y...
```python q = int(input()) def full_way(u): res = set() while u >= 1: res.add(u) u //= 2 return res def get_way(u, v): res1 = full_way(u) res2 = full_way(v) m = max(res1 & res2) res = set() for x in res1 | res2: if x > m: res.add(x) retur...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Once upon a time, a king and a few of his soldiers were caught by an enemy king in a war. He puts them in a circle. The first man in the circle has to kill the second man, the third man has to kill the fourth, fifth man to kill the sixth and ...
```python n=int(input()) arr=[] for i in range(1,n+1): arr.append(i) c=0 i=0 f=0; while(c<n-1): if(arr[i%n]!=-1 and f): arr[i%n]=-1 c=c+1 f=0 if(arr[i%n]!=-1): f=1 i=i+1 for i in range(0,n): if(arr[i]!=-1): ans=arr[i] break; print(ans) ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam. All the $2n$ jars are arranged in a row. The stairs to the basement are exact...
```python for tcase in range(int(input())): n=int(input()) ls = list(map(int, input().split())) oneneed = 2*(n - ls.count(1)) ldct = {0:0} ctr = 0 eaten = 0 for i in range(n-1,-1,-1): eaten += 1 ctr += (1 if ls[i] == 2 else -1) if ctr not in ldct: ldct[ctr...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Lots of geeky customers visit our chef's restaurant everyday. So, when asked to fill the feedback form, these customers represent the feedback using a binary string (i.e a string that contains only characters '0' and '1'. Now since chef is not...
```python # cook your dish here t=int(input()) for i in range(t): s=input() fl=-1 n=len(s) for i in range(n-2): if(s[i:i+3]=="010" or s[i:i+3]=="101"): fl=0 print("Good") break if(fl==-1): print("Bad") ```
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Let's denote as $\text{popcount}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤...
```python def popcount(n): res = 0 while n > 0: res += n & 1 n >>= 2 def A(l, r): r += 1 t = 1 << 64 while t & (l ^ r) == 0: t >>= 1 res = l | (t - 1) #print(t, res) return res def __starting_point(): """assert(A(1, 2) == 1) assert(A(2, 4) == 3) assert(A(1, 10) == 7) assert(A(13, 13) == 13) assert(...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: Chef is going to organize a hill jumping competition and he is going to be one of the judges in it. In this competition there are N hills in a row, and the initial height of i-th hill is Ai. Participants are required to demonstrate their jumping...
```python n,q=list(map(int,input().split())) final=[] height=list(map(int,input().split())) for k in range(0,q): b=input().split() if int(b[0])==1: step=int(b[1])-1 for k in range(0,int(b[2])): temp = 0 j=1 while j in range(1,101) and temp==0 and step+j<n: if height[step+j]>height[step]: step=st...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: People in Karunanagar are infected with Coronavirus. To understand the spread of disease and help contain it as early as possible, Chef wants to analyze the situation in the town. Therefore, he does the following: - Chef represents the populatio...
```python # cook your dish here T = int(input()) for i in range(T): N,data,D,People = int(input()),list(map(int,list(input()))),int(input()),list(map(int,input().split())) data.insert(0,"|"),data.append("|") infected = [] for i in range(1,N+1): if(data[i]==1): infected.append(i...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: This problem is a version of problem D from the same contest with some additional constraints and tasks. There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$). You have to prepare a gift using some of...
```python # @author import sys class GCandyBoxHardVersion: def solve(self): q = int(input()) for _ in range(q): n = int(input()) a = [0] * n f = [0] * n for i in range(n): a[i], f[i] = [int(_) for _ in input().split()] d...
open-r1/verifiable-coding-problems-python-10k
Solve the following coding problem using the programming language python: You visit a doctor on a date given in the format $yyyy:mm:dd$. Your doctor suggests you to take pills every alternate day starting from that day. You being a forgetful person are pretty sure won’t be able to remember the last day you took the me...
```python t=int(input()) li1=[31,29,31,30,31,30,31,31,30,31,30,31] li2=[31,28,31,30,31,30,31,31,30,31,30,31] for z in range(t): y,m,d=list(map(int,input().split(':'))) if y%4 == 0: if y%100 == 0: if y%400 == 0: li=li1 else: li=li2 else: li=li1 else: li=li2 c=0 if d%2 == 0: while d%2 == 0: ...