problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding dire... | 3 | import sys,functools,collections,bisect,math,heapq
input = sys.stdin.readline
#print = sys.stdout.write
sys.setrecursionlimit(200000)
mod = 10**9 + 7
def fun(a,b,s):
x,y = 0,0
for d in s:
if d == 'L':
if ((x-1)==a and y==b):
continue
x -= 1
if d == 'R':
... |
You are given N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given f... | 3 | from sys import stdin
N = int(stdin.readline())
A = sorted([int(stdin.readline()) for i in range(N)])
a = [0] * N
b = [0] * N
j = 1
for i in range(N-1):
a[i] += -j
a[i+1] += j
b[i] += j
b[i+1] += -j
j = -j
a.sort()
b.sort()
s1 = s2 = 0
for i in range(N):
s1 += a[i] * A[i]
s2 += b[i] * A[i... |
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | 3 | n = int(input())
doors = [int(i) for i in input().split(' ')]
left = doors.count(0)
right = doors.count(1)
for i, k in enumerate(doors):
if left == 0:
print(i)
break
if right == 0:
print(i)
break
if k == 0:
left -= 1
elif k == 1:
right -= 1
|
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.
Let A be a set of positions in the string. Let's call it pretty if following conditions are met:
* letters on positions from A in the string are all distinct and lowercase; ... | 3 | n=int(input())
s=input()
sub=[]
ans=0
for a in range(0,n):
letter=s[a]
#print("letter",letter)
if (letter not in sub) and letter.islower()==True:
sub.append(letter)
#print(sub)
if letter.islower()==False or a==n-1:
#print(sub)
ans=max(ans,len(sub))
sub=[]
... |
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n=int(input())
l=[]
for i in range(n):
l.append(1)
for i in range (1,n):
for j in range(1,n):
l[j]=l[j]+l[j-1]
print(l[n-1]) |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 1 | a, b = map(int, raw_input().split())
# total = 0
# while a > 0:
# print a, total
# total += a
# a = a/b + a%b
# print a, total
# if a/b == 0:
# print total+a
# exit(0)
# raw_input()
# print total
# left is # candles left from prev round
# a is num candles from curr round
total, ... |
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 | itter = int(input())
while(itter>0):
a= input()
if(len(a))>10:
print(str(a[0])+str(len(a)-2)+str(a[-1]))
else:
print(a)
itter = itter -1
|
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ... | 3 | if __name__== '__main__':
n,m = map(int,input().split())
s=[item for item in input().split()]
t=[item for item in input().split()]
q=int(input())
for i in range(q):
y=int(input())
ps=y%n
pt=y%m
print(s[ps-1]+t[pt-1])
|
There are N mountains ranging from east to west, and an ocean to the west.
At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.
The height of the i-th mountain from the west is H_i.
You can certainly see the ocean from the inn at the top of the westmost mountain.
F... | 3 | n = int(input())
h = list(map(int, input().split()))
c = 1
for i in range(1, n):
if h[i] >= max(h[:i]):
c += 1
print(c) |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | from collections import deque
t = int(input())
def solve():
t = int(input())
q = deque(list(map(int, input().split())))
na = q.popleft()
nb = 0
cnt = 1
prev = na
while len(q)>0:
tmp = 0
if cnt % 2 == 1:
while prev >= tmp and len(q) > 0:
tmp += q.p... |
Sereja loves integer sequences very much. He especially likes stairs.
Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met:
a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.
For example, sequences [1, 2, 3, 2... | 1 | if __name__=="__main__":
m = int(raw_input())
b = map(int, raw_input().split())
b.sort()
b.reverse()
top = b[0]
cnt = 1
tl = top
tr = top
l = []
r = []
while cnt < m:
bc = b[cnt]
if bc < tl:
l.append(bc)
tl = bc
elif bc < tr:... |
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ... | 3 | def read_few_numbers():
nums = map(int, input().split(' '))
return nums
#0 - blue
#1 - red
n = int(input())
s = input()
output = ''
blue_level = 0
red_level = 0
blue_string = ''
red_string = ''
for i in range(n):
if s[i] == '(':
if blue_level < red_level:
output += '0'
blu... |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | n = int(input())
nicknames = {}
for i in range(n):
query = input()
try:
k = nicknames[query]
except:
nicknames[query] = 0
if nicknames[query] == 0:
print('OK')
nicknames[query] += 1
else:
print(query + str(nicknames[query]))
nicknames[query] += 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 | n = input().lower()
m = input().lower()
if n < m:
print(int(-1))
elif m < n:
print(int(1))
else:
print(int(0)) |
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb... | 3 | def cnt(a):
a.sort()
n = len(a)
ans = 0
cnt = a[n//2-1]
for i in a:
ans+=abs(i-cnt)
return ans
for _ in range(int(input())):
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
b = []
ans = 0
c = [[False fo... |
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 | '''
Amirhossein Alimirzaei
Telegram : @HajLorenzo
Instagram : amirhossein_alimirzaei
University of Bojnourd
'''
C=0
N1=int(input())
N=input()
for _ in range(N1-1):
if N[_]==N[_+1]:
C+=1
print(C) |
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.
Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.
He is allowed to at most once discard two or three cards wi... | 3 | def solve(arr):
d = {}
for i in arr:
if d.get(i):
d[i]+=1
else:
d[i] = 1
max_val = 0
for i in d:
if d[i] > 1:
count = d[i] if d[i] <= 3 else 3
if count*int(i) > max_val:
max_val = count*int(i)
return sum(arr)-max_val
def main() :
arr = list(map(int, inp... |
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... | 1 | if __name__ == "__main__":
string = raw_input()
string = string.lower()
vocals = ['a', 'e', 'i', 'o', 'u', 'y']
for e in vocals:
string = string.replace(e, '')
buff2 = list()
for e in string:
buff2.append('.' + e)
st = ""
st = st.join(buff2)
print st |
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 | x = int(input())
y = list(map(int, input().split()))
o = 0
e = 0
a = 0
for i in range(x):
if (y[i] % 2 == 0):
e+=1
else:
o+=1
if(o>e):
for ia in range(x):
if (y[ia] %2 == 0):
print(ia+1)
quit()
if(e>o):
for ib in range(x):
if (y[ib] % 2 != 0):
print(ib+1)
quit() |
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 1 | a = []
b = int(raw_input())
lister = []
temp = b
rows = 2
columns = 1
while b>0:
a.append(1)
b-=1
while rows <= temp:
while columns <= temp:
if columns ==1:
lister.append(1)
else:
lister.append(lister[columns - 2]+a[columns -1])
columns +=1
rows... |
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.
You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca... | 3 | q = int(input())
for fwefe in range(q):
n = int(input())
j = 0
z = 0
par = []
npar = []
for i in range(n):
s = input()
je = s.count('1')
ze = s.count('0')
j += je
z += ze
if len(s) % 2 == 0:
par.append(len(s))
else:
npar.append(len(s))
par.sort()
wyn = 0
for i in par:
if j < 0 or z < 0:
... |
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.
Help Kurt find the maximum possible product of digits among all integers from 1 to n.
Input
The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9).
Output
Print the... | 1 | #! /usr/bin/python
n = int(raw_input())
sn = [int(x) for x in str(n)]
def prod(arr):
res = 1
for x in arr:
res *= x
return res
if sn[0] == 1:
print 9**(len(sn) - 1)
else:
maxP = prod(sn)
for i in range(0, len(sn) - 1):
cur = prod([int(x) for x in sn[:i]] + [int(sn[i]) - 1] + [9 for _ in range(i + 1, len(s... |
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | for _ in range(int(input())):
x,y=map(int,input().split())
a,b=map(int,input().split())
if x>y:
x,y=y,x
print((y-x)*a+min(x*b,2*x*a)) |
A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$.
Constraints
* $2 \leq |V... | 3 | import sys
from collections import deque
sys.setrecursionlimit(200000)
class Dinic:
def __init__(self,v, inf =10**10):
self.v = v
self.inf = inf
self.G = [[] for _ in range(v)]
self.level = [-1]*v#深さ
self.ite = [0]*v#DFSでの探索が済んでいるか否か
def add_edge(self, fr, to,... |
Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.
She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).
However, as mentioned before, she is very ... | 3 | n, k =map(int, input().split())
d = list(map(int, input().split()))
a = [0]*10
for i in d:
a[i]=1
ans = n
while True:
flg = False
temp = str(n)
l = len(temp)
for i in range(l):
if a[int(temp[i])]==1:
n+=1
flg = True
break
if flg:
continue
else:
print(n)
quit()
|
Takahashi is practicing shiritori alone again today.
Shiritori is a game as follows:
* In the first turn, a player announces any one word.
* In the subsequent turns, a player announces a word that satisfies the following conditions:
* That word is not announced before.
* The first character of that word is the same a... | 3 | n = int(input())
words = [input()]
for i in range(n-1):
s = input()
if s in words or words[-1][-1] != s[0]:
print("No")
exit()
words.append(s)
print("Yes")
|
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n=int(input())
count=0
while(n>0):
n=n-1
k=input()
if k.count('1') >= 2:
count+=1
print(count) |
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | 3 | input()
a = list(map(int, input().split()))
for i in range(1,3005):
if i not in a:
print(i)
exit() |
Nauuo is a girl who loves writing comments.
One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.
It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul... | 3 | x, y, z = map(int, input().split())
p = x - y
if abs(p)>z and p>0:
print("+")
elif abs(p)>z and p<0:
print("-")
elif abs(p)==z and z==0:
print("0")
elif abs(p)<=z and z!=0:
print("?")
|
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.
They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all c... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 02:06:24 2020
@author: Dark Soul
"""
n=int(input(''))
arr=list(map(int,input().split()))
arr.sort()
x=arr.count(arr[n-1])
if x%2:
print("Conan")
else:
cnt=[0]*100005
for i in arr:
cnt[i]+=1
flag=0
for i in cnt:
if i%2:
f... |
We have a grid with N rows and M columns of squares. Initially, all the squares are white.
There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attach... | 3 | n,m,K = map(int,input().split())
ans = "No"
for k in range(n+1):
for l in range(m+1):
if k*(m-l)+(n-k)*l == K:
ans = "Yes"
break
print(ans) |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 1 | n=input()
if(n<=4 or n%2!=0):
print "0"
else:
if(n%4==0):
print n/4-1
else:
print n/4
|
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 | from math import ceil
t = int(input())
ans = []
for i in range(t):
n, d = map(int,input().split())
for j in range(n):
if j + ceil(d / (j + 1)) <= n:
ans.append('YES')
break
else:
ans.append('NO')
for i in ans:
print(i) |
You are given a number g. Find a sequence A of length n which satisfies the following condition:
GCD ( A0, A1, A2, .... ,Ai, ..... ,An-1 ) = g.
Ai > g, ∀ 0 ≤ i < n.
Ai ≥ Aj, ∀ j ≤ i
Define a function, *sum(A) = A0 + A1 + .... + An-1.
If multiple sequences satisfy first three properties, print the one which minim... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
T = input()
for i in range(T):
[g,n] = map(int,raw_input().split())
if g!=0:
for i in range(n-1):
print g*2,
print g*3 |
Petya has a rectangular Board of size n × m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the oper... | 3 | import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from sys import stdout
print = stdout.write
n, m, k = map(int, input().split())
for _ in range(k*2):
a = input()
k = ['L']*(m-1)
j = ['R']*(m-1)
ans = ['D']*(n-1)
ans += j
ans += k
for i in range(n-1):
ans += ['U']
if i%2 ==0:
ans += j
else... |
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that... | 1 | a = map(int, raw_input().split())
print -1 if(sum(a) % len(a) != 0 or sum(a) == 0) else (sum(a) / len(a))
|
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | print(1/int(input())*sum(int(i) for i in input().split() )) |
Fatal Eagle is trying his best to save his city, but he's failing to do so. He knows he needs some external help; some guidance, something... something out of ordinary to defeat this powerful enemy called Mr. XYZ.
"Find out the number of pairs in the list you've made, who sum up to
an even number!"
"Who are you? And w... | 1 | t = int(raw_input())
while t:
t-=1
n = int(raw_input())
l = [int(x) for x in raw_input().split()]
count = 0
for i in range(n):
for j in range(i,n):
#print l[i],l[j]
if l[i]!=l[j] and (l[i]+l[j])%2==0:
count+=1
print count |
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.
Input
The first line contains a single... | 3 | import time,math as mt,bisect,sys
from sys import stdin,stdout
from collections import defaultdict
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin... |
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | 3 | V = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y']
C = ['b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G',
'h', 'H', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M',
'n', 'N', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S',
't', 'T', 'v', 'V', 'w', 'W', 'x', 'X', 'z', 'Z']
s = [x for x in input() if x.isal... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w = int(input())
if w%2 != 0 or w == 2:
w = "NO"
else:
w="YES"
print(w) |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | n = int(input())
ans = int((n*n*n + 5*n)/6)
print(ans) |
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high.
Vladimir has just planted n bamboos in a row, each of... | 3 | import itertools
unfold = itertools.chain.from_iterable
speedup = 400000
def jumps(a):
d = speedup
while d < a - 1:
c = (a + d - 1) // d
d = (a + c - 2) // (c - 1)
yield d
def calc(d):
return sum(d - 1 - (i - 1) % d for i in a)
def ans():
for d, pd in zip(D, D[1:]):
... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | n=int(input())
s=input()
s=s.split()
a=0
for i in range(0, n):
a=a+int(s[i])
print(a/n) |
Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started t... | 1 | from math import factorial
n=int(raw_input())
d=[[]]*n
for i in xrange(n):
d[i]=raw_input()
l1=0
for i in xrange(n):
k=0
for i2 in xrange(n):
if d[i][i2]=="C":
k+=1
if k>1:
l1+=factorial(k)/(factorial(2)*factorial(k-2))
l2=0
for i in xrange(n):
k=0
for i2 in xrange(n)... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
s = 0
for i in range(n):
views = input()
views_a = views.split(" ")
if views.count("1") > 1:
s += 1
else:
pass
print(s)
|
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes.
A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe... | 3 | k, n, s, p = map(int, input().split())
pn = k * (n // s + (n % s != 0))
print(pn // p + (pn % p != 0))
|
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 | s=input()
for i in range(len(s)):
if(int(s[i])>=5):
s=s.replace(s[i],str(9-int(s[i])),1)
if(s[0]=='0'):
s=s.replace(s[0],'9',1)
print(s)
|
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, ... | 3 | from collections import Counter
k = int(input())
s = input()
c = Counter(s)
s1 = ""
x = 0
for i in c:
if c[i]%k==0:
s1 += i*(c[i]//k)
else:
x = 1
print(-1)
break
if x==0:
print(s1*k)
|
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... | 1 | x=map(int,raw_input().split())
z=x[0]
for i in range (0,x[1]):
if z%10==0:
z=z/10
else:
z=z-1
print z
|
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia... | 3 | def startchis(s):
if len(s) > 0 and s[0] == 'x':
return 1 + startchis(s[1:])
return 0
def f(s):
output = 0
while len(s) > 0:
m = startchis(s)
if m == 0:
s = s[1:]
else:
if m >= 3:
output += (m-2)
s = s[m:]
return ou... |
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit... | 3 | from collections import defaultdict
def test_case():
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
groups = defaultdict(lambda: defaultdict(int))
for y, row in enumerate(a):
for x, val in enumerate(row):
groups[x + y][int(val)] += 1
... |
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | 1 | n = int(raw_input())
s = raw_input().strip()
ans = 0
x = 0
y = 0
sw = 0
p = "X"
for i in s:
if i == "U":
y += 1
else:
x += 1
if sw == 1 and p == i:
ans += 1
if x == y:
sw = 1
else:
sw = 0
p = i
print ans |
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only th... | 3 | n,d,h = (int(i) for i in input().split())
if h*2 < d or n < d+1 or d == 1 and n > 2 :
print(-1)
else:
for i in range(h):
print(i+1,i+2)
ost = h+1
if d > h:
print(1,ost+1)
for i in range(d-h-1):
print(ost+i+1,ost+i+2)
if d != h:
for i in range(1,n-d):
p... |
At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.
The nameplate is to be rectangular an... | 3 | s = input()
for i in range(1, 6):
for j in range(1, 21):
if len(s) > i * j:
continue
y = i * j - len(s)
z = y % i
p = y // i
start = 0
print(i, j)
for k in range(i):
a = j - p
print("*" * p, end="")
if z > 0:
... |
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.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | a=list(input())
count=0
for i in a:
if i=='4' or i=='7':
count+=1
if count==4 or count==7:
print('YES')
else:
print('NO') |
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
* f(599) = 6: 599 + 1 = 600 → 60 → 6;
* f(7) = 8: 7 + 1 = 8;
* f(9) = 1: 9 + 1 = 10 → 1;
* f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101.
... | 3 | g = 1
dict = {}
def f(x):
global dict
dict[x] = dict.get(x, 0) + 1
x += 1
while x % 10 == 0:
x //= 10
return x
n = int(input())
while n not in dict or n + 1 % 10 !=0 and (n + 1) not in dict:
n = f(n)
print(len(dict)) |
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive in... | 3 | num_cases = int(input())
for _ in range(num_cases):
num = int(input())
x = input().strip().split()
x = [int(a) for a in x]
even = []
odd = []
for a in x:
if (a%2 == 0):
even.append(a)
else:
odd.append(a)
if (len(even)%2 == 0):
print("YES")
else:
x.sort()
found = 0
for i in range(len(x)-1):
... |
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | 3 | a,n=0,int(input())
if n%2<1:
n//=2
while n:n//=5;a+=n
print(a) |
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats... | 3 | t=int(input())
while(t):
t-=1
r=list(map(int,input().split()))
r.sort()
d=0
re=r[2]-r[1]
if(re>=r[0]):
d+=r[0]
r[2]-=r[0]
d+=min(r[1],r[2])
print(d)
continue
d+=re
r[2]-=re
r[0]-=re
r[2]-=(r[0]-(r[0]//2))
r[1]-=r[0]//2
d+=(r[0]-(r[0]//2))+(r[0]//2)
d+=min(r[1],r[2])
print(d)
|
Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array a = [a_1, a_2, …, a_n] of n distinct integers. An array b = [b_1, b_2, …, b_k] is called nice if for any two distinct elements b_i, b_j of b, |b_i-b_j| appears ... | 3 | import math,sys
#sys.stdin=open('input.txt','r')
#sys.stdout=open('output.txt','w')
inp=lambda : int(input())
li=lambda: list(map(int,input().split()))
ma=lambda : map(int,input().split())
def solve():
n=inp()
l=li()
r=[]
r=l
flag2=1
flag=0
count=len(l)
s=set(l)
while(count<300):
... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
result = 0
for i in range(n):
if (input().split().count('1') >= 2):
result += 1
print(result) |
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... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 12:48:19 2018
@author: Lenovo
"""
s=input()
n1=s.count('1')
n2=s.count('2')
n3=s.count('3')
string=n1*'1+'+n2*'2+'+n3*'3+'
l=list(string)
del l[len(string)-1]
'''
delimiter=''
print(delimiter.join(l))
'''
print(''.join(l)) |
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | for _ in range(int(input())):
a,b,c,n=map(int,input().split())
if (a+b+c+n)%3==0:
x=max(a,b,c)
y=min(a,b,c)
z=a+b+c-x-y
if (n-x-x+y+z)>=0 and (n-x-x+y+z)%3==0:
print('YES')
else:
print('NO')
else:
print('NO')
|
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | 3 | n=input()
a= n.find('AB')
b= n[a+2:].find('BA')
c= n.find('BA')
d= n[c+2:].find('AB')
print("YES" if a>=0 and b>=0 or c>=0 and d>=0 else "NO ") |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | n , m = input().split()
n , m = [ int(n) , int(m) ]
s = []
k = 0
for i in input().split() :
k += int(i)
s.append(k)
ind = 0
for i in input().split() :
if int(i) <= s[ind] :
if ind == 0 :
print(ind+1 , int(i) )
else :
print(ind+1 , int(i) - s[ind-1] )
else :
... |
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro... | 3 | n = int(input())
string = str(input())
count = 0
first = 0
for i in range(n-10):
if string[i] == '8':
count += 1
if count > (n-11)/2:
print("YES")
else:
print("NO")
|
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a , b = map(int, input().split())
ctr=0
while a<=b:
a=a*3
b=b*2
ctr+=1
print(ctr) |
Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:
for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key
Note... | 3 | n = int(input())
a = list(map(int,input().split()))
for i in range(n):
v = a[i]
j = i-1
while j>=0 and a[j]>v:
a[j+1] = a[j]
j -= 1
a[j+1] = v
print(*a,sep=' ')
|
You are given an array a, consisting of n integers.
Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
l = list(map(int, input().split()))
a2 = [a[i] for i in range(n) if l[i] == 0]
a2.sort(key=lambda x: -x)
i = 0
for j in range(n):
if l[j] == 0:
a[j] = a2[i]
i += 1
print(*a)... |
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...
What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone... | 1 | import sys
sys.setrecursionlimit(10 ** 6)
# pow(3,2,5)==4
n,m=map(int,raw_input().split())
if n==m:
print 0
elif m==0:
print 1
else:
print min(n-m,m)
# 7 0 - 1
# 7 1 - 1
# 7 2 - 2
# 7 3 - 3
# 7 4 - 3
# 7 5 - 2
# 7 6 - 1
# 7 7 - 0
# 1 3 5 7
|
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j).
Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o... | 3 | rr = lambda: input().strip()
rrm = lambda: map(int, rr().split())
def solve():
n,m = rrm()
ans = 0
for i in range(n):
s = rr()
if(s[-1]=='R'):
ans += 1
ans += s.count('D')
return ans
T = int(rr())
for _ in range(T):
ans = solve()
print(ans) |
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five proble... | 3 | num_of_participants=int(input())
users=[]
users_names=[]
dic_user={}
res=0
for i in range(num_of_participants):
users.append(input().split())
users_names.append(users[i][0])
for i in range(len(users)):
users[i].append(int(users[i][1])*100+int(users[i][2])*-50+int(users[i][3])+int(users[i][4])+int(users[i][... |
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... | 3 | # Tasks
# - Create a script to `WORDLIST` problem using the .in and .out files
# - IMPLEMENT ROT13, ROT47, ETC...
# - Implement combinations(arr, r) -> returns all possible combinations or a generator
# --------------------
# 158 B - Taxi
# n = int(input())
# A = list(map(int, input().split()))
# A.sort(reverse=True)
#... |
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his... | 3 | k=int(input())
L={}
s=".123456789"
for i in s:
L[i]=0
for j in range(4):
s=input()
for i in s:
L[i]+=1
s="123456789"
done=True
for i in s:
if(L[i]>2*k):
print("NO")
done=False
break
if(done):
print("YES")
|
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum numb... | 3 | n=int(input())
h=list(map(int,input().split()))+[1e9+1]
c,d=0,0
for i in range(1,n+1):
if h[i-1]>=h[i]:
d+=1
else:
c=max(c,d)
d=0
print(c) |
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do t... | 3 | from math import*
from random import*
n = int(input())
flag = False
A, B = 0, 0
for i in range(n):
a, b = list(map(int, input().split()))
if a % 2 != b % 2:
flag = True
A, B = A + a, B + b
if A % 2 == 0 and B % 2 == 0:
print(0)
elif A % 2 == 1 and B % 2 == 1 and flag:
print(1)
else:
pri... |
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())
b=1
while sum(a*(a+1)/2 for a in range(1,b+1))<=n:b+=1
print(b-1) |
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.
These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o... | 3 | import math
def solve():
n, m, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
current = k
index = 0
iteration = 0
while index < m:
# None of the numbers found
if current < arr[index]:
current += math.ceil((arr[index] - current) / k) * k
... |
You survived several months of exam wars and were able to enter ICPC University on a sunny day. On the day of admission, there was an enthusiastic recruitment of circles on the campus of the university, and you received a large number of pamphlets and returned. When you return to your room, you find one of the pamphlet... | 3 | while True:
n=int(input())
if(n==0):
break
a=[]
for i in range(1, n):
a.append(i)
k=0
for i in range(n-2):
for j in range(i+2, n):
if(sum(a[i:j])==n):
k+=1
if(sum(a[i:j])>n):
break
print(k)
|
AtCoder Mart sells 1000000 of each of the six items below:
* Riceballs, priced at 100 yen (the currency of Japan) each
* Sandwiches, priced at 101 yen each
* Cookies, priced at 102 yen each
* Cakes, priced at 103 yen each
* Candies, priced at 104 yen each
* Computers, priced at 105 yen each
Takahashi wants to buy s... | 3 | x=int(input())
n=x//100
if 0<=x%100<=5*n:
print(1)
else:
print(0)
|
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.
Some examples of beautiful numbers:
* 12 (110);
* 1102 (610);
* 11110002 (12010);
* 111110... | 3 | n=int(input())
k=1
while n&1==0:
k+=1
n>>=1
while k>0:
d=(1<<k)-1
if n%d==0:
print(d<<k-1)
break
k-=1
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | n = int(input())
a=input()
b=input()
count=0
for i in range(n):
count+=min(abs(int(a[i])-int(b[i])),10-max(int(a[i]),int(b[i]))+min(int(a[i]),int(b[i])))
print(count) |
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ... | 3 | from sys import stdin
phrase=input()
i=0
while i<len(phrase) and phrase[i]=='a':
i+=1
j=i
while j<len(phrase) and phrase[j]!='a':
j+=1
if i>=len(phrase):
print(phrase[:-1]+"z")
else:
nouvellePhrase=phrase[:i]
for indice in range(i,j):
caractere=phrase[indice]
nouvelIndice= (ord(c... |
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 3 | # one with inexperience e must join a group of size >= e
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in... |
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... | 3 | n = input()
n = int(n)
a = list(map(int,input().split()))
e = max(a)
f = min(a)
if e == f:
print(0,(n*(n-1))//2)
else:
print (e-f,a.count(e)*a.count(f))
|
You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.
Input
The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains... | 1 | n = input()
arr = map(int,raw_input().split())
dist = []
cnt = 300000
dist1 = []
for x in xrange(n):
if arr[x] == 0:
cnt = 0
dist.append(cnt)
cnt += 1
cnt = 300000
for x in xrange(n):
if arr[n-1-x] == 0:
cnt = 0
dist1.append(cnt)
cnt += 1
for x in xrange(n):
print min(dist[x],dist1[n-1-x]), |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | import re
s = input()
print( len( set( re.split( r'[{,}]\s*', s ) ) ) - 1 ) |
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangle... | 3 | N, Max = int(input()), max(map(int, input().split()))
for i in range(N - 1):
X = list(map(int, input().split()))
if Max >= max(X):
Max = max(X)
elif Max >= min(X):
Max = min(X)
else:
print("NO")
exit()
print("YES")
# UB_CodeForces
# Advice: Life is all about moments, do... |
Little C loves number «3» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 ≤ n ≤ 10^9) — the integ... | 3 | def f(m):
for i in range(1,n+1):
for j in range(1,n-i):
if i%3!=0 and j%3!=0 and (n-i-j)%3!=0:
return i, j, n-i-j
n=eval(input())
nums=f(n)
print('{} {} {}'.format(nums[0], nums[1], nums[2]),end='')
|
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.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | n = int(input())
c=0
f=1
while n>0:
if n%10 == 4 or n%10 == 7:
c+=1
n//=10
#print(c)
while c>0:
if c%10!=4 and c%10!=7:
f=1
break
else:
f=0
c//=10
#print(f)
if f==0:
print("YES")
else:
print("NO") |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | word1 = input()
word2 = input()
word3 = word2[::-1]
if (word1 == word3):
print("YES")
else:
print("NO")
|
Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there a... | 3 | def inpl(): return [int(i) for i in input().split()]
N, M = inpl()
mod = 10**9+7
fac = [1 for _ in range(N+3)]
for i in range(N+2):
fac[i+1] = (i+1)*fac[i]%mod
if abs(N-M) > 1:
print(0)
elif N == M:
print(2*fac[N]*fac[M]%mod)
else:
print(fac[N]*fac[M]%mod) |
«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 | a=int(input())
b=int(input())
c=int(input())
d=int(input())
n=int(input())
l=[a,b,c,d]
count=0
for x in range(1,n+1) :
for y in l :
if not ( x % y ) :
count+=1
break
print(count)
|
Income Inequality
We often compute the average as the first step in processing statistical data. Yes, the average is a good tendency measure of data, but it is not always the best. In some cases, the average may hinder the understanding of the data.
For example, consider the national income of a country. As the term ... | 3 | while True:
n = int(input())
if n == 0:
break
datum = list(map(int, input().split()))
ave = sum(datum) / n
res = 0
for data in datum:
if data <= ave:
res += 1
print(res)
|
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | 3 | import random, math
a, b = map(int, input().split())
r = 1
if b > a + 6:
print(0)
else:
for i in range(a + 1, b + 1):
r *= i % 10
print(r % 10) |
A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.
You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasin... | 3 | def main():
n, d = map(int, input().split()) #n: Número de elementos, d:Número a agregar
sec = list(map(int, input().split())) #Secuancia
ans = 0
for i in range(1,n):
while sec[i] <= sec[i-1]:
need = (sec[i-1] - sec[i]) // d #Enteros necesarios para llegar a lo necesario
... |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 1 | import sys
def gcd(a, b):
if a < b:
a, b = b, a
while b != 0:
temp = a % b
a = b
b = temp
return a
inputs = sys.stdin.readline().split()
a = int(inputs[0])
b = int(inputs[1])
n = int(inputs[2])
turn = 1 #1 stands for simon's turn, 0 stands for Antisimon's turn
while True:
... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | num = int(input())
for i in range(num):
n = int(input())
k = 2
while n % (2**k - 1) != 0:
k += 1
print(n // (2**k - 1))
|
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ... | 3 | n,k = map(int,input().split())
string = input()
if k>=n:
print('YES')
else:
dic = {}
for i in string:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
count = 0
length = len(dic)
for i in dic:
if dic[i] > k:
break
count += 1
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.