problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re...
1
def f(i, b): return ['DEAD', 'LIVE'][sum(x - y for t, x, y in b if t == i) >= 0] n = input() b = [map(int, raw_input().split()) for _ in range(n)] print f(1, b) print f(2, b)
You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S. Here, a ACGT string is a string that contains no characters other than `A`, `C`, `G` and `T`. Constraints * S is a string of length between 1 and 10 (inclusive). * Each c...
3
s = input() import re l = re.split('B|D|E|F|H|I|J|K|L|M|N|O|P|Q|R|S|U|V|W|X|Y|Z', s) print(max([len(i) for i in l]))
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
q = int(input()) out = [False]*q for i in range(q): bigs,smalls,n,S = map(int,input().split()) if smalls < S%n: continue result = S%n smalls -= S%n result += n*(smalls//n) result += n*bigs out[i] = result >= S for i in out: if i: print("YES") else: print("NO...
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next t lines...
3
for i in range(int(input())): n, k = map(int, input().split()) s = 0 if n >= (k*k): if n % 2 != 0 and k % 2 != 0: print("YES") elif n % 2 == 0 and k % 2 == 0: print("YES") else: print("NO") else: print("NO")
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
x=int(input()) for i in range(x): a=int(input()) y=list(map(int,input().split())) z=len(y) y.sort() for i in range (len(y)-1): if(y[i+1]-y[i]<=1): z=z-1; if(z==1): print("YES") else: print("NO")
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u...
3
n=int(input()) a=list(map(int,input().split()))[:n] c,d,mini=n,1,abs(a[-1]-a[0]) for i in range(n-1): if mini>abs(a[i]-a[i+1]): c,d=i+1,i+2 mini=abs(a[i]-a[i+1]) print(c,d)
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec". Now Mike asks himself: what...
3
n = int(input()) s = [] for _ in range(n): s.append(input()) c = True ans = 1e9 for i in s: cnt = 0 for j in s: pat = j + j x = pat.find(i) if x < 0: c = False else: cnt += x ans = min(ans, cnt) print(ans if c else -1)
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si...
3
count = int(input()) for _ in range(count): test = int(input()) print(int(test / 2) + 1)
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
1
print " ".join(raw_input().split('WUB')).strip()
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
import operator as op import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from functools import reduce from itertools import ( accumulate, combinations, combinations_with_replacemen...
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
for _ in range(int(input())): n, k = [int(x) for x in input().split()] a = sorted([int(x) for x in input().split()]) b = sorted([int(x) for x in input().split()], reverse = True) for i in range(k): if(a[i]<=b[i]): a[i] = b[i] else: break print(sum(a))
You are given a string S consisting of lowercase English letters. Another string T is initially empty. Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times: * Append one of the following at the end of T: `dream`, `dreamer`, `erase` and `eraser`. Constrain...
3
S = input() x = S.replace('eraser', '').replace('erase', '').replace('dreamer','').replace('dream','') print('YES' if not x else 'NO')
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an ...
3
q = int(input()) for _ in range(q): n = int(input()) a = [0] b = [] if n ==1: print(2) print(0, 1) else: t = 1 for i in range(1, int(n**0.5)+1): if i*i<=n: a.append(i) l = i b.append(n//i) b = b[::-1] if b[0]==l: print(len(a)+len(b)-1) else: print(len(a)+len(b)) for t in a: ...
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es...
3
''' Codeforces Round #280 (Div. 2) | C - Vanya and Exams ''' def mergesort(arr, sup): if len(arr) > 1: mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] leftsup = sup[:mid] rightsup = sup[mid:] mergesort(left, leftsup) mergesort(right, rightsup) ...
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
n=int(input()) for i in range(n): k=input() print(len(k)-k.count('0')) print(' '.join([str(int(k[i])*(10**(len(k)-i-1))) for i in range(len(k)) if k[i]!='0']))
Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show". Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes...
3
import sys,math,heapq from collections import defaultdict,Counter def li(): return list(map(int,sys.stdin.readline().split())) def ls(): return list(map(int,list(input()))) def la(): return list(input()) def ii(): return int(input()) n= ii() a = la() ans = 0 s = [] count = 0 for i in range(n): # print(count , i,s...
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
3
from sys import stdin, stdout, setrecursionlimit input = stdin.readline flush = stdout.flush #setrecursionlimit(1000000) ############################################################ OUT = [] def write(item, sep = " "): if type(item) is int: OUT.append(str(item)) elif type(item) is list: if t...
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner. For each of the p...
3
from sys import stdin def sin(): return stdin.readline() n,k = map(int, sin().split()) p = list(map(int, sin().split(" "))) ans=0 for i in range(n): c=0 for j in range(i+1,n): if p[i]>p[j]: c+=1 else: break if i!=0 and p[i-1]<p[i]: c+=1 if c>=k: ...
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
3
n=int(input()) m=0 x=0 for i in range(n): a,b=map(int,input().split()) if a>m: m=a x=a+b print(x)
We have N cards. A number a_i is written on the i-th card. Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first. The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards...
3
input(); al=[int(i) for i in input().split()] al.sort() al = al[::-1] print(sum(al[::2])-sum(al[1::2]))
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal). Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met: (((x mod a_1) m...
3
p = 998244353 n, k = map(int, input().split()) F, R = [1], [1] for i in range(1, n + 1): F.append(F[i - 1] * i % p) R.append(pow(F[i], p - 2, p)) print(sum(F[n // i - 1] * R[k - 1] * R[n // i - k] % p for i in range(1, n + 1) if (n - i) >= (k - 1) * i) % p)
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers...
3
import math n=int(input()) s=2*n t=(math.sqrt)(1+4*s)-1 #print (t) if t%2==0: print ("YES") else: print ("NO")
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
word = input() print("%s%s" %(word[0].upper(),word[1:len(word)]))
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t. Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second...
1
data1 = map(int,raw_input().split(':')) data2 = map(int,raw_input().split(':')) diff1 = data1[0] - data2[0] diff2 = data1[1] - data2[1] if diff2 < 0 : diff2 += 60 diff1 -= 1 if diff1 < 0 : diff1 += 24 print "%02d:%02d" % (diff1,diff2)
You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan). In how many ways can we select some of these coins so that they are X yen in total? Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that co...
1
# -*- coding: utf-8 -*- import sys a = int(raw_input().split()[0]) b = int(raw_input().split()[0]) c = int(raw_input().split()[0]) x = int(raw_input().split()[0]) n = 0 for an in range(0, a + 1): if 500*an > x: break for bn in range(0, b + 1): if (500*an + 100*bn) > x: break ...
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
n = 4 horseShose = input().split(" ") sum = 0 for i in range(0,n-1): for j in range(i+1,n): if(horseShose[i] == horseShose[j]): sum+=1 break print(sum)
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
n = int(input()) final = set(input().split()[1:] + input().split()[1:]) print('I become the guy.' if len(final) == n else 'Oh, my keyboard!')
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
n=int(input()) a=list(map(int,input().split())) max=a[0] min=a[0] c=0 for i in a: if(i<min): min=i c+=1 if(i>max): max=i c+=1 print(c)
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
import math m,n,a = input().split() m = math.ceil(int(m)/int(a)) n = math.ceil(int(n)/int(a)) print(n*m)
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte...
3
l = int(input()) n = input() left, right = l//2, l//2 + (1 if l&1 else 0) while n[left] == '0': left -= 1 while right < l and n[right] == '0': right += 1 if left == 0: ans = int(n[:right]) + int(n[right:]) elif right == l: ans = int(n[:left]) + int(n[left:]) else: ans = min(int(n[:left]) + i...
Chef has bought N robots to transport cakes for a large community wedding. He has assigned unique indices, from 1 to N, to each of them. How it will happen? Chef arranges the N robots in a row, in the (increasing) order of their indices. Then, he chooses the first M robots and moves them to the end of the queue. Now, C...
1
# cook your code here from fractions import gcd t = int(raw_input()) while(t): t-=1 n, m = map(int,raw_input().split()) g = gcd(n, m) if g == 1: print "Yes" else: print "No " + str(n / g)
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
3
for z in range(int(input())): n,k=map(int,input().split()) if(n<=k): #initially assume B to be at position of A #because in that case position of B will be at k only..so we have to reach k from A print(k-n) else: #else if k is less than n , then b will be mid point of k and n #|...
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
3
def f(x):return x*(x-1)//2 a=list(map(int,input().split())) print((a[1]-a[0]%a[1])*f(a[0]//a[1])+(a[0]%a[1])*f(a[0]//a[1]+1),f(a[0]-a[1]+1))
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
y=int(input()) if y!=2: if y%2==0: print('YES') else: print('NO') else: print('NO')
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
3
n, m = map(int, input().split()) oddNum = n//2 + (n % 2 > 0) if (m <= oddNum): print(m * 2 - 1)#get from odd else: print((m - oddNum) * 2)#get from even
You are given two arrays a and b, both of length n. Let's define a function f(l, r) = ∑_{l ≤ i ≤ r} a_i ⋅ b_i. Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of ∑_{1 ≤ l ≤ r ≤ n} f(l, r). Since the answer can be very large, you have to print it modulo...
1
#!/usr/bin/env python """<https://github.com/cheran-senthil/PyRival>""" from __future__ import division, print_function import operator as op 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, ...
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S? Input The only line of the input contains two integers n and S ...
3
nm = list(map(int, input().split(" "))) n = nm[1]/nm[0] res = int(n) print(res if res == n or n < 0 else res+1)
There are N blocks arranged in a row. Let us paint these blocks. We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways. Find the number of ways to paint the blocks under the following conditions: * For each block, use one of the M colors...
3
n,m,k=map(int,input().split()) fact,factinv,mod=[1]*n,[1]*n,998244353 for i in range(2,n): fact[i]=fact[i-1]*i%mod factinv[n-1]=pow(fact[n-1],mod-2,mod) for i in range(n-2,0,-1): factinv[i]=factinv[i+1]*(i+1)%mod ncr=lambda n,r:fact[n]*factinv[r]%mod*factinv[n-r]%mod ans=pow(m,n,mod) for i in range(k+1,n): ans+=m...
You have N cards. On the i-th card, an integer A_i is written. For each j = 1, 2, ..., M in this order, you will perform the following operation once: Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j. Find the maximum possible sum of the integers written o...
3
n,m=map(int,input().split()) a=sorted(map(int,input().split())) b=sorted([list(map(int,input().split())) for i in range(m)],key=lambda x:x[1])[::-1] i=0 for num,v in b: for j in range(num): if i<n and a[i]<v: a[i]=v i+=1 else: print(sum(a)) exit() else: print(sum(a))
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
3
def dead(n,d): if d<=n: return "YES" for i in range(n): if d%(i+1)==0: x=d//(i+1) else: x=d//(i+1)+1 if x+i<=n: return "YES" return "NO" l=[] t=int(input()) for i in range(t): n,d=input().split() l.append([int(n),int(d)]) for j in l: ...
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
3
def value(n): if n >= 2 and n < 10: return 4 elif n == 10: return 15 elif n == 11 or n == 1: return 4 else: return 0 if __name__ == "__main__": n = int(input()) print (value(n - 10))
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
n=input().split(" ") k=int(n[1]) result=n[0] for i in range(k): if result[len(result)-1]=="0": result=str(int(result)//10) else: result=str(int(result)-1) print(result)
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ...
3
(n,d)=map(int, input().split()) l=list(map(int, input().split())) def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j]...
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ...
3
t=int(input()) while(t!=0): s=list(input()) Rs = [] m = 0 if('R' in s): for i in range(len(s)): if(s[i]=='R'): Rs.append(i) for i in range(1, len(Rs)): m = max(m, Rs[i]-Rs[i-1]) m = max(Rs[0]+1, m, len(s)-Rs[-1]) else: m = len(s...
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the sma...
3
from collections import defaultdict as dd, deque as dq import sys input=sys.stdin.readline def bfs(tot,val,parent,d): q=dq([1]) while q: u=q.pop() if(u!=1): #print(u,parent[u],tot[u],tot[parent[u]]) #print(u,tot[u]) val[u]=max(val[u],n-tot[u]-1) ...
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
1
import sys, collections range = xrange input = raw_input n = int(input()) P = [1]*(n + 1) smallest = [n + 2]*(n + 1) smallest[1] = 1 for i in range(2, n + 1): if P[i]: smallest[i] = min(i, smallest[i]) j = i * i while j <= n: P[j] = 0 smallest[j] = min(i, smallest[j...
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer. Reliable sources have informed the financier Anton of some information about the exchange rate of...
3
n=input() x=0 y=len(n) c='a' for i in range(0,y): if int(n[i])%2==0 and n[i]<n[y-1]: c=n[i] x=i break if c=='a': for i in range(1,y): if int(n[y-i-1])%2==0: c=n[y-i-1] x=y-i-1 break if c=='a': print(-1) else: for i in range(0,y): if i==x: print(n[y-1],end="") elif...
The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions: * 1 ≤ i < j < k ≤ |T| (|T| is the length of T.) * T_i = `A` (T_i is the i-th character of T from the beginning.) * T_j = `B` * T_k = `C` For example, when T = `ABCBC`, there are three triples of...
3
S = input() s = 'ABC' N = len(S) C = 10**9+7 dp = [[0]*4 for _ in range(N+1)] dp[N][3] = 1 for i in reversed(range(N)): for j in range(3): if i < j: continue dp[i][j] = ((1+(S[i] == '?')*2)*dp[i+1][j] + (S[i] in {s[j], '?'})*dp[i+1][j+1]) % C if i>=3: dp[i...
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams. The strength of a team is defined as the second largest strength among its members. For ...
1
# -*- coding: utf-8 -*- import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys def s(): return raw_input().strip() def n(): return int(raw_input()) def d(): return float(raw_input()) def ls(): return raw_input().strip().split() def ln(): return map(int, raw_input().strip().sp...
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
from sys import stdin, stdout import math,sys from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict from os import path import bisect as bi import heapq def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------------------Sublime-----------...
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
3
t = int(input()) for _ in range(t): n = int(input()) print(n - 1) print(' '.join([str(x) for x in range(2, n + 1)]))
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ...
3
n,a,x,b,y=map(int,input().split()) ans=0 while(a!=x and b!=y): a = (a+1) b = (b-1) if a > n: a = 1 if b < 1: b = n if a == b: ans=1 break if ans==1: print("YES") else: print("NO")
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
3
import sys # sys.setrecursionlimit(10**6) input=sys.stdin.readline t=int(input()) for t1 in range(t): n=int(input()) l=list(map(int,input().split(" "))) if(l[0]+l[1]<=l[-1]): print(1,2,n) else: print(-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=map(int,input().split()) a=sorted(list(map(int,input().split()))) ans=a[n-1]-a[0] for i in range(1,n): ans=min(ans,k-(a[i]-a[i-1])) print(ans)
Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point...
3
x=input() xx=x.split(' ') l=[] n,k=int(xx[0]),int(xx[1]) xxx=input() l=xxx.split(' ') l2=[] for i in l: l2.append(int(i)) for i in range(1,(2 * n) + 1,2): if (l2[i] - 1)> l2[i - 1] and (l2[i] - 1) > l2[i + 1] and k > 0: k-=1 l2[i] = l2[i] - 1 for i in l2: print(i,end=' ')
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
for _ in range(int(input())): n, m, k = map(int, input().split()) per = n // k if m <= per: print(m) continue other = 0 m -= per while m > 0: other += 1 m -= k-1 print(per - other)
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight. So, if there are k teams (a_1, b_1), (a_2, b_2)...
3
for t in range(int(input())): n=int(input()) arr=list(map(int,input().split())) ans=dict() for i in range(n): ele=arr[i] if ele in ans: ans[ele]+=1 else: ans[ele]=1 sums=dict() for i in range(1,51): for j in range(i,51): tot=i+j...
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
1
n = int(input()) if n >=0: print n elif len(str(n))==2: print 0 else: s = str(n) if int(s[-1])<int(s[-2]): print int(s[:-2]+s[-1]) else: print int(s[:-1])
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
3
# -*- coding: utf-8 -*- """ Created on Thu Jan 18 22:25:04 2018 @author: User """ a,b=map(int,input().split()) arr=list(map(int,input().split())) arr.sort() for i in range(a-1,-1,-1): if b%arr[i]==0: print(b//arr[i]) break
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
1
n=input() cards=map(int,raw_input().split()) start=0 end=n-1 sums=0 sumd=0 i=0 while start<=end: if cards[start]>cards[end]: take=cards[start] start+=1 else: take=cards[end] end-=1 if i%2==0: sums+=take else: sumd+=take i+=1 print sums,sumd
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
3
t = int(input()) for i in range(t): line = [int(n) for n in input().split()] N = line[0] K = line[1] A = [int(n) for n in input().split()] A.sort(reverse=True) s = 0 for j in range(K + 1): s += A[j] print(s)
Input The input contains a single integer a (10 ≤ a ≤ 999). Output Output 0 or 1. Examples Input 13 Output 1 Input 927 Output 1 Input 48 Output 0
3
a = int(input()) print(1 if a % 2 == 1 else 0)
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single ...
3
n, k = list(map(int, input().split())) s = list(map(int, input().split())) i, o, r, e = n-1, k, s[n-1], 0 while (o-1)*2 >= i: o, i = o-1, i-1 while e < i: r = max(r, s[e]+s[i]) e, i = e+1, i-1 print(r)
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
1
# -*- coding: utf-8 -*- import itertools, math, random, re, string, sys from bisect import * from collections import * from decimal import * from fractions import * from itertools import combinations, permutations, product from math import ceil, exp, log, sqrt from Queue import * getcontext().prec = 100 sys.setrecursi...
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct). You are given one integer ...
3
for i in range(int(input())): n=int(input()) l=[] for j in range(n): l.append(1) for j in range(len(l)): if j==len(l)-1: print(l[j]) else: print(l[j],end=" ")
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
3
# Lets goto the next level # AIM Specialist at CF *__* asap # template taken from chaudhary_19 # Remember you were also a novice when you started, # hence never be rude to anyone who wants to learn something # Never open a ranklist untill and unless you are done with solving problems, wastes 3/4 minuts # Donot tr...
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
my_input = input() n, m, a = my_input.split () n = int(n) m = int(m) a = int(a) if n/a>n//a: x = (n//a +1) else: x= n//a if m/a>m//a: y= m//a+1 else: y= m//a print (x * y)
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
1
#!/usr/bin/env python #coding: utf-8 #a = [([0] * 3) for _ in xrange(4)] #a = [1, 5, 2, 6, 9, 4] #b = sorted(a, cmp = lambda x, y: cmp(y, x), reverse = True) #class Node: # def __init__(self, X, Y): # self.x = X # self.y = Y #a = [] #a.append(Node(1, 2)) #print a[0].x, a[0].y in1 = lambda : int(raw_input()) in2 = l...
Haruna is a high school student. She must remember the seating arrangements in her class because she is a class president. It is too difficult task to remember if there are so many students. That is the reason why seating rearrangement is depress task for her. But students have a complaint if seating is fixed. One da...
1
while True: r, c = map(int, raw_input().split()) if (r,c) == (0,0): break if r%2!=0 and c%2!=0: print 'no' else: print 'yes'
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next t lines...
3
t = int(input()) for i in range(t): n,k = list(map(int,input().split())) if (n-k)%2 == 0 and n>=k*k: print("YES") else: print("NO")
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
import math t = int(input()) for i in range(t): x,y,a,b = list(map(int,input().split())) if (y - x) % (a+b) == 0 and (a+b) <= (y - x): print((y-x)//(a+b)) else: print(-1)
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
l = int(input()) s = input() ans = '' i = 0 step = 1 while i < l: ans += s[i] i += step step += 1 print(ans)
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side. Determine a minimal number of wooden bars which are needed t...
3
#!/usr/bin/env python3 # Door Frames n = int(input()) a = int(input()) b = int(input()) res = [[0 for i in range(5)] for j in range(3)] size = [[0 for i in range(5)] for j in range(3)] def get_max_size(i, j): u = size[j-1][i] if j else 0 l = size[j][i-1] if i else 0 ru = res[j-1][i] if j else i rl = ...
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he...
3
n,p,q,r= map(int, input().split()) a=list(map(int,input().split())) pmax=[None]*n smax=[None]*n pmax[0]=a[0]*p for i in range (1,n): pmax[i]=max(pmax[i-1],a[i]*p) smax[n-1]=r*a[n-1] for i in range(n-2,-1,-1): smax[i]=max(smax[i+1],a[i]*r) answer=-99999999999999999999999999999999999999999999999999 for i in ra...
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
num = int(input()) value = list(map(int,input().split())) value.sort() big = [] while sum(big) <= sum(value): big.append(value.pop()) print(len(big))
Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides. Print the answer in degrees, but do not print units. Constraints * 3 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print an integer representing the sum of th...
3
N = int(input()) print(str(180*(N-2)))
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ...
3
import sys import math s = list(input()) l = len(s) m = int(input()) ai = list(map(int, input().split())) k = [0] * int(l / 2) for i in ai: k[i - 1] += 1 v = 0 for i in range(int(l / 2)): z = (k[i] + v) % 2 if(z != 0): s[i], s[l - i - 1] = s[l - i - 1], s[i] v = z print("".j...
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
n=int(input()) p=list(map(int,input().split())) q=list(map(int,input().split())) if len(p)>0: p.pop(0) if len(q)>0: q.pop(0) d=list(set(list(set(p))+list(set(q)))) if 0 in d: d.remove(0) if len(d)==n: print ("I become the guy.") else: print ("Oh, my keyboard!")
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b...
3
S = input() ans = 0 for i in range(1,len(S)): if S[i] != S[i-1]: ans += 1 print(ans)
Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible. String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too. Input First line of input con...
3
s=input() k=set(s) n=int(input()) l= len(s) m=len(k) if(n>l): print("impossible") else: if m>=n: print("0") else: print(n-m)
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) if n%2!=0: k=n//2 #x.append(a[0]) for i in range(1,n-2,2): a[i],a[i+2]=a[i+2],a[i] a[n-2],a[n-1]=a[n-1],a[n-2] print(k) for i in a: print(i,end=" ") else: k=n//2-1 for i in range(1,n-2,2): a[i],a[i+2]=a[i+2],a[i] print(k) for i in ...
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that: 1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'. 2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s...
3
import sys # import heapq from math import ceil,floor RI = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() mod = 10**9+7 # for _ in range(int(ri())): st = ri() a = [] cnt = 0 for i in st: if i == 'a': cnt+=1 if i == 'b': if cnt!= 0: ...
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it. Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time...
3
input() a = list(map(int, input().split())) b = list(map(int, input().split())) a_min, b_min = min(a), min(b) a_max, b_max = max(a), max(b) if a_min * 2 >= b_min or b_min <= a_max: print("-1") elif a_max >= a_min * 2: print(a_max) else: print(a_min * 2)
There are N cats. We number them from 1 through N. Each of the cats wears a hat. Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me." Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats. Constraints * 2 ≤ N ...
3
n = int(input()) l = list(map(int,input().split())) l.sort() ans = "Yes" count = 1 if l[0] == l[-1]: if ((n // 2) < l[0]) and (l[0] != 1) and (l[0] != n - 1): ans = "No" elif l[-1] - l[0] >= 2: ans = "No" else: for i in range(n-1): if l[i+1] - l[i] == 0: count += 1 elif l[i+1] - l[i] == 1: ...
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
3
def f(letra): c=0 if letra in ['a','e','i','o','u']: c=1 return c s=input() t=input() if len(s)!=len(t): print('No') else: for i in range(len(s)): if f(s[i])!=f(t[i]): print('No') break else: print('Yes')
You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i...
3
import bisect def occurances(s, t): locations = [] for i in range(len(s) - len(t) + 1): if t == s[i:i+len(t)]: locations.append(i) return locations if __name__ == '__main__': n, m, num_queries = list(map(int, input().split(' '))) s = input() t = input() locations = occ...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
3
from sys import stdin,stdout ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() mod = 1000000007 n = ii1() print('abcd' * (n // 4) + 'abcd'[: n % 4])
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive). In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content? Here the subsequence of A is a sequence obtained by removing zero or ...
3
n,m = map(int,input().split()) S = list(map(int,input().split())) T = list(map(int,input().split())) mod = 10**9+7 dp = [1]*(m+1)#Tをiまで見た時のSとの部分列のも場合の数 for i in range(n): tmp = dp[:] for j in range(m): if S[i]==T[j]: dp[j+1] = (tmp[j+1] + dp[j])%mod else: dp[j+1] =(tmp[j+...
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break. The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch...
3
n,k=[int(x) for x in input().split()] a=[[int(x) for x in input().split()] for j in range(n)] #n,k=1,5 #a=[[1,7]] f=[] for i in range(n): if(a[i][1]<=k): f.append(a[i][0]) else: f.append(a[i][0]-(a[i][1]-k)) print(max(f))
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
def main(): n, k = map(int, input().split()) res = n * (k // (n - 1)) + (k % (n - 1) if k % (n - 1) else -1) print(res) for _ in range(int(input())): main()
A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R. Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and pl...
3
a,b,c,d = map(int, input().split()) if a+b > c+d: print('Left') elif c+d > a+b: print('Right') else: print('Balanced')
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() x = list(s) sample = list("he") if "h" in x: x = x[x.index("h") + 1:] if "o" in x: x = x[::-1][x[::-1].index("o") + 1:][::-1] if "e" in x: x = x[x.index("e") + 1:] if "l" in x: x = x[::-1][x[::-1].index("l") + 1:][::-1] if "l" ...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
# -*- coding: utf-8 -*- """ Created on Fri Aug 14 15:34:10 2020 @author: Lucky """ n = int(input()) lst = [] for i in range(n): lst.append(input()) s = 1 for i in range(n-1): if lst[i] != lst[i+1]: s += 1 print(s)
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the s...
3
a=input() b=input() i=len(a)-1 j=len(b)-1 ans=0 while i>=0 and j>=0 and a[i]==b[j]: i-=1 j-=1 print(ans+i+2+j)
Given is a positive integer N. We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K. * Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K. In how many choices of K will N become 1 in the end? Constraints * 2 \leq N ...
3
N = int(input()) def divisors(n): ret1 = [] ret2 = [] i = 1 while i**2 <= N: if n%i == 0: ret1 += [i] ret2 += [n//i] i += 1 return ret1 + ret2 ans1 = len(set(divisors(N-1))) - 1 ans2_cand = set(divisors(N)) ans2 = 0 for k in ans2_cand: if k == 1: continu...
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline ...
1
from math import fabs,sqrt n,k =[int (c) for c in raw_input().split(" ")] x,y=[float (c) for c in raw_input().split(" ")] res=0.0 for i in range(1,n): x1,y1=[float (c) for c in raw_input().split(" ")] ax=fabs(x1-x) ay=fabs(y1-y) x=x1; y=y1; res+=(sqrt(ax*ax+ay*ay)) res = res/50.0*k; prin...
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the n piles with stones numbered from 1 to n. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ...
1
import sys def solve(): lines = [] for line in sys.stdin: lines.append(line) xs = [int(x) for x in lines[1].split(" ")] ys = [int(y) for y in lines[2].split(" ")] if sum(xs) < sum(ys): print "No" else: print "Yes" if __name__ == '__main__': solve()
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
1
# -*- coding: utf-8 -*- import sys def fi(): return int(sys.stdin.readline()) def fi2(): return map(int, sys.stdin.readline().split()) def fi3(): return sys.stdin.readline() def fo(*args): for s in args: sys.stdout.write(str(s)+' ') sys.stdout.write('\n') INF=10**9+7 sys.setrecursionlimit...
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
n = int(input()) string = input().lower() letters = 'abcdefghijklmnopqrstuvwxyz' if n < 26: print('NO') else: for i in letters: if not i in string: print('NO') break else: print('YES')
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa...
3
import math a, b, c, d = [int(s) for s in input().split(" ")] p = [a, b, c] p.sort() ans = 0 if d > abs(p[1]-p[0]): ans += d - abs(p[1]-p[0]) if d > abs(p[1]-p[2]): ans += d-abs(p[1]-p[2]) print(ans)