contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
---|---|---|---|
109 | Lucky Interval | Title: Lucky Interval
Time Limit: 4 seconds
Memory Limit: 512 megabytes
Problem Description:
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.
One day Petya came across an interval of numbers [*a*,<=*a*<=+<=*l*<=-<=1]. Let *F*(*x*) be the number of lucky digits of number *x*. Find the minimum *b* (*a*<=<<=*b*) such, that *F*(*a*) = *F*(*b*), *F*(*a*<=+<=1) = *F*(*b*<=+<=1), ..., *F*(*a*<=+<=*l*<=-<=1) = *F*(*b*<=+<=*l*<=-<=1).
Input Specification:
The single line contains two integers *a* and *l* (1<=≤<=*a*,<=*l*<=≤<=109) — the interval's first number and the interval's length correspondingly.
Output Specification:
On the single line print number *b* — the answer to the problem.
Demo Input:
['7 4\n', '4 7\n']
Demo Output:
['17\n', '14\n']
Note:
Consider that [*a*, *b*] denotes an interval of integers; this interval includes the boundaries. That is, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/18b4a6012d95ad18891561410f0314497a578d63.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
import sys
class HappyNumbers:
def solve(self):
a, l = map(int, input().split())
print(self.doit(a, l))
def doit(self, a, l):
if l >= 10:
first = a
last = a + l - 1
return self.doit(first // 10, last // 10 - first // 10 + 1) * 10 + first % 10
else:
cnts = [self.count_lucky(a + i) for i in range(l)]
return self.doit_from(cnts, a + 1)
def doit_from(self, cnts, min_val):
if len(cnts) == 1:
return self.doit_one(cnts[0], min_val)
elif len(cnts) == 2 and min_val <= 1:
return self.doit_two_simple(cnts[0], cnts[1], min_val)
res = sys.maxsize
for last_digit in range(10):
max_val = last_digit + len(cnts) - 1
ncnts = [-1] * ((max_val // 10) + 1)
ok = True
for i in range(len(cnts)):
cur = last_digit + i
need = cnts[i]
if cur % 10 == 4 or cur % 10 == 7:
need -= 1
if need < 0:
ok = False
break
if ncnts[cur // 10] < 0 or ncnts[cur // 10] == need:
ncnts[cur // 10] = need
else:
ok = False
break
if not ok:
continue
new_min = min_val // 10 - 3
while new_min * 10 + last_digit < min_val:
new_min += 1
tmp = self.doit_from(ncnts, new_min) * 10 + last_digit
res = min(res, tmp)
return res
def doit_two_simple(self, cnt_first, cnt_second, min_val):
if cnt_first == 0 and cnt_second == 0:
return min_val
if cnt_first == cnt_second:
res = 0
for _ in range(cnt_first):
res = res * 10 + 4
return res * 10
elif cnt_first == cnt_second + 1:
res = 0
for _ in range(cnt_first):
res = res * 10 + 4
return res
elif cnt_first + 1 == cnt_second:
res = 0
for _ in range(cnt_second):
res = res * 10 + 4
return res - 1
else:
return sys.maxsize
def doit_one(self, cnt, min_val):
p10 = 1
pow_val = 0
while p10 <= min_val:
p10 *= 10
pow_val += 1
p10 *= 100
pow_val += 2
while pow_val < cnt + 2:
p10 *= 10
pow_val += 1
res = 0
while True:
for cur_digit in range(10):
cur_cnt = 0
if cur_digit == 4 or cur_digit == 7:
cur_cnt = 1
if self.possible(res, p10, pow_val, cnt - cur_cnt, min_val):
cnt -= cur_cnt
break
res += p10
if cur_digit == 9:
raise RuntimeError()
if p10 == 1:
break
p10 //= 10
pow_val -= 1
return res
def possible(self, res, p10, pow_val, need_lucky, min_val):
if need_lucky > pow_val or need_lucky < 0:
return False
cur = 0
for _ in range(pow_val - need_lucky):
cur = cur * 10 + 9
for _ in range(need_lucky):
cur = cur * 10 + 7
return res + cur >= min_val
def count_lucky(self, x):
res = 0
while x > 0:
digit = x % 10
x //= 10
if digit == 4 or digit == 7:
res += 1
return res
def main(self):
self.reader = sys.stdin
self.writer = sys.stdout
self.solve()
self.reader.close()
self.writer.close()
def next_int(self):
return int(self.next_token())
def next_long(self):
return int(self.next_token())
def next_double(self):
return float(self.next_token())
def next_token(self):
while not self.tokenizer or not self.tokenizer.hasMoreTokens():
self.tokenizer = input().split()
return self.tokenizer.pop(0)
if __name__ == "__main__":
happy_numbers = HappyNumbers()
happy_numbers.main()# 1693083120.1205668
``` |
113 | Grammar Lessons | Title: Grammar Lessons
Time Limit: 5 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
- There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. - There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. - Masculine adjectives end with -lios, and feminine adjectives end with -liala. - Masculine nouns end with -etr, and feminime nouns end with -etra. - Masculine verbs end with -initis, and feminime verbs end with -inites. - Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. - It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. - There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. - A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
- Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. - All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input Specification:
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output Specification:
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Demo Input:
['petr\n', 'etis atis animatis etis atis amatis\n', 'nataliala kataliala vetra feinites\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
s=input().split()
if(len(s)==1):
if(s[0].endswith("lios") or s[0].endswith("etr") or s[0].endswith("liala") or s[0].endswith("etra") or s[0].endswith("inites") or s[0].endswith("initis")):
print("YES")
else:
print("NO")
elif(s[0].endswith("lios") or s[0].endswith("etr")):
n=len(s)
i=0
while(i<n and s[i].endswith("lios")):
i+=1
if(i==n):
print("NO")
elif(s[i].endswith("etr")):
i+=1
while(i<n and s[i].endswith("initis")):
i+=1
if(i==n):
print("YES")
else:
print("NO")
else:
print("NO")
elif(s[0].endswith("liala") or s[0].endswith("etra")):
n=len(s)
i=0
while(i<n and s[i].endswith("liala")):
i+=1
if(i==n):
print("NO")
elif(s[i].endswith("etra")):
i+=1
while(i<n and s[i].endswith("inites")):
i+=1
if(i==n):
print("YES")
else:
print("NO")
else:
print("NO")
else:
print("NO")
``` |
61 | Capture Valerian | Title: Capture Valerian
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
It's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.
Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.
Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.
Each door has 4 parts. The first part is an integer number *a*. The second part is either an integer number *b* or some really odd sign which looks like R. The third one is an integer *c* and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.
*c* is an integer written in base *a*, to open the door we should write it in base *b*. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!
Here's an explanation of this really weird number system that even doesn't have zero:
Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.:
- I=1- V=5- X=10- L=50- C=100- D=500- M=1000
Symbols are iterated to produce multiples of the decimal (1, 10, 100, 1,<=000) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I 1, II 2, III 3, V 5, VI 6, VII 7, etc., and the same for other bases: X 10, XX 20, XXX 30, L 50, LXXX 80; CC 200, DCC 700, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.
Also in bases greater than 10 we use A for 10, B for 11, etc.
Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.
Input Specification:
The first line contains two integers *a* and *b* (2<=≤<=*a*,<=*b*<=≤<=25). Only *b* may be replaced by an R which indicates Roman numbering system.
The next line contains a single non-negative integer *c* in base *a* which may contain leading zeros but its length doesn't exceed 103.
It is guaranteed that if we have Roman numerals included the number would be less than or equal to 300010 and it won't be 0. In any other case the number won't be greater than 101510.
Output Specification:
Write a single line that contains integer *c* in base *b*. You must omit leading zeros.
Demo Input:
['10 2\n1\n', '16 R\n5\n', '5 R\n4\n', '2 2\n1111001\n', '12 13\nA\n']
Demo Output:
['1\n', 'V\n', 'IV\n', '1111001\n', 'A\n']
Note:
You can find more information about roman numerals here: http://en.wikipedia.org/wiki/Roman_numerals | ```python
a, b = input().strip().split(' ')
c = input()
a = int(a)
def conv(num,b):
convStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num < b:
return convStr[num]
else:
return conv(num//b,b) + convStr[num % b]
def write_roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
t = int(c.lower(),a)
if b != 'R':
print(conv(t,int(b)))
else:
print(write_roman(t))
``` |
61 | Hard Work | Title: Hard Work
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!
Some days before the contest, the teacher took a very simple-looking exam and all his *n* students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.
Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.
Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.
Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said:
- As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. - As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. - The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 - My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. - Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN - You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. - I should remind you that none of the strings (initial strings or answers) are empty. - Finally, do these as soon as possible. You have less than 2 hours to complete this.
Input Specification:
The first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively.
In the fourth line there is a single integer *n* (0<=≤<=*n*<=≤<=1000), the number of students.
Next *n* lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively.
Output Specification:
For each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK.
Demo Input:
['Iran_\nPersian;\nW_o;n;d;e;r;f;u;l;\n7\nWonderfulPersianIran\nwonderful_PersIAN_IRAN;;_\nWONDERFUL___IRAN__PERSIAN__;;\nIra__Persiann__Wonderful\nWonder;;fulPersian___;I;r;a;n;\n__________IranPersianWonderful__________\nPersianIran_is_Wonderful\n', 'Shapur;;\nis___\na_genius\n3\nShapur__a_is___geniUs\nis___shapur___a__Genius;\nShapur;;is;;a;;geni;;us;;\n']
Demo Output:
['ACC\nACC\nACC\nWA\nACC\nACC\nWA\n', 'WA\nACC\nACC\n']
Note:
none | ```python
word1 = input().lower()
word1 = word1.replace(";", "").replace("-", "").replace("_", "")
word2 = input().lower()
word2 = word2.replace(";", "").replace("-", "").replace("_", "")
word3 = input().lower()
word3 = word3.replace(";", "").replace("-", "").replace("_", "")
possibilities = [word1+word2+word3, word3+word2+word1, word2+word1+word3, word3+word1+word2, word1+word3+word2, word2+word3+word1]
n = int(input())
for i in range(n):
current = input().lower()
current = current.replace(";", "").replace("-", "").replace("_", "")
if current in possibilities:
print("ACC")
else:
print("WA")
``` |
61 | Ultra-Fast Mathematician | Title: Ultra-Fast Mathematician
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input Specification:
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output Specification:
Write one line — the corresponding answer. Do not omit the leading 0s.
Demo Input:
['1010100\n0100101\n', '000\n111\n', '1110\n1010\n', '01110\n01100\n']
Demo Output:
['1110001\n', '111\n', '0100\n', '00010\n']
Note:
none | ```python
s=input()
s1=input()
n=""
for i in range(len(s)):
if s[i]=="1" and s1[i]=="1":
n=n+"0"
elif s[i]=="0" and s1[i]=="0":
n=n+"0"
else:
n=n+"1"
print(n)
``` |
6 | President's Office | Title: President's Office
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with *n* rows and *m* columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
Input Specification:
The first line contains two separated by a space integer numbers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the length and the width of the office-room, and *c* character — the President's desk colour. The following *n* lines contain *m* characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output Specification:
Print the only number — the amount of President's deputies.
Demo Input:
['3 4 R\nG.B.\n.RR.\nTTT.\n', '3 3 Z\n...\n.H.\n..Z\n']
Demo Output:
['2\n', '0\n']
Note:
none | ```python
# / *
#
# / \ | | / \ | | | |
# / __\ | | / __\ |--| | |
# / \ |__ | __ / \ | | \__ /
#
# __ __
# / \ | / | ) / \ | )
# / __\ |< |-< / __\ |-<
# / \ | \ |__) / \ | \
#
# * /
def main():
nc, mc, p_c = [i for i in input().split()]
n, m = int(nc), int(mc)
arr = []
empty = str('.' * (m + 2))
# print(empty)
arr.append(empty)
for j in range(n):
x = '.' + input() + '.'
arr.append(x)
arr.append(empty)
dabsha_set = {"0"}
for i, ele1 in enumerate(arr):
for j, ele2 in enumerate(ele1):
if ele2 == p_c:
if arr[i - 1][j] != '.' and arr[i - 1][j] != p_c:
dabsha_set.add(arr[i - 1][j])
if arr[i + 1][j] != '.' and arr[i + 1][j] != p_c:
dabsha_set.add(arr[i + 1][j])
if arr[i][j - 1] != '.' and arr[i][j - 1] != p_c:
dabsha_set.add(arr[i][j - 1])
if arr[i][j + 1] != '.' and arr[i][j + 1] != p_c:
dabsha_set.add(arr[i][j + 1])
print(len(dabsha_set) - 1)
if __name__ == '__main__':
main()
``` |
56 | Bar | Title: Bar
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw *n* people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?
The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) which is the number of the bar's clients. Then follow *n* lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators.
Only the drinks from the list given above should be considered alcohol.
Output Specification:
Print a single number which is the number of people Vasya should check to guarantee the law enforcement.
Demo Input:
['5\n18\nVODKA\nCOKE\n19\n17\n']
Demo Output:
['2\n']
Note:
In the sample test the second and fifth clients should be checked. | ```python
def readln(): return tuple(map(int, input().split()))
lst = 'ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE'.split(', ')
n, = readln()
ans = 0
for _ in range(n):
inp = input()
try:
if int(inp) < 18:
ans += 1
except:
if inp in lst:
ans += 1
print(ans)
``` |
8 | Beads | Title: Beads
Time Limit: 5 seconds
Memory Limit: 64 megabytes
Problem Description:
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue — instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.
It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 — for a blue one. From two strings the Martian puts earlier the string with a red bead in the *i*-th position, providing that the second string has a blue bead in the *i*-th position, and the first two beads *i*<=-<=1 are identical.
At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index *k*.
All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
Input Specification:
The input file contains two integers *n* and *k* (2<=≤<=*n*<=≤<=50;1<=≤<=*k*<=≤<=1016) —the length of a string of beads, and the index of the string, chosen by Zorg.
Output Specification:
Output the *k*-th string of beads, putting 0 for a red bead, and 1 — for a blue one. If it s impossible to find the required string, output the only number -1.
Demo Input:
['4 4\n']
Demo Output:
['0101\n']
Note:
Let's consider the example of strings of length 4 — 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string — 0101. | ```python
n, m = map(int, input().split())
m += 1
def calc(l, r, eq, eq_i):
if l > r:
return 1
key = l, eq, eq_i
if key in f:
return f[key]
t = 0
for x in (['0', '1'] if s[l] == '?' else [s[l]]):
if l == r:
a = [x]
else:
a = ['0', '1'] if s[r] == '?' else [s[r]]
for y in a:
if not((eq and x > y) or (eq_i and x == y == '1')):
t += calc(l + 1, r - 1, eq and x == y, eq_i and x != y)
f[key] = t
return t
s = ['?'] * n
for i in range(n):
s[i] = '0'
f = {}
p = calc(0, n - 1, True, True)
if m > p:
m -= p
s[i] = '1'
if s[0] == '0':
print(''.join(s))
else:
print(-1)
``` |
1 | Theatre Square | Title: Theatre Square
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
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's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
Input Specification:
The input contains three positive integer numbers in the first line: *n*,<=<=*m* and *a* (1<=≤<=<=*n*,<=*m*,<=*a*<=≤<=109).
Output Specification:
Write the needed number of flagstones.
Demo Input:
['6 6 4\n']
Demo Output:
['4\n']
Note:
none | ```python
import math
x,y,z=list(map(float, input().split()))
print(math.ceil(x/z)*math.ceil(y/z))
``` |
35 | Animals | Title: Animals
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Once upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once.
DravDe dreamt about managing a successful farm. He dreamt that every day one animal came to him and asked him to let it settle there. However, DravDe, being unimaginably kind, could send the animal away and it went, rejected. There were exactly *n* days in DravDe’s dream and the animal that came on the *i*-th day, ate exactly *c**i* tons of food daily starting from day *i*. But if one day the animal could not get the food it needed, it got really sad. At the very beginning of the dream there were exactly *X* tons of food on the farm.
DravDe woke up terrified...
When he retold the dream to you, he couldn’t remember how many animals were on the farm by the end of the *n*-th day any more, but he did remember that nobody got sad (as it was a happy farm) and that there was the maximum possible amount of the animals. That’s the number he wants you to find out.
It should be noticed that the animals arrived in the morning and DravDe only started to feed them in the afternoon, so that if an animal willing to join them is rejected, it can’t eat any farm food. But if the animal does join the farm, it eats daily from that day to the *n*-th.
Input Specification:
The first input line contains integers *n* and *X* (1<=≤<=*n*<=≤<=100,<=1<=≤<=*X*<=≤<=104) — amount of days in DravDe’s dream and the total amount of food (in tons) that was there initially. The second line contains integers *c**i* (1<=≤<=*c**i*<=≤<=300). Numbers in the second line are divided by a space.
Output Specification:
Output the only number — the maximum possible amount of animals on the farm by the end of the *n*-th day given that the food was enough for everybody.
Demo Input:
['3 4\n1 1 1\n', '3 6\n1 1 1\n']
Demo Output:
['2\n', '3\n']
Note:
Note to the first example: DravDe leaves the second and the third animal on the farm. The second animal will eat one ton of food on the second day and one ton on the third day. The third animal will eat one ton of food on the third day. | ```python
import sys
sys.stdin = open('input.txt')
sys.stdout = open('output.txt', 'w')
A = lambda: map(int, input().split())
yesh, s = A()
k = 0
for q in sorted(q * (yesh - i) for i, q in enumerate(A())):
s -= q
if s < 0: break
k += 1
print(k)
``` |
34 | Sale | Title: Sale
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains *n* space-separated integers *a**i* (<=-<=1000<=≤<=*a**i*<=≤<=1000) — prices of the TV sets.
Output Specification:
Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most *m* TV sets.
Demo Input:
['5 3\n-6 0 35 -2 4\n', '4 2\n7 0 0 -7\n']
Demo Output:
['8\n', '7\n']
Note:
none | ```python
n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
res = 0
for i in range(m):
if a[i] < 0:
res += abs(a[i])
else:
break
print(res)
``` |
32 | Borze | Title: Borze
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input Specification:
The first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).
Output Specification:
Output the decoded ternary number. It can have leading zeroes.
Demo Input:
['.-.--\n', '--.\n', '-..-.--\n']
Demo Output:
['012', '20', '1012']
Note:
none | ```python
ls=[]
str=input()
op=" "
i=0
while i<len(str):
if str[i]=='.':
op=op+"0"
if str[i]=='-':
if str[i+1]=='.':
i=i+1
op=op+"1"
elif str[i+1]=='-':
i=i+1
op=op+"2"
i=i+1
print(op)
``` |
29 | Traffic Lights | Title: Traffic Lights
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A car moves from point A to point B at speed *v* meters per second. The action takes place on the X-axis. At the distance *d* meters from A there are traffic lights. Starting from time 0, for the first *g* seconds the green light is on, then for the following *r* seconds the red light is on, then again the green light is on for the *g* seconds, and so on.
The car can be instantly accelerated from 0 to *v* and vice versa, can instantly slow down from the *v* to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0.
What is the minimum time for the car to get from point A to point B without breaking the traffic rules?
Input Specification:
The first line contains integers *l*, *d*, *v*, *g*, *r* (1<=≤<=*l*,<=*d*,<=*v*,<=*g*,<=*r*<=≤<=1000,<=*d*<=<<=*l*) — the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light.
Output Specification:
Output a single number — the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10<=-<=6.
Demo Input:
['2 1 3 4 5\n', '5 4 3 1 1\n']
Demo Output:
['0.66666667\n', '2.33333333\n']
Note:
none | ```python
l, d, v, g, r = map(int,input().split())
t = 0.0
if (d/v)%(g+r) < g:
t = l/v
else:
t = ((d / v)// (g + r)+1)*(g+r) + (l-d)/v
print("%.8f"%t)
``` |
20 | Equation | Title: Equation
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given an equation:
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input Specification:
The first line contains three integer numbers *A*,<=*B* and *C* (<=-<=105<=≤<=*A*,<=*B*,<=*C*<=≤<=105). Any coefficient may be equal to 0.
Output Specification:
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Demo Input:
['1 -5 6\n']
Demo Output:
['2\n2.0000000000\n3.0000000000']
Note:
none | ```python
a,b,c=map(int,input().split())
t=[1,-c/b]if b else[-(c==0)]
if a:
d,x=b*b-4*a*c, -2*a
if d: t=[0]if d<0 else[2]+sorted([(b-d**0.5)/x,(b+d**0.5)/x])
else: t=[1,b/x]
print(*t)
``` |
78 | Easter Eggs | Title: Easter Eggs
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The Easter Rabbit laid *n* eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
- Each of the seven colors should be used to paint at least one egg. - Any four eggs lying sequentially should be painted different colors.
Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
Input Specification:
The only line contains an integer *n* — the amount of eggs (7<=≤<=*n*<=≤<=100).
Output Specification:
Print one line consisting of *n* characters. The *i*-th character should describe the color of the *i*-th egg in the order they lie in the circle. The colors should be represented as follows: "R" stands for red, "O" stands for orange, "Y" stands for yellow, "G" stands for green, "B" stands for blue, "I" stands for indigo, "V" stands for violet.
If there are several answers, print any of them.
Demo Input:
['8\n', '13\n']
Demo Output:
['ROYGRBIV\n', 'ROYGBIVGBIVYG\n']
Note:
The way the eggs will be painted in the first sample is shown on the picture: | ```python
lst='ROYGBIV'
n=int(input())
print(lst,end='')
for j in range(7,n):
k=(j-4)
print(lst[k],end='')
lst+=lst[k]
print()
``` |
47 | Coins | Title: Coins
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
Input Specification:
The input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters «A», «B» and «C». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B.
Output Specification:
It the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters «A», «B» and «C» which represent the coins in the increasing order of their weights.
Demo Input:
['A>B\nC<B\nA>C\n', 'A<B\nB>C\nC>A\n']
Demo Output:
['CBA', 'ACB']
Note:
none | ```python
def find_coin_order(weightings):
coins = [0, 0, 0]
for weighting in weightings:
coin1, relation, coin2 = weighting
if relation == '>':
coins[ord(coin1) - ord('A')] += 1
coins[ord(coin2) - ord('A')] -= 1
else:
coins[ord(coin1) - ord('A')] -= 1
coins[ord(coin2) - ord('A')] += 1
if coins.count(0) != 1:
return "Impossible"
order = ['A', 'B', 'C']
order.sort(key=lambda x: coins[ord(x) - ord('A')])
return ''.join(order)
weightings = []
for _ in range(3):
weighting = input().strip()
weightings.append(weighting)
coin_order = find_coin_order(weightings)
print(coin_order)
``` |
43 | Letter | Title: Letter
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading *s*1 and text *s*2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.
Input Specification:
The first line contains a newspaper heading *s*1. The second line contains the letter text *s*2. *s*1 и *s*2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.
Output Specification:
If Vasya can write the given anonymous letter, print YES, otherwise print NO
Demo Input:
['Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog\n', 'Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'abcdefg hijk\nk j i h g f e d c b a\n']
Demo Output:
['NO\n', 'YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
a=''.join(input().split())
b=''.join(input().split())
c=set(list(b))
q=True
for i in c:
if b.count(i)>a.count(i):
q=False
if q:
print('YES')
else:
print('NO')
``` |
112 | Petya and Square | Title: Petya and Square
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya loves playing with squares. Mum bought him a square 2*n*<=×<=2*n* in size. Petya marked a cell inside the square and now he is solving the following task.
The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal up to rotation.
Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.
Input Specification:
The first line contains three space-separated integers 2*n*, *x* and *y* (2<=≤<=2*n*<=≤<=100,<=1<=≤<=*x*,<=*y*<=≤<=2*n*), representing the length of a square's side and the coordinates of the marked cell. It is guaranteed that 2*n* is even.
The coordinates of the marked cell are represented by a pair of numbers *x* *y*, where *x* represents the number of the row and *y* represents the number of the column. The rows and columns are numbered by consecutive integers from 1 to 2*n*. The rows are numbered from top to bottom and the columns are numbered from the left to the right.
Output Specification:
If the square is possible to cut, print "YES", otherwise print "NO" (without the quotes).
Demo Input:
['4 1 1\n', '2 2 2\n']
Demo Output:
['YES\n', 'NO\n']
Note:
A sample test from the statement and one of the possible ways of cutting the square are shown in the picture: | ```python
a,b,c=map(int,input().split())
if(b==a//2 or b==a//2+1) and (c==a//2 or c==a//2+1):
print("NO")
else:
print("YES")
``` |
58 | Chat room | Title: Chat room
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
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 Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
Input Specification:
The first and only line contains the word *s*, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.
Output Specification:
If Vasya managed to say hello, print "YES", otherwise print "NO".
Demo Input:
['ahhellllloou\n', 'hlelo\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
s=list(input())
n='NO'
for i in range(len(s)):
if s[i]=='h' :
for i_1 in range(i,len(s)):
if s[i_1]=='e' :
for i_2 in range(i_1,len(s)):
if s[i_2]=='l' :
for i_3 in range(i_2+1,len(s)):
if s[i_3]=='l' :
for i_4 in range(i_3,len(s)):
if s[i_4]=='o' :
n='YES'
break
continue
continue
continue
print(n)
``` |
71 | Way Too Long Words | Title: Way Too Long Words
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
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 like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). Each of the following *n* lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output Specification:
Print *n* lines. The *i*-th line should contain the result of replacing of the *i*-th word from the input data.
Demo Input:
['4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis\n']
Demo Output:
['word\nl10n\ni18n\np43s\n']
Note:
none | ```python
def way_too_long_words(txt_arr):
res = []
for input_txt in txt_arr:
n = len(input_txt)
if n <= 10:
res.append(input_txt)
else:
res.append(input_txt[0] + str(n-2) + input_txt[-1])
return res
if __name__ == "__main__":
n = int(input())
txt_arr = []
for _ in range(n):
txt_arr.append(input())
res_arr = way_too_long_words(txt_arr)
for res in res_arr:
print(res)
``` |
50 | Domino piling | Title: Domino piling
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input Specification:
In a single line you are given two integers *M* and *N* — board sizes in squares (1<=≤<=*M*<=≤<=*N*<=≤<=16).
Output Specification:
Output one number — the maximal number of dominoes, which can be placed.
Demo Input:
['2 4\n', '3 3\n']
Demo Output:
['4\n', '4\n']
Note:
none | ```python
m, n = [int(i) for i in input().split()]
x = 2
S = n * m
s = 0
print(S // x)
``` |
43 | Football | Title: Football
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of lines in the description. Then follow *n* lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.
Output Specification:
Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.
Demo Input:
['1\nABC\n', '5\nA\nABA\nABA\nA\nA\n']
Demo Output:
['ABC\n', 'A\n']
Note:
none | ```python
n=int(input())
has={}
for i in range(n):
x=input()
if x in has:
has[x]=has[x]+1
else:
has[x]=1
x=max(has.values())
for i in has.keys():
if has[i]==x:
print(i)
``` |
59 | Word | Title: Word
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
Input Specification:
The first line contains a word *s* — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
Output Specification:
Print the corrected word *s*. If the given word *s* has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.
Demo Input:
['HoUse\n', 'ViP\n', 'maTRIx\n']
Demo Output:
['house\n', 'VIP\n', 'matrix\n']
Note:
none | ```python
x = input()
upper = 0
lower = 0
for i in x:
if i.isupper():
upper = upper +1
if i.islower():
lower = lower +1
if lower>=upper:
print(x.lower())
else:
print(x.upper())
``` |
41 | Translation | Title: Translation
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
Input Specification:
The first line contains word *s*, the second line contains word *t*. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output Specification:
If the word *t* is a word *s*, written reversely, print YES, otherwise print NO.
Demo Input:
['code\nedoc\n', 'abb\naba\n', 'code\ncode\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
none | ```python
s = input()
s_2 = input()
print('YES' if s == s_2[::-1] else 'NO')
``` |
110 | Nearly Lucky Number | Title: Nearly Lucky Number
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.
Input Specification:
The only line contains an integer *n* (1<=≤<=*n*<=≤<=1018).
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output Specification:
Print on the single line "YES" if *n* is a nearly lucky number. Otherwise, print "NO" (without the quotes).
Demo Input:
['40047\n', '7747774\n', '1000000000000000000\n']
Demo Output:
['NO\n', 'YES\n', 'NO\n']
Note:
In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".
In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".
In the third sample there are no lucky digits, so the answer is "NO". | ```python
#!/usr/bin/env python
# coding: utf-8
# In[38]:
n = input()
count = 0
for digit in n:
if digit == '4' or digit == '7':
count += 1
if set(str(count)) <= set('47'):
print("YES")
else:
print("NO")
#
# In[ ]:
``` |
29 | Spit Problem | Title: Spit Problem
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the amount of camels in the zoo. Each of the following *n* lines contains two integers *x**i* and *d**i* (<=-<=104<=≤<=*x**i*<=≤<=104,<=1<=≤<=|*d**i*|<=≤<=2·104) — records in Bob's notepad. *x**i* is a position of the *i*-th camel, and *d**i* is a distance at which the *i*-th camel spitted. Positive values of *d**i* correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.
Output Specification:
If there are two camels, which spitted at each other, output YES. Otherwise, output NO.
Demo Input:
['2\n0 1\n1 -1\n', '3\n0 1\n1 1\n2 -2\n', '5\n2 -10\n3 10\n0 5\n5 -5\n10 1\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
def camels_spits():
n = int(input())
camels_map = [0]*20001 # (-)-10000 + 10000 + 1 (referente ao zero) - Assim o vetor vai do 0 ao 20.000
to_map = 10000
camels = []
for i in range(n):
x, d = input().split()
camels.append({"x": int(x), "d": int(d)})
camels_map[int(x)+to_map] = {"x": int(x), "d": int(d)}
for camel in camels:
spit_position1 = camel["x"] + camel["d"] + to_map
if (spit_position1 >= 0 and spit_position1 <= 20000 and camels_map[spit_position1] != 0): # Primeiro camelo cuspiu em algum outro
camel2 = camels_map[spit_position1]
spit_position2 = camel2["x"] + camel2["d"] + to_map
if (spit_position2 >= 0 and spit_position2 <= 20000 and camels_map[spit_position2] == camel):
print("YES")
return
print("NO")
return
camels_spits()
``` |
49 | Sleuth | Title: Sleuth
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
Input Specification:
The single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line — as the last symbol and that the line contains at least one letter.
Output Specification:
Print answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".
Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters.
Demo Input:
['Is it a melon?\n', 'Is it an apple?\n', 'Is it a banana ?\n', 'Is it an apple and a banana simultaneouSLY?\n']
Demo Output:
['NO\n', 'YES\n', 'YES\n', 'YES\n']
Note:
none | ```python
klh = input().strip(" ?").lower()
if klh[-1] in "aeiouy":
print("YES")
else:
print("NO")
``` |
112 | Petya and Strings | Title: Petya and Strings
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 corresponding lowercase letter. Help Petya perform the comparison.
Input Specification:
Each of the first two lines contains a bought string. The strings' lengths range from 1 to 100 inclusive. It is guaranteed that the strings are of the same length and also consist of uppercase and lowercase Latin letters.
Output Specification:
If the first string is less than the second one, print "-1". If the second string is less than the first one, print "1". If the strings are equal, print "0". Note that the letters' case is not taken into consideration when the strings are compared.
Demo Input:
['aaaa\naaaA\n', 'abs\nAbz\n', 'abcdefg\nAbCdEfF\n']
Demo Output:
['0\n', '-1\n', '1\n']
Note:
If you want more formal information about the lexicographical order (also known as the "dictionary order" or "alphabetical order"), you can visit the following site:
- http://en.wikipedia.org/wiki/Lexicographical_order | ```python
# Read the two strings
str1 = input().lower() # Convert to lowercase
str2 = input().lower() # Convert to lowercase
# Compare the two strings
if str1 < str2:
print("-1")
elif str1> str2:
print("1")
else:
print("0")#vii
``` |
34 | Reconnaissance 2 | Title: Reconnaissance 2
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000). The soldier heights are given in clockwise or counterclockwise direction.
Output Specification:
Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.
Demo Input:
['5\n10 12 13 15 10\n', '4\n10 20 30 40\n']
Demo Output:
['5 1\n', '1 2\n']
Note:
none | ```python
count_time=False
if count_time:
import time
start_time = time.time()
#-----------------------------------------
n=int(input())
a=list(map(int,input().split()))
x,y=n,1
mino=abs(a[-1]-a[0])
for i in range(1,n):
e=abs(a[i]-a[i-1])
if e<mino:
x,y=i,i+1
mino=e
print(x,y)
#------------------------------------------
if count_time:
end_time = time.time()
print('----------------\nRunning time: {} s'
.format(end_time - start_time))
``` |
84 | Toy Army | Title: Toy Army
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of *n* men (*n* is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.
The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.
You are asked to calculate the maximum total number of soldiers that may be killed during the game.
Input Specification:
The input data consist of a single integer *n* (2<=≤<=*n*<=≤<=108, *n* is even). Please note that before the game starts there are 2*n* soldiers on the fields.
Output Specification:
Print a single number — a maximum total number of soldiers that could be killed in the course of the game in three turns.
Demo Input:
['2\n', '4\n']
Demo Output:
['3\n', '6\n']
Note:
The first sample test:
1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1.
2) Arcady's soldier 2 shoots at Valera's soldier 1.
3) Valera's soldier 1 shoots at Arcady's soldier 2.
There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 and 2. | ```python
import sys
input = sys.stdin.readline
n = int(input())
print(n*3//2)
``` |
63 | Sinking Ship | Title: Sinking Ship
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All *n* crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to *n*) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:
The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.
If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).
For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.
Input Specification:
The first line contains an integer *n*, which is the number of people in the crew (1<=≤<=*n*<=≤<=100). Then follow *n* lines. The *i*-th of those lines contains two words — the name of the crew member who is *i*-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.
Output Specification:
Print *n* lines. The *i*-th of them should contain the name of the crew member who must be the *i*-th one to leave the ship.
Demo Input:
['6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman\n']
Demo Output:
['Teddy\nAlice\nBob\nJulia\nCharlie\nJack\n']
Note:
none | ```python
# Function to determine the evacuation order
def evacuate_crew(n, crew_info):
# Create a list of tuples (name, status, position)
crew_list = [(crew_info[i][0], crew_info[i][1], i) for i in range(n)]
# Define a custom sorting order
def sorting_order(member):
order = {"rat": 1, "woman": 2, "child": 2, "man": 3, "captain": 4}
return order[member[1]]
# Sort the crew list based on the custom order and original position
crew_list.sort(key=lambda x: (sorting_order(x), x[2]))
# Print the names of the crew members in the sorted order
for member in crew_list:
print(member[0])
# Read the input
n = int(input().strip())
crew_info = []
for _ in range(n):
name, status = input().strip().split()
crew_info.append((name, status))
# Call the evacuation function
evacuate_crew(n, crew_info)
``` |
108 | Palindromic Times | Title: Palindromic Times
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.
In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.
However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.
Input Specification:
The first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits.
Output Specification:
Print the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time.
Demo Input:
['12:21\n', '23:59\n']
Demo Output:
['13:31\n', '00:00\n']
Note:
none | ```python
h,m=map(int,input().split(':'))
while True:
m+=1
if m==60:
m=0
h+=1
if h==24:
h=0
if len(str(h))<2:
soat='0'+str(h)
else:
soat=str(h)
if len(str(m))<2:
daqiqa='0'+str(m)
else:
daqiqa=str(m)
vaqt=soat+':'+daqiqa
if vaqt==vaqt[::-1]:
break
print(vaqt)
``` |
92 | Chips | Title: Chips
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There are *n* walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number *n*.
The presenter has *m* chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number *i* gets *i* chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given *n* and *m* how many chips the presenter will get in the end.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=50, 1<=≤<=*m*<=≤<=104) — the number of walruses and the number of chips correspondingly.
Output Specification:
Print the number of chips the presenter ended up with.
Demo Input:
['4 11\n', '17 107\n', '3 8\n']
Demo Output:
['0\n', '2\n', '1\n']
Note:
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | ```python
n,m=map(int,input().split())
temp=n*(n+1)//2
for i in range(100000000):
if temp<=m:
m-=temp
elif temp>m:
break
if m==0:
print(0)
else:
for i in range(1,n+1):
if m>=i:
m-=i
elif m<i:
print(m)
break
``` |
80 | Panoramix's Prediction | Title: Panoramix's Prediction
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input Specification:
The first and only input line contains two positive integers — *n* and *m* (2<=≤<=*n*<=<<=*m*<=≤<=50). It is guaranteed that *n* is prime.
Pretests contain all the cases with restrictions 2<=≤<=*n*<=<<=*m*<=≤<=4.
Output Specification:
Print YES, if *m* is the next prime number after *n*, or NO otherwise.
Demo Input:
['3 5\n', '7 11\n', '7 9\n']
Demo Output:
['YES', 'YES', 'NO']
Note:
none | ```python
c=0
p=0
n,m=map(int,input().split())
f=True
for i in range(2, int(m/2)+1):
if (m % i) == 0:
print('NO')
f=False
break
for i in range(n+1,m+1):
for j in range(2, m+1):
if (i % j) == 0:
c+=1
if c==1:
p+=1
c=0
if f:
if p==0 or p>1:
print('NO')
elif p==1:
print('YES')
``` |
35 | Shell Game | Title: Shell Game
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Today the «Z» city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. The performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so that on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct they get a prize. Maybe you can try to find the ball too?
Input Specification:
The first input line contains an integer from 1 to 3 — index of the cup which covers the ball before the shuffles. The following three lines describe the shuffles. Each description of a shuffle contains two distinct integers from 1 to 3 — indexes of the cups which the performer shuffled this time. The cups are numbered from left to right and are renumbered after each shuffle from left to right again. In other words, the cup on the left always has index 1, the one in the middle — index 2 and the one on the right — index 3.
Output Specification:
In the first line output an integer from 1 to 3 — index of the cup which will have the ball after all the shuffles.
Demo Input:
['1\n1 2\n2 1\n2 1\n', '1\n2 1\n3 1\n1 3\n']
Demo Output:
['2\n', '2\n']
Note:
none | ```python
with open("input.txt") as f :
d = f.readlines()
d = [i.strip('\n') for i in d]
ball = d[0]
lines = d[1:]
for i in lines :
initial, final = [j for j in i.split()]
if initial == ball :
ball = final
elif final == ball :
ball = initial
with open("output.txt","w") as m :
m.write(ball)
``` |
69 | Young Physicist | Title: Young Physicist
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input Specification:
The first line contains a positive integer *n* (1<=≤<=*n*<=≤<=100), then follow *n* lines containing three integers each: the *x**i* coordinate, the *y**i* coordinate and the *z**i* coordinate of the force vector, applied to the body (<=-<=100<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=100).
Output Specification:
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Demo Input:
['3\n4 1 7\n-2 4 -1\n1 -5 -3\n', '3\n3 -1 7\n-5 2 -4\n2 -1 -3\n']
Demo Output:
['NO', 'YES']
Note:
none | ```python
n=int(input())
c1=c2=c3=0
for i in range(n):
x,y,z=map(int,input().split())
c1+=x
c2+=y
c3+=z
if(c1==c2==c3==0):
print('YES')
else:
print('NO')
``` |
104 | Blackjack | Title: Blackjack
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!
Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.
In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals *n*, then the player wins, otherwise the player loses.
The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals *n*.
Input Specification:
The only line contains *n* (1<=≤<=*n*<=≤<=25) — the required sum of points.
Output Specification:
Print the numbers of ways to get the second card in the required way if the first card is the queen of spades.
Demo Input:
['12\n', '20\n', '10\n']
Demo Output:
['4', '15', '0']
Note:
In the first sample only four two's of different suits can earn the required sum of points.
In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.
In the third sample there is no card, that would add a zero to the current ten points. | ```python
n = int ( input () )
if n >= 1 and n <= 25:
b = int ( n - 10 )
if b < 10 and b > 0:
print ( 4 )
elif b == 10 :
print ( 15 )
elif b == 11 :
print ( 4 )
else :
print ( 0 )
``` |
51 | Cheaterius's Problem | Title: Cheaterius's Problem
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2<=×<=2 which are the Cheaterius' magic amulets!
After a hard night Cheaterius made *n* amulets. Everyone of them represents a square 2<=×<=2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.
Write a program that by the given amulets will find the number of piles on Cheaterius' desk.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=1000), where *n* is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.
Output Specification:
Print the required number of piles.
Demo Input:
['4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13\n', '4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53\n']
Demo Output:
['1\n', '2\n']
Note:
none | ```python
def Contains(myList, helper):
for i in range(4):
if helper in myList:
return True
helper = '{}{}{}{}'.format(helper[2], helper[0], helper[3], helper[1])
return False
n = int(input())
myList = []
helper = ""
while n > 0:
helper = input() + input()
if not Contains(myList, helper):
myList.append(helper)
helper = ""
if n > 1:
input()
n -= 1
print(len(myList))
``` |
31 | Worms Evolution | Title: Worms Evolution
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are *n* forms of worms. Worms of these forms have lengths *a*1, *a*2, ..., *a**n*. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of worm's forms. The second line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=1000) — lengths of worms of each form.
Output Specification:
Output 3 distinct integers *i* *j* *k* (1<=≤<=*i*,<=*j*,<=*k*<=≤<=*n*) — such indexes of worm's forms that *a**i*<==<=*a**j*<=+<=*a**k*. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that *a**j*<==<=*a**k*.
Demo Input:
['5\n1 2 3 5 7\n', '5\n1 8 1 5 1\n']
Demo Output:
['3 2 1\n', '-1\n']
Note:
none | ```python
n=int(input())
a=list(map(int,input().split()))
f=0
for j in range(n):
for k in range(n):
if j!=k:
if a[j]+a[k] in a:
print(a.index(a[j]+a[k])+1,j+1,k+1)
f=1
break
if f==1:
break
if f==0:
print(-1)
``` |
90 | Cableway | Title: Cableway
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: *r* of them like to ascend only in the red cablecars, *g* of them prefer only the green ones and *b* of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
Input Specification:
The first line contains three integers *r*, *g* and *b* (0<=≤<=*r*,<=*g*,<=*b*<=≤<=100). It is guaranteed that *r*<=+<=*g*<=+<=*b*<=><=0, it means that the group consists of at least one student.
Output Specification:
Print a single number — the minimal time the students need for the whole group to ascend to the top of the mountain.
Demo Input:
['1 3 2\n', '3 2 1\n']
Demo Output:
['34', '33']
Note:
Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the *r* group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the *g* group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the *b* group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the *g* group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes. | ```python
num_inp=lambda: int(input())
arr_inp=lambda: list(map(int,input().split()))
sp_inp=lambda: map(int,input().split())
str_inp=lambda:input()
r,g,b=map(int,input().split())
f=lambda x:(0--x//2-1)*3
print(max(f(r),1+f(g),2+f(b))+30)
``` |
75 | Life Without Zeros | Title: Life Without Zeros
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation *a*<=+<=*b*<==<=*c*, where *a* and *b* are positive integers, and *c* is the sum of *a* and *b*. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?
For example if the equation is 101<=+<=102<==<=203, if we removed all zeros it will be 11<=+<=12<==<=23 which is still a correct equation.
But if the equation is 105<=+<=106<==<=211, if we removed all zeros it will be 15<=+<=16<==<=211 which is not a correct equation.
Input Specification:
The input will consist of two lines, the first line will contain the integer *a*, and the second line will contain the integer *b* which are in the equation as described above (1<=≤<=*a*,<=*b*<=≤<=109). There won't be any leading zeros in both. The value of *c* should be calculated as *c*<==<=*a*<=+<=*b*.
Output Specification:
The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise.
Demo Input:
['101\n102\n', '105\n106\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
n1 = int(input())
n2 = int(input())
sum = n1 + n2
n1 , n2 , sum = str(n1) , str(n2) , str(sum)
n1 =n1.replace("0","")
n2 = n2.replace("0", "")
sum = sum.replace("0", "")
n1 , n2 , sum = int(n1) , int(n2) , int(sum)
sum1 = (n1) + n2
if sum1 == sum :
print("YES")
else:
print("NO")
``` |
78 | Haiku | Title: Haiku
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
Input Specification:
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The *i*-th line contains the *i*-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
Output Specification:
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
Demo Input:
['on codeforces \nbeta round is running\n a rustling of keys \n', 'how many gallons\nof edo s rain did you drink\n cuckoo\n']
Demo Output:
['YES', 'NO']
Note:
none | ```python
print('YES' if [sum(s.count(x) for x in "aeiou") for s in [input() for _ in range(3)]]==[5,7,5] else 'NO')
``` |
27 | Next Test | Title: Next Test
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
«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 as the smallest positive integer which is not used as an index for some previously added test.
You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=3000) — the amount of previously added tests. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=3000) — indexes of these tests.
Output Specification:
Output the required default value for the next test index.
Demo Input:
['3\n1 7 2\n']
Demo Output:
['3\n']
Note:
none | ```python
def solve(arr) :
arr.sort()
arr.insert(0,0)
for i in range(n) :
if arr[i+1]-arr[i]>1 :
return arr[i]+1
return arr[-1]+1
from sys import stdin
input = stdin.readline
n=int(input())
arr=[int(x) for x in input().split()]
print(solve(arr))
'''
t=int(input())
for i in range(t) :
print(solve())
n=int(input())
x=input().strip()
n,m= [int(x) for x in input().split()]
n=int(input())
arr=[int(x) for x in input().split()]
n,m= [int(x) for x in input().split()]
arr=[]
for i in range(n):
arr.append([int(x) for x in input().split()])
n,m= [int(x) for x in input().split()]
arr=[]
for i in range(n):
arr.append([x for x in input().strip()])
n=int(input())
arr=[]
for i in range(n):
arr.append([int(x) for x in input().split()])
'''
``` |
26 | Almost Prime | Title: Almost Prime
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and *n*, inclusive.
Input Specification:
Input contains one integer number *n* (1<=≤<=*n*<=≤<=3000).
Output Specification:
Output the amount of almost prime numbers between 1 and *n*, inclusive.
Demo Input:
['10\n', '21\n']
Demo Output:
['2\n', '8\n']
Note:
none | ```python
r = int(input())
k = [0]*(r+1)
for x in range(2, r+1):
if k[x]==0:
for y in range(2*x, r+1, x):
k[y]+=1
print(k.count(2))
``` |
70 | Cookies | Title: Cookies
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square *k*<=×<=*k* in size, divided into blocks 1<=×<=1 in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie *k* in size. Fangy also has a box with a square base 2*n*<=×<=2*n*, divided into blocks 1<=×<=1 in size. In a box the cookies should not overlap, and they should not be turned over or rotated. See cookies of sizes 2 and 4 respectively on the figure:
To stack the cookies the little walrus uses the following algorithm. He takes out of the repository the largest cookie which can fit in some place in the box and puts it there. Everything could be perfect but alas, in the repository the little walrus has infinitely many cookies of size 2 and larger, and there are no cookies of size 1, therefore, empty cells will remain in the box. Fangy wants to know how many empty cells will be left in the end.
Input Specification:
The first line contains a single integer *n* (0<=≤<=*n*<=≤<=1000).
Output Specification:
Print the single number, equal to the number of empty cells in the box. The answer should be printed modulo 106<=+<=3.
Demo Input:
['3\n']
Demo Output:
['9']
Note:
If the box possesses the base of 2<sup class="upper-index">3</sup> × 2<sup class="upper-index">3</sup> (as in the example), then the cookies will be put there in the following manner: | ```python
n=int(input())
print(3**((max(0,n-1)))%1000003)
``` |
20 | BerOS file system | Title: BerOS file system
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.
A path called normalized if it contains the smallest possible number of characters '/'.
Your task is to transform a given path to the normalized form.
Input Specification:
The first line of the input contains only lowercase Latin letters and character '/' — the path to some directory. All paths start with at least one character '/'. The length of the given line is no more than 100 characters, it is not empty.
Output Specification:
The path in normalized form.
Demo Input:
['//usr///local//nginx/sbin\n']
Demo Output:
['/usr/local/nginx/sbin\n']
Note:
none | ```python
s=input()
l=s.split("/")
l=[i for i in l if i!=""]
print("/"+"/".join(l))
``` |
36 | Extra-terrestrial Intelligence | Title: Extra-terrestrial Intelligence
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for *n* days in a row. Each of those *n* days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of days during which Vasya checked if there were any signals. The second line contains *n* characters 1 or 0 — the record Vasya kept each of those *n* days. It’s guaranteed that the given record sequence contains at least three 1s.
Output Specification:
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Demo Input:
['8\n00111000\n', '7\n1001011\n', '7\n1010100\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
readFile = open('input.txt', 'r')
n = int(readFile.readline())
line = readFile.readline()
readFile.close()
prev, sample, ans = -1, -1, 'YES'
for i in range(n):
if line[i] == '1' and prev == -1:
prev = i
elif line[i] == '1' and sample == -1:
sample = i - prev - 1
prev = i
elif line[i] == '1':
temp = i - prev - 1
prev = i
if temp != sample:
ans = 'NO'
break
writeFile = open('output.txt','w')
writeFile.write(ans)
writeFile.close()
``` |
82 | Double Cola | Title: Double Cola
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.
For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.
Write a program that will print the name of a man who will drink the *n*-th can.
Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
Input Specification:
The input data consist of a single integer *n* (1<=≤<=*n*<=≤<=109).
It is guaranteed that the pretests check the spelling of all the five names, that is, that they contain all the five possible answers.
Output Specification:
Print the single line — the name of the person who drinks the *n*-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" (without the quotes). In that order precisely the friends are in the queue initially.
Demo Input:
['1\n', '6\n', '1802\n']
Demo Output:
['Sheldon\n', 'Sheldon\n', 'Penny\n']
Note:
none | ```python
a = int(input())
i = 0
s = 5
while s < a:
i += 1
s += 5 * 2 ** i
n = ['Sheldon'] + ['Leonard'] + ['Penny'] + ['Rajesh'] + ['Howard']
print(n[(a - (s - 5 * 2 ** i) - 1) // 2 ** i])
``` |
47 | Triangular numbers | Title: Triangular numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The *n*-th triangular number is the number of dots in a triangle with *n* dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).
Your task is to find out if a given integer is a triangular number.
Input Specification:
The first line contains the single number *n* (1<=≤<=*n*<=≤<=500) — the given integer.
Output Specification:
If the given integer is a triangular number output YES, otherwise output NO.
Demo Input:
['1\n', '2\n', '3\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
n = int(input())
cont, i = [], 1
while i * (i + 1) // 2 <= 500:
cont.append(i * (i + 1) // 2)
i += 1
print('YES' if n in cont else 'NO')
``` |
12 | Fruits | Title: Fruits
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of *m* fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times.
When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most «lucky» for him distribution of price tags) and the largest total price (in case of the most «unlucky» for him distribution of price tags).
Input Specification:
The first line of the input contains two integer number *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains *n* space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following *m* lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to *n*. Also it is known that the seller has in stock all fruits that Valera wants to buy.
Output Specification:
Print two numbers *a* and *b* (*a*<=≤<=*b*) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.
Demo Input:
['5 3\n4 2 1 10 5\napple\norange\nmango\n', '6 5\n3 5 1 6 8 1\npeach\ngrapefruit\nbanana\norange\norange\n']
Demo Output:
['7 19\n', '11 30\n']
Note:
none | ```python
enter1 = list(map(int, input().split()))
n = enter1[0]
m = enter1[1]
li = list(map(int, input().split()))
fruits = list()
for i in range(m):
fruits.append(input())
se = set(fruits)
kol_vo = []
li_se = list(se)
for i in range(len(li_se)):
kol_vo.append(fruits.count(li_se[i]))
kol_vo.sort()
kol_vo.reverse()
li.sort()
sum1 = 0
sum2 = 0
for i in range(len(kol_vo)):
sum1 += (li[i]*kol_vo[i])
li.reverse()
for j in range(len(kol_vo)):
sum2 += (li[j]*kol_vo[j])
print(sum1, sum2)
``` |
44 | Anfisa the Monkey | Title: Anfisa the Monkey
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into *k* lines not shorter than *a* and not longer than *b*, for the text to resemble human speech more. Help Anfisa.
Input Specification:
The first line contains three integers *k*, *a* and *b* (1<=≤<=*k*<=≤<=200, 1<=≤<=*a*<=≤<=*b*<=≤<=200). The second line contains a sequence of lowercase Latin letters — the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output Specification:
Print *k* lines, each of which contains no less than *a* and no more than *b* symbols — Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Demo Input:
['3 2 5\nabrakadabra\n', '4 1 2\nabrakadabra\n']
Demo Output:
['ab\nrakad\nabra\n', 'No solution\n']
Note:
none | ```python
k,a,b= map(int, input().split())
s = input()
n = len(s)
if k*a>n or k*b<n:
print("No solution")
else:
c = 0
o = n//k
m = n%k
for i in range(k):
d = o + (i < m)
print(s[c:c + d])
c+= d
``` |
44 | Indian Summer | Title: Indian Summer
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of leaves Alyona has found. The next *n* lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.
Output Specification:
Output the single number — the number of Alyona's leaves.
Demo Input:
['5\nbirch yellow\nmaple red\nbirch yellow\nmaple yellow\nmaple green\n', '3\noak yellow\noak yellow\noak yellow\n']
Demo Output:
['4\n', '1\n']
Note:
none | ```python
lst1=[]
lst2=[]
test=int(input())
for i in range(test):
x=input()
if x not in lst1:
lst1.append(x)
else:
lst2.append(x)
print(len(lst1))
``` |
45 | Codecraft III | Title: Codecraft III
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly *k* months. He looked at the calendar and learned that at the moment is the month number *s*. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.
All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
Input Specification:
The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer *k* (0<=≤<=*k*<=≤<=100) — the number of months left till the appearance of Codecraft III.
Output Specification:
Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December.
Demo Input:
['November\n3\n', 'May\n24\n']
Demo Output:
['February\n', 'May\n']
Note:
none | ```python
month=input()
k=int(input())
month_list=['January','February','March','April','May','June','July','August','September','October','November','December']
for i in range(12):
if month_list[i]==month:
index=i
break
list_index=index+k+1
if list_index>12:
list_index%=12
print(month_list[list_index-1])
``` |
25 | IQ test | Title: IQ test
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 different in evenness.
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of numbers in the task. The second line contains *n* space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.
Output Specification:
Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.
Demo Input:
['5\n2 4 7 8 10\n', '4\n1 2 1 1\n']
Demo Output:
['3\n', '2\n']
Note:
none | ```python
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 11 15:33:18 2022
@author: 86158
"""
n = int(input())
list0 = [int(i) for i in input().split()]
list1 = []
for i in range(n):
list1.append(list0[i]%2)
a = list1.count(0)
if a == 1:
print(list1.index(0)+1)
else:
print(list1.index(1)+1)
``` |
17 | Noldbach problem | Title: Noldbach problem
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least *k* prime numbers from 2 to *n* inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.
Two prime numbers are called neighboring if there are no other prime numbers between them.
You are to help Nick, and find out if he is right or wrong.
Input Specification:
The first line of the input contains two integers *n* (2<=≤<=*n*<=≤<=1000) and *k* (0<=≤<=*k*<=≤<=1000).
Output Specification:
Output YES if at least *k* prime numbers from 2 to *n* inclusively can be expressed as it was described above. Otherwise output NO.
Demo Input:
['27 2\n', '45 7\n']
Demo Output:
['YES', 'NO']
Note:
In the first sample the answer is YES since at least two numbers can be expressed as it was described (for example, 13 and 19). In the second sample the answer is NO since it is impossible to express 7 prime numbers from 2 to 45 in the desired form. | ```python
n, k = map(int, input().split())
prime = [3, 5]
curr = 2
res = 0
for number in range(7, n+1, 2):
i = 0
while i < curr and number % prime[i] != 0:
i += 1
if i == curr:
for j in range(1, curr):
if prime[j] + prime[j-1] + 1 == number:
k -= 1
break
prime.append(number)
curr += 1
if k == 0:
break
print('YES' if k == 0 else 'NO')
``` |
25 | Phone numbers | Title: Phone numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Phone number in Berland is a sequence of *n* digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) — amount of digits in the phone number. The second line contains *n* digits — the phone number to divide into groups.
Output Specification:
Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.
Demo Input:
['6\n549871\n', '7\n1198733\n']
Demo Output:
['54-98-71', '11-987-33\n']
Note:
none | ```python
n = int(input())
s = list(input())
l = []
if n%2 == 0:
for i in range(n):
if i%2 == 0:
a = s[i] + s[i+1]
l.append(a)
else:
for i in range(n-3):
if i%2 == 0:
a = s[i] + s[i+1]
l.append(a)
a = s[-3] + s[-2] + s[-1]
l.append(a)
string = ""
for i in l:
string += i + "-"
print(string[:-1])
``` |
22 | Second Order Statistics | Title: Second Order Statistics
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
Input Specification:
The first input line contains integer *n* (1<=≤<=*n*<=≤<=100) — amount of numbers in the sequence. The second line contains *n* space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.
Output Specification:
If the given sequence has the second order statistics, output this order statistics, otherwise output NO.
Demo Input:
['4\n1 2 2 -4\n', '5\n1 2 3 1 1\n']
Demo Output:
['1\n', '2\n']
Note:
none | ```python
input();
d=sorted(set(map(int,input().split())));
print(d[1] if len(d)>1 else "NO")
``` |
12 | Super Agent | Title: Super Agent
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3<=×<=3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
Input Specification:
Input contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.».
Output Specification:
Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.
Demo Input:
['XX.\n...\n.XX\n', 'X.X\nX..\n...\n']
Demo Output:
['YES\n', 'NO\n']
Note:
If you are not familiar with the term «central symmetry», you may look into http://en.wikipedia.org/wiki/Central_symmetry | ```python
a = [ input() for i in range(3)]
b = "YES"
for i in range(3):
if a[0][i] != a[2][2-i]:
b = "NO"
if a[1][0] != a[1][2]:
b = "NO"
print(b)
``` |
38 | Army | Title: Army
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The Berland Armed Forces System consists of *n* ranks that are numbered using natural numbers from 1 to *n*, where 1 is the lowest rank and *n* is the highest rank.
One needs exactly *d**i* years to rise from rank *i* to rank *i*<=+<=1. Reaching a certain rank *i* having not reached all the previous *i*<=-<=1 ranks is impossible.
Vasya has just reached a new rank of *a*, but he dreams of holding the rank of *b*. Find for how many more years Vasya should serve in the army until he can finally realize his dream.
Input Specification:
The first input line contains an integer *n* (2<=≤<=*n*<=≤<=100). The second line contains *n*<=-<=1 integers *d**i* (1<=≤<=*d**i*<=≤<=100). The third input line contains two integers *a* and *b* (1<=≤<=*a*<=<<=*b*<=≤<=*n*). The numbers on the lines are space-separated.
Output Specification:
Print the single number which is the number of years that Vasya needs to rise from rank *a* to rank *b*.
Demo Input:
['3\n5 6\n1 2\n', '3\n5 6\n1 3\n']
Demo Output:
['5\n', '11\n']
Note:
none | ```python
def years_to_reach_rank(a, b, rank_times):
total_years = 0
for i in range(a, b):
total_years += rank_times[i - 1]
return total_years
n = int(input(""))
rank_times = list(map(int, input("").split(" ")))
ab = input("").split(' ')
a, b = int(ab[0]), int(ab[1])
print(years_to_reach_rank(a, b, rank_times))
``` |
46 | Ball Game | Title: Ball Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to *n* clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if *n*<==<=5, then after the third throw the child number 2 has the ball again. Overall, *n*<=-<=1 throws are made, and the game ends.
The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=100) which indicates the number of kids in the circle.
Output Specification:
In the single line print *n*<=-<=1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.
Demo Input:
['10\n', '3\n']
Demo Output:
['2 4 7 1 6 2 9 7 6\n', '2 1\n']
Note:
none | ```python
n = int(input())
current = 0
for k in range(1, n):
current += k
current %= n
print(current + 1, end=" ")
print()
``` |
39 | Multiplication Table | Title: Multiplication Table
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix *k*.
Input Specification:
The first line contains a single integer *k* (2<=≤<=*k*<=≤<=10) — the radix of the system.
Output Specification:
Output the multiplication table for the system of notations with the radix *k*. The table must contain *k*<=-<=1 rows and *k*<=-<=1 columns. The element on the crossing of the *i*-th row and the *j*-th column is equal to the product of *i* and *j* in the system of notations with the radix *k*. Each line may have any number of spaces between the numbers (the extra spaces in the samples are put for clarity).
Demo Input:
['10\n', '3\n']
Demo Output:
['1 2 3 4 5 6 7 8 9\n2 4 6 8 10 12 14 16 18\n3 6 9 12 15 18 21 24 27\n4 8 12 16 20 24 28 32 36\n5 10 15 20 25 30 35 40 45\n6 12 18 24 30 36 42 48 54\n7 14 21 28 35 42 49 56 63\n8 16 24 32 40 48 56 64 72\n9 18 27 36 45 54 63 72 81\n', '1 2\n2 11']
Note:
none | ```python
k = int(input())
base = list(range(1, k))
result = [[i * x for x in base] for i in range(1, k)]
for i in range(k - 1):
row = []
for j in range(k - 1):
product = []
while result[i][j]:
product.append(str(result[i][j] % k))
result[i][j] //= k
row.append("".join(product[::-1]))
print(" ".join(row))
``` |
7 | Kalevitch and Chess | Title: Kalevitch and Chess
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, the chessboard is a square-checkered board with the squares arranged in a 8<=×<=8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.
Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.
It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
Input Specification:
The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black.
It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).
Output Specification:
Output the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.
Demo Input:
['WWWBWWBW\nBBBBBBBB\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\nWWWBWWBW\n', 'WWWWWWWW\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
board = [input(), input(), input(), input(), input(), input(), input(), input()]
row_count = 0
col_count = 0
col_index = []
def return_index(ele, inp):
rslt = []
for i in range(len(inp)):
if inp[i] == ele:
rslt.append(i)
return rslt
for row in board:
if row == 'BBBBBBBB':
row_count += 1
else:
if 'B' in row:
arr = return_index('B', row)
for i in arr:
if i not in col_index:
col_index.append(i)
col_count += 1
print(col_count+row_count)
``` |
16 | Flag | Title: Flag
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
According to a new ISO standard, a flag of every country should have a chequered field *n*<=×<=*m*, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.
Input Specification:
The first line of the input contains numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100), *n* — the amount of rows, *m* — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following *n* lines contain *m* characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.
Output Specification:
Output YES, if the flag meets the new ISO standard, and NO otherwise.
Demo Input:
['3 3\n000\n111\n222\n', '3 3\n000\n000\n111\n', '3 3\n000\n111\n002\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
none | ```python
n, m = map(int, input().split())
failure = False
cur = -1
for i in range(0, n):
st = set(input())
for a in st:
if a == cur:
failure = True
else:
cur = a
if len(st) > 1:
failure = True
print('YES') if failure == False else print('NO')
``` |
39 | Company Income Growth | Title: Company Income Growth
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to *a*1 billion bourles, in 2002 — to *a*2 billion, ..., and in the current (2000<=+<=*n*)-th year — *a**n* billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers *a**i* can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers *a**i* from the sequence and leave only some subsequence that has perfect growth.
Thus Petya has to choose a sequence of years *y*1, *y*2, ..., *y**k*,so that in the year *y*1 the company income amounted to 1 billion bourles, in the year *y*2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100). The next line contains *n* integers *a**i* (<=-<=100<=≤<=*a**i*<=≤<=100). The number *a**i* determines the income of BerSoft company in the (2000<=+<=*i*)-th year. The numbers in the line are separated by spaces.
Output Specification:
Output *k* — the maximum possible length of a perfect sequence. In the next line output the sequence of years *y*1, *y*2, ..., *y**k*. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.
Demo Input:
['10\n-2 1 1 3 2 3 4 -10 -2 5\n', '3\n-1 -2 -3\n']
Demo Output:
['5\n2002 2005 2006 2007 2010\n', '0\n']
Note:
none | ```python
n = int(input())
a = list(map(int, input().split()))
result = []
curr = 1
for i, e in enumerate(a):
if e == curr:
curr += 1
result.append(2001 + i)
print(len(result))
if result:
print(*result)
``` |
15 | Cottage Village | Title: Cottage Village
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» *n* square houses with the centres on the *Оx*-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.
The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the *Оx*-axis, to be square in shape, have a side *t*, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the *Ox*-axis and it shouldn't overlap any of the houses in the village.
Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?
Input Specification:
The first line of the input data contains numbers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=1000). Then there follow *n* lines, each of them contains two space-separated integer numbers: *x**i* *a**i*, where *x**i* — *x*-coordinate of the centre of the *i*-th house, and *a**i* — length of its side (<=-<=1000<=≤<=*x**i*<=≤<=1000, 1<=≤<=*a**i*<=≤<=1000).
Output Specification:
Output the amount of possible positions of the new house.
Demo Input:
['2 2\n0 4\n6 2\n', '2 2\n0 4\n5 2\n', '2 3\n0 4\n5 2\n']
Demo Output:
['4\n', '3\n', '2\n']
Note:
It is possible for the *x*-coordinate of the new house to have non-integer value. | ```python
n,t=map(int,input().split()); a=[]; q=2
a=sorted(list(map(int,input().split()))for _ in range(n))
for i in range(n-1):
l=a[i][0]+t+(a[i][1]+a[i+1][1])/2;r=a[i+1][0]
if l==r:q+=1
if l<r:q+=2
print(q)
``` |
6 | Triangle | Title: Triangle
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input Specification:
The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.
Output Specification:
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Demo Input:
['4 2 1 3\n', '7 2 2 4\n', '3 5 9 1\n']
Demo Output:
['TRIANGLE\n', 'SEGMENT\n', 'IMPOSSIBLE\n']
Note:
none | ```python
def check (x,y,z) :
if x + y > z and x + z > y and z + y > x :
return 'T'
if x + y == z or x + z == y or z + y == x:
return 'S'
return 'I'
a, b, c, d = [int(item) for item in input().split(' ')]
if check(a,b,c) == 'T' or check(a,b,d) == 'T' or check(a,d,c) == 'T' or check(d,b,c) == 'T' :
print("TRIANGLE")
elif check(a,b,c) == 'S' or check(a,b,d) == 'S' or check(a,d,c) == 'S' or check(d,b,c) == 'S' :
print("SEGMENT")
else :
print("IMPOSSIBLE")
``` |
48 | Rock-paper-scissors | Title: Rock-paper-scissors
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.
Input Specification:
The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture.
Output Specification:
Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?".
Demo Input:
['rock\nrock\nrock\n', 'paper\nrock\nrock\n', 'scissors\nrock\nrock\n', 'scissors\npaper\nrock\n']
Demo Output:
['?\n', 'F\n', '?\n', '?\n']
Note:
none | ```python
f = input()
m = input()
s = input()
out = 0
if f == "rock":
if m == "scissors" and s == "scissors":
out = 1
elif m == "rock" and s == "paper":
out = 3
elif s == "rock" and m == "paper":
out = 2
elif f == "paper":
if m == "rock" and s == "rock":
out = 1
elif m == "paper" and s == "scissors":
out = 3
elif s == "paper" and m == "scissors":
out = 2
elif f == "scissors":
if m == "paper" and s == "paper":
out = 1
elif m == "scissors" and s == "rock":
out = 3
elif s == "scissors" and m == "rock":
out = 2
if (out == 0):
print("?")
elif out == 1:
print("F")
elif out == 2:
print("M")
else:
print("S")
``` |
46 | Hamsters and Tigers | Title: Hamsters and Tigers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.
Input Specification:
The first line contains number *n* (2<=≤<=*n*<=≤<=1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of *n* symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.
Output Specification:
Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.
Demo Input:
['3\nHTH\n', '9\nHTHTHTHHT\n']
Demo Output:
['0\n', '2\n']
Note:
In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7. | ```python
n = int(input())
s = input()
s = s+s
count = s.count("H") // 2
x = 0
for i in range(n):
z = s[i:i + count].count('H')
x = max(x,z)
print(count-x)
``` |
39 | Cubical Planet | Title: Cubical Planet
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
Input Specification:
The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly.
Output Specification:
Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO".
Demo Input:
['0 0 0\n0 1 0\n', '1 1 0\n0 1 0\n', '0 0 0\n1 1 1\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
none | ```python
# LUOGU_RID: 133990995
a=map(int,input().split())
a=list(a)
b=map(int,input().split())
b=list(b)
for i in range(3): #有三个坐标0-2,没有取到三
if a[i]==b[i]: #当比较到相同的就相遇
print('YES')
break #然后结束
if i==2: #当比较到第三个坐标没有相同就是不相遇
print('NO')
``` |
38 | Chess | Title: Chess
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Two chess pieces, a rook and a knight, stand on a standard chessboard 8<=×<=8 in size. The positions in which they are situated are known. It is guaranteed that none of them beats the other one.
Your task is to find the number of ways to place another knight on the board so that none of the three pieces on the board beat another one. A new piece can only be placed on an empty square.
Input Specification:
The first input line contains the description of the rook's position on the board. This description is a line which is 2 in length. Its first symbol is a lower-case Latin letter from a to h, and its second symbol is a number from 1 to 8. The second line contains the description of the knight's position in a similar way. It is guaranteed that their positions do not coincide.
Output Specification:
Print a single number which is the required number of ways.
Demo Input:
['a1\nb2\n', 'a8\nd4\n']
Demo Output:
['44\n', '38\n']
Note:
none | ```python
q=input()
w=input()
s={q,w}
l=set()
for i in"abcdefgh":
for j in "12345678":
l.add(i+j)
s.add(q[0]+j)
s.add(i+q[1])
for i in [-2,-1,1,2]:
for j in [-2,-1,1,2]:
if abs(i)!=abs(j):
z=chr(ord(q[0])+i)+str(int(q[1])+j)
if z in l:
s.add(z)
for i in [-2,-1,1,2]:
for j in [-2,-1,1,2]:
if abs(i)!=abs(j):
z=chr(ord(w[0])+i)+str(int(w[1])+j)
if z in l:
s.add(z)
print(64-len(s))
``` |
24 | Ring road | Title: Ring road
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all *n* cities of Berland were connected by *n* two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all *n* roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input Specification:
The first line contains integer *n* (3<=≤<=*n*<=≤<=100) — amount of cities (and roads) in Berland. Next *n* lines contain description of roads. Each road is described by three integers *a**i*, *b**i*, *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*,<=1<=≤<=*c**i*<=≤<=100) — road is directed from city *a**i* to city *b**i*, redirecting the traffic costs *c**i*.
Output Specification:
Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Demo Input:
['3\n1 3 1\n1 2 1\n3 2 1\n', '3\n1 3 1\n1 2 5\n3 2 1\n', '6\n1 5 4\n5 3 8\n2 4 15\n1 6 16\n2 3 23\n4 6 42\n', '4\n1 2 9\n2 3 8\n3 4 7\n4 1 5\n']
Demo Output:
['1\n', '2\n', '39\n', '0\n']
Note:
none | ```python
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
n=int(input())
l=[]
for _ in range(n):
l.append(list(map(int,input().split())))
d={}
adj=[[] for t in range(n+1)]
for ele in l:
a , b , val= ele
adj[a].append([b,val])
adj[b].append([a,val])
d[(a,b)]=val
visited=[0 for t in range(n+1)]
visited[1]=1
'''print(d)
print(adj)'''
cost1=0
current=1
nxt=adj[1][0][0]
while 1:
#print(type((current,nxt)),type(current),type(nxt))
if (current,nxt) not in d:
cost1+=d[(nxt,current)]
visited[nxt]=1
flag=0
for ele in adj[nxt]:
nei=ele[0]
if visited[nei]==0:
flag=1
current=nxt
nxt=nei
if flag==0:
if (nxt,1) not in d:
cost1+=d[(1,nxt)]
break
visited=[0 for t in range(n+1)]
visited[1]=1
cost2=0
current=1
nxt=adj[1][1][0]
while 1:
if (current,nxt) not in d:
cost2+=d[(nxt,current)]
visited[nxt]=1
flag=0
for ele in adj[nxt]:
nei=ele[0]
if visited[nei]==0:
flag=1
current=nxt
nxt=nei
if flag==0:
if (nxt,1) not in d:
cost2+=d[(1,nxt)]
break
print(min(cost2,cost1))
``` |
37 | Towers | Title: Towers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
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 possible.
Input Specification:
The first line contains an integer *N* (1<=≤<=*N*<=≤<=1000) — the number of bars at Vasya’s disposal. The second line contains *N* space-separated integers *l**i* — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.
Output Specification:
In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.
Demo Input:
['3\n1 2 3\n', '4\n6 5 6 7\n']
Demo Output:
['1 3\n', '2 3\n']
Note:
none | ```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
x = y = 1
t = 1
for i in range(1, n):
if a[i] != a[i-1]:
t = 1
y += 1
else:
t += 1
if t > x: x = t
print(str(x)+' '+str(y))
``` |
62 | A Student's Dream | Title: A Student's Dream
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.
A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.
The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams.
So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has *a**l* fingers on her left hand and *a**r* fingers on the right one. The boy correspondingly has *b**l* and *b**r* fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable."
The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.
Input Specification:
The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.
Output Specification:
Print YES or NO, that is, the answer to Petr Palych's question.
Demo Input:
['5 1\n10 5\n', '4 5\n3 3\n', '1 2\n11 6\n']
Demo Output:
['YES', 'YES', 'NO']
Note:
The boy and the girl don't really care who goes to the left. | ```python
def readln(): return tuple(map(int, input().split()))
al, ar = readln()
bl, br = readln()
print('YES' if al - 1 <= br <= (al + 1) * 2 or ar - 1 <= bl <= (ar + 1) * 2 else 'NO')
``` |
43 | Lucky Tickets | Title: Lucky Tickets
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2*t* pieces he ended up with *t* tickets, each of which was lucky.
When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.
Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.
What maximum number of tickets could Vasya get after that?
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=104) — the number of pieces. The second line contains *n* space-separated numbers *a**i* (1<=≤<=*a**i*<=≤<=108) — the numbers on the pieces. Vasya can only glue the pieces in pairs. Even if the number of a piece is already lucky, Vasya should glue the piece with some other one for it to count as lucky. Vasya does not have to use all the pieces. The numbers on the pieces an on the resulting tickets may coincide.
Output Specification:
Print the single number — the maximum number of lucky tickets that will be able to be restored. Don't forget that every lucky ticket is made of exactly two pieces glued together.
Demo Input:
['3\n123 123 99\n', '6\n1 1 1 23 10 3\n']
Demo Output:
['1\n', '1\n']
Note:
none | ```python
input()
myList = list(map(int, input().split()))
rem0, rem1, rem2 = 0, 0, 0
for it in myList:
if it % 3 == 0:
rem0 += 1
elif it % 3 == 1:
rem1 += 1
else:
rem2 += 1
print(rem0//2 + min(rem2,rem1))
``` |
66 | Petya and File System | Title: Petya and File System
Time Limit: 3 seconds
Memory Limit: 256 megabytes
Problem Description:
Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders).
More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder.
For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples.
You are given a few files that Petya has managed to create. The path to each file looks as follows:
*diskName*:\*folder*1\*folder*2\...\ *folder**n*\*fileName*
- *diskName* is single capital letter from the set {C,D,E,F,G}.- *folder*1, ..., *folder**n* are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (*n*<=≥<=1)- *fileName* is a file name in the form of *name*.*extension*, where the *name* and the *extension* are nonempty sequences of lowercase Latin letters and digits from 0 to 9.
It is also known that there is no file whose path looks like *diskName*:\*fileName*. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder.
Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders.
Input Specification:
Each line of input data contains the description of one file path. The length of each line does not exceed 100, and overall there are no more than 100 lines. It is guaranteed, that all the paths are correct and meet the above rules. It is also guaranteed, that there are no two completely equal lines. That is, each file is described exactly once.
There is at least one line in the input data.
Output Specification:
Print two space-separated numbers. The first one is the maximal number of possible subfolders in a folder (including nested folders, nested folders of nested folders, and so on). The second one is the maximal number of files in a folder (including nested files in subfolders). Note that the disks are not regarded as folders.
Demo Input:
['C:\\folder1\\file1.txt', 'C:\\folder1\\folder2\\folder3\\file1.txt\nC:\\folder1\\folder2\\folder4\\file1.txt\nD:\\folder1\\file1.txt\n', 'C:\\file\\file\\file\\file\\file.txt\nC:\\file\\file\\file\\file2\\file.txt']
Demo Output:
['0 1', '3 2', '4 2']
Note:
In the first sample we have one folder on the "C" disk. It has no subfolders, which is why the first number in the answer is 0. But this folder contains one file, so the second number of the answer is 1.
In the second sample we have several different folders. Consider the "folder1" folder on the "C" disk. This folder directly contains one folder, "folder2". The "folder2" folder contains two more folders — "folder3" and "folder4". Thus, the "folder1" folder on the "C" drive has exactly 3 subfolders. Also this folder contains two files, even though they do not lie directly in the folder, but they are located in subfolders of "folder1".
In the third example we see that the names of some folders and some subfolders are identical. Consider the "file" folder, which lies directly on the "C" disk. That folder contains another "file" folder, which in turn contains another "file" folder, which contains two more folders, "file" and "file2". Thus, the "file" folder, which lies directly on the "C" disk, contains 4 subfolders. | ```python
import sys
def main():
path_set = set()
is_created = {}
storage = {}
freq_folders = {}
folder_recorded = {}
for path in sys.stdin:
path = path.strip()
if path in path_set:
continue
path_set.add(path)
if path not in is_created:
is_created[path] = True
disk, dir = path.split(":", 1)[0], path.split(":", 1)[1]
dir = dir.lstrip("\\")
root = ""
inserted_file = 0
length = len(dir)
if disk not in storage:
storage[disk] = {}
freq_folders[disk] = {}
folder_recorded[disk] = {}
for i in range(length):
root += dir[i]
if dir[i] == "\\":
current_folder = root + "\\"
current_root = freq_folders[disk]
current_root_record = folder_recorded[disk]
if root not in storage[disk]:
current_root[root] = 0
storage[disk][root] = 0
storage[disk][root] += 1
for j in range(i + 1, length):
current_folder += dir[j]
if dir[j] == "\\" and current_folder not in current_root_record:
current_root[root] += 1
current_root_record[current_folder] = True
break
max_files = 0
max_folders = 0
for p in storage.values():
for freq in p.values():
max_files = max(max_files, freq)
for freq_disk in freq_folders.values():
for freq in freq_disk.values():
max_folders = max(max_folders, freq)
print(max_folders, max_files)
if __name__ == "__main__":
main()
``` |
33 | What is for dinner? | Title: What is for dinner?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".
For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).
It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.
Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.
As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.
We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.
Input Specification:
The first line contains three integers *n*, *m*, *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000,<=0<=≤<=*k*<=≤<=106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow *n* lines, each containing two integers: *r* (1<=≤<=*r*<=≤<=*m*) — index of the row, where belongs the corresponding tooth, and *c* (0<=≤<=*c*<=≤<=106) — its residual viability.
It's guaranteed that each tooth row has positive amount of teeth.
Output Specification:
In the first line output the maximum amount of crucians that Valerie can consume for dinner.
Demo Input:
['4 3 18\n2 3\n1 2\n3 6\n2 3\n', '2 2 13\n1 13\n2 12\n']
Demo Output:
['11\n', '13\n']
Note:
none | ```python
I=[int(i) for i in input().split()]
n, m, k = I[0], I[1], I[2]
Min=[10**6 for i in range(m)]
for i in range(n):
I=[int(j) for j in input().split()]
r, c = I[0], I[1]
if c<Min[r-1]: Min[r-1]=c
ans=sum(Min)
if ans>k: print(k)
else: print(ans)
``` |
55 | Pie or die | Title: Pie or die
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Volodya and Vlad play the following game. There are *k* pies at the cells of *n*<=<=×<=<=*m* board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.
Input Specification:
First line contains 3 integers, separated by space: 1<=≤<=*n*,<=*m*<=≤<=100 — dimensions of the board and 0<=≤<=*k*<=≤<=100 — the number of pies. Each of the next *k* lines contains 2 integers, separated by space: 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* — coordinates of the corresponding pie. There could be more than one pie at a cell.
Output Specification:
Output only one word: "YES" — if Volodya wins, "NO" — otherwise.
Demo Input:
['2 2 1\n1 2\n', '3 4 0\n', '100 50 2\n50 25\n50 25\n']
Demo Output:
['YES', 'NO', 'NO']
Note:
none | ```python
n, m, k = [int(x) for x in input().split()]
canwin = False
for i in range(k):
x, y = [int(x) for x in input().split()]
canwin |= x < 6 or n - x < 5
canwin |= y < 6 or m - y < 5
print("YES" if canwin else "NO")
``` |
7 | Defining Macros | Title: Defining Macros
Time Limit: 3 seconds
Memory Limit: 256 megabytes
Problem Description:
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input Specification:
The first line contains the only number *n* (0<=≤<=*n*<=≤<=100) — the amount of #define constructions in the given program.
Then there follow *n* lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
- name — the macro name, - expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output Specification:
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Demo Input:
['1\n#define sum x + y\n1 * sum\n', '1\n#define sum (x + y)\nsum - sum\n', '4\n#define sum x + y\n#define mul a * b\n#define div a / b\n#define expr sum + mul * div * mul\nexpr\n', '3\n#define SumSafe (a+b)\n#define DivUnsafe a/b\n#define DenominatorUnsafe a*b\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)\n']
Demo Output:
['Suspicious\n', 'OK\n', 'OK\n', 'Suspicious\n']
Note:
none | ```python
class Macro:
def __init__(self, level):
self.level = level
def __add__(self, other):
return Macro('+0'[self.level == '0' or other.level == '0'])
def __sub__(self, other):
return Macro('+0'[self.level == '0' or other.level in '0+'])
def __mul__(self, other):
return Macro('*0'[self.level in '0+' or other.level in '0+'])
def __truediv__(self, other): # Changed __div__ to __truediv__ in Python 3
return Macro('*0'[self.level in '0+' or other.level in '0+*'])
def mkmacro(c):
return 'Macro("' + c + '")'
def calc(s):
f, n = [''], ''
for c in ''.join(s):
if c in '+-*/()':
if n != '':
f[-1] += mkmacro(v.get(n, '1'))
n = ''
if c == '(':
f.append('')
elif c == ')':
m = mkmacro('10'[eval(f.pop()).level == '0'])
f[-1] += m
else:
f[-1] += c
else:
n += c
if n != '':
f[0] += mkmacro(v.get(n, '1'))
return eval(f[0]).level
v = {}
for _ in range(int(input())): # Changed xrange to range in Python 3
s = input().split()
if s[0] == '#':
s.pop(0)
v[s[1]] = calc(s[2:])
result = calc(input().split())
print('Suspicious' if result == '0' else 'OK')
``` |
26 | Regular Bracket Sequence | Title: Regular Bracket Sequence
Time Limit: 5 seconds
Memory Limit: 256 megabytes
Problem Description:
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
Input Specification:
Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.
Output Specification:
Output the maximum possible length of a regular bracket sequence.
Demo Input:
['(()))(\n', '((()())\n']
Demo Output:
['4\n', '6\n']
Note:
none | ```python
L=input()
c1=0
c2=0
for i in L:
if i=="(":
c1+=1
else:
if c1>0:
c2+=2
c1-=1
print(c2)
``` |
27 | Number With The Given Amount Of Divisors | Title: Number With The Given Amount Of Divisors
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Given the number *n*, find the smallest positive integer which has exactly *n* divisors. It is guaranteed that for the given *n* the answer will not exceed 1018.
Input Specification:
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=1000).
Output Specification:
Output the smallest positive integer with exactly *n* divisors.
Demo Input:
['4\n', '6\n']
Demo Output:
['6\n', '12\n']
Note:
none | ```python
ans = 2e18
now = []
p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def dfs(x):
global ans
if x == 1:
res = 1
for i in range(len(now)):
res *= pow(p[i], now[i] - 1)
if res > 1e18:
return
ans = min(ans, res)
for i in range(x, 1, -1):
if x % i == 0:
now.append(i)
dfs(x // i)
now.pop()
n = int(input())
dfs(n)
print(ans)
``` |
49 | Game | Title: Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1<=×<=*n* square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.
Input Specification:
The first line contains number *n* (1<=≤<=*n*<=≤<=1000) which represents the stripe’s length. The second line contains exactly *n* symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.
Output Specification:
If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.
Demo Input:
['6\n111010\n', '5\n10001\n', '7\n1100010\n', '5\n00100\n']
Demo Output:
['1\n', '1\n', '2\n', '2\n']
Note:
In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.
In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. | ```python
n=int(input())
s=input()
q="01"*n
k=0
for i in range(n):
if s[i]!=q[i]:
k+=1
print(min(k,n-k))
``` |
31 | Chocolate | Title: Chocolate
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Bob has a rectangular chocolate bar of the size *W*<=×<=*H*. He introduced a cartesian coordinate system so that the point (0,<=0) corresponds to the lower-left corner of the bar, and the point (*W*,<=*H*) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line *x*<==<=*x**c* or *y*<==<=*y**c*, where *x**c* and *y**c* are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made *n* breaks and wrote them down in his notebook in arbitrary order. At the end he got *n*<=+<=1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
Input Specification:
The first line contains 3 integers *W*, *H* and *n* (1<=≤<=*W*,<=*H*,<=*n*<=≤<=100) — width of the bar, height of the bar and amount of breaks. Each of the following *n* lines contains four integers *x**i*,<=1,<=*y**i*,<=1,<=*x**i*,<=2,<=*y**i*,<=2 — coordinates of the endpoints of the *i*-th break (0<=≤<=*x**i*,<=1<=≤<=*x**i*,<=2<=≤<=*W*,<=0<=≤<=*y**i*,<=1<=≤<=*y**i*,<=2<=≤<=*H*, or *x**i*,<=1<==<=*x**i*,<=2, or *y**i*,<=1<==<=*y**i*,<=2). Breaks are given in arbitrary order.
It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output Specification:
Output *n*<=+<=1 numbers — areas of the resulting parts in the increasing order.
Demo Input:
['2 2 2\n1 0 1 2\n0 1 1 1\n', '2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1\n', '2 4 2\n0 1 2 1\n0 3 2 3\n']
Demo Output:
['1 1 2 ', '1 1 1 1 ', '2 2 4 ']
Note:
none | ```python
from bisect import bisect as bt
w,h,n=map(int,input().split())
N,M=max(w,h),10
x=[[0,h]]+[[] for _ in range(N-1)]
y=[[0,w]]+[[] for _ in range(N-1)]
xy=[[0]*(N+1) for _ in range(N+1)]
g=[0]*M+[[]]
xy[0][0]=1
xs,ys={0},{0}
def t(k,p):
for i,j in zip(k,p):
q=bt(i,j)
if q==0 or i[q-1]!=j:
i[q:q]=[j]
for a,b,c,d in [[*map(int,input().split())] for i in range(n)]:
m=min((a,b),(c,d))
xy[m[0]][m[1]]=1
xs.add(m[0])
ys.add(m[1])
if a==c:
t([x[a],x[a],y[m[1]]],[b,d,m[0]])
if b==d:
t([y[b],y[b],x[m[0]]],[a,c,m[1]])
for i in xs:
for j in range(len(x[i])):
if xy[i][x[i][j]]:
xy[i][x[i][j]]*=x[i][j+1]-x[i][j]
for i in ys:
for j in range(len(y[i])):
if xy[y[i][j]][i]:
p=xy[y[i][j]][i]*(y[i][j+1]-y[i][j])
if p<len(g)-1:g[p]+=1
else:g[-1].append(p)
s=[]
for i,j in enumerate(g[:-1]):
s.extend([str(i)]*j)
g[-1].sort()
s.extend([str(i) for i in g[-1]])
print(' '.join(s))
``` |
26 | Tickets | Title: Tickets
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly *n*<=+<=*m* people will come to buy a ticket. *n* of them will have only a single 10 euro banknote, and *m* of them will have only a single 20 euro banknote. Currently Charlie has *k* 10 euro banknotes, which he can use for change if needed. All *n*<=+<=*m* people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
Input Specification:
The input consist of a single line with three space separated integers, *n*, *m* and *k* (0<=≤<=*n*,<=*m*<=≤<=105, 0<=≤<=*k*<=≤<=10).
Output Specification:
Output on a single line the desired probability with at least 4 digits after the decimal point.
Demo Input:
['5 3 1\n', '0 5 5\n', '0 1 0\n']
Demo Output:
['0.857143\n', '1\n', '0\n']
Note:
none | ```python
num,p,w=map(int,input().split())
if w<p<=w+num:
n=1
for i in range(w+1):
n*=(p-i)/(num+w-(i-1))
print(1-n)
else:
print(0 if p>num+w else 1)
``` |
66 | Petya and His Friends | Title: Petya and His Friends
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to *n*.
Let us remind you the definition of the greatest common divisor: *GCD*(*a*1,<=...,<=*a**k*)<==<=*d*, where *d* represents such a maximal positive number that each *a**i* (1<=≤<=*i*<=≤<=*k*) is evenly divisible by *d*. At that, we assume that all *a**i*'s are greater than zero.
Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives *a*1 sweets, the 2-nd one gives *a*2 sweets, ..., the *n*-th one gives *a**n* sweets. At the same time, for any *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=*n*) they want the *GCD*(*a**i*,<=*a**j*) not to be equal to 1. However, they also want the following condition to be satisfied: *GCD*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1. One more: all the *a**i* should be distinct.
Help the friends to choose the suitable numbers *a*1,<=...,<=*a**n*.
Input Specification:
The first line contains an integer *n* (2<=≤<=*n*<=≤<=50).
Output Specification:
If there is no answer, print "-1" without quotes. Otherwise print a set of *n* distinct positive numbers *a*1,<=*a*2,<=...,<=*a**n*. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.
Do not forget, please, that all of the following conditions must be true:
- For every *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=*n*): *GCD*(*a**i*,<=*a**j*)<=≠<=1- *GCD*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1- For every *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=*n*,<=*i*<=≠<=*j*): *a**i*<=≠<=*a**j*
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Demo Input:
['3\n', '4\n']
Demo Output:
['99\n55\n11115\n', '385\n360\n792\n8360\n']
Note:
none | ```python
def func(a):
for i in range(2,a):
if a%i==0:
return False
return True
t = int(input())
if t==2:
print(-1)
else:
k = 2
d = []
c=0
while c+1 <= t:
if func(k):
d.append(k)
c+=1
k+=1
f = 1
for i in range(1,t):
print(d[0]*d[i])
f *= d[i]
print(f)
``` |
27 | Ring Road 2 | Title: Ring Road 2
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
It is well known that Berland has *n* cities, which form the Silver ring — cities *i* and *i*<=+<=1 (1<=≤<=*i*<=<<=*n*) are connected by a road, as well as the cities *n* and 1. The goverment have decided to build *m* new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).
Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?
Input Specification:
The first line contains two integers *n* and *m* (4<=≤<=*n*<=≤<=100,<=1<=≤<=*m*<=≤<=100). Each of the following *m* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*). No two cities will be connected by more than one road in the list. The list will not contain the roads which exist in the Silver ring.
Output Specification:
If it is impossible to build the roads in such a way that no two roads intersect, output Impossible. Otherwise print *m* characters. *i*-th character should be i, if the road should be inside the ring, and o if the road should be outside the ring. If there are several solutions, output any of them.
Demo Input:
['4 2\n1 3\n2 4\n', '6 3\n1 3\n3 5\n5 1\n']
Demo Output:
['io\n', 'ooo\n']
Note:
none | ```python
m=int(input().split()[1])
s=[[sorted([*map(int,input().split())]),-1,[]] for _ in range(m)]
def d(n,c):
if s[n][1]==c:return
if s[n][1]!=-1:
print('Impossible')
exit()
s[n][1]=c
for i in s[n][2]:d(i,1-c)
for i,j in enumerate(s):
for h,k in enumerate(s[i+1:],i+1):
if ((k[0][0]<j[0][0]<k[0][1]and k[0][1]<j[0][1])or
(k[0][0]<j[0][1]<k[0][1]and k[0][0]>j[0][0])):
j[2].append(h)
k[2].append(i)
r=''
for i,j in enumerate(s):
if j[1]==-1:d(i,0)
r+=['i','o'][j[1]]
print(r)
``` |
63 | Dividing Island | Title: Dividing Island
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A revolution took place on the Buka Island. New government replaced the old one. The new government includes *n* parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island.
The island can be conventionally represented as two rectangles *a*<=×<=*b* and *c*<=×<=*d* unit squares in size correspondingly. The rectangles are located close to each other. At that, one of the sides with the length of *a* and one of the sides with the length of *c* lie on one line. You can see this in more details on the picture.
The *i*-th party is entitled to a part of the island equal to *x**i* unit squares. Every such part should fully cover several squares of the island (it is not allowed to cover the squares partially) and be a connected figure. A "connected figure" presupposes that from any square of this party one can move to any other square of the same party moving through edge-adjacent squares also belonging to that party.
Your task is to divide the island between parties.
Input Specification:
The first line contains 5 space-separated integers — *a*, *b*, *c*, *d* and *n* (1<=≤<=*a*,<=*b*,<=*c*,<=*d*<=≤<=50, *b*<=≠<=*d*, 1<=≤<=*n*<=≤<=26). The second line contains *n* space-separated numbers. The *i*-th of them is equal to number *x**i* (1<=≤<=*x**i*<=≤<=*a*<=×<=*b*<=+<=*c*<=×<=*d*). It is guaranteed that .
Output Specification:
If dividing the island between parties in the required manner is impossible, print "NO" (without the quotes). Otherwise, print "YES" (also without the quotes) and, starting from the next line, print *max*(*b*,<=*d*) lines each containing *a*<=+<=*c* characters. To mark what square should belong to what party, use lowercase Latin letters. For the party that is first in order in the input data, use "a", for the second one use "b" and so on. Use "." for the squares that belong to the sea. The first symbol of the second line of the output data should correspond to the square that belongs to the rectangle *a*<=×<=*b*. The last symbol of the second line should correspond to the square that belongs to the rectangle *c*<=×<=*d*.
If there are several solutions output any.
Demo Input:
['3 4 2 2 3\n5 8 3\n', '3 2 1 4 4\n1 2 3 4\n']
Demo Output:
['YES\naaabb\naabbb\ncbb..\nccb..\n', 'YES\nabbd\ncccd\n...d\n...d\n']
Note:
none | ```python
def solve(x0, y0, dx, X):
for i, x in enumerate(X):
while x > 0:
x-=1
m[y0][x0] = i
x0 += dx
if x == 0 and i == len(X)-1:
break
if x0 == -1:
y0 += 1
x0 = 0
dx *= -1
if m[y0][x0] == -1:
return False
elif x0 == a+c:
y0 += 1
x0 = a+c-1
dx *=-1
if m[y0][x0] == -1:
return False
elif m[y0][x0] == -1:
y0 +=1
x0 -=dx
dx *=-1
return True
a, b, c, d, n = map(int, input().split())
X = list(map(int, input().split()))
m = [[0] * (a+c) for _ in range(max(b, d))]
if b < d:
for i in range(b, d):
for j in range(a):
m[i][j] = -1
else:
for i in range(d, b):
for j in range(a, a+c):
m[i][j] = -1
if solve(a+c-1, 0, -1, X) == False:
solve(0, 0, 1, X)
print('YES')
for x in m:
print(''.join([chr(c+97) if c>=0 else '.' for c in x]))
``` |
34 | Page Numbers | Title: Page Numbers
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).
Your task is to write a part of the program, responsible for «standardization» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format *l*1-*r*1,*l*2-*r*2,...,*l**k*-*r**k*, where *r**i*<=+<=1<=<<=*l**i*<=+<=1 for all *i* from 1 to *k*<=-<=1, and *l**i*<=≤<=*r**i*. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element *i* from the new sequence *l**i*<==<=*r**i*, this element should be output as *l**i*, and not as «*l**i*<=-<=*l**i*».
For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.
Input Specification:
The only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.
Output Specification:
Output the sequence in the required format.
Demo Input:
['1,2,3,1,1,2,6,6,2\n', '3,2,1\n', '30,20,10\n']
Demo Output:
['1-3,6\n', '1-3\n', '10,20,30\n']
Note:
none | ```python
a = sorted(set(map(int, input().split(","))))
left = right = a[0]
for x in a[1:]:
if x - right > 1:
if left == right:
print(left, end=",")
else:
print(left, right, sep="-", end=",")
left = x
right = x
if left == right:
print(left)
else:
print(left, right, sep="-")
``` |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 39