problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
if __name__ == "__main__": n=int(input()) N=list(map(int,input().split())) minmum=N[0] maxmum=N[0] amazing=0 for i in N[1:]: if (i<minmum): minmum=i amazing+=1 if (i>maxmum): maxmum=i amazing+=1 print (amazing)
We have A apples and P pieces of apple. We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan. Find the maximum number of apple pies we can make with what we have now. Constraints * All values in input are integers. * 0 \leq A, P \leq 100 Input Input is g...
1
#!/usr/bin/env python from collections import deque import itertools as ite import sys import math sys.setrecursionlimit(1000000) INF = 10 ** 18 MOD = 10 ** 9 + 7 A, P = map(int, raw_input().split()) print (A * 3 + P) / 2
"Fukusekiken" is a popular ramen shop where you can line up. But recently, I've heard some customers say, "I can't afford to have vacant seats when I enter the store, even though I have a long waiting time." I'd like to find out why such dissatisfaction occurs, but I'm too busy to check the actual procession while the ...
3
# -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0147 """ import sys from sys import stdin from heapq import heappop, heappush from collections import deque input = stdin.readline class Seat(): def __init__(self, n): self.seat = '_' * n def get(self, num): ...
Manao has invented a new mathematical term β€” a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
3
a = [int(i) for i in input().split()] n = a[0] m = a[1] x = min(n,m) print(x+1) if(n == x): for i in range(x+1): print(i,x-i) else: for i in range(x+1): print(x-i,i)
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane...
3
def main(): l1, s1, r1, p1 = map(int, input().split()) l2, s2, r2, p2 = map(int, input().split()) l3, s3, r3, p3 = map(int, input().split()) l4, s4, r4, p4 = map(int, input().split()) if p1 == 1: if s1 == 1 or l1 == 1 or r1 == 1 or s3 == 1 or l2 == 1 or r4 == 1: return "YES" ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n,k = map(int, input().split()) a = list(map(int, input().split())) b= a[k-1] c=0 for i in a: if i>=b and i>0: c=c+1 print(c)
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
s = input() s = s.lower() vowel = ('a', 'o', 'y', 'e', 'u', 'i') for v in vowel: s = s.replace(v, '') for char in s: print('.' + char, end = "")
There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of ea...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys def dot_z(v1,v2): if v1[0]*v2[1]-v1[1]*v2[0] > 0: return 1 else: return -1 def diff_p(p1,p2): return [ p2[0]-p1[0], p2[1]-p1[1] ] for s in sys.stdin: d = map(float , s.split() ) a = [d[0],d[1]] b = [d[2],d[3]] c = [d[4],d[5]] p = [d[6]...
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the ...
1
n = input() a = sorted(zip(map(int, raw_input().split()), xrange(1, n + 1))) f = [a[i][1] for i in xrange(0, n, 2)] s = [a[i][1] for i in xrange(1, n, 2)] print len(f) print ' '.join(map(str, f)) print len(s) print ' '.join(map(str, s))
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
# cf 580 A 1000 n = int(input()) A = [*map(int, input().split())] # maximum non-decreasing subsegment gmax_ = 0 lmax_ = 0 for i, a in enumerate(A): if i == 0: lmax_ = 1 elif i > 0 and A[i] >= A[i - 1]: lmax_ += 1 else: lmax_ = 1 gmax_ = max(gmax_, lmax_) print(gmax_)
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. I...
3
a=int(input()) dice_results=[input() for i in range(a)] mishka=0 chris=0 for i in dice_results: j=i.split() if int(j[0])>int(j[1]): mishka+=1 elif int(j[0])<int(j[1]): chris+=1 if mishka > chris: print("Mishka") elif mishka < chris: print("Chris") else: print("Friendship is magic!^^")
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead. As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such). Brain took a ...
3
n, m = map(int, input().split(" ")) answer = "#Black&White" for i in range(n): if sum([1 for x in input().split(" ") if x in ["W", "G", "B"]]) != m: answer = "#Color" break print(answer)
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
nol = 5 lines = "" for i in range(nol): lines+=input()+"\n" one_line = lines.split() n = one_line.index("1") if n == 0 or n == 4 or n == 20 or n==24: print("4") elif n == 1 or n == 3 or n == 5 or n==9 or n==15 or n==19 or n==21 or n==23: print("3") elif n==2 or n==6 or n==8 or n==10 or n==14 or...
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i...
3
MOD = int(1e9 + 7) C = [[0]*(1001) for i in range(1001)] C[0][0] = 1 for n in range(1,1001): C[n][0] = 1 C[n][n] = 1 for k in range(1,n): C[n][k] = C[n-1][k-1] + C[n-1][k] k = int(input()) r = 1 n = 0 for i in range(k): c = int(input()) n += c r = (r * C[n-1][c-1]) % MOD print(r)
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the re...
3
n = int(input()) matrix = [] for i in range(n): old, new = [item for item in input().split()] if i == 0: matrix.append([old, new]) else: for c in range(len(matrix)): ver = 0 if matrix[c][1] == old: matrix[c][1] = new ver = 1 ...
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant β€” "Alice's". The restaurant "Alice's" serves n kinds of food. The cost for the i-th kind is always c_i. Initially, the restaurant has enough ingredients for serving exactly a_i dishes of the i-th kind. In the New Year's Eve, m customers w...
3
n, m = map(int, input().split()) a = [0, *map(int, input().split())] c = [0, *map(int, input().split())] il = [i for i in range(n + 1)] ci = sorted(zip(c, il), key=lambda x: x[0], reverse=True) for _ in range(m): t, d = map(int, input().split()) if a[t] >= d: a[t] -= d print(d * c[t]) els...
problem Once upon a time there were settlements and many people lived there. People built buildings of various shapes and sizes. But those buildings have already been lost, only the literature and the pillars found in the ruins. Was a clue to the location of the building. There is a description of the temple in the l...
1
while True: n = input() if n == 0: break P = set(tuple(map(int, raw_input().split())) for i in range(n)) ans = 0 for xi, yi in P: for xj, yj in P: q = (xj - yj + yi, yj + xj - xi) r = (xi - yj + yi, yi + xj - xi) if q in P and r in P: ans =...
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β€” a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec...
3
n = int(input()) cities = list(map(int, input().split())) d_min = cities[1] - cities[0] d_max = cities[-1] - cities[0] print (d_min, d_max) for i in range(1, n - 1): d_min = min(abs(cities[i] - cities[i-1]), abs(cities[i] - cities[i+1])) d_max = max(abs(cities[i] - cities[0]), abs(cities[i] - cities[-1])) ...
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k β‰₯ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
3
t = int(input()) cnt = 0 while (cnt < t): cnt += 1 n = int(input()) s = input() dp = [0] * n tmp = n deg = 0 while (tmp != 1): tmp //= 2 deg += 1 p = deg for i in range(n): if s[i] == str(chr(97 + deg)): dp[i] = 0 else: dp[i] = ...
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β». The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ...
1
(n, m, k) = map(int, raw_input().split()) nums = [int(raw_input()) for _ in xrange(0, m)] origin = int(raw_input()) count = 0 for num in nums: x = num ^ origin differentBits = 0 for i in range(0, n): if x & 1 == 1: differentBits += 1 x >>= 1 if differentBits <= k: count += 1 print count
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
1
t = int(raw_input()) while t: dic = {} strg = raw_input() for s in strg: if s not in dic: dic[s] = 1 else: dic[s] += 1 if len(dic) > 1: st = "" for d in dic.keys(): st += d*dic[d] print st else: print -1 t -= 1...
A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied t...
3
n=int(input()) s=str(input()) A=[] x='' for i in range(1,n+1): if(n%i==0): A.append(i) for i in A: s=s[i-1::-1]+s[i:] print(s)
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break. The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch...
3
I,r=lambda:map(int,input().split()),-10**9;n,k=I();exec("f,t=I();q=min(f,f+k-t);r=max(r,q);"*n);print(r)
There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:...
3
def f_minimum_bounding_box(N, Positions, INF=float('inf')): # 参考: https://betrue12.hateblo.jp/entry/2019/06/17/202327 x_dict, y_dict = [{'L': [], 'R': [], 'U': [], 'D': []} for _ in range(2)] for x, y, d in Positions: x_dict[d].append(int(x) * 2) y_dict[d].append(int(y) * 2) xs, ys = []...
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....
3
n = int(input()) count=0 for i in range(0,n): a = list(map(int, input().split())) if a[0]+a[1]+a[2] > 1: count = count+1 else: count = count print(count)
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points. At any time Andrew can visit the store where tasty buns are sold (y...
1
hours, minu = map(int, raw_input().split()) h, d, c, n = map(int, raw_input().split()) if hours >= 20: c = c - (c*0.2) print (h/n)*c if h%n == 0 else ((h/n) + 1)*c quit() cost1 = (h/n)*c if h%n == 0 else ((h/n) + 1)*c c = c - (0.2*c) h += ((19-hours)*60 + (60-minu))*d cost2 = (h/n)*c if h%n == 0 else ((h/n) + 1)*c p...
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
read = lambda:map(int, input().split()) x, y, z = read() m = min(x, y - 1, z - 2) print(3 * m + 3)
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations: 1. Increase all elements of a suffix of the array by 1. 2. Decrease all elements of a suffix of the array by 1. A suffix is a subsegment (contiguous elements) of the array that contains a_n. I...
3
# B. Suffix Operations for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) # Editorial - https://codeforces.com/blog/entry/85288 ans = 0 for i in range(1, n): ans += abs(a[i] - a[i-1]) # Corner cases mx = max(abs(a[0]-a[1]), abs(a[n-1]-a[n-2])) ...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
n = int(input()) i = 1 v = 1 k = [] while n//i >= 4: m = 0 if n%i == 0: m = n//i m = str(m) m = list(m) v += 1 if m.count("7") + m.count("4") == len(m): print("YES") break i += 1 if i == v: print("NO")
You are given two integers b and w. You have a chessboard of size 10^9 Γ— 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white. Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s...
3
t= int(input()) for z2 in range(t): y,x=input().split() x=int (x) y=int (y) sum=x+y if x!=y and (min(x,y)*3 +1 ) < max (x,y): print("NO") elif x is y: print("YES") for z in range(1,2*x+1): print('1 '+str(z)) else: print("YES") if x>y: ...
It is September 9 in Japan now. You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N? Constraints * 10≀N≀99 Input Input is given from Standard Input in the following format: N Output If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No...
3
n = input() print("Yes" if n.count("9") > 0 else "No")
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. Input The first line of the input contains a...
3
n=int(input()) s=str(input()).upper() c=0 b=0 for i in range(0,n): if s[i]=='A': c+=1 else: b+=1 if c>b: print("Anton") elif c<b: print("Danik") else: print("Friendship")
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of sw...
3
#Mamma don't raises quitter................................................. from collections import deque as de import math import re from collections import Counter as cnt from functools import reduce from typing import MutableMapping from itertools import groupby as gb from fractions import Fraction as fr from bisec...
Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks. There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each. What is the minimum amount of money with which he can bu...
3
z=0;n,m,*l=map(int,open(0).read().split()) for s,t in sorted(zip(l[::2],l[1::2])): z+=s*min(m,t);m-=t if m<=0:print(z);break
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string con...
3
n=int(input()) lis=[input() for i in range(n)] shablon=lis[0] fl=[True]*len(lis[0]) for st in lis[1:]: shb='' for i in range(len(shablon)): if(st[i]==shablon[i]): shb+=st[i] elif(st[i]=='?')and(shablon[i]!='?'): shb+=shablon[i] elif(st[i]!='?')and(shablon[i]=='?')...
Please notice the unusual memory limit of this problem. Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white. For each iteration of the game (the initial iteration is 0), the color of...
3
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.wr...
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that: * If we consider any color, all elements of this color must be divisible by the minimal element of this color. * The number of used colors must be minimized. For example, it's fine to paint elements [40, 1...
3
a=int(input()) b=input().split() d=[] kek=[] ans=0 for i in b: d.append(int(i)) d=sorted(d) for i in d: l=i if l not in kek: for j in range(len(d)): if d[j]!= 0 and (d[j] % l) == 0: d[j]=l d=set(d) print(len(d))
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
# https://codeforces.com/problemset/problem/510/A def main(): n, m = map(int, input().split()) for i in range(1, n+1): if i % 2 != 0: print('#'*m) else: if i//2 % 2 != 0: print(f"{'.'*(m-1)}#") else: print(f"#{'.'*(m-1)}") i...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
mag = '' for i in range(int(input())): mag+=input() print(mag.count('00')+mag.count('11')+1)
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-di...
3
n = input() numb = 0 ans = 0 if int(n) > 9: ans += 1 for num in n: numb += int(num) if numb > 9: ans += 1 n = str(numb) numb = 0 for num in n: numb += int(num) if numb > 9: ans += 1 if numb % 10 + numb // 10 > 9: ...
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
3
def check(n): count=0 if (n == 0): return False while (n != 1): if (n % 2 != 0): return 1,False n = n // 2 count+=1 return count,True def answer(a,b): if a==b: return 0 if a>b: if a%b!=0: return -1...
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For example, tripl...
1
n = int(raw_input()) if n==1 or n==2: print -1 else: if n%2==1: a = (n*n-1)/2 b = (n*n+1)/2 print a,b else: a = (n*n/4-1) b = (n*n/4+1) print a,b
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
s=input() count=0 x=s[0] for c in s: if(x==c): count+=1 else: count=1 x=c if(count==7): print("YES") exit() print("NO")
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
3
t=int(input()) i=0 while i<t: n,m,k=map(int,input().split()) if m==0: print(0) else: a=n//k b=a if b>=m: print(m) else: re=b q=m-b r1=q//(k-1) if q%(k-1)!=0: r1=r1+1 print...
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
a=int(input()) count=0 for i in range(a): b=input() if b=="Icosahedron": count+=20 elif b=="Cube": count+=6 elif b=="Octahedron": count+=8 elif b=="Dodecahedron": count+=12 elif b=="Tetrahedron": count+=4 print(count)
[Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY) A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them. It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location...
3
for ttt in range(int(input())): n,s,k=map(int,input().split()) arr=list(map(int,input().split())) ans=10**9 flag=0 for i in range(k+1): if s+i<=n and s+i not in arr: print(i) break if s-i>=1 and s-i not in arr: print(i) break
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
3
from sys import stdin from collections import Counter, deque from itertools import product input = stdin.buffer.readline n = int(input()) ls = list(map(int, input().split())) def gcd(a, b): return a if b == 0 else gcd(b, a%b) if n == 2: a, b = ls print(a*b//gcd(a,b)); exit() res = 1 u, mx = 2, max(ls) while ...
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland s...
3
def replacement(str): str2 = str.replace("oo","u") str3 = str2.replace("kh","h") if str3 == str: return str3 else : str3 = replacement(str3) return str3 n = int(input()) myList = [] myList2 = [] for i in range(n): myList.append(input()) for x in myList: str4 = replacement(x) str4 = str4.replace("u"...
The development of algae in a pond is as follows. Let the total weight of the algae at the beginning of the year i be x_i gram. For iβ‰₯2000, the following formula holds: * x_{i+1} = rx_i - D You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order. Constraints * 2 ≀ r ≀ 5 * 1 ≀ D...
1
a,b,c = map(int, raw_input().split()) for i in range(10): c =a*c-b print(c)
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 ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number...
3
n=int(input()) a=[int(x) for x in input().split()] m=int(input()) q=[int(x) for x in input().split()] s=1 W=[0]*(10**6+1) for i in range (n): W[s:s+a[i]]=[i+1]*a[i] s+=a[i] for i in q: print(W[i])
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≀ n) from the string s. Polycarp uses the following algorithm k times: * if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; * if th...
3
n, k = map(int, input().split()) s = sorted(sorted(list(zip(input(), range(n))))[k:], key=lambda x: x[1]) for i in s: print(i[0], end="") """ n, k = [int(i) for i in input().split()] s = input() for i in range(97, 123): amount = s.count(chr(i)) if amount <= k: s = s.replace(chr(i), "") k -=...
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. Input First line of input con...
3
s = input() k = int(input()) n = len(s) un = len(set(s)) if n < k: print('impossible') elif un >= k: print(0) else: print(k - un)
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
def checker(num): if num % 2 == 1 or num == 2: return 'NO' else: return 'YES' print(checker(int(input())))
There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so t...
1
n,a,b = map(int, raw_input().split()) txt2 = str(raw_input()) txt = list(txt2) wyn = 0 licz_a = 0 licz_b = 0 parz = True if a > b: w = a w2 = b else: w = b w2 = a for x in range(0, len(txt), +1): if txt[x] == '.' and parz == True: if w == 0 and w2 == 0: break if w >= w2: ...
Input The input contains a single integer a (0 ≀ a ≀ 35). Output Output a single integer. Examples Input 3 Output 8 Input 10 Output 1024
3
n = int(input()) ans = 0 if (n & 1) != 0: ans += 16 if (n&2)!= 0: ans += 2 if (n&4)!=0: ans += 8 if (n&8)!=0: ans += 4 if (n&16) != 0: ans += 1 if (n&32) != 0: ans += 32 print(ans)
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
l=[] for i in range(2): e=input() l.append(e) x=l[1] y=[0] x=list(x) for i in x: if i != y[-1]: y.append(i) else: continue removes = len(x)-(len(y)-1) print(removes)
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a...
3
m = list(map(int, input().split())) w = list(map(int, input().split())) hs, hu = map(int, input().split()) print(sum(max(150 * (i + 1), ((i + 1) * 500 - m[i] * (i + 1) * 2) - 50 * w[i]) for i in range(5)) + hs * 100 - hu * 50)
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
3
from sys import stdin, stdout input = stdin.readline def nod(a,b): if b == 0: return a else: return nod(b, a%b) def good(a): while a > 1: if a % 2 == 0: a //= 2 elif a % 3 == 0: a //= 3 else: return False return True n = int...
The Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ...
1
n=int(raw_input()) N=map(int,raw_input().split()) M=sorted(N) a=[] for i in range(n): if M[i]!=N[i]: a.append(i) if len(a)>2: print "NO" elif len(a)==0: print "YES" else: N[a[0]],N[a[1]]=N[a[1]],N[a[0]] if M==N: print "YES" else: print "NO"
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The next t lines...
3
t = int(input()) for i in range(t): n, m = map(int, input().split(' ')) if n % 2 == m % 2 and n /m >= m: print('YES') else: print("NO")
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
ncases = int(input()) n = 0 k = 0 for x in range(0,ncases): n, k = tuple([int(x) for x in input().split()]) x = k while x - x//n != k: if x - x//n > k: x -= x - x//n - k else: x += k - (x - x//n) print(x)
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
3
n = int(input()) x = list(map(int, input().split())) ans, flag = 0,0 for i in range(n): a = list(map(int, input().split())) if (flag == 0): ans = sum(a)*5 + (15 * (len(a))) temp = sum(a)*5 + (15 * (len(a))) flag += 1 if (ans > temp): ans = temp print(ans)
You are given a rectangular cake, represented as an r Γ— c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 Γ— 4 cake may look as follows: <image> The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain...
3
r, c = map(int, input().split()) matrix = [] for _ in range(r): matrix.append(input()) row, col = 0, 0 for i in range(r): if matrix[i].find('S') != -1: row += 1 for j in range(c): for i in range(r): if matrix[i][j] == 'S': col += 1 break print(r * c - row * col)
You are given a set of nβ‰₯ 2 pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups A and B, such that the following condition holds: For every two points P and Q, write the [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between them o...
3
from sys import stdin def rl(): return [int(w) for w in stdin.readline().split()] n, = rl() x0,y0 = rl() d = [0] for i in range(n-1): x,y = rl() d.append((x-x0)**2 + (y-y0)**2) while not any(x&1 for x in d): for i in range(n): d[i] >>= 1 A = [i+1 for i in range(n) if d[i]&1] print(len(A)) p...
During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n Γ— m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell ...
3
def put(): return map(int, input().split()) def diff(x,y): ans = 0 for i in range(n*m): if s[x][i]!= s[y][i]: ans+=1 return ans def find(i): if i==p[i]: return i p[i] = find(p[i]) return p[i] def union(i,j): if rank[i]>rank[j]: i,j = j,i elif rank[...
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
3
w=0 bl=0 for i in range(8): a=input() R=a.count('R') Q=a.count('Q') B=a.count('B') N=a.count('N') P=a.count('P') K=a.count('K') q=a.count('q') r=a.count('r') b=a.count('b') n=a.count('n') p=a.count('p') k=a.count('k') w+=(R*5)+(Q*9)+(B*3)+(N*3)+P bl+=(r*5)+(q...
You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n. It is known that each of the n integers 1,...,n appears at least once in this sequence. For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given s...
3
mod=10**9+7 MAX=10**5+1000 g1=[1,1] g2=[1,1] for i in range(2,MAX+1): num_1=g1[-1]*i%mod g1.append(num_1) g2.append(pow(num_1,mod-2,mod)) def cmb(n,r,MOD): return g1[n]*g2[r]*g2[n-r]%MOD n=int(input()) a=list(map(int,input().split())) data=[0]*(n+1) for i in range(n+1): data[a[i]]+=1 for i in...
You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t. Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For exa...
3
#Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue sys.setrecursionlimit(1000000) #sys.stdin = open("input.txt", "r") n = int(input()) a = list(input()) b = list(input()) a = [ord(ai)-97 for ai in a] b = [ord(bi)-97 for bi in b] a = [a[i] for i in range(-1, -n-1, -1)] b = [b[i] for i in range(-1...
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
3
w = 0 d = { 'Q' : 9 , 'R' : 5 , 'B' : 3 , 'N' : 3 , 'P' : 1 , 'K' : 0 , 'q' : -9 , 'r' : -5 , 'b' : -3 , 'n' : -3 , 'p' : -1 , 'k' : 0 , '.' : 0 } for i in range (8) : s = input() for c in s : w += d[c] if w>0 : print("White") if w<0 : print("Black") if w ==0 : print("Draw")
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
n=int(input()) #int==integer(entero) x=0 def operacion (s): if s[1]=='+': return 1 else: return -1 while n>0: linea=input() x=operacion(linea)+x n=n-1 print(x)
Your task is to calculate the distance between two $n$ dimensional vectors $x = \\{x_1, x_2, ..., x_n\\}$ and $y = \\{y_1, y_2, ..., y_n\\}$. The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance. \\[ D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)...
1
import math n = int(raw_input()) X = map(float, raw_input().split(" ")) Y = map(float, raw_input().split(" ")) print(sum([math.fabs(X[i] - Y[i]) for i in range(n)])) print(math.sqrt(sum([math.fabs(X[i] - Y[i])**2 for i in range(n)]))) print(math.pow(sum([math.fabs(X[i] - Y[i])**3 for i in range(n)]), (1.0/3.0))) prin...
Ibis is fighting with a monster. The health of the monster is H. Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points. The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health. Ibis wins wh...
3
def main(): h,n,*t=map(int,open(0).read().split()) d=[0]+[10**18]*h for a,b in zip(*[iter(t)]*2): for j in range(h+1): k=j-a if k<0:k=0 c=d[k]+b if c<d[j]:d[j]=c print(d[h]) main()
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
t=int(input()) for i in range(t): a,b=map(int,input().split()) print((abs(a-b)+9)//10)
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()) snake="#"*m nosnake="."*(m-1)+"#" even=snake+"\n"+nosnake odd=snake+"\n"+nosnake[::-1] for i in range(n//2+1): if(i+1>n//2): print(snake) else: if(i%2==0): print(even) else: print(odd)
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≀ x,y,z ≀ n), a_{x}+a_{y} β‰  a_{z} (not necessarily distinct). You are given one integer ...
1
from sys import stdin, stdout def main(): N = int(stdin.readline().rstrip()) for _ in range(N): n = int(stdin.readline().rstrip()) # arr = [int(x) for x in stdin.readline().split()] ans = ['44'] * n stdout.write(str(' '.join(ans))+'\n') if __name__ == "__main__": main()
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy...
3
from math import sqrt, floor def isPerfect(N): if (sqrt(N) - floor(sqrt(N)) != 0): return False else: return True def getClosestPerfectSquare(N): if (isPerfect(N)): print(N, "0") return aboveN = -1 belowN = -1 n1 = 0 n1 = N + 1 while (True): if...
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
console_input = input().split() n = console_input[0] k = int(console_input[1]) N = int(n) for i in range(0, k): if n[-1] != '0': N -= 1 else: N = int(N/10) n = str(N) print(n)
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
3
t = int(input()) for _ in range(t): x, y = map(int, input().split()) a, b = map(int, input().split()) x, y = min(x, y), max(x, y) print(min((y - x) * a + x * b, (x + y) * a))
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....
3
n = int(input()) sols=[] for i in range(n): sols.append(input()) fin=0 for sol in sols: count=0 views=sol.split() for view in views: if int(view)==1: count+=1 if count>1: fin+=1 print(fin)
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
a = int(input()) b = 0 if a % 2 == 0: print(int(a/2)) else: print(int(a/2)-a)
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
exec(int(input())*'s=input();print(10*int(s[0])+len(s)*(len(s)+1)//2-10);')
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
n=int(input()) s=input() a=set(s.upper()) if len(a)==26: print('YES') else: print('NO')
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers. Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits. Input The on...
1
n = input() m = (2**n) - 1 ans = 2*m print ans
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
1
N = input() mas = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"] if N > 5: i = 5 k = 5 while True: i*=2 if k+i>N: break k+=i N-=k i/=5 print mas[N/i] else: print mas[N-1]
You are given a string s consisting of n lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String s = s_1 s_2 ... s_n is lexicograp...
3
""" Codeforces Practice Problem 1076 A. Minimizing the String @author yamaton @date 2018-11-27 """ import itertools as it import functools import operator import collections import math import sys def solve(s): idx = len(s) - 1 for i, (c1, c2) in enumerate(zip(s, s[1:])): if c1 > c2: id...
Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the g...
3
n,m = [int(a) for a in input().split()] a = [int(a) for a in input().split()] c = [0 for i in range(m)] minv = 0 maxm = int(n/m) for i in a: if(i <= m): c[i-1]+=1 for i in range(len(a)): if a[i] > m or c[a[i]-1] > maxm: for j in range(m): if c[j] < maxm: minv+...
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
for i in range(int(input())): a=input() a=list(a) a.reverse() arr=[] i=0 while i<len(a): if a=='0': pass else: arr.append(int(a[i])*((10**(i)))) i+=1 x=[0] res = [i for i in arr if i not in x] print(len(res)) for j in range(len(...
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) d = list(map(int, input().split())) e = list(map(int, input().split())) bigL = [] for i in a, b, c, d, e: bigL.append(i) for row in bigL: for column in row: if column == 1: x = row...
For an integer n not less than 0, let us define f(n) as follows: * f(n) = 1 (if n < 2) * f(n) = n f(n-2) (if n \geq 2) Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N). Constraints * 0 \leq N \leq 10^{18} Input Input is given from Standard Input in the following format: ...
3
n=int(input()) if n%2==1: print(0) else: n//=2 c=0 x=5 while x<=n: c+=n//x x*=5 print(c)
An n Γ— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n = int(input()) mas = [1]*n def func(massive): massive1 = [1] for i in range(1,n): massive1.append(massive[i]+massive1[i-1]) return massive1 for i in range(n-1): mas = func(mas) print(max(mas))
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
word = input() for c in range(0,len(word)): if c==0: print(word[c].capitalize(),end ='') else: print(word[c],end='')
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$. A column vector with m elements is represented by the following equation. \\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\] A $n \times m$ matrix with $m$ column ve...
3
n,m=map(int,input().split()) a=[list(map(int,input().split())) for _ in range(n)] b=[list(map(int,input().split())) for _ in range(m)] for i in range(n): c = 0 for j in range(m): c+=a[i][j]*b[j][0] print(c)
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction. More specifically, in one move, he can go from coordinate x to x + D or x - D. He wants to make K moves so that the absolute value of the coordinate of the destination wil...
3
x,k,d=map(int,input().split()) if x<0: x=-1*x n=x//d ans=x if n>=k: ans-=k*d elif (k-n)%2==0: ans-=n*d else: ans-=(n+1)*d print(abs(ans))
Vasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n. Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty...
3
n = int(input()) s = input().strip() a = [0] + list(map(int, input().split())) MX = 105 dp = [0] * (MX ** 3) idx = lambda i, j, k: i * MX * MX + j * MX + k for i in range(n + 1): for k in range(1, n + 1): dp[idx(i, i, k)] = 0 for gap in range(1, n + 1): for i in range(n): j = i + gap i...
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction. More specifically, in one move, he can go from coordinate x to x + D or x - D. He wants to make K moves so that the absolute value of the coordinate of the destination wil...
3
x,k,d=map(int,input().split()) x=abs(x) m=min(k,x//d) k=k-m if k%2==0: print(abs(x-m*d)) else: print(abs(x-(m+1)*d))
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....
3
t = input() s = input() if t == s[::-1]: print( "YES") else: print( "NO")
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subar...
3
n , k = map(int, input().split()) s = [int(i) for i in input().split()] sum = [] total = s[-1]-s[0] for i in range(len(s)-1): sum.append(s[i+1]-s[i]) sorted_sum = sorted(sum,reverse=True) for i in range(k-1): total-=sorted_sum[i] print(total)
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with ve...
1
#!/usr/bin/python from __future__ import division from sys import stdin, stdout, maxint from fractions import Fraction import bisect, collections, heapq, itertools, operator, math N = int(stdin.readline()) best = 0 for i in xrange(N + 1): if i * i <= N: best = i else: break nonsquares = N - best * best rows = ...
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()) if w%2==0 and w!=2: print("yes") else: print("NO")
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n=int(input()) l=[] c=1 for i in range(0,n): a=int(input()) l.append(a) for i in range(1,n): if(l[i-1]!=l[i]): c=c+1 print(c)