problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., n. * The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i. * If the i-th character in s is `1`, we can have a connected component of size i by rem...
3
S=input() N=len(S) if S[-1]=="1": print(-1) exit() if S[0]=="0": print(-1) exit() if S[-2]=="0": print(-1) exit() for i in range(N-1): if S[i]!=S[N-2-i]: print(-1) exit() ans=[] nowzero=0 for i in range(N): if S[i]=="0": break nowzero+=1 if nowzero==N-1: f...
Salem gave you n sticks with integer positive lengths a_1, a_2, …, a_n. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x. A stick length a_i is...
3
# -*- coding: utf-8 -*- # @Date : 2019-01-21 13:04:33 # @Author : raj lath (oorja.halt@gmail.com) # @Link : link # @Version : 1.0.0 from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def read_ints() : return [int(x) for x in stdin.readline().spli...
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
import collections import sys n, k = map(int, input().split()) a = [int(x) for x in input().split()] col = [] t = 0 for i in range(n): col.append(t) t = (t+1)%k d = collections.defaultdict(set) for i in range(n): if not col[i] in d[a[i]]: d[a[i]].add(col[i]) else: cnt = 0 while((...
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
3
n,m,k=map(int,input().split()) if k<=n-1 : print(k+1,1) exit() r=m-1 ma=n*r k1=k-n+1 if k1>=ma : print(1,2) exit() p=k1//r if k1%r!=0 : p+=1 k1-=(m-1)*(p-1) if abs(n-p)%2!=0 : print(n-p+1,k1+1) else : print(n-p+1,m-k1+1)
One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written. As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≀ i < j ≀ n, ...
3
x,y= map(int,input().split()) a=[] for i in range(0,x): p=input() a.append(p) ans=1 b=[] for i in range (0,y): for j in range(0,x): b.append(a[j][i]) c=set(b) ans*=len(c) ans%=1000000007 b=[] print(ans)
We call a 4-digit integer with three or more consecutive same digits, such as 1118, good. You are given a 4-digit integer N. Answer the question: Is N good? Constraints * 1000 ≀ N ≀ 9999 * N is an integer. Input Input is given from Standard Input in the following format: N Output If N is good, print `Yes`; ot...
3
a=int(input()) print("YNeos"[(a//10)%111*(a%1000)%111>0::2])
Theater stage is a rectangular field of size n Γ— m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not. You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the fou...
3
inp = lambda: map(int, input().rstrip().split()) n, m = inp() mat = [] row = [] col = [] for i in range(n): mat += [list(inp())] row += [[0] * m] col += [[0] * m] # COunting across each row for i in range(n): t = 0 for j in range(m): if mat[i][j] == 1: t += 1 row[i][j] = ...
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
n = int(input()) s = input() def func(m): l = r = t = "" for i in range(0, m): l += s[i] for i in range(m, n): r += s[i] cn = 0 for i in range(0, len(r)): if r[i] == '0': l += '0' cn = cn+1 else: break r = r[cn:] if len...
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n Γ— m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
t=int(input()) while t>0: inp=[int(x) for x in input().split()] n,m=inp[0],inp[1] for i in range(n): for j in range(m): if i==n-1 and j==m-1: print("W",end="") else: print("B",end="") print() t-=1
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
3
n=int(input()) c=input() l=len(c) s=c[l-2:l] for i in range(1,n-1): ll=len(s) s=s[0:i//2+i%2]+c[l-2-i]+s[i//2+i%2:ll] print(s)
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
3
n,m = map(int, input().split()) d = {} for i in range(0, n): s = input() d[s] = 0 for i in range(0, m): s = input() if s in d: d[s] = 2 else: d[s] = 1 i = 0; two = False while True: two = False one = False for p in d: if d[p] == 2: del d[p] ...
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
3
n=int(input()) l=[*map(int,input().split())] l.sort() for i in range(n-2): a=l[i] b=l[i+1] c=l[i+2] if a+b>c and a+c>b and b+c>a: print("YES") break else: print("NO")
Write a program which computes the digit number of sum of two integers a and b. Constraints * 0 ≀ a, b ≀ 1,000,000 * The number of datasets ≀ 200 Input There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF. ...
1
while True: try: a, b = raw_input().split() #print a, b print len(str(int(a)+int(b))) except EOFError: break
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly n flowers. Vladimir went to a flower shop, and he was amazed to see that there are m types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers ...
3
import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) t=int(input()) for _ in range(t): n,m=[int(x) for x in input().split()] arr=[] #[(a,b),...] for __ in range(m): a,b=[int(x) for x in input().split()] arr.append((a,b)) if _!=t-1: i...
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
3
a=int(input());d=dict() for i in map(int,input().split()):d[i]=d.get(i,0)+1 print(a-max(d.values()))
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
1
s = raw_input() l = list(s) sumu = 0 suml = 0 for i in l: if i.isupper() == True: sumu += 1 else: suml += 1 if sumu > suml: print s.upper() else: print s.lower()
Β«One dragon. Two dragon. Three dragonΒ», β€” the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
3
from sys import stdin,stdout sum = 0 k = int(stdin.readline()) l = int(stdin.readline()) m = int(stdin.readline()) n = int(stdin.readline()) d = int(stdin.readline()) for i in range(1,d+1): if i % k == 0 or i % l ==0 or i % m == 0 or i % n == 0: sum += 1 else: pass print(sum)
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
1
n = int(raw_input()) ai = [int(x) for x in raw_input().split()] maxa = max(ai) suma = sum(ai) res = maxa holes = maxa * len(ai) - suma if (holes < res): res += (res - holes + len(ai) - 2) / (len(ai) - 1) #print (holes, maxa, res) print res
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
n=input() if n == n.upper(): print(n.lower()) elif n[0].islower() and n[1:] == n[1:].upper(): print(n[0].upper()+n[1:].lower()) else: print(n)
You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions: * each integer must be greater than 0; * the product of all n-1 numbers should be equal to k; * the number of 1-s among all n-1 integers must be minimum po...
3
from types import GeneratorType # Pajenegod's Infinite Recursion trick def recursive(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: ...
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume. There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea...
3
for _ in range(int(input())): a,b=map(int,input().split()) c=abs(a-b) k=int(0) k=k+c//5 c=c%5 k=k+c//2 c=c%2 k=k+c print(k)
Snuke loves puzzles. Today, he is working on a puzzle using `S`- and `c`-shaped pieces. In this puzzle, you can combine two `c`-shaped pieces into one `S`-shaped piece, as shown in the figure below: 9b0bd546db9f28b4093d417b8f274124.png Snuke decided to create as many `Scc` groups as possible by putting together one ...
3
n,m=map(int,input().split()) if 2*n<=m: res=m-2*n ans=n+res//4 else: ans=m//2 print(ans)
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()) count = 0 count1 = 0 for i in range(n): a, c, b = input() if a < b: count += 1 elif a > b: count1 += 1 else: count1 += 1 count += 1 if count > count1: print("Chris") elif count < count1: print("Mishka") else: print("Friendship is magic!^^")
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Syl...
1
n = input() s = raw_input() d = ["vaporeon","jolteon","flareon","espeon","umbreon","leafeon","glaceon","sylveon"] for x in d: if len(x) == len(s) and all(x[i]==j for i,j in enumerate(s) if s[i] != "."): print x break
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
from math import ceil n = int(input()) for x in range(n): a, b = [int(x) for x in input().split(" ")] highest = ceil(a/b) print(b*highest-a)
Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as follows. If all the numbers are equal, the game ends. Otherwise Select two numbers which are unequal Subtract the smaller number from the larger number Replace the larger number with the result from above (see the e...
1
#amsgame1.py """Chef is playing a game on a sequence of N positive integers, say A1, A2, ... AN. The game is played as follows. If all the numbers are equal, the game ends. Otherwise Select two numbers which are unequal Subtract the smaller number from the larger number Replace the larger number with the result from ab...
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
1
n, px, py = map(int, raw_input().split()) points = [] for i in range(n): x, y = map(int, raw_input().split()) points.append((x - px, y - py)) def dot(u, v): return u[0] * v[0] + u[1] * v[1] def closest(edge): u = (edge[1][0] - edge[0][0], edge[1][1] - edge[0][1]) v = (-edge[0][0], -edge[0][1]) ...
Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the...
3
n = int(input()) sp = list(map(int, input().split())) d = sp[1] - sp[0] for i in range(n-1): if d != sp[i+1] - sp[i]: print(sp[n-1]) break else: print(sp[n-1] + d)
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≀ i ≀ n and do one of the following operations: * eat exactly...
3
# n,m,ta,tb,k=map(int,input().split()) # lsta=list(map(int,input().split())) # lstb=list(map(int,input().split())) # j=0 # if(n<=k or m<=k): # print(-1) # exit() # # indx=-1 # for i in range(m): # if(lstb[i]>=lsta[0]+ta): # indx=i+1 # break # if(indx==-1): # print(-1) # exit() # if(i...
You are given four integers n, c_0, c_1 and h and a binary string s of length n. A binary string is a string consisting of characters 0 and 1. You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change. After some changes (possibly zero) ...
3
from collections import Counter from sys import stdin input = stdin.readline for _ in range(int(input())): n, c0, c1, h = map(int, input().split()) s = input().strip() c = Counter(s) #print(c) t1 = c0 * c['0'] + c1 * c['1'] t2 = n * c0 + h * c['1'] t3 = n * c1 + h * c['0'] #print(t1,t...
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
3
for i in range(int(input())): n=int(input());a=list(map(int,input().split())) for i in range(n): if i&1: print(-abs(a[i]),end=' ') else: print(abs(a[i]),end=' ') print()
Rama is in love with geometry. So once he was playing with circles and rectangles. Given the center of circle and radius and also the co-ordinates of vertices of rectangle, he wants to check whether the rectangle lies inside the circle or not. Note: If all the vertices are lie the circumference of circle then it shoul...
1
import sys def main(): t = int(raw_input()) for i in xrange(t): r,xc,yc = map(int,raw_input().split()) flag = True for j in xrange(4): x,y = map(int,raw_input().split()) if ((xc-x)**2)+((yc-y)**2)-(r**2) > 0: flag = False if flag: print "Yes" else: print "No" main()
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
3
for __ in range(int(input())): s=input() a=[0,*s,0] if any(x*2 in s for x in 'abc'): print(-1) continue for i in range(len(a)): if a[i]=='?': a[i] = (set('abc')-{a[i-1],a[i+1]}).pop() print(''.join(a[1:-1]))
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a=input() b=input() a=a.upper() b=b.upper() if a<b: print("-1") elif a>b: print("1") else: print(0)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
def abbreviate(s): if len(s) > 10: print(f"{s[0]}{len(s)-2}{s[-1]}") else: print(s) for _ in range(int(input())): abbreviate(input())
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
w = input() p = list("hello") for i in w: if i == p[0]: del p[0] if len(p) == 0: print("YES") break else: print("NO")
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a...
1
def is_palin(s): return s == s [::-1] s = raw_input() flg = 0 for i in range(97, 97+26): for j in range(0, len(s)+1): if is_palin(s[:j]+chr(i)+s[j:]): print s[:j]+chr(i)+s[j:] flg = 1 break if flg==1: break if flg==0: print 'NA'
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the...
3
n, m = map(int, input().split()) def fast_pow(a, b): res, ret = a, 1 while b > 0: if b % 2 == 1: ret = (ret * res) % m res = (res * res) % m b //= 2 return ret % m print((fast_pow(3, n) - 1) % m)
Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column. Gildong plays the g...
3
def sol(n,m,k,arr): for i in range(n-1): if m<0: print("NO") return m+=arr[i]-max(0,(arr[i+1]-k)) if m<0: print("NO") else: print('YES') t = int(input()) for _ in range(t): n, m, k = map(int, input().split()) arr = list(map(int, input().sp...
You are given an array a consisting of n integers. You can remove at most one element from this array. Thus, the final length of the array is n-1 or n. Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array. Recall that the contiguous subarray a wi...
3
n = int(input()) a = [1e18] + [int(i) for i in input().split()] + [-1] l, r = [0] * (n + 1), [0] * (n + 1) cnt = 0 for i in range(1, n + 1): if a[i] <= a[i - 1]: cnt = 0 cnt += 1 l[i] = cnt for i in reversed(range(1, n + 1)): if a[i] >= a[i + 1]: cnt = 0 cnt += 1 r[i] = cnt ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
s=input() s2=input() s,s2=s.lower(),s2.lower() if s<s2: print(-1) elif s==s2: print(0) else: print(1)
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water. It turned out that among Pasha's friends there are exactly n boys and exactly n...
1
from sys import stdin n, w = map(int, stdin.readline().split()) a = [float(item) for item in stdin.readline().split()] a.sort() if a[n]/2<=a[0]: tot = a[n]*n/2*3 else: tot = a[0]*3*n if tot<=w: print tot else: print w
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
3
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase import threading from bisect import bisect_right from math import gcd,log from collections import Counter,defaultdict from pprint import pprint def lcs(a,b): ans=0 dp=[[0]*(len(b)+1) for i in range(len(a)+1)] for i in range(1...
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
# @author import sys class BCodeforcesSubsequences: def solve(self, tc=0): from collections import defaultdict def factor(x): factors = [] i = 2 while x > 1: if x % i == 0: x = x / i factors.append(i) ...
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
for t in range(int(input())): x, y, n = map(int, input().split()) if n % x >= y: print(n - n % x + y) else: print(n - n % x - x + y)
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
3
n=int(input()) s=input() cnt=0 for i in range(0,n): s1=input() if s1[0]==s[0] and s1[1]==s[1] and s1[2]==s[2]: cnt+=1 else: cnt-=1 if cnt==0: print("home") else: print("contest")
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
1
import math n, m, a = map(float, raw_input().split(" ")) print int(math.ceil(n/a) * math.ceil(m/a))
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively. <image> An example of a trapezoid Find the area of this trapezoid. Constraints * 1≦a≦100 * 1≦b≦100 * 1≦h≦100 * All input values are integers. * h is even. Input The input is given from Standard Input i...
3
a = int(input()) b = int(input()) n = int(input()) print(int((a+b)*n/2))
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
n = int(input()) """ get from `a` to a multiple of `b` by increasing by 1 (1 move) make `a` divisible by `b` """ for _ in range(n): a, b = list(map(int, input().split())) result = ((b - a) % b + b) % b print(result)
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
k =int(input()) s='codeforces' count=0 check=0 val='' for i in range(1,51): if k<=i**10: if (i==1): break check=i-1 x=(i-1)**10 for j in range(0,10): x=int((x*i)/(i-1)) if x>=k: count=j+1 break break for m...
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any p...
3
def balls_game(balls, x): counts = [] for a in range(len(balls)): copy = balls.copy() copy.insert(a, x) this_count = 0 while True: i = 0 j = 0 while i < len(copy): j = i while j < len(copy) and copy[i] == copy[j]...
The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king. Check the king's moves here https://en.wikipedia.org/wiki/King_(chess). <image> King moves from the posi...
3
s=input() a=s[0] b=int(s[1]) count=0 if b+1<=8 and b+1>=1: #print(ord(a)) if ord(a)-1>=97 and ord(a)-1<=104: count+=1 if ord(a)+1<=104 and ord(a)+1>=97: count+=1 count+=1 #print(count) if b-1>=1 and b-1<=8: count+=1 if ord(a)+1<=104 and ord(a)+1>=97: count+=1 ...
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≀ x ≀ r_i, and ((x mod a) mod b) β‰  ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
3
t=int(input()) for i in range(t): a,b,q=map(int,input().split()) p=[0 for i in range(a*b)] j=1 for j in range(1,a*b): p[j]=p[j-1] if(((j%a)%b)!=((j%b)%a)): p[j]=p[j]+1 #j=j+1 m=[] for k in range(q): l,r=map(int,input().split()) x=r//(len(p)) y=(l-1)//len(p) m.append(p[r%(len(p))]-p[(l-1)%(len(p)...
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
3
n = input() laptops = [] for z in range(int(n)): laptop = dict() laptop['price'], laptop['quality'] = map(int, input().split(' ')) laptops.append(laptop) laptops.sort(key=lambda k: (k['price'], k['quality'])) laptops_copy = list(laptops) laptops_copy.sort(key=lambda k: (k['quality'], k['price'])) if lap...
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
3
rows, prevR, nextR, a, res = int(input()), [int(x) for x in input().split()], [], 0, [] def consumer(prevR): nextR, a, res = [], 0, [] for i in range(1, max(prevR) + 1): for x in prevR: if x >= i: nextR.append(x) a += 1 res.append(a) ...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
def arbus(): w = int(input()) if w == 2: return 'NO' elif w % 2: return 'NO' else: return 'YES' if __name__ == "__main__": print(arbus())
Let us consider the following operations on a string consisting of `A` and `B`: 1. Select a character in a string. If it is `A`, replace it with `BB`. If it is `B`, replace with `AA`. 2. Select a substring that is equal to either `AAA` or `BBB`, and delete it from the string. For example, if the first operation is ...
3
# https://atcoder.jp/contests/arc071/submissions/6325840 from itertools import accumulate convert = {'A': 1, 'B': 2} S = tuple(convert[x] for x in input()) T = tuple(convert[x] for x in input()) # ζœ€ι€Ÿ: convert # 欑点: *A, = map() # ζœ€δΈ‹δ½: A = tuple(map()) acc_s = (0,) + tuple(accumulate(S)) acc_t = (0,) + tuple(accum...
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x Γ— y, after that a mine will be i...
1
#L, R, U, D dx = [0, 0, -1, 1] dy = [-1, 1, 0, 0] dic = {'L':0, 'R':1, 'U':2, 'D':3} X, Y, x0, y0 = map(int, raw_input().split()) x0 -= 1; y0 -= 1 li = raw_input() done = [[False for j in xrange(Y)] for i in xrange(X)] nx, ny = x0, y0 done[nx][ny] = True cnt = 1 #num of True(visited) print 1, for i in xrange(len(li)...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
l=input() a='qwertyuiopasdfghjklzxcvbnm' A='QWERTYUIOPASDFGHJKLZXCVBNM' h=len(l) g=0 j=0 for i in l: if i in A: g=g+1 if g==h-1 and l[0] in a: j=1 if g==h: j=1 if j==1: p='' for x in l: if x in a: b=x.upper() p=p+b elif x in A: b=x.lower() p=p+b print(p) else: print(l)
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume. There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea...
3
n=int(input()) for i in range(n): a,b =map(int,input().split()) if a==b: print(0) else: s=0 c,d=max(a,b),min(a,b) s=(c-d)//5 m=(c-d)%5 if (m==4) or (m==3): print(s+2) elif(m==2) or (m==1): print(s+1) else: pr...
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kep...
3
from math import floor def bounded_sum(l, p1, p2): r = 0 for i in range(p1, p2 + 1): r += l[i] return r def solve(n, k, a): r = 0 for i in range(k): r += a[i] aux = r for j in range(k, n): r += a[j] - a[j-k] aux += r return aux/(n - k + 1) N, K = [int(i) for i in input().split()] A ...
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people" Igor just c...
3
n=int(input()) adj=[set() for i in range(6)] for _ in range(n): a,b=map(int,input().split()) adj[a].add(b) adj[b].add(a) for i in range(1,6): for j in adj[i]: for k in adj[j]: if i in adj[k]: print("WIN") exit() for i in range(1,6): adj[i]={1,2,3,4...
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 β‹… n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
3
import sys n = int(sys.stdin.readline()) h1 = list(map(int, sys.stdin.readline().split())) h2 = list(map(int, sys.stdin.readline().split())) best_last_up = [0] * (n + 2) best_last_down = [0] * (n + 2) for i in range(n): best_last_up[i + 1] = max(best_last_up[i + 1], best_last_down[i] + h1[i]) best_last_up[i ...
n! = n Γ— (n βˆ’ 1) Γ— (n βˆ’ 2) Γ— ... Γ— 3 Γ— 2 Γ— 1 Is called the factorial of n. For example, the factorial of 12 12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600 And there are two consecutive 0s at the end. Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of...
1
while 1: n = int(raw_input()) if n==0: break c = 0 while n: n /= 5 c += n print c
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
# http://codeforces.com/problemset/problem/25/A def main(): n = int(input()) numbers = [int(x) for x in input().split()] even = [] odd = [] for i, number in enumerate(numbers): if number % 2 == 0: even.append(i) else: odd.append(i) if len(even) >= ...
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
for i in range(int(input())): n,k,k1 = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) if max(a) > max(b): print("YES") continue print("NO")
N people are arranged in a row from left to right. You are given a string S of length N consisting of `0` and `1`, and a positive integer K. The i-th person from the left is standing on feet if the i-th character of S is `0`, and standing on hands if that character is `1`. You will give the following direction at mo...
3
N, K = map(int, input().split()) s = input() I = [] for j in range(len(s)): if j == 0: I.append(0) else: if s[j-1] != s[j]: I.append(j) r = len(I) I = I + [N] * (3*K) x = [] for k in range(r): if s[I[k]] == '0': x.append(I[k+2*K] - I[k]) else: x.append(I[k + 2...
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
3
n = int(input()) s = input() l = len(s) if l < 4: print(0) elif l == 4: if n == 3: if s[0] == s[1] and s[1] == s[2]: print(1) else: print(0) else: print(0) else: k = 0 dr = 0 while k + n < len(s): k += n if s[k - 1] == s[k - 2] and ...
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: * if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma...
3
t = int(input()) while t: s = input() n = len(s) x = int(input()) ans = ['1']*n for i in range(n): if s[i] == '0': if i+x<n: ans[i+x] = '0' if i-x>=0: ans[i-x] = '0' sdash = '' for i in range(n): if i+x<n: i...
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
n = int(input()) while 1: n += 1 s = list(str(n)) if len(set(s)) == 4: print(n) break
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor. The game is played on a square field consisting of n Γ— n cells. Initially all cells are empty. On each turn a pla...
3
if int(input()) %2 ==1: print ('1') else: print ('2')
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi, yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinate...
3
# import itertools # import bisect import math from collections import defaultdict import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10 ** 5) ii = lambda: int(input()) lmii = lambda: list(map(int, input().split())) slmii = lambda: sorted(map(int, input().split())) li = lambda: list(input()) m...
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a ...
1
import sys def shortest(s): x,y = 0,0 p = set([(x,y)]) for c in s: q = [(x+1,y),(x-1,y),(x,y+1),(x,y-1)] if c=='L': x,y = x-1,y elif c=='R': x,y = x+1,y elif c=='U': x,y = x,y+1 elif c=='D': x,y = x,y-1 if ...
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
z,zz=input,lambda:list(map(int,z().split())) zzz=lambda:[int(i) for i in stdin.readline().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collections import * from math import * fro...
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
3
from math import factorial as f def C(n, k): return f(n) // (f(n - k) * f(k)) s = input() t = input() p = s.count('+') p2 = t.count('+') q = t.count('?') if p == p2: ans = 0.5 ** q elif p2 > p: ans = 0 elif q < p - p2: ans = 0 else: ans = (C(q, p - p2) / 2 ** q) print(ans)
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
1
a= input() b= [int(i) for i in raw_input().split()] d=max(b)-min(b) if max(b)!=min(b): w=b.count(max(b))*b.count(min(b)) else: c=b.count(max(b))-1 w=int((float(c)/2)*(2+(c-1))) print d,w
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
3
x = int(input()) y = [int(i) for i in input().split()] a = sum(y) b = 0 for i in y: if (a - i) % 2 == 0: b += 1 print(b)
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
3
n = int(input()) b = sorted(map(int,input().split())) c = set(b) if len(b)==len(c):print(1,n) else: q=1 for i in c: q = max(q,b.count(i)) print(q,len(c))
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()) a = input() d = a.lower() f = 'abcdefghijklmnopqrstuvwxyz' z = len(d) y = [] for i in range(z): if d[i] in f and d[i] not in y: y.append(d[i]) if len(y) >= 26: print('YES') else: print('NO')
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got n positive integers....
3
n,k = map(int,input().split()) a = list(map(int,input().split())) c =0 for i in a: st = str(i) ct = st.count("4")+st.count("7") if ct<=k: c +=1 print(c)
Our Code Monk recently learnt about Graphs and is very excited! He went over to the Graph-making factory to watch some freshly prepared graphs. Incidentally, one of the workers at the factory was ill today, so Monk decided to step in and do her job. The Monk's Job is to Identify whether the incoming graph is a tr...
1
n=input() a=map(int,raw_input().split()) if sum(a)==(2*n-2): print "Yes" else: print "No"
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
3
a, b, c, d = map(int, input().split()) misha, vasya = max((3 * a) / 10, a - (a / 250) * c), max((3 * b) / 10, b - (b / 250) * d) if (misha > vasya): print("Misha") elif (vasya > misha): print('Vasya') else: print('Tie')
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≀ i, j ≀ n; 0 ≀ x ≀ 10^9); 2. assign a_i := a_i - x β‹… i, a_j := a_j + x β‹… i. After each operation, all elements of the array s...
3
import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) if sum(a)%n!=0: print(-1) continue objective=sum(a)//n ans=[] for i in range(2,n+1): if a[i-1]%i!=0: ans.ap...
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
lucky = [4, 7, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777] n = int(input()) flag = 0 for i in lucky: if n % i == 0: print("YES") flag = 0 break else: flag = 1 if flag == 1: print("NO")
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
a = int(input()) b = input() d = {i: 0 for i in ['o', 'n', 'e', 'z', 'r']} for i in b: d[i] += 1 ones = min(d['n'], d['o'], d['e']) d['e'] -= ones d['o'] -= ones zeros = min(d['z'], d['e'], d['r'], d['o']) for i in range(ones): print(1, end = " ") for i in range(zeros): print(0, end = " ") print()
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
n=int(input()) s=input() r=0 k=0 for i in range(n): if s[i]=='R': r+=1 else: k+=1 print(r+1+k)
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
3
import sys n=int(input()) arr=list(map(int,input().split())) min1=sys.maxsize for i in range(n): temp=list(map(int,input().split())) temp2=0 temp2+=sum(temp)*5+arr[i]*15 if min1>temp2: min1=temp2 print(min1)
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ...
3
n=int(input()) a=0 b=0 c=0 for i in range(n): c=i+1 s=int((c*(c+1))/2) # print(s) a+=s if a<=n: # print(a) b=i+1 # print(b) else: break print(b)
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive. You are allowed to do the following changes: * Choose any index i (1 ≀ i ≀ n) and swap characters a_i and b_i; * Choose any index i (1 ≀ i ≀ n) and sw...
3
from collections import defaultdict,Counter,deque read = lambda: list(map(int,input().split())) getinfo = lambda grid: print(list(map(print,grid))) p = lambda x: print(x,end=" ") inf = float('inf') mod = 10**9+7 n = int(input()) A = input() B = input() res = 0 for i in range(n//2): j = n-i-1 if Counter([A[i]...
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo...
1
string = raw_input() n=int(string) result=None def luckynumber(entry,four,seven): global result # print (entry) if seven==four: if not result: if entry>=n: result=entry else: if entry>=n and result>entry: result=entry if entry>...
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph. There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ...
1
###Codeforces problem 456A### n = input() C = [] for i in xrange(n): a = map(int, raw_input().split()) c = 0 for j in xrange(n): if a[j] == 1 or a[j] == 3: c += 1 if c == 0: C.append(i + 1) k = len(C) print k for i in xrange(k): print C[i],
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,...
3
import sys from sys import stdin from collections import defaultdict import bisect def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def inputs(f=int): return list(map(f, stdin.readline().strip().split())) def solve(): N = int(input()) arr = inputs() assert N == len(arr) ...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
str=input() l=len(str) i=0 ans="" while i<l : a=str[i] a=a.lower() if a=="a" or a=="e" or a=="i" or a=="o" or a=="u" or a=="y" : b="" else : b="."+a ans=ans+b i=i+1 print(ans)
You are given four integers a, b, x and y. Initially, a β‰₯ x and b β‰₯ y. You can do the following operation no more than n times: * Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y. Your task is to fi...
1
for _ in range(input()): a,b,x,y,n=map(int,raw_input().split()) op1=min(a-x,n) op2=min(b-y,n-op1) ans1=(a-op1)*(b-op2) op1=min(b-y,n) op2=min(a-x,n-op1) ans2=(a-op2)*(b-op1) print min(ans1,ans2)
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()) s=input() c=0 for i in range(1,n): if(s[i]==s[i-1]): c=c+1 print(c)
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≀ i ≀ j ≀ n - 1), that <image>...
3
import sys import math from collections import defaultdict def read_line(): return sys.stdin.readline()[:-1] def read_int(): return int(sys.stdin.readline()) def read_int_line(): return [int(v) for v in sys.stdin.readline().split()] n = read_int() a = read_int_line() s = [0]*(n+1) for i in range(n): s[i+1] ...
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
y,w=list(map(int,input().split())) x=max(y,w) p=(6-x)+1 pl=['1/1','5/6','2/3','1/2','1/3','1/6'] print(pl[x-1])
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
3
n,x = [int(i) for i in input().split()] dis = 0 for _ in range(n): arr = [i for i in input().split()] if arr[0] == '+': x = x + int(arr[1]) if arr[0] == '-' and x < int(arr[1]): dis = dis + 1 if arr[0] == '-' and x >= int(arr[1]): x = x - int(arr[1]) print(x,dis)
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D e...
3
def solve(n, m, k): if k < n: return k+1, 1 else: kk = k-n mm = m-1 kc = kk%mm kr = kk//mm if kr%2 == 0: return n-kr, 2+kc else: return n-kr, m-kc n,m,k = [int(s) for s in input().split()] x,y = solve(n,m,k) print(x, y)
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct. Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exi...
3
K = int(input()) used = set() S = input() indexes = [] ind = 0 while len(indexes) < K and ind < len(S): if S[ind] not in used: indexes += [ind] used.add(S[ind]) ind += 1 if len(indexes) < K: print("NO") else: print("YES") for i, v in enumerate(indexes): if i ...