problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers...
1
n = int(raw_input()) for i in range(1, n + 1): if (i * (i + 1)) / 2 == n: print 'YES' break else: print 'NO'
ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then ever...
1
n,k=map(int, raw_input().split()) ls=map(int, raw_input().split()) prev=0 cnt=0 for x in ls: if x-prev>k: cnt=0 cnt+=1 prev=x print cnt
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: 1. dr(n) = S(n), if S(n) < 10; 2. dr(n) = dr( S(n) ), i...
1
print [(k==0 and n>1) and 'No solution' or str(k)+'0'*(n-1) for n,k in [[int(c) for c in raw_input().split()]]][0]
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,...
1
n,m,k=map(int,raw_input().split()) M=10**9+9 x=max(n/k-n+m,0) a=k*2*(pow(2,x,M) - 1) print (a + m - k*x +M )%M
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t...
3
a,b=map(int,input().split()) ans=0 while a>0 and b>0: if a>b: ans+=a//b a%=b else: ans+=b//a b%=a print(ans)
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
# cook your dish here for _ in range(int(input())): c,d=map(int,input().split()) if (c==d): print(0) elif d-c>0: if(d-c)%2==0: print(2) else: print(1) elif d-c<0: if(d-c)%2==0: print(1) else: print(2)
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
x=input() if len(x)==1 and x.islower(): print(x.upper()) elif x.isupper(): print(x.lower()) elif x[0].islower and x[1:].isupper(): print(x[0].upper()+x[1:].lower()) else: print(x)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
z=str(input()).lower() arr=[] for i in range(len(z)) : if (z[i]!="a" and z[i]!="o" and z[i]!="y" and z[i]!="e" and z[i]!="u" and z[i]!="i"): arr.append(".") arr.append(z[i]) for i in range(len(arr)): print(arr[i],end="")
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
x,y=[int(i) for i in input().split()] p=[] for i in range(x): o=[] if i%2==0: for i in range(y): o.append('#') p.append(o) else: if (i+1)%4==0: o.append('#') for i in range(y-1): o.append('.') p.append(o) else: ...
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...
3
d1 = '0000000' d2 = '1111111' s = input() if d1 in s or d2 in s: print("YES") else: print("NO")
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 Square? It'...
1
# 1A.py a = map(int,raw_input().split()) l,b,s = a[0],a[1],a[2] print(((l+s-1)/s)*((b+s-1)/s))
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
3
import sys Input = sys.stdin.readline N = int(Input()) Segments = list(sorted(map(int, Input().split()))) for i in range(N - 2): if (Segments[i] + Segments[i + 1]) > Segments[i + 2]: exit(print('YES')) print('NO') # گرمای دستانت را میخواهم # کنار شیرین زبونی های زهرا کوچولو
<image> One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the l...
1
n, m = map(int, raw_input().split()) maxR, minL = 0, n+1 for k in range(m): s,d =raw_input().rsplit(None, 1) if 'r' in s: maxR = max(maxR, int(d)) else: minL = min(minL, int(d)) q = minL - maxR - 1 print (q if q>0 else -1)
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
t = int(input()) while t!=0: t-=1 x,y,n = map(int, input().split()) if n%x == y: print(n) elif n < x: print(y) else: r = n%x diff = (y-r) if diff > 0: print(n + diff -x) else: print(n + diff)
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
n,m=map(int,input().split()) a=list(map(int,input().split())) a.sort() s=a[n-1] for i in range(m-n+1): if a[i+n-1]-a[i]<s: s=a[i+n-1]-a[i] print(s)
Let a be a matrix of size r × c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i ∈ [1, r], let b_i be the greatest common divisor of integers in the i-th ...
3
from collections import defaultdict, deque from itertools import permutations from sys import stdin,stdout from bisect import bisect_left, bisect_right from copy import deepcopy int_input=lambda : int(stdin.readline()) string_input=lambda : stdin.readline() multi_int_input =lambda : map(int, stdin.readline().split()) ...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
w = int(input()) found = True while found == True: if w > 100 or w< 0: found = False if w == 2: print("NO") found = False elif w % 2 == 0: print("YES") found = False elif w % 2 != 0: print("NO") found = False
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can...
1
n = input() a = map(int, raw_input().split()) ids = [i for i, x in enumerate(a) if x == 1] red = [] if len(ids) == 0: print 0 elif len(ids) == 1: print 1 elif len(ids) == n: print 1 else: for i in xrange(len(ids)-1): if ids[i+1]-ids[i] > 1: red.append(ids[i+1]-ids[i]) print reduce(lambda x,y...
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
3
n = int(input()) s = input() mx = 0 ans = "" for i in range(n - 1): cnt = 0 for j in range(n - 1): if s[i] == s[j] and s[i + 1] == s[j + 1]: cnt += 1 if cnt > mx: mx = cnt ans = s[i] + s[i + 1] print(ans)
There is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N. We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for V...
3
import sys def input(): return sys.stdin.readline().strip() def bellman_ford(edges, N, start): dist = [float("inf") for _ in range(N)] dist[start] = 0 # 辺の情報を見ることを1ループとすると # 1回のループで,最低でも1つの頂点について,スタートからの最短距離が求まる # つまり,スタートからの全ての頂点への距離は, # スタートを除いた頂点の数である,(N-1)回のループで求まる. for i in rang...
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 two squa...
3
input_data = input() list_we_use = input_data.split(' ') h = [] for i in list_we_use: h.append(int(i)) a = h[0]*h[1] print(a//2) #kghkjghjk
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
t = int(input()) for _ in range(t): n, x = [int(x) for x in input().split()] a = set([int(x) for x in input().split()]) for i in range(1, 1000): if i in a: continue if x == 0: print(i - 1) break x -= 1
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied: * For any two vertices p...
3
n=int(input()) g=[[] for _ in range(n)] for _ in range(n-1): u,v,w=map(int,input().split()) g[u-1]+=[(v-1,w%2)] g[v-1]+=[(u-1,w%2)] l=[-1]*n q=[(0,0)] while q: a,b=q.pop(); l[a]=b for c,d in g[a]: if l[c]<0: q+=[(c,b^d)] print(*l,sep='\n')
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n=input() n=int(n) ans=0 b=input().split(" ") for k in b: if k=='1': ans+=1 if ans==0: print("EASY") else: print("HARD")
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2. Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly <image> times consecutively. In other words, array a is k-periodic, if it has period...
1
st = raw_input() st = st.split(" ", 1); n = int( st[0] ) k = int( st[1] ) st = raw_input() ar = [] st = st.split(" ", n-1) for s in st: ar.append( int(s) ) if k == n: print 0 else: res = 0 i = 0 while i < k: i += 1 j = 0 ones = 0 twos = 0 while j < int(n...
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i...
1
n,p=map(int,raw_input().split()) str1=list(raw_input()) store=[1] counter=0 flag=0 pos=0 sum1=0 for i in range(n): if (str1[i]!='#'): for j in range(i+1,n): if (str1[j]==str1[i]): store[counter]+=1 str1[j]='#' counter+=1 store.append(1) while(True): max1=0 pos=0 for i in range(counter): ...
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 ...
3
n, a, b, c = map(int, input().split()) nums = {"A": a, "B": b, "C": c} s = [] for i in range(n): line = input() s.append(line) def add(a, b): nums[a] += 1 nums[b] -= 1 ans.append(a) flag = True ans = [] for i in range(n): a = s[i][0] b = s[i][1] if nums[a] == 0 and nums[b] == 0: ...
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http...
3
import statistics import math import datetime import collections import array n=int(input()) for i in range(0,n): x,y=map(int,input().split()) print(x^y)
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
n = int(input()) if n & 1: print(- (n + 1) // 2) else: print((n + 1) // 2)
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation ⊙ of two ternary n...
3
for _ in range(int(input())): n=int(input()) c=input() boo=True a='' b='' s1='1' s2='1' for i in c: if(i=='0'): a+='0';b+='0' if(i=='1'): a+='1';b+='0' if(i=='2'): a+=s1;b+=s2 if(a!=b and boo): boo=False a,b=b,a s1='2...
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too. A team of SIS students is going to make a trip on a submarine....
1
from __future__ import division, print_function def main(): from itertools import product n = int(input()) a = input_as_list() tb = array_of(int, 10, 10) cnt = array_of(int, 10) for e in a: s = str(e) cnt[len(s)-1] += 1 for i, c in enumerate(reversed(s)): ...
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the...
3
a, b, c = map(int, input().split()) if c == 0: if a == b: print("YES") else: print("NO") elif c > 0: if b < a: print("NO") else: if (b - a) % c == 0: print("YES") else: print("NO") else: if b > a: print("NO") else: if (a - b) % c == 0: print("YES") else: print("NO")
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
def solve(): n = int(input()) a = list(map(int, input().split())) total = sum(a) if total == 0: print ('NO') elif total > 0: b = sorted(a, reverse=True) print ('YES') print (' '.join(map(str, b))) else: b = sorted(a) print ('YES') print (' ...
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
q = int(input()); for i in range(q) : n = int(input()); if n == 2 : print(2); else : print(n%2);
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t...
3
from collections import deque H,W = map(int, input().split()) A = 0 dp = [None] * H mat = deque() for h in range(H): s = list(input()) for w, x in zip(range(W), s): if x == "#": mat.append((h, w, 0)) s[w] = 1 else: s[w] = 0 dp[h] = s while len(mat): h...
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
1
Jugadores=map(int,raw_input().split()) suma=0 Cantidad=len(Jugadores) for k in range (Cantidad): suma+=Jugadores[k] if (suma==0): print -1 else: if(suma%Cantidad==0): print suma/Cantidad else: print -1
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
3
n= int(input()) l= list(map(int,input().split())) c={} for i in range(n): j=l[i]-i if j not in c.keys(): c[j]=l[i] else: c[j]+=l[i] print(max(c.values()))
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 two squa...
3
s = input().split() a=int(s[0]) b=int(s[1]) res=0 if a>1 or b>1: poa=a/2 res+=int(poa)*b if poa!=int(poa): pob=b//2 res+=pob print(res) else: print(0)
Paul was the most famous character in Tekken-3. Of course he went to college and stuff. In one of the exams he wasn't able to answer a question which asked to check if a tuple of 3 non negative integers constituted a Primitive Pythagorian Triplet or not. Paul was not able to answer it correctly and henceforth, he coul...
1
import fractions import math T=int(raw_input()) for i in range(0,T): a,b,c=[int(x) for x in raw_input().split(' ')] #print a,b,c if (c*c==a*a + b*b or a*a==b*b + c*c or b*b==a*a + c*c) and (fractions.gcd(a,b)==1 and fractions.gcd(b,c)==1 and fractions.gcd(c,a)==1): print 'YES' el...
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Eac...
3
import math c,d = map(int,input().split()) n,m = map(int,input().split()) k=int(input()) if k>=n*m: print('0') else: left=n*m-k t=c*(math.ceil(left/n)) j= c*(left//n) + (left%n)*d l=d*(left) print(min(t,j,l))
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
3
a=list(map(int,input().split())) ans=0 ans+=min(a[0],a[2],a[3]) a[0]-=ans ans*=256 ans+=32*min(a[0],a[1]) print(ans)
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs. Visitors are more likely to buy a pair of shovels if their total cost ends with severa...
3
n = int(input()) largest = n + n - 1 possible = [0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, 999999999] maximum9 = 0 indx1 = 0 i = 0 for p in possible: if p <= largest and p > maximum9: maximum9 = p indx1 = i i += 1 indx2 = 0 for i in range(9): if largest >= i*10**indx1+maximum9: ...
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak...
3
#Complexity - For finding out HCF - o(logn) where n is the largest number #Overall complexity - O(n.logN) import math import functools n, m = map(int, input().split()) arr = list(map(int, input().split())) intervals = list(map(int, input().split())) diff = [] for i in range(n-1): diff.append(arr[i+1] - arr[i]) ...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
n,k=map(int,input().split()) s=list(input()) for i in range(k): j=1 while(j<n): if(s[j]=='G' and s[j-1]=='B'): temp=s[j] s[j]=s[j-1] s[j-1]=temp j+=1 j+=1 print("".join(s))
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
1
vars = raw_input().split() vars[0] = int(vars[0]) vars[1] = int(vars[1]) vars[2] = int(vars[2]) if vars[0] <= 100 and vars[1] <= 100 and vars[2] <= 100 and vars[0] >= 1 and vars[1] >= 1 and vars[2] >= 1: if vars[1] >= vars[0] and vars[2] >= vars[0]: print("Yes") else: print("No") else: ...
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board. The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns. How many ways are there to choose where ...
3
n=int(input()) h=n-int(input())+1 w=n-int(input())+1 print(h*w)
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
t = input() for i in range(int(t)): n, k = map(int, input().split(' ')) if k % (n - 1) != 0: print(k // (n - 1) * n + k % (n - 1)) else: print(k // (n - 1) * n - 1)
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph. There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ...
3
n = int(input()) #n, m = map(int, input().split()) #s = input() a = [] for i in range(1, n + 1): c = list(map(int, input().split())) for j in range(n): if c[j] == 1 or c[j] == 3: break else: a.append(i) print(len(a)) print(*a)
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, Kirito'...
3
s,n=map(int,input().split()) l=[] for i in range(n): l.append(list(map(int,input().split()))) l.sort() i=0 while i<n: if s>l[i][0]: s+=l[i][1] else: break i+=1 if i==n: print("YES") else: print("NO")
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
1
for t in range(input()): n = input() a = [int(ai) for ai in raw_input().split(" ")] c = 0 mp = [0 for _ in xrange(n)] mp[n-1] = a[n-1] m_ = mp[n-1] for i in range(n-1,-1,-1): m_ = min(m_,a[i]) mp[i] = m_ c = 0 for i in range(0,n-1): if a[i] > mp[i+1]: c+=1 print c
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'...
3
n, m = [int(x) for x in input().split()] a = [] for i in range(n): a.append(input()) if any(x != a[-1][0] for x in a[-1]): print('NO') exit() if any(x[0] == y[0] for x, y in zip(a[:-1], a[1:])): print('NO') else: print('YES')
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
3
x,y=[int(a) for a in input().split()] i=0 if x>y: i=y else: i=x if i%2==0: print("Malvika") else: print("Akshat")
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
3
import sys def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) n=iinput() a=list(map(int, input().split())) m=iinput() b=list(map(int...
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
1
def solution(n, k, colors): dict = {} for c in colors: if (dict.get(c) == None): dict[c] = 1 else: dict[c] = dict[c] + 1 if dict[c] > k: print("NO") return print("YES") return n, k = map(int, raw_input().split()) c = list(raw_inp...
Ashishgup and FastestFinger play a game. They start with a number n and play in turns. In each turn, a player can make any one of the following moves: * Divide n by any of its odd divisors greater than 1. * Subtract 1 from n if n is greater than 1. Divisors of a number include the number itself. The player...
3
import math l=[] i=4 while(i<1000000007): l.append(i) i*=2 def printDivisors(n) : i = 1 ct=0 b=int(math.sqrt(n)) for i in range(2,b+1): if n%i == 0: if (n // i == i) : if i%2 != 0:ct+=1 else : if i%2 !=0:ct+=1 ...
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, if...
3
""" https://codeforces.com/problemset/problem/58/A """ a = "h e l l o".split(" ") i = 0 s = input() for c in s: if c == a[i]: i += 1 if i == 5: print("YES") exit() print("NO")
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de...
3
t = int(input().strip()) while t > 0: a, b, n = map(int , input().split()) if(n%3 == 0): print(a) elif(n%3 == 1): print(b) else: print(a^b) t-=1
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist. Divisor of n is any such natural number, that n can be divided by it without remainder. Input The first line contains two integers n and k (1 ≤ n ≤ 1015, 1 ≤ k ≤ 109). Output If n has less than k divisors, output ...
3
import math n,k=map(int,input().split()) a=list() c=1 i=1 while i<=math.sqrt(n): if(n%i==0): if n/i==i: a.append(i) c+=1 else: a.append(i) a.append(n/i) c+=2 i+=1 a.sort() if(len(a)<k): print("-1") else: print(int(a[k-1]))
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`. So he has decided to make a program that puts the single space he omitted. You are given a string s with 12 letters. Output the string putting a single space between the fi...
3
n = input() print(n[:4], n[4:])
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools # import time,random,resource sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI():...
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ...
3
n, k = map(int, input().split()) a = list(map(int, input().split())) an = [i+1 for i in range(n)] result = [] j = 0 for i in range(k): j += a[i] % len(an) if j >= len(an): j -= len(an) result.append(an[j]) an.pop(j) print(" ".join(map(str, result)))
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
3
a , b = map(int , input().split()) arr = set() brr = set() for _ in range(a): arr.add(input()) for _ in range(b): brr.add(input()) crr = arr.intersection(brr) x = len(crr)%2 arr = arr.difference(crr) brr = brr.difference(crr) if x == 0: if len(arr) > len(brr): print("YES") else: print("NO"...
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n...
3
import string n = int(input()) letters = ' '.join(string.ascii_letters[:26]).split() for i in range(n): word = input() a = [] b = [] for j in range(len(word)): a.append(letters.index(word[j])) b.append(letters.count(word[j])) a = sorted(a) b = sorted(b) if [j for j in range(...
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom. Constraints * 1 \leq w \leq |S| \leq 1000 * S consists of lowercase E...
1
s=raw_input() w=int(raw_input()) ans="" i=0 while(w*i<len(s)): ans+=s[w*i] i+=1 print ans
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, if...
1
line = raw_input() s = "hello" ind = 0 for c in line : if c == s[ind] : ind += 1 if ind == len(s) : break if ind == len(s) : print "YES" else : print "NO"
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of dama...
3
a, b, c = map(int, input().split()) for i in range(101): t = (c - a * i) / b if t >= 0 and int(t) == t: print('Yes') exit() print('No')
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead. You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s...
3
import math for x in range(int(input())): n=int(input()) a=[] o=[] e=[] ans=[] if n%2==0: t=0 else: t=1 for i in range(n): if (i+1)%2==0: e.append(i+1) else: o.append(i+1) if n: ...
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
3
for _ in range (int(input())): n=int(input()) a=list(map(int,input().split())) if a.count(1)==n: if n%2==0: print("Second") else: print("First") continue if a[0]!=1: print("First") else: k=0 for i in a: if i==1: ...
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
import sys import math input=sys.stdin.readline t=int(input()) while t>0: t-=1 a=list(input().rstrip()) prev=-9 c=0 for i in range(len(a)): if a[i]=='1': if prev==-9: prev=i else: c+=(i-prev-1) prev=i print(c) ...
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
3
for _ in range(int(input())): n,k=map(int,input().split()) if k>n: print(abs(n-k)) else: if (n-k)%2==0: print(0) else: print(1)
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
3
import re def main(): n = int(input()) res = False rows = [] for i in range(0, n): row_original = input() row_modified = re.sub('OO', '++', row_original, 1) if not res and row_modified != row_original: res = True rows.append(row_modified) else: ...
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
3
for _ in range(int(input())): coin=[int(i)for i in input().split()] n=coin.pop();coin.sort() count=0 for i in range(2): count+=coin[len(coin)-1]-coin[i] n=n-count if n>=0: if n%3==0: print("YES") else: print("NO") else: print("NO")
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the...
3
m = 998244353 n = int(input()) f = [0 for i in range(n+1)] ff = [0 for i in range(n+1)] f[1] = 1 ff[n] = n for i in range(2,n+1): f[i] = (f[i-1]%m * i%m) %m for i in range(n-1,1,-1): ff[i] =(ff[i+1]%m * i%m) %m ans = (f[n]%m * n%m)%m for i in range(2,n+1,1): ans = (ans%m + (-1 * ff[i]%m)%m)%m print(ans) ...
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
3
s=[] s.append("qwertyuiop") s.append("asdfghjkl;") s.append("zxcvbnm,./") x=input() y=input() for item in y: for i in range(3): for j in range(len(s[i])): if(s[i][j]==item): if(x=='R'): print(s[i][j-1],end="") else: print(...
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
3
n = int(input()) arr = list(map(int,input().split())) ans = 0 cnt = 1 for i in range(n-1): if arr[i] == arr[i+1]: cnt += 1 continue ans += (cnt*(cnt+1))//2 cnt = 1 ans += (cnt*(cnt+1))//2 print(ans)
Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≤ a, b ≤ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest comm...
3
x,y=map(int,input().split()) c=x%y while c!=0: x=y y=c c=x%y print(y)
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks. Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off. You know that there will be n interesting minutes t1, t2, ..., tn. Yo...
3
n = int(input()) times = [0] + list(map(int, input().split())) + [90] for i in range(n + 1): if times[i + 1] - times[i] > 15: print(times[i] + 15) exit() print(90)
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
#dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] for _ in range(inp()): n = inp() ct = 0 cnt = 0 flag = 0 while n != 1: if n%6 == 0: n //= 6 ct += 1 cn...
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W. Output the list...
3
import sys input = sys.stdin.readline for nt in range(int(input())): n,w = map(int,input().split()) a = list(map(int,input().split())) s = 0 b = [] for i in range(n): if (w+1)//2 <= a[i] <= w: print(1) print(i + 1) break elif a[i] < (w+1)//2: s += a[i] b.append(i + 1) if s >= (w+1)//2: ...
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
tests = int(input()) while tests > 0: tests -= 1 n = int(input()) arr = list(map(int, input().split())) arr.sort() dist = 0 ds = [] fs = [] idx = 0 while idx < n: oidx = idx dist += 1 while idx < n and arr[oidx] == arr[idx]: idx += 1 cnt = ...
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most k pebbles in each pocket at the same time....
3
from math import ceil n, k = map(int, input().split()) arr = map(int, input().split()) s = 0 for p in arr: s += ceil(p / k) print(ceil(s/2))
We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds. Initially, the hand of every clock stands still, pointing directly upward. Now, Dolphin starts all the clocks simultaneously. In how many seconds will the hand of every clock point directly upward again? Constraints * 1≤...
3
import fractions N = int(input()) ans = 1 for i in range(N): t = int(input()) ans = (ans*t) // fractions.gcd(ans, t) print(ans)
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...
3
def input_ints(): return list(map(int, input().split())) def solve(): n = int(input()) a = input_ints() for i in range(1, n-1): if a[i-1] and a[i+1]: a[i] = 1 print(a.count(1)) if __name__ == '__main__': solve()
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 1....
3
num = int(input()) i = 0 for x in range(0, num): st = input() if "+" in st: i+=1 if "-" in st: i-=1 print(i)
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
n,m = map(int, input().split()) arr = [['.' for j in range(m)] for i in range(n)] i,c = 0,0 while i < n: if c % 2 == 0: for j in range(m): arr[i][j] = '#' if i+1 < n: arr[i+1][-1] = '#' else: ...
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order. Constraints * C is a lowercase English letter that is not `z`. Input Input is given from Standard Input in the following format: C Output Print the letter that follows C in alphabetical order. Example...
3
l = input() print(chr(ord(l)+1))
Given is a positive integer N. Consider repeatedly applying the operation below on N: * First, choose a positive integer z satisfying all of the conditions below: * z can be represented as z=p^e, where p is a prime number and e is a positive integer; * z divides N; * z is different from all integers chosen in previous...
3
n=int(input()) def prime_factor(n): ass=[] for i in range(2,int(n**0.5)+1): while n%i==0:ass.append(i);n//=i if n!=1:ass.append(n) return ass d=prime_factor(n) from collections import Counter ans=0 c=Counter(d) for i in c: m=c[i] mm=1 while mm<=m: m-=mm mm+=1 ans+=1 print(ans)
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
3
n = int(input()) a = [int(t) for t in input().split(' ')] p = [0 for _ in range(n+1)] for i in range(1, n+1): p[i] = p[i-1] ^ a[i-1] counts = [{}, {}] for t in range(2): for l in range(t, n+1, 2): counts[t][p[l]] = counts[t].get(p[l], 0) + 1 count = 0 for t in range(2): cur_dict = counts[t] ...
You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not...
3
n=int(input()) l=list(map(int,input().split())) x=list(filter(lambda x:x>0, l)) y=list(filter(lambda x:x<0, l)) lx=len(x) ly=len(y) if(n%2!=0): n+=1 if(lx==ly==0): print(0) elif(lx>=ly): if(lx>=n//2): print(1) else: print(0) else: if(ly>=n//2): print(-1) else: print(0)
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
q = int(input()) for i in range(q): n = int(input()) a = sum(map(int, input().split())) x = int(a / n) while x * n < a: x += 1 else: print(x)
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
3
import math import sys from collections import defaultdict,Counter,deque,OrderedDict import bisect #sys.setrecursionlimit(1000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) def list2d(a, b, c): return [[c...
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...
3
n = int(input()) s = str(input()) a = 0 b = 0 for i, num in enumerate(s): if num != '7' and num != '4': print("NO") a=-1 b=-2 break else: if i+1<=n/2: a+=int(num) else: b+=int(num) else: if a==b: print("YES") else: ...
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh...
3
t=int(input()); for i in range(t): a,b,c,d=[int(x) for x in input().split()]; x=b; z=c; y=max(c-b+1,c); print(x,y,z);
You have three piles of candies: red, green and blue candies: * the first pile contains only red candies and there are r candies in it, * the second pile contains only green candies and there are g candies in it, * the third pile contains only blue candies and there are b candies in it. Each day Tanya eats...
3
t=int(input()) while t>0: l=list(map(int,input().split())) l.sort() if l[0]+l[1]>=l[2]: print((l[0]+l[1]+l[2])//2) else: print(l[0]+l[1]) t-=1
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 Square? It'...
3
n, m, a = map(int, input().split()) if n%a == 0: v1 = n//a else: v1 = n//a + 1 if m%a == 0: v2 = m//a else: v2 = m // a + 1 print(v1*v2)
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numb...
3
t = int(input()) hey = [] ba = [] sa = [] for v in range(t): n,q = map(str,input().split()) n = int(n) a1 = 0 a2 = 0 a3 = 0 for i in range(n): c = list(input()) d = set(c) if len(d) == 2: a1+=1 else: k1 = c[:2]+c[3:5] + c[6:8] k1 = list(map(int,k1)) u = sorted(k1) u.sort(r...
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
1
n,m=map(int,raw_input().split(' ')) k=0 for i in range(33): for j in range (33): if i**2+j==n and j**2+i==m: k+=1 print k
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market! In the morning, there are n opportunities to buy shares. The i-th of them allows to buy as many shares as you want, each at the price o...
3
def function1(): line1 = [int(x) for x in str(input()).split()] buy_prices = [int(x) for x in str(input()).split()] sell_prices = [int(x) for x in str(input()).split()] n, m, r = line1[0], line1[1], line1[2] buy_price = min(buy_prices) sell_price = max(sell_prices) if sell_price <= buy_pri...
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f...
3
from collections import Counter a = int(input()) b = int(input()) p = abs(a - b) if p == 1: print(1) else: q = p//2 m = p - (q * 2) print((q * (q + 1)) + ((q + 1) if p%2 != 0 else 0))
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},...
3
from sys import stdin, gettrace, stdout # if not gettrace(): # def input(): # return next(stdin)[:-1] # def main(): n = int(input()) aa = [int(a) for a in input().split()] sum = [0] for a in aa: sum.append(sum[-1] + a) def mean(i,j): return (sum[j] - sum[i])/(j - i) ...