problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread. Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows...
1
n=int(raw_input()) N=map(int,raw_input().split()) add=0 for i in range(n): if i==n-1 or i==n-2: if N[i]==1: add+=1 else: if N[i]==1: add+=1 if N[i+1]==0: if 1 in N[i+1:]: add+=1 print add
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each ...
1
N = int(raw_input()) map = {0: [8], 1: [0,3, 4, 7, 8, 9], 2: [8], 3: [8, 9], 4: [8, 9], 5: [6, 8, 9], 6: [8], 7: [0, 3, 8, 9], 8: [], 9: [8] } print (len(map[N % 10]) + 1) * (len(map[N // 10]) + 1)
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once. A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character...
3
import sys def solve(S): A = [int(c) for c in S] n = len(A) #DP = [0]*n MIN = 200001 last = [-1]*4 for i in range(n): v = A[i] prev = last[v] last[v] = i have_all = len([x for x in last[1:] if x >= 0])==3 if have_all: MIN = min(MIN,i-min(las...
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: <image> Petr called his car dealer, who in...
3
n = int(input()) cs = [] for i in range(n): cs.append(int(input())) ok = False for mask in range(2**(n)): count =0 for x in range(n): if((mask>>x)&1): count+=cs[x] else: count-=cs[x] if(count%360==0): ok=True break if(ok): print('YES') else: ...
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number....
1
import sys if __name__ == "__main__": n = int(raw_input()) sec = map(int, raw_input().split()) calls = {} for s in sec: if s != 0: if calls.has_key(s): if calls[s] == 2: print "-1" sys.exit(0) calls[s] += 1 ...
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
3
def answer(x,y,z): a=0 b=0 c=0 if x==y and y==z: a=x b=x c=x print("YES") print(a,end=" ") print(b,end=" ") print(c) return if x==y: if z>x: print("NO") return if z<y: a=x b=z c=z print("YES") print(a,end=" ") print(b,end=" ") print(c) return if x==z: if y>x: ...
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that. The ...
1
n = int(raw_input()) d = raw_input().split(" ") ret = 0 for i in range(0, n): for j in range(i, n): s = 0 for h in range(i, j + 1): s = s ^ int(d[h]) if ret < s: ret = s print ret
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
def fun(A,B): j = 0 x = 0 while (A or B): if ((A & 1) and (B & 1)): x += (1 << j) A >>= 1 B >>= 1 j += 1 return x for _ in range(int(input())): a,b=list(map(int,input().split())) x=fun(a,b) print((a^x)+(b^x))
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i. He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied: * a < b + c * b < c + a * c < a + b How...
3
import bisect N=int(input()) L=sorted(list(map(int,input().split()))) ans=0 for i in range(N-2): for j in range(N-i-2): ans+=min(N-i-j-2,N-bisect.bisect_left(L,L[-j-1]-L[i]+1)-j-1) print(ans)
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
def solve(n): if(n==1): print(1) return a=n//2 b=n//2+1 while(b<=n): if(a==0): print(b,end=" ") else: print(b,a,end=" ") a-=1 b+=1 print() t=int(input()) for _ in range(t): n=int(input()) solve(n)
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters. Input A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200. Output Print the converted text. Example Input t...
3
a=input() print(a.upper())
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
a,b,c,d= map(int,input().split()) n=max(a,b,c,d) if (n==a): x=n-b y=n-c z=n-d elif (n==b): x=n-a y=n-c z=n-d elif (n==c): x=n-a y=n-b z=n-d else: x=n-a y=n-b z=n-c print (x,y,z)
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him;...
3
from collections import Counter s1 = input().replace(" ", "") s2 = input().replace(" ", "") c1 = Counter(s1) c2 = Counter(s2) for letter in c2: if letter in c1 and c1[letter] >= c2[letter]: pass else: print("NO") exit() print("YES")
Given are three integers A_1, A_2, and A_3. If A_1+A_2+A_3 is greater than or equal to 22, print `bust`; otherwise, print `win`. Constraints * 1 \leq A_i \leq 13 \ \ (i=1,2,3) * All values in input are integers. Input Input is given from Standard Input in the following format: A_1 A_2 A_3 Output If A_1+A_2+A_...
3
i=list(map(int,input().split())) print("win" if sum(i) <= 21 else "bust")
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet. The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re...
3
for _ in range (int(input())): n=int(input()) s=input() l=[] if n==1: print("YES") else: f=0 for i in s: if i in l and l[len(l)-1]!=i: print("NO") f=1 break else: l.append(i) i...
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert...
3
def solve(): n = int(input()) p = list(map(int, input().split(" "))) # 2...n s = list(map(int, input().split(" "))) # 1...n MAX_VAL = 10**9 + 2 v_child = [None] * n # 1...n for i, p_i in enumerate(p): idx = i + 1 if v_child[p_i - 1]: v_child[p_i...
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
n=int(input()) m=0 c=0 for i in range(n): m1,c1=map(int,input().split()) if m1>c1: m+=1 elif m1<c1: c+=1 if m>c: print("Mishka") elif m<c: print("Chris") else: print("Friendship is magic!^^")
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
3
for i1 in range(int(input())): n=int(input()) l=list(map(int,input().split())) if n==2: if l[0]>l[1]: print('NO') else: print('YES') else: dict={} for i in l: dict[i]=0 for i in l: dict[i]+=1 flag=0 ...
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
for i in range(int(input())): n=int(input()) a=sorted([int(i) for i in input().split()]) s=sum(a) if s==0: print('NO') else: a=sorted(a,reverse=s>0) print('YES') print(*a)
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta...
3
from math import inf def diff(s, t): ans = 0 for i in range(len(s)): if s[i] != t[i]: ans += 1 return ans n, m = map(int, input().split()) s = input() t = input() ans = inf index = 0 selected_string = t[0: n] for i in range(m-n+1): sub = t[i: i+n] calc_diff = diff(sub, s)...
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...
1
weight = input() if weight%2 ==0 and weight !=0 and weight != 2 : print "YES" else: print "NO"
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: <image> where <image> is equal to 1 if some ...
3
import sys def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def rlinput(): return list(rinput()) m,n = rinput() A=[] for _ in range(m): A.append(rlinput()) visited = [...
Today is Sid’s birthday and he is very excited about this as he is giving a special birthday party to all his friends. In this party they are going to play a game for which Sid have to arrange all his friends in a row such that no two boys should be present which are adjacent to each other. There are total M girls and ...
1
t=int(raw_input()) k=1000000007 while(t>0): m,n=(raw_input().split()) m,n=[int(m),int(n)] res=1; if m>=n-1: for i in range (m+1-n+1,m+2): res=(res*i)%k for i in range (1,m+1): res=(res*i)%k print(res) else: print(-1) t=t-1
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
string = input().lower() for letter in "aeiuoy": string = string.replace(letter, "") print("." + ".".join(string))
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following: * Empty — '.' * Wall — '#' * Good person — 'G' * Bad person — 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a...
3
def solve(grid,n,m,ans): for i in range(n): for j in range(m): if grid[i][j] == 'B': if i+1 < n: if grid[i+1][j] == '.': grid[i+1][j] = '#' if j+1 < m: if grid[i][j+1] == '.': ...
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l...
3
import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) t,=I() for _ in range(t): n,m=I() g=[[] for i in range(n)] dg=[[0,i] for i in range(n)] for i in range(m): x,y=I() x-=1;y-=1; dg[x][0]+=1;dg[y][0]+=1 g[x].append(y) g[y].append(x) dg.sort(key = lambda x: [-x[0],-x[1]]) an...
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with n buttons. Determine if it is fasten...
1
n = int(raw_input()) p = raw_input().split() if len(p) == 1: if p[0] == "1": print "YES" else: print "NO" else: if p.count("1") == n-1: print "YES" else: print "NO"
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
def rec(l, r): if l == r: return 1 t = 1 for i in range(l, r): if a[i] > a[i + 1]: t = 0 if t == 1: return r - l + 1 else: m1 = rec(l, (l + r) // 2) m2 = rec((l + r) // 2 + 1, r) return max(m1, m2) n = int(input()) a = [int(i) for i in inp...
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct str...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase 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...
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()) A = [] B = [] C = [] for i in range(m): A.append('#') B.append('.') C.append('.') B[-1] = '#' C[0] = '#' for x in range(1,n+1): if x % 2 == 1: print(''.join(A)) elif x % 4 == 2:...
Vasya is reading a e-book. The file of the book consists of n pages, numbered from 1 to n. The screen is currently displaying the contents of page x, and Vasya wants to read the page y. There are two buttons on the book which allow Vasya to scroll d pages forwards or backwards (but he cannot scroll outside the book). F...
3
__author__ = 'tanunia' from sys import stdin t = int(stdin.readline()) for _ in range(t): n, x, y, d = [int(k) for k in stdin.readline().split()] ans = 1000000005000 if x % d == y % d: ans = abs(x - y) // d if 1 == y % d: to_start = (x - 1) // d if (x - 1) % d > 0: ...
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it. They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card. Let th...
3
n=int(input()) a=[int(i) for i in input().split()] l=a[0] m=sum(a)-a[0] mi=abs(m-l) for i in range(1,n-1): l+=a[i] m-=a[i] mi=min(mi,abs(m-l)) print(mi)
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Let p be any permutation of length ...
3
from math import ceil t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) a=a[-1::-1] for i in a: print(i,end=" ") print()
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases...
3
t = int(input()) for i in range(t): n = int(input()) p = 0 c = 0 s = 0 for x in range(n): pn, cn = map(int, input().split()) if cn > pn and s == 0: print('NO') s += 1 continue if (cn < c or pn < p) and s == 0: print('NO') ...
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the...
3
n=int(input()) a=[int(i) for i in input().split()] i,j,b,z,s,s1,s2,b1=0,n-1,0,10**6,'','','',0 while i<=j: if a[i]<=b and a[j]<=b: break if a[i]==z and a[j]==z: break if a[i]==a[j]: b1=b while i<=n-1: if a[i]>b1: b1=a[i] s1+='L' ...
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
3
for _ in range(int(input())): b, p, f = map(int, input().split()) h, c = map(int, input().split()) if h == max(h, c): print(h*min(b//2,p)+c*min(f,b//2-min(b//2,p))) else: print(c*min(b//2,f)+h*min(p,b//2-min(b//2,f)))
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
3
import sys def main(): n = int(sys.stdin.readline()) for i in range(n): x = sys.stdin.readline().split() if int(x[1])>=2400 and int(x[2])-int(x[1])>0 : print("YES") return print("NO") main()
Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice. Given is a string S. Find the minimum number of hugs needed to make S palindromic. Constraints * S is a string consisting of lowercase English ...
3
S = input() S_r = S[::-1] print(sum(S[i]!=S_r[i] for i in range(len(S)))//2)
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually cal...
3
n, k = input().split() n = int(n) k = int(k) p = [] a = [float(x) for x in input().split()] p.append(int(0)) for i in range(1,len(a)+1): p.append(p[i-1]+a[i-1]) mx = float(0) for i in range(k, n+1): for j in range(0,n-i+1): cur = float((p[j+i] - p[j]) / float(i)) mx = max(cur,mx) print(mx)
You are given nonnegative integers a and b (a ≤ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x? Constraints * 0 ≤ a ≤ b ≤ 10^{18} * 1 ≤ x ≤ 10^{18} Input The input is given from Standard Input in the following format: a b x Output Print the number of th...
3
a,b,x = map(int, input().split()) ans = (b//x) - ((a-1)//x) print(ans)
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. <image> The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t...
1
n = int(raw_input()) a = raw_input() b = raw_input() ans = 0 for i in range(n): l,r = map(int,sorted([a[i],b[i]])) ss = min(r-l, 10+l-r) ans += ss print ans
Takahashi is a member of a programming competition site, ButCoder. Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating. The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn...
3
n,k=map(int,input().split()) print(k+100*(10-n) if n<10 else k)
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
import math n=int(input()) res=n/5 print(math.ceil(res))
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times. Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 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(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): ...
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
import math as mt import sys,string input=sys.stdin.readline #print=sys.stdout.write #import random from collections import defaultdict from heapq import heappush,heapify,heappop L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n=I...
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...
1
start = input() result = 'YES' if start % 2 == 0 and start > 2 else 'NO' print result
You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i. Divide this graph into strongly connected components and print them in their topological order. Constraints * 1 \leq N \leq 500,000 * 1 \leq M \leq 500,000 * 0 \leq a_i,...
3
#-------最強ライブラリSCC(Python) ver25252------ import copy import sys sys.setrecursionlimit(1000000) class csr: # start 頂点iまでの頂点が、矢元として現れた回数 # elist 矢先のリストを矢元の昇順にしたもの def __init__(s, n, edges): s.start = [0] * (n + 1) s.elist = [[] for _ in range(len(edges))] for e in edges: s.start[e.frm + 1] += 1...
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
a=str(input()) b=str(input()) s=[] for i in range(len(a)): if a[i]==b[i]: s.append('0') else: s.append('1') print(''.join(s))
The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Tayl...
3
#!/usr/bin/python3 #coding=utf-8 __metaclass__ = type __author__ = 'xdlove' def isLeap(y): if y % 4 == 0: return y % 400 == 0 or y % 100 != 0 return 0 n = int(input()) res, flag = 0, 365 + isLeap(n) while True: n += 1 tp = 365 + isLeap(n) res = (res + tp % 7) % 7 if res == 0 and tp ==...
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
for _ in range(int(input())): l = int(input()) a = list(map(int, input().split())) r = [] for i in a: if i in r: continue else: r.append(i) print(*r)
Input The input contains a single integer a (1 ≤ a ≤ 40). Output Output a single string. Examples Input 2 Output Adams Input 8 Output Van Buren Input 29 Output Harding
1
print ',Washington,Adams,Jefferson,Madison,Monroe,Adams,Jackson,Van Buren,Harrison,Tyler,Polk,Taylor,Fillmore,Pierce,Buchanan,Lincoln,Johnson,Grant,Hayes,Garfield,Arthur,Cleveland,Harrison,Cleveland,McKinley,Roosevelt,Taft,Wilson,Harding,Coolidge,Hoover,Roosevelt,Truman,Eisenhower,Kennedy,Johnson,Nixon,Ford,Carter,Reag...
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 l r b c`: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c. * `1 l r`: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353. Constraints * 1 \leq N, Q \leq 500000 * 0 \leq a_i, c < 998244353 * 1 \le...
3
# AtCoderのPyPy3環境だとこれが一番速い。 MOD = 998244353 mask32 = (1 << 32) - 1 class LazySegmentTree: __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator): self.me ...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
3
n = int(input()) a = list(map(int,input().split())) x = a[0] % 2 y = a[1] % 2 z = a[2] % 2 if x == y == z: for i in range(3,n): if a[i] % 2 != x: print(i+1) break elif x == y: print('3') elif y == z: print('1') else: print('2')
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
k,n,w = map(int,input().split()) totalCost = k*w*(w+1)//2 print(max(0,totalCost-n))
Polycarp often uses his smartphone. He has already installed n applications on it. Application with number i takes up a_i units of memory. Polycarp wants to free at least m units of memory (by removing some applications). Of course, some applications are more important to Polycarp than others. He came up with the fol...
1
def upper_bound_search(xs, target): lo, hi = 0, len(xs)-1 while lo+1<=hi: mid = (lo + hi)/2 if xs[mid] >= target: hi = mid else: lo = mid+1 return lo INF = 10**15 t = input() for _ in range(t): n, m = map(int, raw_input().split()) ax = map(int, raw_in...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
3
n = int(input()) fact = 1 for i in range(1, n + 1): fact = (fact * i) % 1000000007 print(((fact) - pow(2, n-1)) % 1000000007)
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
def func(an,k): if(k==1): return an else: ak=an an1=an+((int(max(str(an))))*(int(min(str(an))))) k-=1 if(ak==an1): return an1 return func(an1,k) n= int(input()) a=[] out=[] for i in range (n): ai=list(map(int,input().split())) a.append(ai) for...
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100. The shop sells N kinds of cakes. Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i. Th...
3
from itertools import product N,M=map(int,input().split()) scores=[list(map(int,input().split())) for _ in range(N)] def f(score): return sum([score[i]*((-1)**(1-p[i])) for i in range(3)]) ans=0 for p in product(range(2),repeat=3): s = list(map(f,scores)) s = sorted(s,reverse=True) SUM = sum(s[:M]) if ans ...
You are given N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given f...
3
N = int(input()) A = [0] * N for i in range(N): A[i] = int(input()) A.sort() ans = 0 for t in range(2): coef = [0] * N for i in range(N): k = 0 if i == 0 or i == N-1: k = 1 else: k = 2 if (t + i) % 2 == 1: k = -k coef[i] = k coef.sort() val = 0 for i in range(N): val += coef[i] * A[i] ...
Along a road running in an east-west direction, there are A shrines and B temples. The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road. Answer the following Q queries: ...
3
import sys from bisect import bisect_left as bl def I(a): return [-1<<50] + [int(sys.stdin.readline()) for i in range(a)] + [1<<50] A, B, Q = map(int, input().split()) S, T = I(A), I(B) for _ in range(Q): x = int(input()) k, l = bl(S, x), bl(T, x) a, b, c, d = x-S[k-1], x-T[l-1], S[k]-x, T[l]-x print(m...
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player. Find the way to distribute cards such that the sum of values written of the cards will be ...
3
n=int(input()) a=sorted(zip(map(int,input().split()),range(1,n+1))) for i in range(n//2): print(a[i][1],a[-i-1][1])
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
3
ss = 'aeiou13579' s = input() ans = 0 for c in s: if c in ss: ans += 1 print(ans)
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Ban...
1
n, m = map(int, raw_input().split()) t = map(int, raw_input().split()) b = map(int, raw_input().split()) maiores = max(t)*max(b) menores = min(t)*min(b) inverse1 = max(t)*min(b) inverse2 = min(t)*max(b) final = max([maiores, menores, inverse1, inverse2]) if final == maiores or final == inverse1: t.remove(max(t)) el...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
#!/usr/bin/pyhon3 # _*_ coding:utf-8 _*_ def main(): number_of_problem, time_to_friend = input().split() #print(number_of_problem, time_to_friend) totol_time = 4*60 time_left = totol_time - int(time_to_friend) problem_solve = 0 #print("time left", totol_time - int(time_to_friend)) for i i...
— Thanks a lot for today. — I experienced so many great things. — You gave me memories like dreams... But I have to leave now... — One last request, can you... — Help me solve a Codeforces problem? — ...... — What? Chtholly has been thinking about a problem for days: If a number is palindrome and length of its ...
3
# Main maut ko takiya, aur kafan ko chaadar banakar audhta hoon! n,p=map(int,input().split()) sum=0 a=[] for i in range(1,10): s=str(i) s=s+s[::-1] a.append(int(s)%p) for i in range(1,10): for j in range(10): s=str(i)+str(j) s=s+s[::-1] a.append(int(s)%p) for i in range(1,10): for j in range(10): f...
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
a=int(input()) b=input() cnt=0 c=0 if b.count('7')+b.count('4')==a: for i in range(len(b)//2): cnt+=int(b[i]) for i in range(len(b)//2,len(b)): c+=int(b[i]) if cnt==c: print("YES") else: print("NO") else: print("NO")
You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges. The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i. An edge whose removal disconnects the graph is called a bridge. Find the number of the edges that are bridges among the M edges....
3
N,M = map(int,input().split()) G = [[] for _ in range(N)] H = [] for i in range(M): a,b = map(int,input().split()) a-=1;b-=1 #0index G[a].append([b,i]);G[b].append([a,i]) #iを辺のIDとして保存 H.append([a,b]) ans = 0 def dfs(v,ID): #IDの辺を使えない visited.add(v) for u,idx in G[v]: if idx == ID or u in visited: ...
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis! The computers bought for the room were different. Some of them had only USB ...
3
a,b,c=map(int,input().split()) m=int(input()) dct={} if(m==0): print(0,0) exit() for _ in range(m): i,j=input().split() if(j in dct.keys()): dct[j].append(int(i)) else: dct[j]=[int(i)] lst1=["USB","PS/2"] for i in lst1: if(i not in dct.keys()): dct[i]=[] compct=0 cost=0 ...
A programming competition site AtCode provides algorithmic problems. Each problem is allocated a score based on its difficulty. Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points. These p_1 + … + p_D problems are all of the problems available on AtCode. A user...
3
D, G = map(int, input().split()) p = [list(map(int, input().split())) for _ in range(D)] visited = [0] * D def dfs(s, c): temp = 10 ** 3 for i in range(D): if visited[i] == 0: visited[i] = 1 if s >= p[i][0] * (i + 1) * 100 + p[i][1]: temp = min(temp, dfs(s - p[i][0] * (i + 1) * 100 - p[i][1]...
Snuke received a positive integer N from Takahashi. A positive integer m is called a favorite number when the following condition is satisfied: * The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds. Find all favorite numbers and print the sum of those. Con...
3
#商をxとすると、(m+1)*x=N #つまり、約数のうち、商よりも大きいもの−1の和を求める n=int(input()) ans=0 for i in range(1, int(n**0.5)+1): if n%i==0: if n/i-1 > i: ans+=(n//i)-1 print(ans)
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example, * f(599) = 6: 599 + 1 = 600 → 60 → 6; * f(7) = 8: 7 + 1 = 8; * f(9) = 1: 9 + 1 = 10 → 1; * f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101. ...
3
n = int(input()) def f(k): res = k+1 while res%10==0: res/= 10 return res cnt = 0 cur = n reachables = set() while cur not in reachables: reachables.add(cur) cur = f(cur) cnt += 1 print(cnt)
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1...
1
#! python2 m, n = map(int,raw_input().split()) x = [[0] * (n + 1) for _ in xrange(m + 1)] for mp in xrange(1, m + 1): t = map(int, raw_input().split()) for p in xrange(1, n + 1): x[mp][p] = max(x[mp -1 ][p], x[mp][p - 1]) + t[p - 1] print ' '.join(map(str, (x[mp][n] for mp in xrange(1, m + 1))...
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds. Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb...
3
from math import ceil import statistics for _ in range(int(input())): n,mm = [int(x) for x in input().split()] m = [[int(x) for x in input().split()] for j in range(n)] tot_cam = 0 for j in range(ceil(n/2)): for i in range(ceil(mm/2)): summ = m[j][i]+m[n-j-1][i]+m[j][mm-i-1]+...
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day. Days go ...
3
n = int(input()) arr = input().split(" ") # n = 5 # arr = [1, 0, 1, 0, 1] len1 = 0 len2 = 0 for i in range(0, n*2): if(arr[i % n] == '1'): len1 += 1 else: len2 = max(len2, len1) len1 = 0 print(len2)
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
1
from sys import stdin n, l, r = map(int, stdin.readline().split()) bits, ans, p = [int(i) for i in bin(n)[2:]], 0, [1 << i for i in range(50)] for i in range(l, r + 1): for j in range(len(bits) - 1, -1, -1): if i % p[j] == 0: ans += bits[j] break print(ans)
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = a.copy() count = {} tot = {} for i in a: count[i] = [] var = 1 a.sort() an = True tot = {} for i in a: tot[i] = tot.get(i, 0) + 1 for c in tot: if(tot[c] > k): an = False for i in range(n): count[a[i]].append(var) var = (var + 1)%...
There is a circular pond with a perimeter of K meters, and N houses around them. The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond. When traveling between these houses, you can only go around the pond. Find the minimum distance that needs to ...
3
k,n,*a=map(int,open(0).read().split()) l=k-a[n-1]+a[0] for i in range(n-1): l=max(l,a[i+1]-a[i]) print(k-l)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
for i in range(int(input())): n=int(input()) s=input() ans='' i=0 p=n while i<n: x=0 for j in s[i:p]: x|=int(j) ans+=str(x) i+=1 p+=1 print(ans)
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s. We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen? Constraints * All values in input are integers. * 0 \leq A, B, C * 1 \leq K \l...
3
A, B, C, K = map(int, input().split()) print(min(A, K)-max(0,min(C,K-(A+B))))
Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for ...
1
a = raw_input().split() mynumber=int(a[0]) mysystem=a[2] if a[2]=="week": if mynumber==5 or mynumber==6: print 53 else: print 52 else: if mynumber<=29: print 12 elif mynumber==30: print 11 else: print 7
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≤ k ≤ n) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri...
3
fir=input() first=fir.split(" ") sec=input() first=fir.split(" ") second=sec.split(" ") index=0 people=list() num=list() while index<len(second): if second[index] in people: index+=1 else: people.append(second[index]) num.append(index+1) index+=1 if len(people)<int(first[1]): ...
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
t = int(input()) for _ in range(t): n = int(input()) ar = list(map(int, input().split())) mn = 1000000000 count = 0 for i in range(0, n): el = ar[n - i - 1] if el > mn: count += 1 mn = min(mn, el) #print(ar) print(count)
You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course. You decided to rob a town's blacksmith and you take a follower with you. You can carry at most p units and your follower — at most f units. ...
3
from sys import stdin input = stdin.readline q = int(input()) for _ in range(q): p,f = map(int,input().split()) ns,na = map(int,input().split()) s,a = map(int,input().split()) wynik = 0 for ps in range(ns+1): if ps*s > p: continue pa = (p-ps*s)//a pa = min(pa,na) ...
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
import sys n = int(input()) li = [int(i) for i in input().split()] li1 = [] li2 = [] li3 = [] for i in range(len(li)): if(li[i] == 1): li1.append(i+1) elif(li[i] == 2): li2.append(i+1) else: li3.append(i+1) f = len(li1) s = len(li2) t = len(li3) mini = sys.maxsize if(mini > f): m...
You are given a string s, consisting of n lowercase Latin letters. A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length n diverse if and o...
3
n, s = int(input()), input() if n <= 1: print("NO") else: d = {} loc = -1 d[s[0]] = 1 for i in range(1, n): if s[i] not in d: loc = i - 1 break if loc == -1: print('NO') else: print("YES") print(s[loc: loc+2]) ...
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
x=int(input()) for __ in range(x): n=int(input()) a=list(map(int,input().split())) if len(set(a))==1: print(a[0]) else: b=((sum(a)/len(a))) if b==int(b): print(int(b)) else: print(int(b)+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
from math import ceil inplst = input().split(' ') for i in inplst: inplst[inplst.index(i)] = int(i) square = inplst[0]*inplst[1] nrow = inplst[0]/inplst[2] if inplst[0]/inplst[2] == 0 else ceil(inplst[0]/inplst[2]) #if inplst[0]%inplst[2] != 0 ncol = inplst[1]/inplst[2] if inplst[0]/inplst[2] == 0 else ceil(inpls...
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
c=0 for u in range(int(input())): s=input() if(s.count('1')>=2): c=c+1 print(c)
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
3
cards = [] mark = ["S", "H", "C", "D"] for m in mark: for i in range(1, 14): cards.append(m + " " + str(i)) n = int(input()) for _ in range(n): x = input() cards.remove(x) for c in cards: print(c)
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
t=int(input()) for i in range(t): a,b=map(int,input().split()) if a==0: print(0) elif a==1: print(0) elif a==2: print(b) else: print(b*2)
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes. In an undirected graph loops (edges fro...
3
import sys n,a,b = list(map(int, input().split())) if a>1 and b>1: print('NO') sys.exit(0) if n==3 and a==1 and b==1: print('NO') sys.exit(0) if n==2 and a==1 and b==1: print('NO') sys.exit(0) t = [[0 for i in range(n)] for j in range(n)] comp = max(a,b) for i in range(comp-1, n-1): t[i][i+1] = 1 t[i+1...
There was once young lass called Mary, Whose jokes were occasionally scary. On this April's Fool Fixed limerick rules Allowed her to trip the unwary. Can she fill all the lines To work at all times? On juggling the words Right around two-thirds Sh...
3
x = int(input()) f1 = 0 f2 = 0 for i in range(2, 999): if x % i == 0: f1 = i f2 = x // i break print(str(f1) + str(f2))
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them...
3
some_chars=input() sharps=some_chars.split() BD=int(sharps[0]) BK=int(sharps[1]) all_cafe=int(sharps[2]) students=int(sharps[3]) ans=students-BD-BK+all_cafe if ans<=0 or students<all_cafe or students<BK or students<BD or (BD==0 and all_cafe>0) or (BK==0 and all_cafe>0) or students==0 or all_cafe>BK or all_cafe>BD: ...
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
n = int(input()) if n == 2: print('NO') else: print(["YES", "NO"][n % 2])
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
num = int(input()) count = 0 while num//10!=0: num = sum(list(map(int, list(str(num))))) count+=1 print(count)
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
def tran(m): rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))] return rez r,n = map(int,input().strip().split()) c = 0 b = 0 arr = [] for l in range(r): arr.append(list(input())) for row in arr: if 'S' not in row: c += row.count('.') b += 1 arr = tran(arr) for row in arr...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n = int(input()) l = ["hate", "love"] * n print("I"," that I ".join(l[:n]),"it")
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
for _ in range(int(input())): n,k=list(map(int,input().split())) count=(n//k)*k x=n%k if x<=k//2: count+=x else: count+=k//2 print(count)
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy ...
3
from sys import maxsize x, y = [int(i) for i in input().split()] res = maxsize for _ in range(int(input())): a, b, c = [int(i) for i in input().split()] if (c != 0): res = min(res, ((((x - a) ** 2 + (y - b) ** 2) ** 0.5) / c)) else: if (a == x and b == y): res = 0 print(res)
Nezzar loves the game osu!. osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees. <image> Points A,B,...
3
# angles <= 60 degrees even I think n = int(input()) points = [list(map(int,input().split())) for i in range(n)] pointsx = [points[i][0] for i in range(n)] pointsy = [points[i][1] for i in range(n)] vis = [0]*n order = [0] vis[0] = 1 for i in range(n-1): max_dist = 0 best_points = [-1] lastx = pointsx[orde...