problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
def makechange(n,curr,i,count): if n == 0: return count if i<0: return 0 if n >= curr[i]: return makechange(n%curr[i],curr,i,count+(n//curr[i])) else: return makechange(n,curr,i-1,count) n = int(input()) # print(n) curr =[1,5,10,20,100] print(makechange(n,curr,4,0))
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
string=int(input()) if string%2==0 and string>2: print("YES") else: print("NO")
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent. Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct...
1
line = raw_input() n=int(line.split()[0]) a=int(line.split()[1]) b=int(line.split()[2]) if (b<0) : condition = 0 else : condition = 1 b = abs(b) b = b%n if condition==1: print (a+b)%(n+1) + (a+b)/(n+1) else: if (a>b): print a-b else: print n-(b-a)
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k. You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that: * The size of b_i is equal to n for all 1 ≤ i ≤ m. * For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j}...
3
t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) if k == 1: f = True for i in range(1, n): if a[i] != a[i - 1]: f = False if f: print(1) else: print(-1) continu...
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 sys import stdin import math inp = lambda : stdin.readline().strip() t = int(inp()) for _ in range(t): n = int(inp()) a = [int(x) for x in inp().split()] a.reverse() print(* a)
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
x,y = map(int,input().split()) count = 0 while x < y: x = x*3 y = y*2 if x > y: break count = count+1 print(count+1)
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
n, m = map(int, input().split(" ")) words = input() s = words.split(" ") words1 = input() t = words1.split(" ") q = int(input()) y = [None]*q for i in range(q): y[i] = int(input()) for i in range(q): a=y[i]%n b=y[i]%m print(s[a-1]+t[b-1])
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twi...
1
n = int(raw_input()) a = map(int,raw_input().split()) min_i = None counter = None for i in xrange(n-1) : if a[i+1] < a[i] and min_i == None : min_i = i+1 continue if a[i] > a[i+1] and min_i != None : counter = -1 break if min_i==None : if a[0] <= a[1] : counter = 0 ...
The palindrome is a string that can be read the same way from left to right and from right to left. For example, strings "aaaaa", "1221", "bbaabb" are palindromes, however the string "chef" is not a palindrome because if we read it from right to left, we will obtain "fehc" that is not the same as "chef". We call a str...
1
n=input() for i in xrange(n): a=input() if(a%2==0): print a else: print a-1
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: * Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) * Type 2: answer the number of different characters occurring in the substring of S betwee...
3
n = int(input()) S = input() s = [] for i in range(n): s.append(S[i]) q = int(input()) BIT = [] for i in range(26): B = [0]*(n+1) #1-indexed BIT.append(B) def sum_of_1_to_i(i, LIST): z = 0 while i > 0: z += LIST[i] i -= i & (-i) return z def update(i, j, LIST): while i <= n...
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a...
3
t=int(input()) for i in range(t): n,d=map(int,input().split()) l=list(map(int,input().split())) for i in range(1,n): p=min(d,i*l[i]) d=d-p l[0]=l[0]+p//i print(l[0])
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}. Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2. Find the inversion number of B, modulo 10^9 + 7. Here the inversion number of B is defined as the number of o...
3
n,k=map(int,input().split()) *a,=map(int,input().split()) mod=10**9+7 ans=0 cnt=0 for i in range(n): for j in range(i+1,n): ans+=k if a[i]>a[j] else 0 cnt+=0 if a[i]==a[j] else 1 ans%=mod ans+=(cnt*k*(k-1)//2) ans%=mod print(ans)
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n × n is called prime if ...
3
from sys import stdin,stdout for _ in range(int(stdin.readline())): val=int(stdin.readline()) list1=[1,1]+[0]*(val-2) for i in range(val): print(*list1) list1=[list1[-1]]+list1[:-1]
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat. Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-ne...
3
def solution2(x): def find_zero(num): x_s = str(bin(num))[2:] for index, el in enumerate(x_s): if el == '0': return index return -1 operations = list() num_ops = 0 for i in range(40): zero_in = find_zero(x) if zero_in == -1: ...
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i. At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation: * Choose a vertex ...
3
# coding: utf-8 import sys from heapq import heapify, heappop, heappush sr = lambda: sys.stdin.readline().rstrip() ir = lambda: int(sr()) lr = lambda: list(map(int, sr().split())) def dijkstra(start): INF = 10 ** 15 dist = [INF] * (N+1) dist[start] = 0 que = [(0, start)] while que: d, prev...
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}. Process the following q queries in order: * The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mo...
3
import sys input = sys.stdin.readline k, q = map(int, input().split()) d = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(q)] for n, x, mod in info: d_mod = [d[i] % mod for i in range(k)] laps, rem = divmod(n - 1, k) start = x % mod end = start + sum(d_mod) * l...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) xch,ych,zch=0,0,0 l=[] for i in range(n): l.append([]) l[i]=[int(x) for x in input().split()] for k in range(n): xch+=l[k][0] ych+=l[k][1] zch+=l[k][2] if xch==0 and ych==0 and zch==0: print("YES") else: print("NO")
IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer ...
1
d=2520 n=input() print n/2520
We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left. According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is...
3
a=list(map(int,open(0).read().split())) print('Yes' if a[0]-a[1]==a[3]-a[4]==a[6]-a[7] and a[1]-a[2]==a[4]-a[5]==a[7]-a[8] and a[0]-a[3]==a[1]-a[4]==a[2]-a[5] and a[3]-a[6]==a[4]-a[7]==a[5]-a[8] else 'No')
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
year = int(input()) while True: year += 1 yearStr = str(year) if len(set(yearStr)) == len(yearStr): print(year) break
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an...
3
__author__ = 'Esfandiar' import sys from math import gcd input=sys.stdin.readline a,b,x,y = map(int,input().split()) while True: t = gcd(x,y) if t == 1:break x//=t y//=t print(min(a//x,b//y))
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
3
n=int(input()) for i in range(0,n): p,q=map(int,input().split()) l=list(map(int,input().split())) if q==sum(l): print("YES") else: print("NO")
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r ...
3
def num_path2(list_pairs): cnt = 0 l, r = 1, 1 ind = 0 while True: # print(l, r, ind) if ind == len(list_pairs): break l_targ, r_targ = list_pairs[ind] if (l, r) == (l_targ, r_targ): ind += 1 elif r_targ == r: cum = (l_targ - l) // 2 ...
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
s = int(input()) r = list(map(int,input().split())) w = [] count = 1 for i in range(s-1): if r[i] <= r[i+1]: count +=1 else: w.append(count) count = 1 w.append(count) print(max(w))
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list. Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n...
1
"Template made by : https://codeforces.com/profile/c1729 , github repo : https://github.com/cheran-senthil/PyRival" from __future__ import division, print_function import bisect import math import itertools import sys from atexit import register if sys.version_info[0] < 3: from io import BytesIO as stream else: ...
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits. Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of le...
3
s=input() ast=s.split(' ') n,k=int(ast[0]),int(ast[1]) s=input() a=[int(i) for i in s.split(' ')] s=input() b=[int(i) for i in s.split(' ')] L=n//k p=10**k r=10**(k-1) rez=1 for i in range(L): cnt=0 if b[i]>0: cnt+=(b[i]*r-1)//a[i] cnt+=(p-1)//a[i] cnt-=((b[i]+1)*r-1)//a[i] rez*=...
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()) a = input() an = 0 d = 0 for i in range(n): if a[i] == 'A': an += 1 else: d += 1 if an > d: print('Anton') elif d > an: print("Danik") else: print("Friendship")
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
a,b=map(int,input().split()) n=0 while a<=b: a=3*a b=2*b n=n+1 print(n)
Boboniu gives you * r red balls, * g green balls, * b blue balls, * w white balls. He allows you to do the following operation as many times as you want: * Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the b...
3
def ans(a,n): odd = 0 even = 0 for i in a: if i%2==0: even+=1 else: odd+=1 if odd==1: return('Yes') if odd==2: return('No') if odd==4 or odd==0: return('Yes') if odd==3: #if no operation, return no, else yes ...
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference betw...
1
__author__ = 'Shashi' n=input() m=[int(x) for x in raw_input().split(' ')] original=sorted(m,reverse=True) s=sum(m) l=len(m) avg=s/l remainder=s%l m=[avg for x in m] for i in range(0,remainder): m[i]+=1 diff=[abs(a-b) for a,b in zip(m,original)] print sum(diff)/2
Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n). If Nikolay is currently in some room, he c...
3
t = int(input()) for q in range(t): n = int(input()) a = list(input()) ans = n #print(a) for i in range(n): if a[i] == '1': ans = max(ans, (i + 1) * 2, (n - i) * 2) print(ans)
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ...
3
a,b = map(int,input().split()) l = list(map(int,input().split())) z = 2 for i in range(len(l)-1): if l[i+1]-l[i]>(2*b):z+=2 elif l[i+1]-l[i]==(2*b):z+=1 else:pass print(z)
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle. After a long time thinking, Tolik's uncle hasn't any...
1
from sys import stdin n, m = map(int, stdin.readline().split()) out, r = [], [n, 1] for i in range(n >> 1): out.append('%d %d' % (i + 1, 1)) ix, sign, cur, dec = 0, 1, 1, m - 1 while dec > -1: cur += sign * dec out.append('%d %d' % (r[ix], cur)) ix ^= 1 sign *= -1 ...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
k=int(input()) l=set(list(map(int,input().split()))[1:]) m=set(list(map(int,input().split()))[1:]) print("I become the guy."if len(l.union(m))==k else "Oh, my keyboard!")
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
d1, d2, s = input().split() d1, d2, s = [int(d1), int(d2), int(s)] q1 = d1/s q2 = d2/s q11 = d1//s q22 = d2//s r1 = (d1 % s) r2 = (d2 % s) if r1 != 0: if r2 !=0: print((q11+1)*(q22+1)) else: print((q11+1)*(q22)) else: if r2 !=0: print((q11)*(q22+1)) else: print((q11)*...
Ringo is giving a present to Snuke. Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things. You are given a string S representing the Japanese name of ...
1
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function import sys def main(): print("Yes" if sys.stdin.readline().strip().startswith("YAKI") else "No") if __name__ == '__main__': main()
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver...
3
n = int(input()) a = list(map(int, input().split())) count = [0] * (10**5 + 1) diff = 0 j = 0 ans = 0 for i in range(n): if count[a[i]] == 0: diff += 1 count[a[i]] += 1 if diff > 2: ans = max(ans, i - j) while diff > 2: count[a[j]] -= 1 if count[a[j]] == 0: ...
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
1
PROBLEM = "_" FILE = "%s" %(PROBLEM) INF = 999999999999999999L try: inFile = open(FILE+".txt") except: inFile = None def read(): if inFile: return inFile.readline().strip() else: return raw_input().strip() def read_ints(): return map(int,read().split()) '''N = 10 costs = [[0]*N f...
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
3
import sys input=sys.stdin.readline for _ in range(int(input())): n,a,b,da,db=map(int,input().split()) dic={} dis={} for i in range(1,n+1): dic[i]=[] dis[i]=0 for i in range(n-1): x,y=map(int,input().split()) dic[x].append(y) dic[y].append(x) se={a} ne...
Give a pair of integers (A, B) such that A^5-B^5 = X. It is guaranteed that there exists such a pair for the given integer X. Constraints * 1 \leq X \leq 10^9 * X is an integer. * There exists a pair of integers (A, B) satisfying the condition in Problem Statement. Input Input is given from Standard Input in the fo...
3
x = int(input()) for i in range(-150, 150): for j in range(-150, 150): if(i*i*i*i*i - j*j*j*j*j == x): print(i, j) exit()
There are N flowers arranged in a row. For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, \ldots, h_N are all distinct. Taro is pulling out some flowers so that the following condition is met: * The heights of the remaining flowers ar...
3
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor fro...
Vasya has a string s of length n. He decides to make the following modification to the string: 1. Pick an integer k, (1 ≤ k ≤ n). 2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through: * qwe...
1
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip TEST_CASES = True def main(): n = get_int() st = list(input()) mini...
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
num = int(input()) if num%2 is 0 and num is not 2: print("YES") else: print("NO")
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w...
3
import sys input = sys.stdin.readline for f in range(int(input())): n,k=map(int,input().split()) s=input() poss=True sol=[2]*n ones=0 zeros=0 for i in range(n): if i<k: if s[i]=="1": sol[i]=1 ones+=1 if s[i]=="0": ...
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob...
3
n, roboAdvantage, bionicAdvantage = int(input()), 0, 0 roboCoder, bionicSolver = [int(i) for i in input().split()], [int(i) for i in input().split()] for i in range(n): if roboCoder[i] == 1 and bionicSolver[i] == 0: roboAdvantage += 1 elif roboCoder[i] == 0 and bionicSolver[i] == 1: bionicAdvant...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
a,b=list(map(int,input().split())) if a==b: print(1) else: i = 1 ok = True while ok: a = a*3 b = b*2 if a > b: ok = False print(i) else: i +=1
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? Input The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length...
3
n,m=map(int, input().split()) a=list(map(int, input().split())) b=list(map(int, input().split())) min1=10 min2=10 min3=10 for i in range (n): a[i]=int(a[i]) for i in range (m): b[i]=int(b[i]) for i in range (n): if (a[i]<min1): min1=a[i] for i in range (m): if (b[i]<min2): min2=b[i] for...
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized. On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 t...
3
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = [0]*n d = [False]*n bad = [] need = [] for i in range(n): if a[i] == b[i]: d[a[i]-1] = True c[i] = a[i] else: bad.append(i) for i in range(n): if not d[i]: need.append(i+1) d = False...
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()) mishka=0 chris=0 for i in range(0,n): m,c=map(int, input().split()) if m>c: mishka+=1 elif m<c: chris+=1 if mishka>chris: print ("Mishka") elif mishka<chris: print("Chris") else: print("Friendship is magic!^^")
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus. Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which take...
3
t = int(input()) for j in range(t): n,s = map(int,input().split()) l = list(map(int,input().split())) ans = 0 deleted = 0 for i in range(len(l)): if s-l[i]>=0: ans += 1 s -= l[i] else: ind = i break if ans == len(l): print(0...
Recently Petya walked in the forest and found a magic stick. Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: 1. If the chosen number a is even, then the spell will turn it into 3a/2; 2. If t...
3
for _ in range(int(input())): x, y = [int(__) for __ in input().split()] if x == 1: if y == 1: print("YES") else: print("NO") elif x == 2: if y == 1 or y == 3 or y == 2: print("YES") else: print("NO") elif x == 3: if...
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order. One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s...
3
n = int(input()) s=input() s=s.split() d={} for i in range(len(s)): d[int(s[i])-1]=i su=0 for i in range(1,n): su+=abs(d[i-1]-d[i]) print(su)
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
n=int(input()) o=0 for i in range(n): p,q=map(int,input().split()) if p+2<=q: o+=1 print(o)
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
3
from operator import itemgetter #int(input()) #map(int,input().split()) #[list(map(int,input().split())) for i in range(q)] #print("YES" * ans + "NO" * (1-ans)) a,b = map(int,input().split()) x,y,z = map(int,input().split()) ans = max(0,-a + x*2 + y) ans += max(0,- b + z*3 + y) print(ans)
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue. After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence ...
3
for _ in range(int(input())): n=int(input()) r=[int(j) for j in input().split()] m=int(input()) b=[int(k) for k in input().split()] t,s=0,0 e,f=[],[] for i in r: t=t+i e.append(t) for u in b: s=s+u f.append(s) if max(e)*max(f)<0: print(max(max(...
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 ≤ i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated). For example, if you have the ar...
3
from sys import stdin, stdout t = int(stdin.readline()) ans = ["NO" for i in range(t)] for i in range(t): n = int(input()) a = list(map(int, input().split())) if (a[0] > a[-1]): ans[i] = "NO" else: ans[i] = "YES" for i in range(t): print(ans[i])
You are given an integer n and an integer k. In one step you can do one of the following moves: * decrease n by 1; * divide n by k if n is divisible by k. For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0. You are asked to calculate the minimum numbe...
1
def solve(): n, k = map(int, raw_input().split()) ans = 0 while n > 0: if n % k == 0: n /= k ans += 1 else: ans += n % k n -= n % k print ans t = int(raw_input()) for _ in range(t): solve()
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010... Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal...
3
for _ in range(int(input())): n,k=map(int,input().split()) s=input() v=s.count('0') v = 2*v-n fl=False bal,ans=0,0 for i in range(n): if v==0: if bal==k: fl=True break elif abs(k-bal)%abs(v)==0: if (k-bal)//v>=0: ...
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation: * you choose the index i (1 ≤ i ≤ |s|) such that the character at position i occurs at least two times in the string s, and del...
3
for nt in range(int(input())): s = input() n = len(s) vis = [0]*26 d = {} for i in range(n): d[s[i]] = i ans = [] stack = [] for i in range(n): if not vis[ord(s[i])-97]: while stack and s[i]>stack[-1] and i<d[stack[-1]]: vis[ord(stack.pop())-97] = 0 stack.append(s[i]) vis[ord(s[i])-97] = 1 pri...
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
3
from sys import stdin from bisect import bisect_right n = int(stdin.readline()) # shops count x = list(int(x) for x in stdin.readline().strip().split(' ')) # price in shops q = int(stdin.readline()) # days x.sort() for _ in range(q): m = int(stdin.readline().strip()) print(bisect_right(x, m))
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin...
1
class Item: def __init__(self, _income, _num): self.income = _income self.num = _num def __repr__(self): return repr((self.income, self.num)) def Item_cmp(x, y): return x.income - y.income def calc(x, y, m, k): items = [] for i in xrange(m): if b[y][i] > a[x][i]: ...
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
3
k,n,s,p=[int(x) for x in input().split()] each=n//s if n%s!=0: each+=1 total=k*each ans=total//p if total%p!=0: ans+=1 print(ans)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
# Strings n1 = int(input()) n2 = int(input()) n3 = int(input()) a = n1 + n2 + n3 b = n1 + n2 * n3 c = n1 * n2 + n3 d = n1 * n2 * n3 e = (n1 + n2) * n3 f = (n1 * n2) + n3 g = n1 + (n2 * n3) h = n1 * (n2 + n3) print(max(a, b, c, d, e, f, g, h))
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
# import sys # sys.stdin=open("input1.in","r") # sys.stdout=open("output2.out","w") N,K=map(int,input().split()) L=list(map(int,input().split())) count=0 for i in range(N): L[i]=5-L[i] if L[i]>=K: count+=1 print(int(count/3))
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper. At least how many sheets of paper does he need? Constraints * N is an integer. * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the a...
3
v = int(input()) print(v // 2 + v % 2)
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c...
3
a1,a2 = sorted(map(int, input().split())) if a1 == 1 and a2 == 1: print(0) else: count = 0 while a1>0 and a2>0: x = a1+1 y = a2-2 a1 = min(x,y) a2 = max(x,y) count += 1 print(count)
Pay attention to the non-standard memory limit in this problem. In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut...
3
from collections import Counter for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) cnt=Counter(l) c=0 for x in range(n-1): p=l[x] for y in range(x+1,n): p+=l[y] if p>n: break if p in cnt: c+=cnt[p] del cnt[p] print(c)
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
num = input() call = False lucky = [4,7,44,77,47,74,447,444,474,744,774,777,747,477] def checking(): for i in num: if i != '4' and i != '7': for i in lucky: if int(num) % i == 0: return 'YES' return 'NO' return "YES" print(checking())
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! <image> Duck is the ultimate animal! (Image courtesy of See Bang) The journey can be represented as a straight line, consisting of n segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last seg...
3
n = int(input()) dis = list(map(lambda x: int(x) << 1, input().split())) ter = input() st, ans = 0, 0 time = {'G': 5, 'W': 3, 'L': 1} delta = {'G':1, 'W':1, 'L':-1} hasWater = False convert = 0 for i in range(n): st += dis[i] * delta[ter[i]] ans += dis[i] * time[ter[i]] # print('st = %d, ans = %d' % (st, ans)) if t...
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
import collections import math # 011011 # def sortBy(a): return a[0] def gcd(a,b): if (b == 0): return a return gcd(b, a%b) def solve(lst): zeros = 0 for i in lst: if i == '0': zeros+=1 return abs(zeros - (len(lst)-zeros)) k = int(input()) print(solve(input())) # for i in range(k): # k = int(input()) # ...
Snuke has a string s. From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows: * Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with `?`s. For example, if s is `mississippi`, we can choose the su...
3
def main(): a=input() b=input() c=input() X=[a,b,c] LEN=[len(a),len(b),len(c)] MF=[[[1]*2001 for j in range(3)] for i in range(3)] for i in range(3): for j in range(3): if i==j: continue for k in range(2001): for l in rang...
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: * Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) * Type 2: answer the number of different characters occurring in the substring of S betwee...
3
from bisect import bisect_left, bisect_right N = int(input()) S = list(input()) Q = int(input()) D = {chr(ord('a') + i): [] for i in range(26)} for i, s in enumerate(S): D[s].append(i) for q in range(Q): query = list(input().split()) if query[0] == '1': i, x = int(query[1]), query[2] i -...
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
3
n = int(input()) ans = 0 list = [] if n % 2 == 1 : list.append(3) ans = 1 n -= 3 while n > 0 : n -= 2 list.append(2) ans += 1 print(ans) for i in list : print(i, end = ' ')
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
import math; number = int(input()) if (number % 2) == 0: print(math.ceil(number/2)) else: print(-1*math.ceil(number/2))
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y). Valera wants to place...
3
""" Codeforces Round 252 Div 2 Problem C Author : chaotic_iak Language: Python 3.3.4 """ def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: ...
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
3
a = int(input()) a = a % 4 if a == 0: print('1' + " " + 'A') elif a == 1: print('0' + " " + 'A') elif a == 2: print('1'+" " + 'B') elif a == 3: print('2' + " " + 'A')
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s = input() try : a = s.index("h") b = s[a+1:].index("e") + a + 1 c = s[b+1:].index("l") + b + 1 d = s[c+1:].index("l") + c + 1 e = s[d+1:].index("o") + d + 1 print("YES") except ValueError : print("NO")
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
a, b, c = 0, 0, 0 for _ in range(int(input())): x, y, z = map(int, input().split()) a+=x b+=y c+=z if a or b or c: print("NO") else: print("YES")
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly...
3
n = int(input()) arr = [int(z) for z in input().split()] arr.sort() ans = 10**18 for i in range(2*n-1): for j in range(i+1, 2*n): arr1 = [] for k in range(2*n): if k != i and k != j: arr1.append(arr[k]) a = 0 for l in range(0, 2*n-2, 2): a +=...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
x,y = [int(t) for t in input().split()] total = 0 red_needed = 2*x blue_needed = 5*x green_needed = 8*x if (red_needed)%y==0: total+=red_needed/y else: total+=red_needed//y+1 if (blue_needed)%y==0: total+=blue_needed/y else: total+=blue_needed//y+1 if (green_needed)%y==0: total+=green_needed/y else: total+=...
Hr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'. A query is described by a pair of integers l_i, r_i (1 ≤ l_i < r_i ≤ n). For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i… r_...
3
from __future__ import division, print_function import bisect import math import heapq import itertools import sys from collections import deque from atexit import register from collections import Counter from functools import reduce if sys.version_info[0] < 3: from io import BytesIO as stream else: from io im...
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
# brute-force greedy math *1000 T = int(input()) for t in range(T): n, m, k = map(int, input().split()) cards = n // k wj = min(cards, m) lj = m - wj llj = (lj + k-1 - 1)//(k-1) print(wj - llj)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
k=int(input('')) a=[9] i=1 if k<10: print(k) else: while k>a[-1]: a.append((10**(i+1)-10**(i))*(i+1)+a[i-1]) i+=1 #print(a) cat=len(a) diff=k-a[-2] step=int(diff/(cat)) rem=diff%(cat) #print('category={}'.format(cat)) #print('difference={}'.format(diff)) #print('s...
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are given a sequence s of n c...
3
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') ...
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
1
n = int(raw_input()) matrix = [[0 for x in xrange(n)] for x in xrange(n)] sumVert = [0 for x in xrange(n)] sumHor = [0 for x in xrange(n)] for i in range(0,n): matrix[i] = map(int,raw_input().split()) sumHor[i] = sum(matrix[i]) for j in range(0,n): sumVert[j] = sumVert[j] + matrix[i][j] result = 0 ...
There is a grid with H rows and W columns. The square at the i-th row and j-th column contains a string S_{i,j} of length 5. The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from `A` through the W-th letter of the alphabet. <image> Exactly one of...
3
H, W = map(int, input().split()) a = [] for i in range(H): Si = input().split() a += Si n = a.index("snuke") print(chr(ord('A') + n % W) + str(1 + n // W))
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so...
3
def twoBotton(n,m): q = [(n,0)] visited = set() while q: cur, count = q.pop(0) if cur == m: return count if cur * 2 < m * 2 and (cur*2) not in visited: visited.add(cur*2) q.append((cur*2,count+1)) if cur -1 >= 0 and (cur-1) not in visited: ...
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them. Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows: * a_1 = -1 * a_2 = 2 * a_3 = -3 * a_4 = 4 * a_5 = -5 * And so on ... ...
3
n = int(input()) result = [] def calSum(n): if n <= 0: return 0 if n % 2 == 0: even = n * (2 + n) // 4 odd = -(n * n) // 4 else: even = (n//2) * (2 + n-1) // 2 odd = -((n+1)//2) * (1 + n) // 2 return even + odd for i in range(n): [l,r] = [int(x) for x in inp...
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
3
a,b,c = sorted(map(int,input().split())) print(int(a*b/2))
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0. You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d. Calculate the number of indices k such that it is poss...
1
def ints(): return map(int,raw_input().split()) for _ in range(input()): n,x,m = ints() l = [] for _ in range(m): l.append(ints()) f = 0 c = d= 0 for i in range(m): a,b = l[i] if f==0: if a<=x<=b: f = 1 c,d = a,b ...
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i. First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does th...
3
import sys from collections import deque sys.setrecursionlimit(10000000) n,m = map(int,input().split()) to=[[] for _ in range(n)] dist=[[0] *3 for _ in range(100005)] INF=10**15 for i in range(m): a,b=map(int,input().split()) a-=1;b-=1 to[a].append(b) sv,tv=map(int,input().split()) sv-=1;tv-=1 for i in...
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
3
n = int(input()) s = str(bin(n)) print(s.count('1'))
The only difference between easy and hard versions is the maximum value of n. You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n. The positive integer is called good if it can be represented as a sum of distinct powers of 3 (...
3
from functools import reduce import os import sys from collections import * #from fractions import * from math import * from bisect import * from heapq import * from io import BytesIO, IOBase input = lambda: sys.stdin.readline().rstrip("\r\n") def value(): return tuple(map(int, input().split())) # multiple values def a...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
1
n=input(); a=map(int,raw_input().split()); b=map(int,raw_input().split()); if len(set(a[1:]+b[1:]))==n: print "I become the guy." else: print "Oh, my keyboard!"
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
n = int(input()) balls = input() count = 0 for i in range(n-1): if balls[i] == balls[i+1]: count = count + 1 print(count)
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two in...
3
n = int(input()) a = [0] b = [int(i) for i in input().split()] a+=b ans = 0 for i in range(1,n+1): if(a[i-1]<a[i]): ans+=(a[i]-a[i-1])*(n-a[i]+1) else: ans+=a[i]*(a[i-1]-a[i]) print(ans)
You are given three strings A, B and C. Check whether they form a word chain. More formally, determine whether both of the following are true: * The last character in A and the initial character in B are the same. * The last character in B and the initial character in C are the same. If both are true, print `YES`....
3
A,B,C=input().split();print('YES'if A[-1]==B[0] and B[-1]==C[0] else'NO')
Snuke has N hats. The i-th hat has an integer a_i written on it. There are N camels standing in a circle. Snuke will put one of his hats on each of these camels. If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No...
3
_,a=open(0);a,*b=map(int,a.split()) for b in b:a^=b print('YNeos'[a>0::2])
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.) The master's favorite number is 753. The closer to this number, the better. What is the mini...
3
s = input() k = 10**10 for i in range(len(s)-2): k = min(k,abs(753-int(s[i:i+3]))) print(k)
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
t=int(input()) for i in range(t): s=input() k=0 s1="" for j in range(len(s)//2): s1+=s[j+k] k+=1 s1+=s[-1] print(s1)