contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
---|---|---|---|
106 | Choosing Laptop | Title: Choosing Laptop
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya is choosing a laptop. The shop has *n* laptops to all tastes.
Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.
If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.
There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.
Input Specification:
The first line contains number *n* (1<=β€<=*n*<=β€<=100).
Then follow *n* lines. Each describes a laptop as *speed* *ram* *hdd* *cost*. Besides,
- *speed*, *ram*, *hdd* and *cost* are integers - 1000<=β€<=*speed*<=β€<=4200 is the processor's speed in megahertz - 256<=β€<=*ram*<=β€<=4096 the RAM volume in megabytes - 1<=β€<=*hdd*<=β€<=500 is the HDD in gigabytes - 100<=β€<=*cost*<=β€<=1000 is price in tugriks
All laptops have different prices.
Output Specification:
Print a single number β the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to *n* in the order in which they are given in the input data.
Demo Input:
['5\n2100 512 150 200\n2000 2048 240 350\n2300 1024 200 320\n2500 2048 80 300\n2000 512 180 150\n']
Demo Output:
['4']
Note:
In the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop. | ```python
t=int(input())
l=[];ans=1001
for _ in range(t):
s1,r1,h1,c1=map(int,input().split())
l1=[s1,r1,h1,c1]
l.append(l1)
for i in range(t):
for j in range(t):
if l[i][0]<l[j][0] and l[i][1]<l[j][1] and l[i][2]<l[j][2]:
break
else:
if l[i][3]<ans:
ans=l[i][3]
ans_1=i+1
print(ans_1)
``` |
90 | African Crossword | Title: African Crossword
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
An African crossword is a rectangular table *n*<=Γ<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.
When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.
You are suggested to solve an African crossword and print the word encrypted there.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100). Next *n* lines contain *m* lowercase Latin letters each. That is the crossword grid.
Output Specification:
Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.
Demo Input:
['3 3\ncba\nbcd\ncbc\n', '5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf\n']
Demo Output:
['abcd', 'codeforces']
Note:
none | ```python
n,m = list(map(int,input().split()))
matr= [['' for j in range(m)] for i in range(n)]
row_info={}
col_info={}
for i in range(n):
row_info[i]={}
cur_row=input()
for j in range(m):
matr[i][j]=cur_row[j]
if(j not in col_info):
col_info[j]={}
row_info[i][cur_row[j]]=row_info[i].get(cur_row[j],0)+1
col_info[j][cur_row[j]]=col_info[j].get(cur_row[j],0)+1
final_str=[]
for i in range(n):
for j in range(m):
if(row_info[i][matr[i][j]] >1 or col_info[j][matr[i][j]]>1):
continue
else:
final_str.append(matr[i][j])
print(''.join(final_str))
``` |
59 | Fortune Telling | Title: Fortune Telling
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are *n* camomiles growing in the field, possessing the numbers of petals equal to *a*1,<=*a*2,<=... *a**n*. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=100), which is the number of flowers growing in the field. The second line contains *n* integers *a**i* (1<=β€<=*a**i*<=β€<=100) which represent the number of petals on a given *i*-th camomile.
Output Specification:
Print a single number which is the maximal number of petals in the bouquet, the fortune telling on which would result in "Loves". If there are no such bouquet, print 0 instead. The bouquet may consist of a single flower.
Demo Input:
['1\n1\n', '1\n2\n', '3\n5 6 7\n']
Demo Output:
['1\n', '0\n', '13\n']
Note:
none | ```python
n = int(input())
l = list(map(int,input().split()))
even = []
odd = []
for i in range(n):
if(l[i]%2==0):
even.append(l[i])
else:
odd.append(l[i])
odd.sort()
if(len(odd)%2!=0):
print(sum(l))
else:
if(len(odd)==0):
print(0)
else:
print(sum(l) -odd[0])
``` |
80 | Depression | Title: Depression
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!
There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...
Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock.
Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll.
Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00.
You can only rotate the hands forward, that is, as is shown in the picture:
As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction.
Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.
Input Specification:
The only line of input contains current time according to the digital clock, formatted as HH:MM (00<=β€<=HH<=β€<=23, 00<=β€<=MM<=β€<=59). The mantel clock initially shows 12:00.
Pretests contain times of the beginning of some morning TV programs of the Channel One Russia.
Output Specification:
Print two numbers *x* and *y* β the angles of turning the hour and minute hands, respectively (0<=β€<=*x*,<=*y*<=<<=360). The absolute or relative error in the answer should not exceed 10<=-<=9.
Demo Input:
['12:00\n', '04:30\n', '08:17\n']
Demo Output:
['0 0', '135 180', '248.5 102']
Note:
A note to the second example: the hour hand will be positioned exactly in the middle, between 4 and 5. | ```python
a, b = map(int, input().split(':'))
x = ((a * 60) + b) / 2
y = b * 6
x = x % 360
print(x, y)
``` |
102 | Sum of Digits | Title: Sum of Digits
Time Limit: 2 seconds
Memory Limit: 265 megabytes
Problem Description:
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
Input Specification:
The first line contains the only integer *n* (0<=β€<=*n*<=β€<=10100000). It is guaranteed that *n* doesn't contain any leading zeroes.
Output Specification:
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
Demo Input:
['0\n', '10\n', '991\n']
Demo Output:
['0\n', '1\n', '3\n']
Note:
In the first sample the number already is one-digit β Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991βββ19βββ10βββ1. After three transformations the number becomes one-digit. | ```python
string = input()
count = 0
while len(string) > 1:
string = str(sum(map(int, string)))
count += 1
print(count)
``` |
36 | Fractal | Title: Fractal
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as *n*<=Γ<=*n* squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm:
Step 1. The paper is divided into *n*2 identical squares and some of them are painted black according to the model.
Step 2. Every square that remains white is divided into *n*2 smaller squares and some of them are painted black according to the model.
Every following step repeats step 2.
Unfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.
Input Specification:
The first line contains integers *n* and *k* (2<=β€<=*n*<=β€<=3, 1<=β€<=*k*<=β€<=5), where *k* is the amount of steps of the algorithm. Each of the following *n* lines contains *n* symbols that determine the model. Symbol Β«.Β» stands for a white square, whereas Β«*Β» stands for a black one. It is guaranteed that the model has at least one white square.
Output Specification:
Output a matrix *n**k*<=Γ<=*n**k* which is what a picture should look like after *k* steps of the algorithm.
Demo Input:
['2 3\n.*\n..\n', '3 2\n.*.\n***\n.*.\n']
Demo Output:
['.*******\n..******\n.*.*****\n....****\n.***.***\n..**..**\n.*.*.*.*\n........\n', '.*.***.*.\n*********\n.*.***.*.\n*********\n*********\n*********\n.*.***.*.\n*********\n.*.***.*.\n']
Note:
none | ```python
# Function to read file
def read_txt(file_name: str) -> list:
file = open(file_name, "r").read()
return file.split('\n')
def sub_fractal(reference: list, copy: list, n_lines: int) -> list:
# Create all new lines
new_fractal = [''] * (n_lines * len(copy))
# Get old line and cols just to verify if it is empty or filled
for line in range(len(copy)):
for col in range(len(copy[line])):
base_tam = n_lines * line
# For every space in old fractal, create new chars
old_char = copy[line][col]
# Iterator for create new chars
for new_c in range(n_lines):
dict_helper = {
"*": "*" * n_lines,
".": reference[new_c]
}
new_char = dict_helper[old_char]
new_fractal[base_tam + new_c] += new_char
return new_fractal
# Read File
file_readed = read_txt("input.txt")
fractal = [line for line in file_readed[1:-1]]
# Create copy of fractal
new_fractal = list(fractal)
# Get lines and iterations
n_lines, iterations = file_readed[0].split(" ")
# Create new fractals
for i in range(int(iterations) - 1):
new_fractal = list(sub_fractal(fractal, new_fractal, int(n_lines)))
with open("output.txt", "w+") as file:
for line in new_fractal:
print("".join(line), file=file)
``` |
96 | Lucky Numbers (easy) | Title: Lucky Numbers (easy)
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.
Input Specification:
The only line contains a positive integer *n* (1<=β€<=*n*<=β€<=109). This number doesn't have leading zeroes.
Output Specification:
Output the least super lucky number that is more than or equal to *n*.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Demo Input:
['4500\n', '47\n']
Demo Output:
['4747\n', '47\n']
Note:
none | ```python
def luckyNumber(n):
queue = []
queue.append((0,0))
while queue != []:
pair = queue.pop(0)
val = pair[0]
c = pair[1]
if c == 0 and val >= n:
return val
else:
queue.append((val * 10 + 4, c + 1))
queue.append((val * 10 + 7, c - 1))
n = int(input())
ans = luckyNumber(n)
print(ans)
``` |
81 | Sequence Formatting | Title: Sequence Formatting
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2Β ,3,...,Β Β Β 10" will be corrected to "1,Β 2,Β 3,Β ...,Β 10".
In this task you are given a string *s*, which is composed by a concatination of terms, each of which may be:
- a positive integer of an arbitrary length (leading zeroes are not allowed), - a "comma" symbol (","), - a "space" symbol (" "), - "three dots" ("...", that is, exactly three points written one after another, also known as suspension points).
Polycarp wants to add and remove spaces in the string *s* to ensure the following:
- each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it), - each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term), - if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left, - there should not be other spaces.
Automate Polycarp's work and write a program that will process the given string *s*.
Input Specification:
The input data contains a single string *s*. Its length is from 1 to 255 characters. The string *s* does not begin and end with a space. Its content matches the description given above.
Output Specification:
Print the string *s* after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.
Demo Input:
['1,2 ,3,..., 10\n', '1,,,4...5......6\n', '...,1,2,3,...\n']
Demo Output:
['1, 2, 3, ..., 10\n', '1, , , 4 ...5 ... ...6\n', '..., 1, 2, 3, ...\n']
Note:
none | ```python
import sys
def read_input(input_path=None):
if input_path is None:
f = sys.stdin
else:
f = open(input_path, 'r')
return [f.readline().strip()]
def sol(line):
b = []
for e in line.split(','):
c = [' '.join(ee.split()) for ee in e.split('...')]
b.append(' ...'.join(c).strip())
return [', '.join(b).strip()]
def solve(input_path=None):
return sol(*read_input(input_path))
def main():
for line in sol(*read_input()):
print(f"{line}")
if __name__ == '__main__':
main()
``` |
56 | Spoilt Permutation | Title: Spoilt Permutation
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya collects coins: he has exactly one coin for every year from 1 to *n*. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change β he took all the coins whose release year dated from *l* to *r* inclusively and put them in the reverse order. That is, he took a certain segment [*l*,<=*r*] and reversed it. At that the segment's endpoints did not coincide. For example, if *n*<==<=8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2,<=6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... *n* using exactly one segment reversal. If it is possible, find the segment itself.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=1000) which is the number of coins in Vasya's collection. The second line contains space-separated *n* integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to *n*, and every number is used exactly 1 time.
Output Specification:
If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers *l* *r* (1<=β€<=*l*<=<<=*r*<=β€<=*n*) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 ... *n* the given one.
Demo Input:
['8\n1 6 5 4 3 2 7 8\n', '4\n2 3 4 1\n', '4\n1 2 3 4\n']
Demo Output:
['2 6\n', '0 0\n', '0 0\n']
Note:
none | ```python
n = int(input())
data = input().split()
data2 = []
for i in range(n):
if str(i+1) != data[i]:
data2.append((data[i], i))
data2.reverse()
if data2:
o = list(range(1, n+1))
can = True
for i in range(len(data2)):
if o.index(int(data2[i][0])) != int(data2[-i-1][1]):
can = False
break
if can:
print(str(data2[-1][1] + 1) + " " + str(data2[0][1] + 1))
else:
print("0 0")
else:
print("0 0")
``` |
28 | pSort | Title: pSort
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day *n* cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move *i*-th cell can exchange it's value with the value of some other *j*-th cell, if |*i*<=-<=*j*|<==<=*d**i*, where *d**i* is a favourite number of *i*-th cell. Cells make moves in any order, the number of moves is unlimited.
The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to *n*. You are to determine whether the game could move to this state.
Input Specification:
The first line contains positive integer *n* (1<=β€<=*n*<=β€<=100) β the number of cells in the array. The second line contains *n* distinct integers from 1 to *n* β permutation. The last line contains *n* integers from 1 to *n* β favourite numbers of the cells.
Output Specification:
If the given state is reachable in the described game, output YES, otherwise NO.
Demo Input:
['5\n5 4 3 2 1\n1 1 1 1 1\n', '7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1\n', '7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
n=int(input())
p=list(map(int, input().split()))
d=list(map(int, input().split()))
c = list(range(n))
def m(x):
if c[x] != x: c[x] = m(c[x])
return c[x]
for x, k in enumerate(d):
if x >= k: c[m(x)] = m(x - k)
if x < n - k: c[m(x)] = m(x + k)
print('YES' if all(m(x) == m(y - 1) for x, y in zip(c, p)) else 'NO')
``` |
50 | Choosing Symbol Pairs | Title: Choosing Symbol Pairs
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a given string *S* consisting of *N* symbols. Your task is to find the number of ordered pairs of integers *i* and *j* such that
1. 1<=β€<=*i*,<=*j*<=β€<=*N*
2. *S*[*i*]<==<=*S*[*j*], that is the *i*-th symbol of string *S* is equal to the *j*-th.
Input Specification:
The single input line contains *S*, consisting of lowercase Latin letters and digits. It is guaranteed that string *S* in not empty and its length does not exceed 105.
Output Specification:
Print a single number which represents the number of pairs *i* and *j* with the needed property. Pairs (*x*,<=*y*) and (*y*,<=*x*) should be considered different, i.e. the ordered pairs count.
Demo Input:
['great10\n', 'aaaaaaaaaa\n']
Demo Output:
['7\n', '100\n']
Note:
none | ```python
s=input()
print(sum(s.count(k)**2 for k in set(s)) )
``` |
63 | Settlers' Training | Title: Settlers' Training
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly *n* soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.
Every soldier has a rank β some natural number from 1 to *k*. 1 stands for a private and *k* stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.
To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the *n* soldiers are present.
At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank *k* are present, exactly one soldier increases his rank by one.
You know the ranks of all *n* soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank *k*.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*,<=*k*<=β€<=100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains *n* numbers in the non-decreasing order. The *i*-th of them, *a**i*, represents the rank of the *i*-th soldier in the defense building (1<=β€<=*i*<=β€<=*n*, 1<=β€<=*a**i*<=β€<=*k*).
Output Specification:
Print a single integer β the number of golden coins needed to raise all the soldiers to the maximal rank.
Demo Input:
['4 4\n1 2 2 3\n', '4 3\n1 1 1 1\n']
Demo Output:
['4', '5']
Note:
In the first example the ranks will be raised in the following manner:
1 2 2 3 βββ 2 2 3 4 βββ 2 3 4 4 βββ 3 4 4 4 βββ 4 4 4 4
Thus totals to 4 training sessions that require 4 golden coins. | ```python
n,k=list(map(int,input().split(' ')))
nums=list(map(int,input().split(' ')))
ans=0
while nums[0]<k:
ans+=1
prev=-1
for i in range(n-1,-1,-1):
if nums[i]==k:
continue
elif prev==-1:
prev=nums[i]
nums[i]+=1
elif prev!=-1 and nums[i]!=prev:
prev=nums[i]
nums[i]+=1
print(ans)
``` |
30 | Codeforces World Finals | Title: Codeforces World Finals
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that after it the brightest minds will become his subordinates, and the toughest part of conquering the world will be completed.
The final round of the Codeforces World Finals 20YY is scheduled for *DD*.*MM*.*YY*, where *DD* is the day of the round, *MM* is the month and *YY* are the last two digits of the year. Bob is lucky to be the first finalist form Berland. But there is one problem: according to the rules of the competition, all participants must be at least 18 years old at the moment of the finals. Bob was born on *BD*.*BM*.*BY*. This date is recorded in his passport, the copy of which he has already mailed to the organizers. But Bob learned that in different countries the way, in which the dates are written, differs. For example, in the US the month is written first, then the day and finally the year. Bob wonders if it is possible to rearrange the numbers in his date of birth so that he will be at least 18 years old on the day *DD*.*MM*.*YY*. He can always tell that in his motherland dates are written differently. Help him.
According to another strange rule, eligible participant must be born in the same century as the date of the finals. If the day of the finals is participant's 18-th birthday, he is allowed to participate.
As we are considering only the years from 2001 to 2099 for the year of the finals, use the following rule: the year is leap if it's number is divisible by four.
Input Specification:
The first line contains the date *DD*.*MM*.*YY*, the second line contains the date *BD*.*BM*.*BY*. It is guaranteed that both dates are correct, and *YY* and *BY* are always in [01;99].
It could be that by passport Bob was born after the finals. In this case, he can still change the order of numbers in date.
Output Specification:
If it is possible to rearrange the numbers in the date of birth so that Bob will be at least 18 years old on the *DD*.*MM*.*YY*, output YES. In the other case, output NO.
Each number contains exactly two digits and stands for day, month or year in a date. Note that it is permitted to rearrange only numbers, not digits.
Demo Input:
['01.01.98\n01.01.80\n', '20.10.20\n10.02.30\n', '28.02.74\n28.02.64\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
none | ```python
from itertools import*
import sys
m=[32,29,32,31,32,31,32,32,31,32,31,32]
s,t=[map(int,input().split('.'))for p in range(2)]
g=False
a,b,c=s
for d,e,f in permutations(t):g|=b<13 and e<13 and a<m[b-1]+(b==2)*(c%4==0)and d<m[e-1]+(e==2)*(f%4==0)and(c-f>18 or(c-f==18 and(b>e or(b==e and(a>=d)))))
print(["NO","YES"][g])
``` |
94 | Friends | Title: Friends
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.
The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"
Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" β he kept on repeating in his mind. β "Let's take, say, Max, Ilya, Vova β here, they all know each other! And now let's add Dima and Oleg to Vova β none of them is acquainted with each other! Now, that math is just rubbish!"
Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.
Input Specification:
The first line contains an integer *m* (0<=β€<=*m*<=β€<=10), which is the number of relations of acquaintances among the five friends of Igor's.
Each of the following *m* lines contains two integers *a**i* and *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=5;*a**i*<=β <=*b**i*), where (*a**i*,<=*b**i*) is a pair of acquainted people. It is guaranteed that each pair of the acquaintances is described exactly once. The acquaintance relation is symmetrical, i.e. if *x* is acquainted with *y*, then *y* is also acquainted with *x*.
Output Specification:
Print "FAIL", if among those five people there are no either three pairwise acquainted or three pairwise unacquainted people. Otherwise print "WIN".
Demo Input:
['4\n1 3\n2 3\n1 4\n5 3\n', '5\n1 2\n2 3\n3 4\n4 5\n5 1\n']
Demo Output:
['WIN\n', 'FAIL\n']
Note:
none | ```python
def solve(m, relations):
# Create a graph to represent the acquaintances
graph = [[0] * 6 for _ in range(6)]
for i in range(m):
a, b = relations[i]
graph[a][b] = 1
graph[b][a] = 1
# Check all combinations of three people
for i in range(1, 6):
for j in range(i+1, 6):
for k in range(j+1, 6):
# Check if the three people know each other or not
if graph[i][j] == 1 and graph[j][k] == 1 and graph[k][i] == 1:
return "WIN"
if graph[i][j] == 0 and graph[j][k] == 0 and graph[k][i] == 0:
return "WIN"
return "FAIL"
# Read input
m = int(input())
relations = []
for _ in range(m):
a, b = map(int, input().split())
relations.append((a, b))
# Solve the problem
result = solve(m, relations)
# Print the result
print(result)
``` |
75 | Facetook Priority Wall | Title: Facetook Priority Wall
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).
This priority factor will be affected by three types of actions:
- 1. "*X* posted on *Y*'s wall" (15 points), - 2. "*X* commented on *Y*'s post" (10 points), - 3. "*X* likes *Y*'s post" (5 points).
*X* and *Y* will be two distinct names. And each action will increase the priority factor between *X* and *Y* (and vice versa) by the above value of points (the priority factor between *X* and *Y* is the same as the priority factor between *Y* and *X*).
You will be given *n* actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.
Input Specification:
The first line contains your name. The second line contains an integer *n*, which is the number of actions (1<=β€<=*n*<=β€<=100). Then *n* lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.
Output Specification:
Print *m* lines, where *m* is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order.
Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor.
The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line *a* is lexicographically smaller than the line *b*, if either *a* is the prefix of *b*, or if exists such an *i* (1<=β€<=*i*<=β€<=*min*(|*a*|,<=|*b*|)), that *a**i*<=<<=*b**i*, and for any *j* (1<=β€<=*j*<=<<=*i*) *a**j*<==<=*b**j*, where |*a*| and |*b*| stand for the lengths of strings *a* and *b* correspondently.
Demo Input:
["ahmed\n3\nahmed posted on fatma's wall\nfatma commented on ahmed's post\nmona likes ahmed's post\n", "aba\n1\nlikes likes posted's post\n"]
Demo Output:
['fatma\nmona\n', 'likes\nposted\n']
Note:
none | ```python
def compare(item1, item2):
if item1[0] == item2[0]:
return item1[1] < item2[1]
return item1[0] < item2[0]
name = input()
n = int(input())
m = {}
for i in range(n):
s = list(input().split())
if s[1] == 'posted':
p1 = s[0]
p2 = s[3]
if p1 == name:
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
m[p2[:-2]] += 15
if p2[:-2] == name:
if p1 not in m.keys():
m[p1] = 0
m[p1] += 15
if p1 != name and p2[:-2] != name:
if p1 not in m.keys():
m[p1] = 0
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
elif s[1] == 'commented':
p1 = s[0]
p2 = s[3]
if p1 == name:
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
m[p2[:-2]] += 10
if p2[:-2] == name:
if p1 not in m.keys():
m[p1] = 0
m[p1] += 10
if p1 != name and p2[:-2] != name:
if p1 not in m.keys():
m[p1] = 0
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
else:
p1 = s[0]
p2 = s[2]
if p1 == name:
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
m[p2[:-2]] += 5
if p2[:-2] == name:
if p1 not in m.keys():
m[p1] = 0
m[p1] += 5
if p1 != name and p2[:-2] != name:
if p1 not in m.keys():
m[p1] = 0
if p2[:-2] not in m.keys():
m[p2[:-2]] = 0
z = []
m2 = {}
for i in m.keys():
if m[i] not in m2.keys():
z.append(m[i])
m2[m[i]] = []
m2[m[i]].append(i)
z.sort()
z.reverse()
for i in z:
f = sorted(m2[i])
for j in f:
print(j)
``` |
21 | Intersection | Title: Intersection
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0.
Write the program which finds the number of points in the intersection of two given sets.
Input Specification:
The first line of the input contains three integer numbers *A*1,<=*B*1,<=*C*1 separated by space. The second line contains three integer numbers *A*2,<=*B*2,<=*C*2 separated by space. All the numbers are between -100 and 100, inclusive.
Output Specification:
Print the number of points in the intersection or -1 if there are infinite number of points.
Demo Input:
['1 1 0\n2 2 0\n', '1 1 0\n2 -2 0\n']
Demo Output:
['-1\n', '1\n']
Note:
none | ```python
row1 = input().split()
row2 = input().split()
a1 = int(row1[0])
b1 = int(row1[1])
c1 = int(row1[2])
a2 = int(row2[0])
b2 = int(row2[1])
c2 = int(row2[2])
if((a1 == 0 and b1 == 0) and (a2 == 0 and b2 == 0) and c1 != c2):
print(0)
elif((a1 == 0 and b1 == 0 and c1 == 0) or (a2 == 0 and b2 == 0 and c2 == 0)):
print(-1)
elif((a1 == 0 and b1 == 0 and c1 != 0) or (a2 == 0 and b2 == 0 and c2 != 0) and (c1 == c2)):
print(0)
elif(a1 * b2 == b1 * a2 and b2 * c1 == c2 * b1 and c1 * a2 == c2 * a1):
print(-1)
elif(((a1 * b2) - (a2 * b1)) == 0):
print(0)
else:
print(1)
``` |
70 | Text Messaging | Title: Text Messaging
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing *n* characters (which is the size of one text message). Thus, whole sentences and words get split!
Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).
The little walrus's text looks in the following manner:
SPACE stands for the symbol of a space.
So, how many messages did Fangy send?
Input Specification:
The first line contains an integer *n*, which is the size of one message (2<=β€<=*n*<=β€<=255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.
Output Specification:
On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.
Demo Input:
['25\nHello. I am a little walrus.\n', '2\nHow are you?\n', '19\nHello! Do you like fish? Why?\n']
Demo Output:
['2\n', 'Impossible\n', '3\n']
Note:
Let's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?". | ```python
n = int(input()) ;
s = input() ; count = 0 ; ans = 0
i = 0 ; L = []
while i < len(s):
if s[i] not in ['.','?','!'] : count += 1 ; i += 1
elif s[i] in ['.','?','!'] :
L.append(count + 1) ; ans += 1 ; count = 0 ; i += 2
#print(L,n)
i = 1 ; a = len(L)
#print(a)
flag = False
if L[0] > n : flag = True ; print("Impossible")
else :
while i < a:
if L[i] > n : print("Impossible") ; flag = True ; break
elif L[i] + L[i - 1] + 1 <= n : L[i - 1] += L[i] + 1 ; L.pop(i) ; a -= 1
else : i += 1
#print(L)
if not flag :
print(len(L))
``` |
107 | Basketball Team | Title: Basketball Team
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of *n* players, all of which are GUC students. However, the team might have players belonging to different departments. There are *m* departments in GUC, numbered from 1 to *m*. Herr Wafa's department has number *h*. For each department *i*, Herr Wafa knows number *s**i* β how many students who play basketball belong to this department.
Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department.
Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.
Input Specification:
The first line contains three integers *n*, *m* and *h* (1<=β€<=*n*<=β€<=100,<=1<=β€<=*m*<=β€<=1000,<=1<=β€<=*h*<=β€<=*m*) β the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly.
The second line contains a single-space-separated list of *m* integers *s**i* (1<=β€<=*s**i*<=β€<=100), denoting the number of students in the *i*-th department. Note that *s**h* includes Herr Wafa.
Output Specification:
Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10<=-<=6.
Demo Input:
['3 2 1\n2 1\n', '3 2 1\n1 1\n', '3 2 1\n2 2\n']
Demo Output:
['1\n', '-1\n', '0.666667\n']
Note:
In the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.
In the second example, there are not enough players.
In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team. | ```python
n, m, h = map(int, input().split())
s = list(map(int, input().split()))
s[h-1] = s[h-1] - 1
total = sum(s)
tot_withoutwafadep = total - s[h-1]
n = n - 1
if total<n:
print(-1)
exit()
result = 1
res_two = 1
for i in range(n):
result = result * (tot_withoutwafadep - i)
res_two = res_two * (total - i)
print(1 - result/res_two)
``` |
79 | Colorful Field | Title: Colorful Field
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Fox Ciel saw a large field while she was on a bus. The field was a *n*<=Γ<=*m* rectangle divided into 1<=Γ<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:
- Assume that the rows are numbered 1 to *n* from top to bottom and the columns are numbered 1 to *m* from left to right, and a cell in row *i* and column *j* is represented as (*i*,<=*j*). - First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,<=1)<=β<=...<=β<=(1,<=*m*)<=β<=(2,<=1)<=β<=...<=β<=(2,<=*m*)<=β<=...<=β<=(*n*,<=1)<=β<=...<=β<=(*n*,<=*m*). Waste cells will be ignored. - Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.
The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.
Now she is wondering how to determine the crop plants in some certain cells.
Input Specification:
In the first line there are four positive integers *n*,<=*m*,<=*k*,<=*t* (1<=β€<=*n*<=β€<=4Β·104,<=1<=β€<=*m*<=β€<=4Β·104,<=1<=β€<=*k*<=β€<=103,<=1<=β€<=*t*<=β€<=103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell.
Following each *k* lines contains two integers *a*,<=*b* (1<=β€<=*a*<=β€<=*n*,<=1<=β€<=*b*<=β€<=*m*), which denotes a cell (*a*,<=*b*) is waste. It is guaranteed that the same cell will not appear twice in this section.
Following each *t* lines contains two integers *i*,<=*j* (1<=β€<=*i*<=β€<=*n*,<=1<=β€<=*j*<=β€<=*m*), which is a query that asks you the kind of crop plants of a cell (*i*,<=*j*).
Output Specification:
For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.
Demo Input:
['4 5 5 6\n4 3\n1 3\n3 3\n2 5\n3 2\n1 3\n1 4\n2 3\n2 4\n1 1\n1 1\n']
Demo Output:
['Waste\nGrapes\nCarrots\nKiwis\nCarrots\nCarrots\n']
Note:
The sample corresponds to the figure in the statement. | ```python
import bisect
n, m, k, t = map(int, input().split())
def id(i, j):
return j + i*m
wastes = []
for ii in range(k):
i, j = map(int, input().split())
wastes.append(id(i-1, j-1))
wastes.sort()
labels = ['Carrots', 'Kiwis', 'Grapes']
for ii in range(t):
i, j = map(int, input().split())
id_gross = id(i-1, j-1)
waste_count = bisect.bisect_right(wastes, id_gross)
if waste_count > 0 and wastes[waste_count-1] == id_gross:
print('Waste')
continue
id_net = id_gross - waste_count
id_net %= 3
print(labels[id_net])
``` |
69 | Bets | Title: Bets
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.
To begin with friends learned the rules: in the race there are *n* sections of equal length and *m* participants. The participants numbered from 1 to *m*. About each participant the following is known:
- *l**i* β the number of the starting section, - *r**i* β the number of the finishing section (*l**i*<=β€<=*r**i*),- *t**i* β the time a biathlete needs to complete an section of the path,- *c**i* β the profit in roubles. If the *i*-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman.
The *i*-th biathlete passes the sections from *l**i* to *r**i* inclusive. The competitor runs the whole way in (*r**i*<=-<=*l**i*<=+<=1)Β·*t**i* time units. It takes him exactly *t**i* time units to pass each section. In case of the athlete's victory on *k* sections the man who has betted on him receives *k*Β·*c**i* roubles.
In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.
We should also add that Nikita can bet on each section and on any contestant running in this section.
Help the friends find the maximum possible profit.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100). Then follow *m* lines, each containing 4 integers *l**i*, *r**i*, *t**i*, *c**i* (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*, 1<=β€<=*t**i*,<=*c**i*<=β€<=1000).
Output Specification:
Print a single integer, the maximal profit in roubles that the friends can get. In each of *n* sections it is not allowed to place bets on more than one sportsman.
Demo Input:
['4 4\n1 4 20 5\n1 3 21 10\n3 3 4 30\n3 4 4 20\n', '8 4\n1 5 24 10\n2 4 6 15\n4 6 30 50\n6 7 4 20\n']
Demo Output:
['60', '105']
Note:
In the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.
In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles. | ```python
n, m = map(int, input().split())
times = [float('inf')]*(n+1)
profits = [0]*(n+1)
for _ in range(m):
l, r, t, c = map(int, input().split())
for i in range(l, r+1):
if times[i] > t:
times[i] = t
profits[i] = c
print(sum(profits))
``` |
109 | Lucky Probability | Title: Lucky Probability
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.
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer *p* from the interval [*p**l*,<=*p**r*] and Vasya chooses an integer *v* from the interval [*v**l*,<=*v**r*] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [*min*(*v*,<=*p*),<=*max*(*v*,<=*p*)] contains exactly *k* lucky numbers.
Input Specification:
The single line contains five integers *p**l*, *p**r*, *v**l*, *v**r* and *k* (1<=β€<=*p**l*<=β€<=*p**r*<=β€<=109,<=1<=β€<=*v**l*<=β€<=*v**r*<=β€<=109,<=1<=β€<=*k*<=β€<=1000).
Output Specification:
On the single line print the result with an absolute error of no more than 10<=-<=9.
Demo Input:
['1 10 1 10 2\n', '5 6 8 10 1\n']
Demo Output:
['0.320000000000\n', '1.000000000000\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%;"/>
In first case there are 32 suitable pairs: (1,β7),β(1,β8),β(1,β9),β(1,β10),β(2,β7),β(2,β8),β(2,β9),β(2,β10),β(3,β7),β(3,β8),β(3,β9),β(3,β10),β(4,β7),β(4,β8),β(4,β9),β(4,β10),β(7,β1),β(7,β2),β(7,β3),β(7,β4),β(8,β1),β(8,β2),β(8,β3),β(8,β4),β(9,β1),β(9,β2),β(9,β3),β(9,β4),β(10,β1),β(10,β2),β(10,β3),β(10,β4). Total number of possible pairs is 10Β·10β=β100, so answer is 32β/β100.
In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number. | ```python
pl, pr, vl, vr, k = map(int, input().split())
l, result = [0, 10 ** 9], 0
def get_l(x):
if x < 1e9:
l.append(x)
get_l(10 * x + 4), get_l(10 * x + 7)
get_l(4), get_l(7), l.sort()
def crossing(a, b, c, d):
res = max(0, min(b, d) - max(a, c) + 1)
return res
for i in range(1, len(l) - k):
l1 = l[i - 1] + 1
l2 = l[i]
l3 = l[i + k - 1]
l4 = l[i + k] - 1
result += crossing(l1, l2, vl, vr) * crossing(l3, l4, pl, pr) \
+ crossing(l1, l2, pl, pr) * crossing(l3, l4, vl, vr)
if k == 1 and max(vl, pl) <= l2 <= min(vr, pr):
result -= 1
print(1.0 * result / ((pr - pl + 1) * (vr - vl + 1)))
``` |
74 | Train | Title: Train
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A stowaway and a controller play the following game.
The train is represented by *n* wagons which are numbered with positive integers from 1 to *n* from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions β moving or idle. Every minute the players move.
The controller's move is as follows. The controller has the movement direction β to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the 1-st or the *n*-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move.
The stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of *n* wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back.
Let's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train.
If at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again.
At any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner.
Input Specification:
The first line contains three integers *n*, *m* and *k*. They represent the number of wagons in the train, the stowaway's and the controller's initial positions correspondingly (2<=β€<=*n*<=β€<=50, 1<=β€<=*m*,<=*k*<=β€<=*n*, *m*<=β <=*k*).
The second line contains the direction in which a controller moves. "to head" means that the controller moves to the train's head and "to tail" means that the controller moves to its tail. It is guaranteed that in the direction in which the controller is moving, there is at least one wagon. Wagon 1 is the head, and wagon *n* is the tail.
The third line has the length from 1 to 200 and consists of symbols "0" and "1". The *i*-th symbol contains information about the train's state at the *i*-th minute of time. "0" means that in this very minute the train moves and "1" means that the train in this very minute stands idle. The last symbol of the third line is always "1" β that's the terminal train station.
Output Specification:
If the stowaway wins, print "Stowaway" without quotes. Otherwise, print "Controller" again without quotes, then, separated by a space, print the number of a minute, at which the stowaway will be caught.
Demo Input:
['5 3 2\nto head\n0001001\n', '3 2 1\nto tail\n0001\n']
Demo Output:
['Stowaway', 'Controller 2']
Note:
none | ```python
def stowaway_controller_function(steps,n,stowaway_pos,controller_pos, dirr): # ΠΠ°ΠΉΡΠ° ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠΎΠΉΠΌΠ°ΡΡ ΡΠΎΠ»ΡΠΊΠΎ Π² ΠΌΠΎΠΌΠ΅Π½Ρ Π΅Π·Π΄Ρ ΡΠ»Π΅ΠΊΡΡΠΈΡΠΊΠΈ
step_num = 0
for step in steps:
step_num += 1
if int(step) == 0: # ΠΠ»Π΅ΠΊΡΡΠΈΡΠΊΠ° Π΅Π΄Π΅Ρ
# Π₯ΠΎΠ΄ Π·Π°ΠΉΡΠ° ΠΎΠ½ ΠΏΡΠΎΡΡΠΎ ΠΏΡΡΠ°Π΅ΡΡΡ ΡΠΉΡΠΈ Π½Π°ΡΠΊΠΎΠ»ΡΠΊΠΎ ΠΌΠΎΠΆΠ½ΠΎ Π΄Π°Π»ΡΡΠ΅ ΠΎΡ ΠΊΠΎΠ½ΡΡΠΎΠ»Π»Π΅ΡΠ°
if controller_pos > stowaway_pos and stowaway_pos > 1: # ΠΡΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠΎΠ»Π»Π΅Ρ Π±Π»ΠΈΠΆΠ΅ ΠΊ ΠΊΠΎΠ½ΡΡ ΠΏΠΎΠ΅Π·Π΄Π° ΡΠ΅ΠΌ Π·Π°ΡΡ, ΡΠΎΠ³Π΄Π° Π·Π°ΡΡ ΠΈΠ΄Π΅Ρ Π² ΡΠ°ΠΌΠΎΠ΅ Π½Π°ΡΠ°Π»ΠΎ
stowaway_pos-=1
elif controller_pos < stowaway_pos and stowaway_pos < n: # ΠΡΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠΎΠ»Π»Π΅Ρ Π±Π»ΠΈΠΆΠ΅ ΠΊ Π½Π°ΡΠ°Π»Ρ ΠΏΠΎΠ΅Π·Π΄Π°, ΡΠΎΠ³Π΄Π° Π·Π°ΡΡ ΠΈΠ΄Π΅Ρ Π² ΠΊΠΎΠ½Π΅Ρ
stowaway_pos+=1
# ΠΡΠ»ΠΈ Π·Π°ΡΡ Π±ΡΠ» Π² ΡΠ°ΠΌΠΎΠΌ ΠΏΠ΅ΡΠ²ΠΎΠΌ ΠΈΠ»ΠΈ ΡΠ°ΠΌΠΎΠΌ ΠΏΠΎΡΠ»Π΅Π΄Π½Π΅ΠΌ ΠΎΠ½ ΡΠΆΠ΅ Π½ΠΈΠΊΡΠ΄Π° ΠΈ Π½Π΅ ΠΈΠ΄Π΅Ρ Π΅ΠΌΡ ΡΠ°ΠΌ Π²ΡΠ³ΠΎΠ΄Π½ΠΎ
#Π₯ΠΎΠ΄ ΠΊΠΎΠ½Π΄ΡΠΊΡΠΎΡΠ°
if controller_pos+dirr <= n and controller_pos+dirr >= 1: # ΠΠ½ ΠΏΡΠΎΡΡΠΎ Π³ΠΎΠ½ΡΠ΅Ρ ΠΏΠΎΠΊΠ° Π½Π΅ ΡΠΏΠΈΡΠ°Π΅ΡΡΡ, Π΅ΠΌΡ ΠΏΠΎ ΠΏΡΠ΅ΠΊΠΎΠ»Ρ
controller_pos+=dirr
else:
dirr*=-1 #Π’ΡΡ ΠΎΠ½ ΡΠΈΠΏΠΎ ΡΠ°ΠΊΠΎΠΉ ΠΌΠ΅Π½ΡΠ΅Ρ Π΄ΠΈΡΠ΅ΠΊΡΠ΅Π½
controller_pos+=dirr
if controller_pos == stowaway_pos: #ΠΠ°ΠΏΠ΅Ρ Π·Π°ΠΉΡΡ ΠΊΡΡ
return "Controller " + str(step_num)
else: # ΠΠ»Π΅ΠΊΡΡΠΈΡΠΊΠ° ΡΡΠΎΠΈΡ, ΠΊΠΎΠ³Π΄Π° ΡΠ»Π΅ΠΊΡΡΠΈΡΠΊΠ° ΡΡΠΎΠΈΡ Π·Π°ΠΉΡΠ° ΠΊΠ°ΠΊ Π½Π΅ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠΎΠΉΠΌΠ°ΡΡ, ΠΎΠ½ ΡΠ°ΠΌ Π²ΡΠ±ΠΈΡΠ°Π΅Ρ ΠΊΡΠ΄Π° Π·Π°ΠΉΡΠΈ
#ΠΡΠ΅Π΄ΡΡΠ°Π²ΠΈΠΌ ΡΡΠΎ ΡΡΡ Π·Π°ΡΡ Π²ΡΡΠ΅Π» ΠΈ ΠΊΠ°ΠΊ Π±Ρ Ρ
ΠΎΠ΄ΠΈΡ ΠΊΠΎΠ½Π΄ΡΠΊΡΠΎΡ ΠΈ Π½Π° ΠΎΡΠ½ΠΎΠ²Π΅ Π΅Π³ΠΎ Ρ
ΠΎΠ΄Π° Π·Π°ΡΡ Π·Π°ΠΉΠ΄Π΅Ρ Π² ΠΊΠ°ΠΊΠΎΠΉ-ΡΠΎ Π²Π°Π³ΠΎΠ½
if step_num == len(steps):
return "Stowaway" # Π₯ΠΎΠ΄Ρ ΠΊΠΎΠ½ΡΠΈΠ»ΠΈΡΡ, Π·Π°ΡΡ Π²ΡΡΠ΅Π» ΠΈ Π΄ΠΎΠ΅Ρ
Π°Π» Π½Ρ ΠΈ Π±ΠΎΠ»ΡΡΠ΅ Π·Π°Ρ
ΠΎΠ΄ΠΈΡΡ Π½Π΅ Π±ΡΠ΄Π΅Ρ, ΠΎΠ½ ΠΈ ΠΏΠΎΠ±Π΅Π΄ΠΈΠ»
#Π₯ΠΎΠ΄ ΠΊΠΎΠ½Π΄ΡΠΊΡΠΎΡΠ°
if controller_pos+dirr <= n and controller_pos+dirr >= 1: # ΠΠ½ ΠΏΡΠΎΡΡΠΎ Π³ΠΎΠ½ΡΠ΅Ρ ΠΏΠΎΠΊΠ° Π½Π΅ ΡΠΏΠΈΡΠ°Π΅ΡΡΡ, Π΅ΠΌΡ ΠΏΠΎ ΠΏΡΠ΅ΠΊΠΎΠ»Ρ
controller_pos+=dirr
else:
dirr*=-1 #Π’ΡΡ ΠΎΠ½ ΡΠΈΠΏΠΎ ΡΠ°ΠΊΠΎΠΉ ΠΌΠ΅Π½ΡΠ΅Ρ Π΄ΠΈΡΠ΅ΠΊΡΠ΅Π½
controller_pos+=dirr
# Π₯ΠΎΠ΄ Π·Π°ΠΉΡΠ° (Π²ΡΠ±ΠΎΡ Π²ΡΠ³ΠΎΠ΄Π½ΠΎΠ³ΠΎ Π²Π°Π³ΠΎΠ½Π°)
if dirr > 0 and controller_pos!=1: # ΠΠΎΠ½Π΄ΡΠΊΡΠΎΡ ΠΈΠ΄Π΅Ρ ΠΊ ΠΊΠΎΠ½ΡΡ Π²Π°Π³ΠΎΠ½Π°
stowaway_pos = 1 # ΠΠ°ΡΡ Π²ΡΠ±ΠΈΡΠ°Π΅Ρ ΠΏΠ΅ΡΠ²ΡΠΉ Π²Π°Π³ΠΎΠ½
elif dirr > 0 and controller_pos==1: # ΠΠΎΠ½Π΄ΡΠΊΡΠΎΡ ΠΈΠ΄Π΅Ρ ΠΊ ΠΊΠΎΠ½ΡΡ, Π½ΠΎ ΡΠ΅ΠΉΡΠ°Ρ ΠΎΠ½ Π² ΠΏΠ΅ΡΠ²ΠΎΠΌ Π²Π°Π³ΠΎΠ½Π΅
stowaway_pos = n
elif dirr < 0 and controller_pos!=n:
stowaway_pos = n
elif dirr < 0 and controller_pos==n:
stowaway_pos = 1
# print("ΠΠ°ΡΡ: ", stowaway_pos, "ΠΠΎΠ½ΡΡΠΎΠ»Π»Π΅Ρ: ", controller_pos, dirr, "ΠΠΎΠΌΠ΅Ρ Ρ
ΠΎΠ΄Π°: ", step_num, step)
n, m, k = input().split()
n, m, k = int(n), int(m), int(k)
direction = input()
a = list(input())
if direction == "to head":
dirr = -1
else:
dirr = 1
print(stowaway_controller_function(a,n,m,k,dirr))
``` |
30 | Accounting | Title: Accounting
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.
The total income *A* of his kingdom during 0-th year is known, as well as the total income *B* during *n*-th year (these numbers can be negative β it means that there was a loss in the correspondent year).
King wants to show financial stability. To do this, he needs to find common coefficient *X* β the coefficient of income growth during one year. This coefficient should satisfy the equation:
Surely, the king is not going to do this job by himself, and demands you to find such number *X*.
It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient *X* must be integers. The number *X* may be zero or negative.
Input Specification:
The input contains three integers *A*, *B*, *n* (|*A*|,<=|*B*|<=β€<=1000, 1<=β€<=*n*<=β€<=10).
Output Specification:
Output the required integer coefficient *X*, or Β«No solutionΒ», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.
Demo Input:
['2 18 2\n', '-1 8 3\n', '0 0 10\n', '1 16 5\n']
Demo Output:
['3', '-2', '5', 'No solution']
Note:
none | ```python
import sys
q,w,num = map(int,input().split())
for p in range(-1000,1001):
if q*(p**num)== w:
print(p)
sys.exit()
print("No solution")
``` |
99 | Help Far Away Kingdom | Title: Help Far Away Kingdom
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:
- If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the numberβs integer part. - If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the numberβs integer part.- If the numberβs integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.
Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the Kingβs order?
Input Specification:
The first line contains a single number to round up β the integer part (a non-empty set of decimal digits that do not start with 0 β with the exception of a case when the set consists of a single digit β in this case 0 can go first), then follows character Β«.Β» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.
Output Specification:
If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).
Demo Input:
['0.0\n', '1.49\n', '1.50\n', '2.71828182845904523536\n', '3.14159265358979323846\n', '12345678901234567890.1\n', '123456789123456789.999\n']
Demo Output:
['0', '1', '2', '3', '3', '12345678901234567890', 'GOTO Vasilisa.']
Note:
none | ```python
def round_number(num_str):
integer_part, fractional_part = num_str.split('.')
last_digit = int(integer_part[-1])
if last_digit != 9:
if int(fractional_part[0]) < 5:
return integer_part
else:
return str(int(integer_part) + 1)
else:
return "GOTO Vasilisa."
# Read the input
num_str = input().strip()
# Perform rounding and print the result
result = round_number(num_str)
print(result)
``` |
106 | Card Game | Title: Card Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly β you can find them later yourselves if you want.
To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", "D" and "C") and a rank (in the increasing order "6", "7", "8", "9", "T", "J", "Q", "K" and "A"). At the beginning of the game one suit is arbitrarily chosen as trump.
The players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.
A card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cardsβ ranks are. In all other cases you can not beat the second card with the first one.
You are given the trump suit and two different cards. Determine whether the first one beats the second one or not.
Input Specification:
The first line contains the tramp suit. It is "S", "H", "D" or "C".
The second line contains the description of the two different cards. Each card is described by one word consisting of two symbols. The first symbol stands for the rank ("6", "7", "8", "9", "T", "J", "Q", "K" and "A"), and the second one stands for the suit ("S", "H", "D" and "C").
Output Specification:
Print "YES" (without the quotes) if the first cards beats the second one. Otherwise, print "NO" (also without the quotes).
Demo Input:
['H\nQH 9S\n', 'S\n8D 6D\n', 'C\n7H AS\n']
Demo Output:
['YES\n', 'YES', 'NO']
Note:
none | ```python
slv = {'6':0, '7':1, '8':2, '9':3, 'T':4, 'J':5, 'Q':6, 'K':7, 'A':8}
kozyr = input()
card1, card2 = input().split()
val1 = card1 [0]
mast1 = card1 [1]
val2 = card2 [0]
mast2 = card2 [1]
if mast1 == mast2:
if slv[val1] > slv [val2]:
print ('YES')
else:
print ('NO')
elif mast1 == kozyr or mast2 == kozyr:
if mast1 == kozyr:
print ('YES')
else:
print ('NO')
else:
print ('NO')
``` |
65 | Harry Potter and Three Spells | Title: Harry Potter and Three Spells
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert *a* grams of sand into *b* grams of lead, the second one allows you to convert *c* grams of lead into *d* grams of gold and third one allows you to convert *e* grams of gold into *f* grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...
Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.
Input Specification:
The first line contains 6 integers *a*, *b*, *c*, *d*, *e*, *f* (0<=β€<=*a*,<=*b*,<=*c*,<=*d*,<=*e*,<=*f*<=β€<=1000).
Output Specification:
Print "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione".
Demo Input:
['100 200 250 150 200 250\n', '100 50 50 200 200 100\n', '100 10 200 20 300 30\n', '0 0 0 0 0 0\n', '1 1 0 1 1 1\n', '1 0 1 2 1 2\n', '100 1 100 1 0 1\n']
Demo Output:
['Ron\n', 'Hermione\n', 'Hermione\n', 'Hermione\n', 'Ron\n', 'Hermione\n', 'Ron\n']
Note:
Consider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Letβs take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number.
In the forth sample it is impossible to get sand, or lead, or gold, applying the spells.
In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all.
The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold. | ```python
# LUOGU_RID: 112089745
a, b, c, d, e, f = map(int, input().split());
if a * c * e < b * d * f or a == 0 and b * d > 0 or c == 0 and d > 0:
print("Ron");
else:
print("Hermione");
``` |
94 | Restoring Password | Title: Restoring Password
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" β thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input Specification:
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output Specification:
Print one line containing 8 characters β The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Demo Input:
['01001100100101100000010110001001011001000101100110010110100001011010100101101100\n0100110000\n0100110010\n0101100000\n0101100010\n0101100100\n0101100110\n0101101000\n0101101010\n0101101100\n0101101110\n', '10101101111001000010100100011010101101110010110111011000100011011110010110001000\n1001000010\n1101111001\n1001000110\n1010110111\n0010110111\n1101001101\n1011000001\n1110010101\n1011011000\n0110001000\n']
Demo Output:
['12345678\n', '30234919\n']
Note:
none | ```python
n= list(input())
ans =[]
for i in range(len(n)//10):
tmp = n[:10]
n= n[10:]
ans.append(tmp)
a2=[]
for i in ans:
a2.append(''.join(i))
ans=[]
for i in range(10):
ans.append(input())
s=''
for i in a2:
s+=str(ans.index(i))
print(s)
``` |
68 | Irrational problem | Title: Irrational problem
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya was given this problem for homework:
You are given function (here represents the operation of taking the remainder). His task is to count the number of integers *x* in range [*a*;*b*] with property *f*(*x*)<==<=*x*.
It is a pity that Petya forgot the order in which the remainders should be taken and wrote down only 4 numbers. Each of 24 possible orders of taking the remainder has equal probability of being chosen. For example, if Petya has numbers 1, 2, 3, 4 then he can take remainders in that order or first take remainder modulo 4, then modulo 2, 3, 1. There also are 22 other permutations of these numbers that represent orders in which remainder can be taken. In this problem 4 numbers wrote down by Petya will be pairwise distinct.
Now it is impossible for Petya to complete the task given by teacher but just for fun he decided to find the number of integers with property that probability that *f*(*x*)<==<=*x* is not less than 31.4159265352718281828459045%. In other words, Petya will pick up the number *x* if there exist at least 7 permutations of numbers *p*1,<=*p*2,<=*p*3,<=*p*4, for which *f*(*x*)<==<=*x*.
Input Specification:
First line of the input will contain 6 integers, separated by spaces: *p*1,<=*p*2,<=*p*3,<=*p*4,<=*a*,<=*b* (1<=β€<=*p*1,<=*p*2,<=*p*3,<=*p*4<=β€<=1000,<=0<=β€<=*a*<=β€<=*b*<=β€<=31415).
It is guaranteed that numbers *p*1,<=*p*2,<=*p*3,<=*p*4 will be pairwise distinct.
Output Specification:
Output the number of integers in the given range that have the given property.
Demo Input:
['2 7 1 8 2 8\n', '20 30 40 50 0 100\n', '31 41 59 26 17 43\n']
Demo Output:
['0\n', '20\n', '9\n']
Note:
none | ```python
a , b , c , d , x , y = map(int,input().split())
m1 = min(a,b,c,d)
answer = 0
for i in range(x,y+1):
if i == i%m1:
answer+=1
print(answer)
``` |
40 | Find Color | Title: Find Color
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Not so long ago as a result of combat operations the main Berland place of interest β the magic clock β was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture:
The picture shows only the central part of the clock. This coloring naturally extends to infinity.
The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball.
All the points located on the border of one of the areas have to be considered painted black.
Input Specification:
The first and single line contains two integers *x* and *y* β the coordinates of the hole made in the clock by the ball. Each of the numbers *x* and *y* has an absolute value that does not exceed 1000.
Output Specification:
Find the required color.
All the points between which and the origin of coordinates the distance is integral-value are painted black.
Demo Input:
['-2 1\n', '2 1\n', '4 3\n']
Demo Output:
['white\n', 'black\n', 'black\n']
Note:
none | ```python
import math
a,b=map(int,input().split())
c=math.ceil(math.sqrt(a*a+b*b))
k=0
k+=c%2
if c**2==a**2+b**2:
print("black")
else:
if a*b<0:
k+=1
print(['white','black'][k%2])
``` |
42 | Guilty --- to the kitchen! | Title: Guilty --- to the kitchen!
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.
According to the borscht recipe it consists of *n* ingredients that have to be mixed in proportion litres (thus, there should be *a*1<=Β·*x*,<=...,<=*a**n*<=Β·*x* litres of corresponding ingredients mixed for some non-negative *x*). In the kitchen Volodya found out that he has *b*1,<=...,<=*b**n* litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a *V* litres volume pan (which means the amount of soup cooked can be between 0 and *V* litres). What is the volume of borscht Volodya will cook ultimately?
Input Specification:
The first line of the input contains two space-separated integers *n* and *V* (1<=β€<=*n*<=β€<=20,<=1<=β€<=*V*<=β€<=10000). The next line contains *n* space-separated integers *a**i* (1<=β€<=*a**i*<=β€<=100). Finally, the last line contains *n* space-separated integers *b**i* (0<=β€<=*b**i*<=β€<=100).
Output Specification:
Your program should output just one real number β the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10<=-<=4.
Demo Input:
['1 100\n1\n40\n', '2 100\n1 1\n25 30\n', '2 100\n1 1\n60 60\n']
Demo Output:
['40.0\n', '50.0\n', '100.0\n']
Note:
none | ```python
n, V = list(map(float, input().split(" ")))
a = list(map(int, input().split(" ")))
b = list(map(float, input().split(" ")))
minB = min(b)
if minB == 0:
print(0)
else:
x = b[0]/a[0]
for i, j in enumerate(a):
if x > b[i]/a[i]:
x = b[i]/a[i]
output = sum(a)*x
print(min(output, V))
``` |
88 | Chord | Title: Chord
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones
Vasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads β major and minor.
Let's define a major triad. Let the triad consist of notes *X*, *Y* and *Z*. If we can order the notes so as the distance along the musical scale between *X* and *Y* equals 4 semitones and the distance between *Y* and *Z* is 3 semitones, then the triad is major. The distance between *X* and *Z*, accordingly, equals 7 semitones.
A minor triad is different in that the distance between *X* and *Y* should be 3 semitones and between *Y* and *Z* β 4 semitones.
For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F β 4 semitones.
Help Vasya classify the triad the teacher has given to him.
Input Specification:
The only line contains 3 space-separated notes in the above-given notation.
Output Specification:
Print "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously.
Demo Input:
['C E G\n', 'C# B F\n', 'A B H\n']
Demo Output:
['major\n', 'minor\n', 'strange\n']
Note:
none | ```python
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H"]
def get_index(s):
for i in range (12):
if notes[i] == s:
return i
return 0
def check(index1, index2, index3):
first_tones = 0
second_tones = 0
if index2 < index1:
first_tones = index2 + 12 - index1
else:
first_tones = index2 - index1
if index3 < index2:
second_tones = index3 + 12 - index2
else:
second_tones = index3 - index2
if first_tones == 4 and second_tones == 3:
return "major"
elif first_tones == 3 and second_tones == 4:
return "minor"
else:
return "strange"
s1, s2, s3 = input ().split ()
index1 = get_index (s1)
index2 = get_index (s2)
index3 = get_index (s3)
s = []
s.append (check (index1, index2, index3))
s.append (check (index1, index3, index2))
s.append (check (index2, index1, index3))
s.append (check (index2, index3, index1))
s.append (check (index3, index1, index2))
s.append (check (index3, index2, index1))
for i in range (6):
if s[i] == "major" or s[i] == "minor":
print (s[i])
break
else:
print ("strange")
``` |
74 | Room Leader | Title: Room Leader
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly *n* participants. During the contest the participants are suggested to solve five problems, *A*, *B*, *C*, *D* and *E*. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.
You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
Input Specification:
The first line contains an integer *n*, which is the number of contestants in the room (1<=β€<=*n*<=β€<=50). The next *n* lines contain the participants of a given room. The *i*-th line has the format of "*handle**i* *plus**i* *minus**i* *a**i* *b**i* *c**i* *d**i* *e**i*" β it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems *A*, *B*, *C*, *D*, *E* correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:
- 0<=β€<=*plus**i*,<=*minus**i*<=β€<=50; - 150<=β€<=*a**i*<=β€<=500 or *a**i*<==<=0, if problem *A* is not solved; - 300<=β€<=*b**i*<=β€<=1000 or *b**i*<==<=0, if problem *B* is not solved; - 450<=β€<=*c**i*<=β€<=1500 or *c**i*<==<=0, if problem *C* is not solved; - 600<=β€<=*d**i*<=β€<=2000 or *d**i*<==<=0, if problem *D* is not solved; - 750<=β€<=*e**i*<=β€<=2500 or *e**i*<==<=0, if problem *E* is not solved.
All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).
Output Specification:
Print on the single line the handle of the room leader.
Demo Input:
['5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0\n']
Demo Output:
['tourist']
Note:
The number of points that each participant from the example earns, are as follows:
- Petr β 3860 - tourist β 4140 - Egor β 4030 - c00lH4x0R β β-β350 - some_participant β 2220
Thus, the leader of the room is tourist. | ```python
n=int(input())
line=[]
line1=[]
line_i=[]
leader={}
for i in range(n):
line.append(input())
line1.append([s for s in line[i].split()])
for j in range(7):
#print(line1[i][j+1])
line_i.append(int(line1[i][j+1]))
#print(line_i)
sum1=line_i[0]*100-line_i[1]*50
for k in range(5):
sum1+=line_i[k+2]
leader[line1[i][0]]=sum1
line_i.clear()
#print(leader)
keys=[key for key,value in leader.items() if value==max(leader.values())]
print(keys[0])
``` |
60 | Where Are My Flakes? | Title: Where Are My Flakes?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of *n* boxes. The boxes stand in one row, they are numbered from 1 to *n* from the left to the right. The roommate left hints like "Hidden to the left of the *i*-th box" ("To the left of *i*"), "Hidden to the right of the *i*-th box" ("To the right of *i*"). Such hints mean that there are no flakes in the *i*-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=1000,<=0<=β€<=*m*<=β€<=1000) which represent the number of boxes and the number of hints correspondingly. Next *m* lines contain hints like "To the left of *i*" and "To the right of *i*", where *i* is integer (1<=β€<=*i*<=β€<=*n*). The hints may coincide.
Output Specification:
The answer should contain exactly one integer β the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.
Demo Input:
['2 1\nTo the left of 2\n', '3 2\nTo the right of 1\nTo the right of 2\n', '3 1\nTo the left of 3\n', '3 2\nTo the left of 2\nTo the right of 1\n']
Demo Output:
['1\n', '1\n', '2\n', '-1\n']
Note:
none | ```python
n, m = map(int, input().split())
l = 0
r = n + 1
for i in range(m):
a = input().split()
if a[2] == 'right':
l = max(l, int(a[4]))
else:
r = min(r, int(a[4]))
if r - l - 1 <= 0:
print(-1)
else:
print(r - l - 1)
``` |
66 | Petya and Java | Title: Petya and Java
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer *n*?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from <=-<=128 to 127
2) short occupies 2 bytes and allows you to store numbers from <=-<=32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from <=-<=2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from <=-<=9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer *n*. Since BigInteger works much slower, Peter regards it last. Help him.
Input Specification:
The first line contains a positive number *n*. It consists of no more than 100 digits and doesn't contain any leading zeros. The number *n* can't be represented as an empty string.
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).
Output Specification:
Print the first type from the list "byte, short, int, long, BigInteger", that can store the natural number *n*, in accordance with the data given above.
Demo Input:
['127\n', '130\n', '123456789101112131415161718192021222324\n']
Demo Output:
['byte\n', 'short\n', 'BigInteger\n']
Note:
none | ```python
n=int(input())
if n>=-128 and n<=127:print('byte')
elif n>=-32768 and n<=32767:print('short')
elif n>=-2147483648 and n<=2147483647:print('int')
elif n>=-9223372036854775808 and n<=9223372036854775807:print('long')
else: print('BigInteger')
``` |
87 | Trains | Title: Trains
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every *a* minutes, but a train goes to Masha's direction every *b* minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).
We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.
Help Vasya count to which girlfriend he will go more often.
Input Specification:
The first line contains two integers *a* and *b* (*a*<=β <=*b*,<=1<=β€<=*a*,<=*b*<=β€<=106).
Output Specification:
Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency.
Demo Input:
['3 7\n', '5 3\n', '2 3\n']
Demo Output:
['Dasha\n', 'Masha\n', 'Equal\n']
Note:
Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0,β6], he will go to both girls equally often.
If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.
If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.
If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.
If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.
In sum Masha and Dasha get equal time β three minutes for each one, thus, Vasya will go to both girlfriends equally often. | ```python
from math import gcd
n,m=map(int,input().split())
lcm=n*m//(gcd(n,m))
a,b=lcm//n,lcm//m
# print()
if abs(a-b)<=1:
print("Equal")
elif a>b:
print("Dasha")
else:
print("Masha")
``` |
57 | Square Earth? | Title: Square Earth?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Meg the Rabbit decided to do something nice, specifically β to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse β as a square of side *n*. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0,<=0), (*n*,<=0), (0,<=*n*) and (*n*,<=*n*).
Input Specification:
The single line contains 5 space-separated integers: *n*,<=*x*1,<=*y*1,<=*x*2,<=*y*2 (1<=β€<=*n*<=β€<=1000,<=0<=β€<=*x*1,<=*y*1,<=*x*2,<=*y*2<=β€<=*n*) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.
Output Specification:
You must print on a single line the shortest distance between the points.
Demo Input:
['2 0 0 1 0\n', '2 0 1 2 1\n', '100 0 0 100 100\n']
Demo Output:
['1\n', '4\n', '200\n']
Note:
none | ```python
I = input().split()
n = int(I[0])
P1 = (int(I[1]), int(I[2]))
P2 = (int(I[3]), int(I[4]))
l = [0, n]
adjacent = False
opposite = False
for i in range(2):
if P1[i] in l:
if P2[int(not i)] in l:
adjacent = True
if P2[i] in l:
if P1[i] == P2[i]:
adjacent = True
else:
opposite = True
if adjacent:
shortest_distance = abs(P1[0] - P2[0]) + abs(P1[1] - P2[1])
print(shortest_distance)
if opposite and not adjacent:
distance = []
if P1[0] in l and P2[0] in l:
distance.append(abs(P1[0] - P2[0]) + abs(P1[1] - P2[1]) + 2*(min(P1[1], P2[1])))
distance.append(abs(P1[0] - P2[0]) + abs(P1[1] - P2[1]) + 2*(n - max(P1[1], P2[1])))
else:
distance.append(abs(P1[0] - P2[0]) + abs(P1[1] - P2[1]) + 2 * (min(P1[0], P2[0])))
distance.append(abs(P1[0] - P2[0]) + abs(P1[1] - P2[1]) + 2 * (n - max(P1[0], P2[0])))
shortest_distance = min(distance)
print(shortest_distance)
``` |
103 | Testing Pants for Sadness | Title: Testing Pants for Sadness
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".
The test consists of *n* questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question *n*. Question *i* contains *a**i* answer variants, exactly one of them is correct.
A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the *n* questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.
Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
Input Specification:
The first line contains a positive integer *n* (1<=β€<=*n*<=β€<=100). It is the number of questions in the test. The second line contains space-separated *n* positive integers *a**i* (1<=β€<=*a**i*<=β€<=109), the number of answer variants to question *i*.
Output Specification:
Print a single number β the minimal number of clicks needed to pass the test it the worst-case scenario.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Demo Input:
['2\n1 1\n', '2\n2 2\n', '1\n10\n']
Demo Output:
['2', '5', '10']
Note:
Note to the second sample. In the worst-case scenario you will need five clicks:
- the first click selects the first variant to the first question, this answer turns out to be wrong. - the second click selects the second variant to the first question, it proves correct and we move on to the second question; - the third click selects the first variant to the second question, it is wrong and we go back to question 1; - the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; - the fifth click selects the second variant to the second question, it proves correct, the test is finished. | ```python
a=int(input());b=[int(x) for x in input().split()];c=b[0]
for i in range(1,a):
c+=b[i]+i*(b[i]-1)
print(c)
``` |
53 | Autocomplete | Title: Autocomplete
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of *n* last visited by the user pages and the inputted part *s* are known. Your task is to complete *s* to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix *s*.
Input Specification:
The first line contains the *s* line which is the inputted part. The second line contains an integer *n* (1<=β€<=*n*<=β€<=100) which is the number of visited pages. Then follow *n* lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.
Output Specification:
If *s* is not the beginning of any of *n* addresses of the visited pages, print *s*. Otherwise, print the lexicographically minimal address of one of the visited pages starting from *s*.
The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.
Demo Input:
['next\n2\nnextpermutation\nnextelement\n', 'find\n4\nfind\nfindfirstof\nfindit\nfand\n', 'find\n4\nfondfind\nfondfirstof\nfondit\nfand\n']
Demo Output:
['nextelement\n', 'find\n', 'find\n']
Note:
none | ```python
s = input()
n = int(input())
length_orig = len(s)
ans = "z"*100
for _ in range(n):
astring = input()
if astring[:length_orig] == s and astring < ans:
ans = astring
print(s if ans == "z"*100 else ans)
``` |
54 | Presents | Title: Presents
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?
In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following *N* days. Besides, he is guided by the principle:
- on each holiday day the Hedgehog will necessarily receive a present, - he receives presents at least every *K* days (i.e., if he received a present on the *i*-th day, he will receive the next present no later than on the *i*<=+<=*K*-th day).
For the given *N* and *K*, as well as the list of holidays among the following *N* days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
Input Specification:
The first line contains integers *N* and *K* (1<=β€<=*N*<=β€<=365, 1<=β€<=*K*<=β€<=*N*).
The second line contains a number *C* which represents the number of holidays (0<=β€<=*C*<=β€<=*N*). Then in the same line follow *C* numbers ranging from 1 to *N* which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
Output Specification:
Print a single number β the minimal number of presents the Hedgehog will receive over the following *N* days.
Demo Input:
['5 2\n1 3\n', '10 1\n3 6 7 8\n']
Demo Output:
['3', '10']
Note:
none | ```python
def findNext(cursor: int, k: int, holidays: list) -> int:
i = cursor + 1
while i < cursor + k:
if i in holidays:
return i
i += 1
return i
n, k = [int(item) for item in input().split(' ')]
holidays = [int(item) for item in input().split(' ')]
del holidays[0]
ans, cursor = 0, 0
while cursor <= n:
cursor = findNext(cursor, k, holidays)
if cursor <= n:
ans += 1
print(ans)
'''
n = 20 k = 5
3 6 14 15
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
^ ^ ^ ^ ^ ^
'''
``` |
109 | Lucky Sum of Digits | Title: Lucky Sum of Digits
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.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to *n*. Help him cope with the task.
Input Specification:
The single line contains an integer *n* (1<=β€<=*n*<=β€<=106) β the sum of digits of the required lucky number.
Output Specification:
Print on the single line the result β the minimum lucky number, whose sum of digits equals *n*. If such number does not exist, print -1.
Demo Input:
['11\n', '10\n']
Demo Output:
['47\n', '-1\n']
Note:
none | ```python
n=int(input());c=0
while n%7!=0:c+=1;n-=4
if n < 0:print(-1)
else:print("4"*c+"7"*(n//7))
``` |
32 | Reconnaissance | Title: Reconnaissance
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most *d* centimeters. Captain Bob has *n* soldiers in his detachment. Their heights are *a*1,<=*a*2,<=...,<=*a**n* centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.
Ways (1,<=2) and (2,<=1) should be regarded as different.
Input Specification:
The first line contains two integers *n* and *d* (1<=β€<=*n*<=β€<=1000,<=1<=β€<=*d*<=β€<=109) β amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains *n* space-separated integers β heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.
Output Specification:
Output one number β amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed *d*.
Demo Input:
['5 10\n10 20 50 60 65\n', '5 1\n55 30 29 31 55\n']
Demo Output:
['6\n', '6\n']
Note:
none | ```python
n,d = list(map(int, input().split()))
lst = list(map(int, input().split()))
cnt=0
i=0
j=1
lst.sort()
while j<n:
if lst[j]-lst[i]<=d:
cnt+= (j-i)
j+=1
else:
i+=1
print(cnt*2)
``` |
86 | Reflection | Title: Reflection
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
For each positive integer *n* consider the integer Ο(*n*) which is obtained from *n* by replacing every digit *a* in the decimal notation of *n* with the digit (9<=<=-<=<=*a*). We say that Ο(*n*) is the reflection of *n*. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals 0, reflection of 91 equals 8.
Let us call the weight of the number the product of the number and its reflection. Thus, the weight of the number 10 is equal to 10Β·89<==<=890.
Your task is to find the maximum weight of the numbers in the given range [*l*,<=*r*] (boundaries are included).
Input Specification:
Input contains two space-separated integers *l* and *r* (1<=β€<=*l*<=β€<=*r*<=β€<=109) β bounds of the range.
Output Specification:
Output should contain single integer number: maximum value of the product *n*Β·Ο(*n*), where *l*<=β€<=*n*<=β€<=*r*.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Demo Input:
['3 7\n', '1 1\n', '8 10\n']
Demo Output:
['20', '8', '890']
Note:
In the third sample weight of 8 equals 8Β·1β=β8, weight of 9 equals 9Β·0β=β0, weight of 10 equals 890.
Thus, maximum value of the product is equal to 890. | ```python
l, r = map(int, input().split(" "))
r_len = len(str(r))
l_len = len(str(l))
tmp = None
def getValue(numbers):
numbers = str(numbers)
ret = ""
for i in range(len(numbers)):
ret += str(9 - int(numbers[i]))
return int(ret)
if r_len == l_len:
tmp = pow(10, r_len) // 2
if l <= tmp and r >= tmp:
print(tmp * getValue(tmp))
elif l > tmp:
print(l * getValue(l))
elif r < tmp:
print(r * getValue(r))
else:
tmp = pow(10, r_len) // 2
if r >= tmp:
print(tmp * getValue(tmp))
else:
print(r * getValue(r))
``` |
55 | Flea travel | Title: Flea travel
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
A flea is sitting at one of the *n* hassocks, arranged in a circle, at the moment. After minute number *k* the flea jumps through *k*<=-<=1 hassoΡks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping.
Input Specification:
The only line contains single integer: 1<=β€<=*n*<=β€<=1000 β number of hassocks.
Output Specification:
Output "YES" if all the hassocks will be visited and "NO" otherwise.
Demo Input:
['1\n', '3\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
n = int(input())
while n>1:
n/=2
if n==1:
print('YES')
else:
print("NO")
``` |
79 | Bus Game | Title: Bus Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
- Initially, there is a pile that contains *x* 100-yen coins and *y* 10-yen coins. - They take turns alternatively. Ciel takes the first turn. - In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins. - If Ciel or Hanako can't take exactly 220 yen from the pile, she loses.
Determine the winner of the game.
Input Specification:
The first line contains two integers *x* (0<=β€<=*x*<=β€<=106) and *y* (0<=β€<=*y*<=β€<=106), separated by a single space.
Output Specification:
If Ciel wins, print "Ciel". Otherwise, print "Hanako".
Demo Input:
['2 2\n', '3 22\n']
Demo Output:
['Ciel\n', 'Hanako\n']
Note:
In the first turn (Ciel's turn), she will choose 2 100-yen coins and 2 10-yen coins. In the second turn (Hanako's turn), she will choose 1 100-yen coin and 12 10-yen coins. In the third turn (Ciel's turn), she can't pay exactly 220 yen, so Ciel will lose. | ```python
def main():
x, y = map(int, input().split())
turns = min(x // 2, y // 24)
x -= 2 * turns
y -= 24 * turns
while True:
if x >= 2 and y >= 2:
x -= 2
y -= 2
elif x >= 1 and y >= 12:
x -= 1
y -= 12
elif y >= 22:
y -= 22
else:
print("Hanako")
break
if y >= 22:
y -= 22
elif x >= 1 and y >= 12:
x -= 1
y -= 12
elif x >= 2 and y >= 2:
x -= 2
y -= 2
else:
print("Ciel")
break
if __name__ == "__main__":
main()
``` |
105 | Transmigration | Title: Transmigration
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills.
Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration.
Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life.
As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the *k* coefficient (if the skill level was equal to *x*, then after transmigration it becomes equal to [*kx*], where [*y*] is the integral part of *y*). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0.
Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible.
You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?
Input Specification:
The first line contains three numbers *n*, *m* and *k* β the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; *n* and *m* are integers, and *k* is a real number with exactly two digits after decimal point (1<=β€<=*n*,<=*m*<=β€<=20, 0.01<=β€<=*k*<=β€<=0.99).
Then follow *n* lines, each of which describes a character's skill in the form "*name* *exp*" β the skill's name and the character's skill level: *name* is a string and *exp* is an integer in range from 0 to 9999, inclusive.
Then follow *m* lines each of which contains names of skills specific for the class, into which the character transmigrates.
All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names.
Output Specification:
Print on the first line number *z* β the number of skills the character will have after the transmigration. Then print *z* lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order.
Demo Input:
['5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost\n']
Demo Output:
['6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0\n']
Note:
none | ```python
# input Operation
first_line = input().split()
n, m, k = int(first_line[0]), int(first_line[1]), int(first_line[2].split('.')[1])
# OutPut Operation
b={}
for i in range(n):
old_skill=input().split()
c=int(old_skill[1])*k/100
if c>=100:
b[old_skill[0]]=c
for i in range(m):
d=input()
if not (d in b):
b[d]=0
print(len(b))
for i in sorted(b):
print(i,int(b[i]))
``` |
73 | The Elder Trolls IV: Oblivon | Title: The Elder Trolls IV: Oblivon
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!
Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size *x*<=Γ<=*y*<=Γ<=*z*, consisting of undestructable cells 1<=Γ<=1<=Γ<=1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.
All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.
Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most *k* times.
Vasya's character uses absolutely thin sword with infinite length.
Input Specification:
The first line of input contains four integer numbers *x*,<=*y*,<=*z*,<=*k* (1<=β€<=*x*,<=*y*,<=*z*<=β€<=106,<=0<=β€<=*k*<=β€<=109).
Output Specification:
Output the only number β the answer for the problem.
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:
['2 2 2 3\n', '2 2 2 1\n']
Demo Output:
['8', '2']
Note:
In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two. | ```python
x, y, z, k = map(int, input().split())
x, y, z = sorted([x, y, z])
a = min(k // 3, x - 1) + 1
k -= a - 1
b = min(k // 2, y - 1) + 1
k -= b - 1
c = min(k, z - 1) + 1
print(a * b * c)
``` |
95 | Hockey | Title: Hockey
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name *w* and the collection of forbidden substrings *s*1,<=*s*2,<=...,<=*s**n*. All those strings consist of uppercase and lowercase Latin letters. String *w* has the length of |*w*|, its characters are numbered from 1 to |*w*|.
First Petya should find all the occurrences of forbidden substrings in the *w* string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.
After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position *i* should be replaced by any other one if for position *i* in string *w* there exist pair of indices *l*,<=*r* (1<=β€<=*l*<=β€<=*i*<=β€<=*r*<=β€<=|*w*|) such that substring *w*[*l*Β ...Β *r*] is contained in the collection *s*1,<=*s*2,<=...,<=*s**n*, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.
Letter *letter* (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the *letter* occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.
Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.
Input Specification:
The first line contains the only integer *n* (1<=β€<=*n*<=β€<=100) β the number of forbidden substrings in the collection. Next *n* lines contain these substrings. The next line contains string *w*. All those *n*<=+<=1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter *letter*.
Output Specification:
Output the only line β Petya's resulting string with the maximum number of letters *letter*. If there are several answers then output the one that comes first lexicographically.
The lexicographical comparison is performed by the standard < operator in modern programming languages. The line *a* is lexicographically smaller than the line *b*, if *a* is a prefix of *b*, or there exists such an *i* (1<=β€<=*i*<=β€<=|*a*|), that *a**i*<=<<=*b**i*, and for any *j* (1<=β€<=*j*<=<<=*i*) *a**j*<==<=*b**j*. |*a*| stands for the length of string *a*.
Demo Input:
['3\nbers\nucky\nelu\nPetrLoveLuckyNumbers\nt\n', '4\nhello\nparty\nabefglghjdhfgj\nIVan\npetrsmatchwin\na\n', '2\naCa\ncba\nabAcaba\nc\n']
Demo Output:
['PetrLovtTttttNumtttt\n', 'petrsmatchwin\n', 'abCacba\n']
Note:
none | ```python
n= int(input())#how many word
b = []
for i in range(n):
b.append(input())# put the word in a list
w = input()#what we whant to change
let = input()#which we change in to
bad=[]
for i in range(len(w)):
bad.append(True)
for i in range(len(w)):
mx = 0
for j in range(n):
if w[i:].lower().startswith(b[j].lower()):
mx =max(mx,len(b[j]))
for j in range(mx):
bad[i + j] = False
ans = ''
for i in range(len(w)):
if bad[i]:
ans += w[i]
else:
if w[i].lower() == let:
newlet = 'a' if let != 'a' else 'b'
ans += newlet.lower() if w[i].lower() == w[i] else \
newlet.upper()
else:
if w[i].lower() == w[i]:
ans += let
else:
ans+=let.upper()
print(ans)
``` |
12 | Correct Solution? | Title: Correct Solution?
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said:
βShuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.
βNo problem! β said Bob and immediately gave her an answer.
Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
Input Specification:
The first line contains one integer *n* (0<=β€<=*n*<=β€<=109) without leading zeroes. The second lines contains one integer *m* (0<=β€<=*m*<=β€<=109) β Bob's answer, possibly with leading zeroes.
Output Specification:
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
Demo Input:
['3310\n1033\n', '4\n5\n']
Demo Output:
['OK\n', 'WRONG_ANSWER\n']
Note:
none | ```python
def solve():
n=list(input().strip())
m=list(input().strip())
n.sort()
if n[0]=='0':
for i in range(1,len(n)):
if n[i]!='0':
n[0],n[i]=n[i],n[0]
break
if m==n:
print("OK")
else:
print("WRONG_ANSWER")
solve()
``` |
46 | T-shirts from Sponsor | Title: T-shirts from Sponsor
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of *K* participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.
Input Specification:
The first line contains five non-negative integers *N**S*,<=*N**M*,<=*N**L*,<=*N**XL*,<=*N**XXL* not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer *K* (1<=β€<=*K*<=β€<=1000) which represents the number of participants. The next *K* lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that *N**S*<=+<=*N**M*<=+<=*N**L*<=+<=*N**XL*<=+<=*N**XXL*<=β₯<=*K*.
Output Specification:
For each contestant, print a line containing the size of the T-shirt he/she got.
Demo Input:
['1 0 2 0 1\n3\nXL\nXXL\nM\n']
Demo Output:
['XXL\nL\nL\n']
Note:
none | ```python
l = list(map(int,input().split()))
k = int(input())
d = {"S":0,"M":1,"L":2,"XL":3,"XXL":4}
d1 = {0:"S",1:"M",2:"L",3:"XL",4:"XXL"}
pref = [[0,1,2,3,4],[1,2,0,3,4],[2,3,1,4,0],[3,4,2,1,0],[4,3,2,1,0]]
for i in range(k):
s = input()
x = d[s]
for j in pref[x]:
if(l[j]>0):
l[j]-=1
print(d1[j])
break
``` |
19 | World Football Cup | Title: World Football Cup
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations:
- the final tournament features *n* teams (*n* is always even) - the first *n*<=/<=2 teams (according to the standings) come through to the knockout stage - the standings are made on the following principle: for a victory a team gets 3 points, for a draw β 1 point, for a defeat β 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β in decreasing order of the difference between scored and missed goals; in the third place β in the decreasing order of scored goals - it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity.
You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
Input Specification:
The first input line contains the only integer *n* (1<=β€<=*n*<=β€<=50) β amount of the teams, taking part in the final tournament of World Cup. The following *n* lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following *n*Β·(*n*<=-<=1)<=/<=2 lines describe the held matches in the format name1-name2 num1:num2, where *name*1, *name*2 β names of the teams; *num*1, *num*2 (0<=β€<=*num*1,<=*num*2<=β€<=100) β amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output Specification:
Output *n*<=/<=2 lines β names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
Demo Input:
['4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3\n', '2\na\nA\na-A 2:1\n']
Demo Output:
['A\nD\n', 'a\n']
Note:
none | ```python
p, n = {}, int(input())
for i in range(n): p[input()] = [0, 0, 0]
for i in range((n * (n - 1)) // 2):
t = input().split()
a, b = t[0].split('-')
x, y = t[1].split(':')
x, y = int(x), int(y)
if x > y: p[a][0] += 3
elif x < y: p[b][0] += 3
else:
p[a][0] += 1
p[b][0] += 1
p[a][1] += y
p[b][1] += x
p[a][2] += x
p[b][2] += y
for c in p: p[c][1] = p[c][2] - p[c][1]
r = sorted(p.items(), reverse = True, key = lambda x: x[1])
print('\n'.join(sorted(r[i][0] for i in range(n // 2))))
``` |
6 | Lizards and Basements 2 | Title: Lizards and Basements 2
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.
Polycarp likes to play computer role-playing game Β«Lizards and BasementsΒ». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the *i*-th archer with his fire ball (they are numbered from left to right), the archer loses *a* health points. At the same time the spell damages the archers adjacent to the *i*-th (if any) β they lose *b* (1<=β€<=*b*<=<<=*a*<=β€<=10) health points each.
As the extreme archers (i.e. archers numbered 1 and *n*) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.
The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?
Polycarp can throw his fire ball into an archer if the latter is already killed.
Input Specification:
The first line of the input contains three integers *n*,<=*a*,<=*b* (3<=β€<=*n*<=β€<=10; 1<=β€<=*b*<=<<=*a*<=β€<=10). The second line contains a sequence of *n* integers β *h*1,<=*h*2,<=...,<=*h**n* (1<=β€<=*h**i*<=β€<=15), where *h**i* is the amount of health points the *i*-th archer has.
Output Specification:
In the first line print *t* β the required minimum amount of fire balls.
In the second line print *t* numbers β indexes of the archers that Polycarp should hit to kill all the archers in *t* shots. All these numbers should be between 2 and *n*<=-<=1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.
Demo Input:
['3 2 1\n2 2 2\n', '4 3 1\n1 4 1 1\n']
Demo Output:
['3\n2 2 2 ', '4\n2 2 3 3 ']
Note:
none | ```python
import sys
n, a, b = map(int, input().split())
h = list(map(int, input().split()))
t = h[-1] // b + 1
h[-1] -= t * b
h[-2] -= t * a
h[-3] -= t * b
res = [sys.maxsize, None]
Ρount = [0] * n
def search(index, current):
if index == n - 1:
res[0] = current
Ρount[n - 2] += t
res[1] = Ρount[:]
return
x = (h[index - 1] // b + 1) if h[index - 1] >= 0 else 0
while current + x < res[0]:
h[index - 1] -= x * b
h[index] -= x * a
h[index + 1] -= x * b
Ρount[index] = x
search(index + 1, current + x)
h[index - 1] += x * b
h[index] += x * a
h[index + 1] += x * b
x += 1
search(1, t)
print(res[0])
s = []
for i in range(n):
for j in range(res[1][i]):
s.append(str(i + 1))
print(' '.join(s))
``` |
48 | Land Lot | Title: Land Lot
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya canβt spend the nights in the garden and guard the fruit because thereβs no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the gardenβs plan. On the plan the garden is represented as a rectangular checkered field *n*<=Γ<=*m* in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldnβt plant the trees too close to each other thatβs why one square contains no more than one tree). Vasya wants to find a rectangular land lot *a*<=Γ<=*b* squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=50) which represent the garden location. The next *n* lines contain *m* numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesnβt grow on this square and the 1 means that there is a growing tree. The last line contains two integers *a* and *b* (1<=β€<=*a*,<=*b*<=β€<=50). Note that Vasya can choose for building an *a*<=Γ<=*b* rectangle as well a *b*<=Γ<=*a* one, i.e. the side of the lot with the length of *a* can be located as parallel to the garden side with the length of *n*, as well as parallel to the garden side with the length of *m*.
Output Specification:
Print the minimum number of trees that needs to be chopped off to select a land lot *a*<=Γ<=*b* in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either *a*<=β€<=*n* and *b*<=β€<=*m*, or *a*<=β€<=*m* ΠΈ *b*<=β€<=*n*.
Demo Input:
['2 2\n1 0\n1 1\n1 1\n', '4 5\n0 0 1 0 1\n0 1 1 1 0\n1 0 1 0 1\n1 1 1 1 1\n2 3\n']
Demo Output:
['0\n', '2\n']
Note:
In the second example the upper left square is (1,1) and the lower right is (3,2). | ```python
n,m = map(int, input().split())
fl = [list(map(int, input().split())) for i in range(n)]
a,b = map(int, input().split())
ans_min = 2500
for i in range(n-a+1):
for j in range(m-b+1):
ans_min=min(ans_min,sum([sum(fl[k][j:j+b]) for k in range(i,i+a)]))
for i in range(n-b+1):
for j in range(m-a+1):
ans_min=min(ans_min,sum([sum(fl[k][j:j+a]) for k in range(i,i+b)]))
print(ans_min)
``` |
23 | You're Given a String... | Title: You're Given a String...
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Input Specification:
The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.
Output Specification:
Output one number β length of the longest substring that can be met in the string at least twice.
Demo Input:
['abcd\n', 'ababa\n', 'zzz\n']
Demo Output:
['0', '3', '2']
Note:
none | ```python
s = input() # input the string
n = len(s) # length of the string
res = 0 # length of the longest substring that appears at least twice
# iterate over all possible substrings of length at least 2
for i in range(n-1):
for j in range(i+1, n):
# check if the substring s[i:j] appears at least twice in s
if s[i:j] in s[i+1:]:
res = max(res, j-i) # update the length of the longest substring found
print(res) # output the length of the longest substring that appears at least twice
``` |
44 | Phone Number | Title: Phone Number
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2<=+<=9)<=/<=2<==<=5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5<=+<=3)<=/<=2<==<=4. In this case the answer is unique. Thus, every *i*-th digit is determined as an arithmetic average of the *i*-th digit of Masha's number and the *i*<=-<=1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get:
Input Specification:
The first line contains nonempty sequence consisting of digits from 0 to 9 β Masha's phone number. The sequence length does not exceed 50.
Output Specification:
Output the single number β the number of phone numbers Masha will dial.
Demo Input:
['12345\n', '09\n']
Demo Output:
['48\n', '15\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n = list(map(int, input()[:-1]))
l = len(n)
dp = [[0] * 10 for _ in range(l)]
dp[0] = [1] * 10
def owncheck(nums):
n = len(nums)
for i in range(0, n - 1):
if abs(nums[i] - nums[i + 1]) > 1:
return 0
return -1
for i in range(1, l):
for j in range(10):
s = n[i] + j
if s % 2:
dp[i][s // 2] += dp[i - 1][j]
dp[i][s // 2 + 1] += dp[i - 1][j]
else:
dp[i][s // 2] += dp[i - 1][j]
print(sum(dp[l - 1]) + owncheck(n))
``` |
14 | Four Segments | Title: Four Segments
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him.
Input Specification:
The input data contain four lines. Each of these lines contains four integers *x*1, *y*1, *x*2, *y*2 (<=-<=109<=β€<=*x*1,<=*y*1,<=*x*2,<=*y*2<=β€<=109) β coordinates of segment's beginning and end positions. The given segments can degenerate into points.
Output Specification:
Output the word Β«YESΒ», if the given four segments form the required rectangle, otherwise output Β«NOΒ».
Demo Input:
['1 1 6 1\n1 0 6 0\n6 0 6 1\n1 1 1 0\n', '0 0 0 3\n2 0 0 0\n2 2 2 0\n0 2 2 2\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
def slope(seg):
if seg[0] == seg[2]:
return 1
elif seg[1] == seg[3]:
return 0
else:
return -1
segs = []
for i in range(4):
segs.append(list(map(int,input().split())))
slopes = [slope(seg) for seg in segs]
isRect = "NO"
if slopes.count(0) == 2 and slopes.count(1) == 2:
slopes0 = [seg for seg in segs if slope(seg) == 0]
slopes1 = [seg for seg in segs if slope(seg) == 1]
if abs(slopes0[0][0]-slopes0[0][2]) == abs(slopes0[1][0]-slopes0[1][2]) and abs(slopes1[0][1]-slopes1[0][3]) == abs(slopes1[1][1]-slopes1[1][3]) and abs(slopes0[0][1]-slopes0[1][1]) == abs(slopes1[0][1]-slopes1[0][3]):
points = [str(seg[0])+"_"+str(seg[1]) for seg in segs]+[str(seg[2])+"_"+str(seg[3]) for seg in segs]
if(len(set(points)) == 4):
isRect="YES"
print(isRect)
``` |
14 | Young Photographer | Title: Young Photographer
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position *x*0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals *n*. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position *a*1 to position *b*1, the second β from *a*2 to *b*2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
Input Specification:
The first line of the input file contains integers *n* and *x*0 (1<=β€<=*n*<=β€<=100; 0<=β€<=*x*0<=β€<=1000). The following *n* lines contain pairs of integers *a**i*,<=*b**i* (0<=β€<=*a**i*,<=*b**i*<=β€<=1000; *a**i*<=β <=*b**i*).
Output Specification:
Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.
Demo Input:
['3 3\n0 7\n14 2\n4 6\n']
Demo Output:
['1\n']
Note:
none | ```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()
n, x0 = map(int, input().split())
x1, x2 = 0, 1000
for j in range(n):
a, b = map(int, input().split())
x1 = max(x1, min(a, b))
x2 = min(x2, max(a, b))
print(max(0, x1 - x0, x0 - x2) if x2 >= x1 else -1)
``` |
38 | Blinds | Title: Blinds
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are *n* blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)
Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)
After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.
Thus, if the blinds consist of *k* pieces each *d* in length, then they are of form of a rectangle of *k*<=Γ<=*d* bourlemeters.
Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than *l* bourlemeter. The window is of form of a rectangle with side lengths as positive integers.
Input Specification:
The first output line contains two space-separated integers *n* and *l* (1<=β€<=*n*,<=*l*<=β€<=100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated *n* integers *a**i*. They are the lengths of initial stripes in bourlemeters (1<=β€<=*a**i*<=β€<=100).
Output Specification:
Print the single number β the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.
Demo Input:
['4 2\n1 2 3 4\n', '5 3\n5 5 7 3 1\n', '2 3\n1 2\n']
Demo Output:
['8\n', '15\n', '0\n']
Note:
In the first sample test the required window is 2βΓβ4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves. | ```python
n, l = list(map(int, input().split()))
a = list(filter(lambda e: e >= l, map(int, input().split())))
max_area = 0
while a:
c = sum(map(lambda e: e // l, a))
max_area = max(max_area, c * l)
l += 1
a = list(filter(lambda e: e >= l, a))
print(max_area)
``` |
25 | Roads not only in Berland | Title: Roads not only in Berland
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are *n* cities in Berland and neighboring countries in total and exactly *n*<=-<=1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.
Input Specification:
The first line contains integer *n* (2<=β€<=*n*<=β€<=1000) β amount of cities in Berland and neighboring countries. Next *n*<=-<=1 lines contain the description of roads. Each road is described by two space-separated integers *a**i*, *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*,<=*a**i*<=β <=*b**i*) β pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.
Output Specification:
Output the answer, number *t* β what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output *t* lines β the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v β it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.
Demo Input:
['2\n1 2\n', '7\n1 2\n2 3\n3 1\n4 5\n5 6\n6 7\n']
Demo Output:
['0\n', '1\n3 1 3 7\n']
Note:
none | ```python
# Python3 STDIN
"""
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
1) inp β For taking integer inputs.
2) inlt β For taking List inputs.
3) insr β For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.
4) invr β For taking space seperated integer variable inputs.
The input = sys.stdin.readline is actually for Faster Inputs, because line reading through System STDIN (Standard Input) is faster in Python.
"""
"""
n = int(input())
for i in range(n):
a, m = map(int, input().split())
lst = list(map(int, input().split()))
"""
import sys
input = sys.stdin.readline
def main():
n = int(input()) + 1
dsu = [ i for i in range(n) ]
rank = [0] * n
olds = []
for _ in range(2, n):
a, b = map(int, input().split())
is_duplicate_edge = union(a, b, dsu, rank)
if is_duplicate_edge:
olds.append([a, b])
if not olds:
print(0)
sys.exit()
print(len(olds))
# For all parents
p = 2
while p < n and olds:
A = find(dsu[p], dsu)
B = find(dsu[p - 1], dsu)
union(dsu[p], dsu[p - 1], dsu, rank)
if A != B:
ea, eb = olds.pop()
print(ea, eb, A, B)
p += 1
def union(a, b, dsu, rank):
A = find(a, dsu)
B = find(b, dsu)
if A == B:
return True
dsu[B] = A
if rank[B] > rank[A]:
A, B = B, A
rank[A] += rank[B]
return False
def find(c, dsu):
if dsu[c] == c:
return c
dsu[c] = find(dsu[c], dsu)
return dsu[c]
if __name__ == "__main__":
main()
``` |
24 | F1 Champions | Title: F1 Champions
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare.
Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.
You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
Input Specification:
The first line contain integer *t* (1<=β€<=*t*<=β€<=20), where *t* is the number of races. After that all races are described one by one. Every race description start with an integer *n* (1<=β€<=*n*<=β€<=50) on a line of itself, where *n* is the number of clasified drivers in the given race. After that *n* lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.
Output Specification:
Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.
Demo Input:
['3\n3\nHamilton\nVettel\nWebber\n2\nWebber\nVettel\n2\nHamilton\nVettel\n', '2\n7\nProst\nSurtees\nNakajima\nSchumacher\nButton\nDeLaRosa\nBuemi\n8\nAlonso\nProst\nNinoFarina\nJimClark\nDeLaRosa\nNakajima\nPatrese\nSurtees\n']
Demo Output:
['Vettel\nHamilton\n', 'Prost\nProst\n']
Note:
It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50. | ```python
t=int(input());
given=[25,18,15,12,10,8,6,4,2,1];
points={};
names=set([]);
orders=[{} for x in range (50)];
for _ in range(t):
n=int(input());
for i in range(n):
name=input();
names.add(name);
if i<10:
if name in points:
points[name]+=given[i];
else:
points[name]=given[i];
if name in orders[i]:
orders[i][name]+=1;
else:
orders[i][name]=1;
for name in names:
if name not in points:
points[name]=0;
for i in range(50):
if name not in orders[i]:
orders[i][name]=0;
highest=[];
best=[];
maxorder=-100;
maxpoint=-100;
for name in names:
if points[name]>maxpoint:
highest.clear();
highest.append(name);
maxpoint=points[name];
elif points[name]==maxpoint:
highest.append(name);
if orders[0][name]>maxorder:
best.clear();
best.append(name);
maxorder=orders[0][name];
elif orders[0][name]==maxorder:
best.append(name);
if len(highest)==1:
print(highest[0]);
else:
i=0;
while 1:
ans=[];
maxorder=-100;
for name in highest:
if orders[i][name]>maxorder:
ans.clear();
ans.append(name);
maxorder=orders[i][name];
elif orders[i][name]==maxorder:
ans.append(name);
if len(ans)==1:
break;
highest[:]=ans[:];
i+=1;
print(ans[0]);
if len(best)==1:
print(best[0]);
else:
ans=[];
maxpoint=-100;
for name in best:
if points[name]>maxpoint:
ans.clear();
ans.append(name);
maxpoint=points[name];
elif points[name]==maxpoint:
ans.append(name);
if len(ans)==1:
print(ans[0]);
else:
best[:]=ans[:];
i=1;
while 1:
ans=[];
maxorder=-100;
for name in best:
if orders[i][name]>maxorder:
ans.clear();
ans.append(name);
maxorder=orders[i][name];
elif orders[i][name]==maxorder:
ans.append(name);
if len(ans)==1:
break;
best[:]=ans[:];
i+=1;
print(ans[0]);
``` |
1 | Ancient Berland Circus | Title: Ancient Berland Circus
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.
Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.
You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
Input Specification:
The input file consists of three lines, each of them contains a pair of numbers ββ coordinates of the pillar. Any coordinate doesn't exceed 1000 by absolute value, and is given with at most six digits after decimal point.
Output Specification:
Output the smallest possible area of the ancient arena. This number should be accurate to at least 6 digits after the decimal point. It's guaranteed that the number of angles in the optimal polygon is not larger than 100.
Demo Input:
['0.000000 0.000000\n1.000000 1.000000\n0.000000 1.000000\n']
Demo Output:
['1.00000000\n']
| ```python
from math import *
p =[list(map(float,input().split())) for i in range(3)]
# print(p)
a,b,c=[hypot(x1-x2,y1-y2) for (x1,y1),(x2,y2) in [(p[0],p[1]),(p[0],p[2]),(p[1],p[2])]]
# print(f"a={a}, b={b}, c={c}")
A,B,C=[acos((y*y+z*z-x*x)/2/z/y) for x,y,z in [(a,b,c),(b,c,a),(c,a,b)]]
# print(f"A={A}, B={B}, C={C}")
R=a/2/sin(A)
def g(x,y):
return x if y<1e-3 else g(y,fmod(x,y))
u=2*g(A,g(B,C))
print(round(R * R * pi / u * sin(u),7))
``` |
44 | Holidays | Title: Holidays
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
School holidays come in Berland. The holidays are going to continue for *n* days. The students of school β*N* are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.
Input Specification:
The first input line contains two numbers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=100) β the number of days in Berland holidays and the number of people in charge of the watering respectively. The next *m* lines contain the description of the duty schedule. Each line contains two integers *a**i* and *b**i* (1<=β€<=*a**i*<=β€<=*b**i*<=β€<=*n*), meaning that the *i*-th person in charge should water the flowers from the *a**i*-th to the *b**i*-th day inclusively, once a day. The duty shifts are described sequentially, i.e. *b**i*<=β€<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1 inclusively.
Output Specification:
Print "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers β the day number and the number of times the flowers will be watered that day.
Demo Input:
['10 5\n1 2\n3 3\n4 6\n7 7\n8 10\n', '10 5\n1 2\n2 3\n4 5\n7 8\n9 10\n', '10 5\n1 2\n3 3\n5 7\n7 7\n7 10\n']
Demo Output:
['OK\n', '2 2\n', '4 0\n']
Note:
Keep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number. | ```python
# LUOGU_RID: 101872602
s=input().split(' ')
days=int(s[0])
people_num=int(s[1])
def is_holidays_OK(days,people_num):
holiday=[0]*days
while(people_num!=0):
input_stream=input().split(' ')
start_day=int(input_stream[0])
end_day=int(input_stream[1])
for j in range(start_day-1,end_day):
holiday[j]+=1
people_num-=1
for i in range(days):
if holiday[i]!=1:
return str(i+1)+' '+str(holiday[i])
return 'OK'
print(is_holidays_OK(days,people_num))
``` |
44 | Cola | Title: Cola
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
To celebrate the opening of the Winter Computer School the organizers decided to buy in *n* liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly *a* bottles 0.5 in volume, *b* one-liter bottles and *c* of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well).
Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly *n* liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer.
All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.
Input Specification:
The first line contains four integers β *n*, *a*, *b*, *c* (1<=β€<=*n*<=β€<=10000, 0<=β€<=*a*,<=*b*,<=*c*<=β€<=5000).
Output Specification:
Print the unique number β the solution to the problem. If it is impossible to buy exactly *n* liters of cola, print 0.
Demo Input:
['10 5 5 5\n', '3 0 0 2\n']
Demo Output:
['9\n', '0\n']
Note:
none | ```python
def get_int_map(input_string):
return map(int, input_string.split())
def cola_catastrophe(inputs):
data = list(get_int_map(inputs))
count = 0
for i in range(min(data[0]//2, data[3]),-1,-1):
current = data[0]-i*2
if current > data[2] and 2*(current-data[2]) > data[1]:
return count
high = min(current, data[2])
low = max(0, current-data[1]//2)
if high >= low:
count+=high-low+1
#print(f"{i*2}: (current = {current}; high = {high}; low = {low}) :{count}")
return count
data = input()
print(cola_catastrophe(data))
``` |
22 | Segments | Title: Segments
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?
Input Specification:
The first line of the input contains single integer number *n* (1<=β€<=*n*<=β€<=1000) β amount of segments. Following *n* lines contain descriptions of the segments. Each description is a pair of integer numbers β endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.
Output Specification:
The first line should contain one integer number β the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.
Demo Input:
['2\n0 2\n2 5\n', '5\n0 3\n4 2\n4 8\n8 10\n7 7\n']
Demo Output:
['1\n2 ', '3\n7 10 3\n']
Note:
none | ```python
n = int(input())
intervals = []
for i in range(n):
a, b = input().split()
a = int(a)
b = int(b)
if a > b:
a, b = b, a
intervals.append((a, b))
intervals.sort(key=lambda x: x[1])
prev = intervals[0][1]
results = []
results.append(prev)
for i in range(1, n):
if prev < intervals[i][0]:
prev = intervals[i][1]
results.append(prev)
print(len(results))
for x in results:
print(x, end=" ")
``` |
17 | Hierarchy | Title: Hierarchy
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Nick's company employed *n* people. Now Nick needs to build a tree hierarchy of Β«supervisor-surbodinateΒ» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are *m* applications written in the following form: Β«employee *a**i* is ready to become a supervisor of employee *b**i* at extra cost *c**i*Β». The qualification *q**j* of each employee is known, and for each application the following is true: *q**a**i*<=><=*q**b**i*.
Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.
Input Specification:
The first input line contains integer *n* (1<=β€<=*n*<=β€<=1000) β amount of employees in the company. The following line contains *n* space-separated numbers *q**j* (0<=β€<=*q**j*<=β€<=106)β the employees' qualifications. The following line contains number *m* (0<=β€<=*m*<=β€<=10000) β amount of received applications. The following *m* lines contain the applications themselves, each of them in the form of three space-separated numbers: *a**i*, *b**i* and *c**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*, 0<=β€<=*c**i*<=β€<=106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application *q**a**i*<=><=*q**b**i*.
Output Specification:
Output the only line β the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.
Demo Input:
['4\n7 2 3 1\n4\n1 2 5\n2 4 1\n3 4 1\n1 3 5\n', '3\n1 2 3\n2\n3 1 2\n3 1 3\n']
Demo Output:
['11\n', '-1\n']
Note:
In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1. | ```python
class Solve:
def __init__(self) -> None:
self.n: int = 0;
self.q:list = [];
self.m:int = 0;
self.cost:list = []
def vao(self) -> None:
self.n = int(input());
self.q = [0] + [int(item) for item in input().split(" ")];
self.m = int(input());
self.cost.append(0);
self.cost += [-1 for _ in range(self.n)];
def dem(self) -> int:
dem:int = 0;
for i in range(self.n + 1):
if self.cost[i] == -1: dem += 1;
return dem;
def tinhTong(self) -> int:
tong: int = 0
for i in self.cost:
if(i != -1): tong += i;
return tong;
def lam(self) -> None:
for _ in range(self.m):
a, b, c = map(int,input().split(" "));
if(self.q[a] > self.q[b]):
if(self.cost[b] == -1): self.cost[b] = c;
else: self.cost[b] = min(self.cost[b], c);
if(self.dem() > 1): print("-1");
else: print(self.tinhTong());
def ra(self) -> None:
pass;
def main():
p = Solve();
p.vao();
p.lam();
p.ra();
main();
``` |
8 | Obsession with Robots | Title: Obsession with Robots
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug β the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest.
The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest.
In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in.
Input Specification:
The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100.
Output Specification:
In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist).
Demo Input:
['LLUUUR\n', 'RRUULLDD\n']
Demo Output:
['OK\n', 'BUG\n']
Note:
none | ```python
# LUOGU_RID: 103627654
import sys
path=input().strip()
x=y=0
vis=[(0,0)]
l=len(path)
for i in range(l):
x_=x
y_=y
nd=path[i]
if nd=='U':
x-=1
elif nd=='L':
y-=1
elif nd=='R':
y+=1
else:
x+=1
if (x,y) not in vis: vis.append((x,y))
else:
print('BUG')
sys.exit(0)
for dx,dy in [(-1,0),(0,-1),(1,0),(0,1)]:
if (x+dx,y+dy)!=(x_,y_) and (x+dx,y+dy) in vis:
print('BUG')
sys.exit(0)
print('OK')
``` |
39 | Pacifist frogs | Title: Pacifist frogs
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to *n* and the number of a hill is equal to the distance in meters between it and the island. The distance between the *n*-th hill and the shore is also 1 meter.
Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is *d*, the frog will jump from the island on the hill *d*, then β on the hill 2*d*, then 3*d* and so on until they get to the shore (i.e. find itself beyond the hill *n*).
However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=β€<=*n*<=β€<=109, 1<=β€<=*m*,<=*k*<=β€<=100) β the number of hills, frogs and mosquitoes respectively. The second line contains *m* integers *d**i* (1<=β€<=*d**i*<=β€<=109) β the lengths of the frogsβ jumps. The third line contains *k* integers β the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.
Output Specification:
In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line β their numbers in increasing order separated by spaces. The frogs are numbered from 1 to *m* in the order of the jump length given in the input data.
Demo Input:
['5 3 5\n2 3 4\n1 2 3 4 5\n', '1000000000 2 3\n2 5\n999999995 999999998 999999996\n']
Demo Output:
['2\n2 3\n', '1\n2\n']
Note:
none | ```python
n, m, k = list(map(int, input().split()))
frogs = list(map(int, input().split()))
mosquitos = list(map(int, input().split()))
best_frogs = []
min_kills = len(mosquitos)
for i, frog in enumerate(frogs):
kills = sum([1 if m % frog == 0 else 0 for m in mosquitos])
if kills < min_kills:
min_kills = kills
best_frogs = []
if kills == min_kills:
best_frogs.append(i + 1)
print(len(best_frogs))
print(*best_frogs)
``` |
14 | Camels | Title: Camels
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with *t* humps, representing them as polylines in the plane. Each polyline consists of *n* vertices with coordinates (*x*1,<=*y*1), (*x*2,<=*y*2), ..., (*x**n*,<=*y**n*). The first vertex has a coordinate *x*1<==<=1, the second β *x*2<==<=2, etc. Coordinates *y**i* might be any, but should satisfy the following conditions:
- there should be *t* humps precisely, i.e. such indexes *j* (2<=β€<=*j*<=β€<=*n*<=-<=1), so that *y**j*<=-<=1<=<<=*y**j*<=><=*y**j*<=+<=1, - there should be precisely *t*<=-<=1 such indexes *j* (2<=β€<=*j*<=β€<=*n*<=-<=1), so that *y**j*<=-<=1<=><=*y**j*<=<<=*y**j*<=+<=1, - no segment of a polyline should be parallel to the *Ox*-axis, - all *y**i* are integers between 1 and 4.
For a series of his drawings of camels with *t* humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with *t* humps for a given number *n*.
Input Specification:
The first line contains a pair of integers *n* and *t* (3<=β€<=*n*<=β€<=20, 1<=β€<=*t*<=β€<=10).
Output Specification:
Output the required amount of camels with *t* humps.
Demo Input:
['6 1\n', '4 2\n']
Demo Output:
['6\n', '0\n']
Note:
In the first sample test sequences of *y*-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 ΠΈ 234321 (each digit corresponds to one value of *y*<sub class="lower-index">*i*</sub>). | ```python
N,t=map(int,input().split());
T=2*t-1;
dp=[[[0 for x in range(5)] for y in range (T+2)] for z in range(N+1)];
for t in range(1,T+2):
for h in range(1,5):
if t==T:
dp[N][t][h]=1;
else:
dp[N][t][h]=0;
for n in range(1,N+1):
for h in range(5):
dp[n][T+1][h]=0;
for n in range(N-1,1,-1):
for t in range(T,-1,-1):
for h in range(1,5):
tmp=0;
if t%2==1:
for i in range(h+1,5):
tmp+=dp[n+1][t+1][i];
for i in range(1,h):
tmp+=dp[n+1][t][i];
else:
for i in range(h+1,5):
tmp+=dp[n+1][t][i];
for i in range(1,h):
tmp+=dp[n+1][t+1][i];
dp[n][t][h]=tmp;
ans=0;
for h in range(1,5):
ans+=(h-1)*dp[2][0][h];
print(ans);
``` |
48 | The Race | Title: The Race
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name β The Huff-puffer.
So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with Ξ± liters of petrol (Ξ±<=β₯<=10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers.
Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with Ξ± liters of petrol. Otherwise, he doesn't stop at the station and drives on.
For example, if Ξ±<==<=43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42<=+<=43.21<==<=49.63 liters. The next stop is at the station number 12, 9.63<=+<=43.21<==<=52.84. The next stop is at the station number 17 and so on.
You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.
One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the Ξ± number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=1000) which represents the number of petrol stations where Vanya has stopped. The next line has *n* space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number Ξ±<=β₯<=10, to which such a succession of stops corresponds.
Output Specification:
Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".
Demo Input:
['3\n1 2 4\n', '2\n1 2\n']
Demo Output:
['unique\n5\n', 'not unique\n']
Note:
In the second example the answer is not unique. For example, if Ξ±β=β10, we'll have such a sequence as 1, 2, 3, and if Ξ±β=β14, the sequence will be 1, 2, 4. | ```python
import math
def readGen(trans):
while 1:
for x in input().split():
yield(trans(x))
readint=readGen(int)
n=next(readint)
a=[0]+[next(readint) for i in range(n)]
p=max((n+1)*a[i]/i-1 for i in range(1,n+1))
q=min((n+1)*(a[i]+1)/i for i in range(1,n+1))
eps=1e-8
u=math.floor(q-eps)
l=math.ceil(p+eps)
#print(p,q,l,u)
if (l<u): print("not unique")
else: print("unique\n%d"%l)
``` |
16 | Logging | Title: Logging
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: Β«[date:time]: messageΒ», where for each Β«[date:time]Β» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer β Alex β managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format Β«[time]: messageΒ». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.
So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).
We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.
Input Specification:
The first input line contains number *n* (1<=β€<=*n*<=β€<=100). The following *n* lines contain recordings in format Β«[time]: messageΒ», where time is given in format Β«hh:mm x.m.Β». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character Β«aΒ» or character Β«pΒ». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.
Output Specification:
Output one number β the minimum amount of days covered by the log.
Demo Input:
['5\n[05:00 a.m.]: Server is started\n[05:00 a.m.]: Rescan initialized\n[01:13 p.m.]: Request processed\n[01:10 p.m.]: Request processed\n[11:40 p.m.]: Rescan completed\n', '3\n[09:00 a.m.]: User logged in\n[08:00 a.m.]: User logged in\n[07:00 a.m.]: User logged in\n']
Demo Output:
['2\n', '3\n']
Note:
Formally the 12-hour time format is described at:
- http://en.wikipedia.org/wiki/12-hour_clock. | ```python
# LUOGU_RID: 102111111
def main():
n = int(input())
last_time = -1
repeats = 0
days = 1
for _ in range(n):
line = input()
e = line.index(']')
line = line[1:e]
h = int(line[:2])
m = int(line[3:5])
h %= 12
if line[6] == 'p':
h += 12
time = 60 * h + m
if time < last_time or (time == last_time and repeats == 10):
days += 1
repeats = 1
elif time == last_time:
repeats += 1
else:
repeats = 1
last_time = time
print(days)
main()
``` |
45 | TCMCF+++ | Title: TCMCF+++
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest *n* problems were suggested and every problem had a cost β a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=100) β the number of the suggested problems. The next line contains *n* space-separated integers *c**i* (<=-<=100<=β€<=*c**i*<=β€<=100) β the cost of the *i*-th task. The tasks' costs may coinΡide.
Output Specification:
Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.
Demo Input:
['5\n1 2 -3 3 3\n', '13\n100 100 100 100 100 100 100 100 100 100 100 100 100\n', '4\n-2 -2 -2 -2\n']
Demo Output:
['3 1 2 3 \n', '100 100 100 100 100 100 100 100 100 100 100 100 100 \n', '-2 -2 -2 -2 \n']
Note:
none | ```python
for _ in range(1):
n = int(input())
a = list(map(int, input().split()))
pos = []
neg = []
zero = 0
for i in range(n):
if a[i] > 0:
pos.append(a[i])
elif a[i] == 0:
zero += 1
else:
neg.append(a[i])
if len(neg) % 2:
neg.remove(max(neg))
ans = pos + neg
if len(ans) == 0:
print(max(a))
else:
print(*ans)
``` |
41 | 3-cycles | Title: 3-cycles
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
During a recent research Berland scientists found out that there were *n* cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.
Input Specification:
The first line contains an integer *n* (1<=β€<=*n*<=β€<=100) β the number of cities in Berland.
Output Specification:
On the first line must be printed number *m* β the maximal number of roads in Berland. Then print *m* lines containing two numbers each β the numbers of cities that the given road joins. The cities are numbered with integers from 1 to *n*. If there are several variants of solving the problem, print any of them.
Demo Input:
['3\n', '4\n']
Demo Output:
['2\n1 2\n2 3\n', '4\n1 2\n2 3\n3 4\n4 1\n']
Note:
none | ```python
# LUOGU_RID: 111250159
n = int(input())
if n & 1 : print((n // 2) * (n // 2 + 1))
else : print((n // 2) * (n // 2))
x = n // 2
y = n // 2 + 1
for i in range(1, x + 1) :
for j in range(y, n + 1) :
print(i, j)
``` |
93 | End of Exams | Title: End of Exams
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!
Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the *m* friends found *n* different kinds of milk on the menu, that's why they ordered *n* bottles β one bottle of each kind. We know that the volume of milk in each bottle equals *w*.
When the bottles were brought in, they decided to pour all the milk evenly among the *m* cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem β and what is actually the way to do it?
Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!
Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
Input Specification:
The only input data file contains three integers *n*, *w* and *m* (1<=β€<=*n*<=β€<=50, 100<=β€<=*w*<=β€<=1000, 2<=β€<=*m*<=β€<=50), where *n* stands for the number of ordered bottles, *w* stands for the volume of each of them and *m* stands for the number of friends in the company.
Output Specification:
Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".
If there is a solution, then print *m* more lines, where the *i*-th of them describes the content of the *i*-th student's cup. The line should consist of one or more pairs that would look like "*b* *v*". Each such pair means that *v* (*v*<=><=0) units of milk were poured into the *i*-th cup from bottle *b* (1<=β€<=*b*<=β€<=*n*). All numbers *b* on each line should be different.
If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.
Demo Input:
['2 500 3\n', '4 100 5\n', '4 100 7\n', '5 500 2\n']
Demo Output:
['YES\n1 333.333333\n2 333.333333\n2 166.666667 1 166.666667\n', 'YES\n3 20.000000 4 60.000000\n1 80.000000\n4 40.000000 2 40.000000\n3 80.000000\n2 60.000000 1 20.000000\n', 'NO\n', 'YES\n4 250.000000 5 500.000000 2 500.000000\n3 500.000000 1 500.000000 4 250.000000\n']
Note:
none | ```python
EPS = 1e-9
class Bottle:
def __init__(self, i, c1, c2, v):
self.i = i
self.c1 = c1
self.c2 = c2
self.v = v
class Cup:
def __init__(self, i, v):
self.i = i
self.v = v
self.b = [0] * 50
def distribute_milk(n, w, m):
if 2 * n < m:
print('NO')
return
w0 = n * w / float(m)
b = [Bottle(i, 0, 0, w) for i in range(1, n + 1)]
c = [Cup(i, 0) for i in range(1, m + 1)]
for k in range(1, 2 * n + 1):
i = (k + 1) // 2
if abs(b[i - 1].v) < EPS:
continue
for j in range(1, m + 1):
if abs(c[j - 1].v - w0) < EPS:
continue
if b[i - 1].c1 == j or b[i - 1].c2 == j:
continue
if b[i - 1].c1 == 0:
b[i - 1].c1 = j
else:
b[i - 1].c2 = j
if b[i - 1].v > w0 - c[j - 1].v + EPS:
b[i - 1].v -= (w0 - c[j - 1].v)
c[j - 1].b[b[i - 1].i - 1] = w0 - c[j - 1].v
c[j - 1].v = w0
else:
c[j - 1].v += b[i - 1].v
c[j - 1].b[b[i - 1].i - 1] = b[i - 1].v
b[i - 1].v = 0
break
for i in range(1, m + 1):
if abs(c[i - 1].v - w0) > EPS:
print('NO')
return
print('YES')
for i in range(1, m + 1):
f = True
for j in range(1, n + 1):
if c[i - 1].b[j - 1] > EPS:
if not f:
print(' ', end='')
print(j, ' %.12f' % c[i - 1].b[j - 1], end='')
f = False
print()
if __name__ == "__main__":
n, w, m = map(int, input().split())
distribute_milk(n, w, m)
``` |
103 | Cthulhu | Title: Cthulhu
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with *n* vertices and *m* edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
Input Specification:
The first line contains two integers β the number of vertices *n* and the number of edges *m* of the graph (1<=β€<=*n*<=β€<=100, 0<=β€<=*m*<=β€<=).
Each of the following *m* lines contains a pair of integers *x* and *y*, that show that an edge exists between vertices *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=*n*,<=*x*<=β <=*y*). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output Specification:
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Demo Input:
['6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4\n', '6 5\n5 6\n4 6\n3 1\n5 1\n1 2\n']
Demo Output:
['FHTAGN!', 'NO']
Note:
Let us denote as a simple cycle a set of *v* vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., *v*β-β1 and *v*, *v* and 1.
A tree is a connected undirected graph consisting of *n* vertices and *n*β-β1 edges (*n*β>β0).
A rooted tree is a tree where one vertex is selected to be the root. | ```python
from collections import deque
n, m = map(int, input().split())
M = m
g = {i: [] for i in range(1, n + 1)}
while m:
n1, n2 = map(int, input().split())
g[n1].append(n2)
g[n2].append(n1)
m = m - 1
v = [False for _ in range(n + 1)]
cities = 0
for start in range(1, n + 1):
if v[start] == False:
v[start] = True
queue = deque([start])
while queue:
curr = queue.popleft()
for i in g[curr]:
if v[i] == False:
v[i] = True
queue.append(i)
cities = cities + 1
if M == n and cities == 1:
print("FHTAGN!")
else:
print('NO')
``` |
60 | Serial Time! | Title: Serial Time!
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped *k*<=Γ<=*n*<=Γ<=*m*, that is, it has *k* layers (the first layer is the upper one), each of which is a rectangle *n*<=Γ<=*m* with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (*x*,<=*y*) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.
Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1<=Γ<=1<=Γ<=1 cubes.
Input Specification:
The first line contains three numbers *k*, *n*, *m* (1<=β€<=*k*,<=*n*,<=*m*<=β€<=10) which are the sizes of the plate. Then follow *k* rectangles consisting of *n* lines each containing *m* characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains *x* and *y* (1<=β€<=*x*<=β€<=*n*,<=1<=β€<=*y*<=β€<=*m*) which are the tap's coordinates. *x* is the number of the line and *y* is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to *n*, columns of each layer are numbered from top to bottom by the integers from 1 to *m*.
Output Specification:
The answer should contain a single number, showing in how many minutes the plate will be filled.
Demo Input:
['1 1 1\n\n.\n\n1 1\n', '2 1 1\n\n.\n\n#\n\n1 1\n', '2 2 2\n\n.#\n##\n\n..\n..\n\n1 1\n', '3 2 2\n\n#.\n##\n\n#.\n.#\n\n..\n..\n\n1 2\n', '3 3 3\n\n.#.\n###\n##.\n\n.##\n###\n##.\n\n...\n...\n...\n\n1 1\n']
Demo Output:
['1\n', '1\n', '5\n', '7\n', '13\n']
Note:
none | ```python
a=[]
b=list(map(int,input().split()))
input()
for i in range(b[0]):
a.append([])
for j in range(b[1]):
a[i].append([])
for z in input():
a[i][j].append(z)
input()
x,y=map(int,input().split()); x-=1; y-=1
ans=[0]
def wv(k,x,y):
if (k<0)or(k==b[0])or(x<0)or(x==b[1])or(y<0)or(y==b[2])or(a[k][x][y]=='#'):
return
ans[0]+=1
a[k][x][y]='#'
wv(k-1,x,y)
wv(k+1,x,y)
wv(k,x-1,y)
wv(k,x+1,y)
wv(k,x,y-1)
wv(k,x,y+1)
wv(0,x,y)
print(ans[0])
``` |
107 | Dorm Water Supply | Title: Dorm Water Supply
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
The German University in Cairo (GUC) dorm houses are numbered from 1 to *n*. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.
In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
Input Specification:
The first line contains two space-separated integers *n* and *p* (1<=β€<=*n*<=β€<=1000,<=0<=β€<=*p*<=β€<=*n*) β the number of houses and the number of pipes correspondingly.
Then *p* lines follow β the description of *p* pipes. The *i*-th line contains three integers *a**i* *b**i* *d**i*, indicating a pipe of diameter *d**i* going from house *a**i* to house *b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*,<=*a**i*<=β <=*b**i*,<=1<=β€<=*d**i*<=β€<=106).
It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.
Output Specification:
Print integer *t* in the first line β the number of tank-tap pairs of houses.
For the next *t* lines, print 3 integers per line, separated by spaces: *tank**i*, *tap**i*, and *diameter**i*, where *tank**i*<=β <=*tap**i* (1<=β€<=*i*<=β€<=*t*). Here *tank**i* and *tap**i* are indexes of tank and tap houses respectively, and *diameter**i* is the maximum amount of water that can be conveyed. All the *t* lines should be ordered (increasingly) by *tank**i*.
Demo Input:
['3 2\n1 2 10\n2 3 20\n', '3 3\n1 2 20\n2 3 10\n3 1 5\n', '4 2\n1 2 60\n3 4 50\n']
Demo Output:
['1\n1 3 10\n', '0\n', '2\n1 2 60\n3 4 50\n']
Note:
none | ```python
from collections import defaultdict
n, p = map(int, input().split())
num_list = [[0, 0, 0] for i in range(n + 1)]
for i in range(p):
a, b, d = map(int, input().split())
num_list[a][0] = b
num_list[b][1] = a
num_list[a][2] = d
ans = []
for i in range(1, n + 1):
if num_list[i][1] != 0:
continue
f = num_list[i][0]
ind = i
diameter = num_list[ind][2]
if not f:
continue
while f > 0:
diameter = min(diameter, num_list[ind][2])
ind = f
f = num_list[ind][0]
ans.append((i, ind, diameter))
print(len(ans))
for i in ans:
print(*i)
``` |
101 | Homework | Title: Homework
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of *n* small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than *k* characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than *k* characters are deleted. You also have to find any possible way to delete the characters.
Input Specification:
The first input data line contains a string whose length is equal to *n* (1<=β€<=*n*<=β€<=105). The string consists of lowercase Latin letters. The second line contains the number *k* (0<=β€<=*k*<=β€<=105).
Output Specification:
Print on the first line the only number *m* β the least possible number of different characters that could remain in the given string after it loses no more than *k* characters.
Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly *m* distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly *m* distinct characters, print any of them.
Demo Input:
['aaaaa\n4\n', 'abacaba\n4\n', 'abcdefgh\n10\n']
Demo Output:
['1\naaaaa\n', '1\naaaa\n', '0\n\n']
Note:
In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.
In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.
In the third sample you are given a line whose length is equal to 8, and *k*β=β10, so that the whole line can be deleted. The correct answer is 0 and an empty string. | ```python
# LUOGU_RID: 104929878
s = input()
k = int(input())
for c, ch in sorted([[s.count(x), x] for x in set(s)]):
if c <= k:
k -= c
s = s.replace(ch, '')
print(len(set(s)))
print(s)
``` |
46 | Parking Lot | Title: Parking Lot
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as *L* meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than *b* meters and the distance between his car and the one in front of his will be no less than *f* meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point *L*. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input Specification:
The first line contains three integers *L*, *b* ΠΈ *f* (10<=β€<=*L*<=β€<=100000,<=1<=β€<=*b*,<=*f*<=β€<=100). The second line contains an integer *n* (1<=β€<=*n*<=β€<=100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output Specification:
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Demo Input:
['30 1 2\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n', '30 1 1\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n', '10 1 1\n1\n1 12\n']
Demo Output:
['0\n6\n11\n17\n23\n', '0\n6\n11\n17\n6\n', '-1\n']
Note:
none | ```python
import sys
readline = sys.stdin.readline
# L, b, f = [int(w) for w in readline().split()]
request =[]
def read_input():
L, f, b = [int(w) for w in readline().split()]
n = int(readline().strip())
for _ in range(n):
request.append([int(w) for w in readline().split()])
return L, b, f
def solve(L: int, b: int, f:int) -> list:
park = [[-f,-f] ,[L + b, L+ b]]
result = []
r2pos = [-1] * len(request)
for ridx, (cmd, op) in enumerate(request):
if cmd == 2:
pos = r2pos[op - 1]
idx = -1
for i,(l,r) in enumerate(park):
if l == pos:
idx = i
park.pop(idx)
elif cmd == 1:
length = f + op + b
found = False
for i in range(len(park) -1):
if park[i + 1][0] - park[i][1] >= length:
park.insert(i + 1, [park[i][1] + f, park[i][1] + f + op])
result.append(park[i + 1][0])
r2pos[ridx] = park[i + 1][0]
found = True
break
if not found:
result.append(-1)
# print(cmd, op, park)
return result
def write_output(result: list):
for n in result:
print(n)
L, b, f = read_input()
write_output(solve(L, b, f))
``` |
110 | Lucky String | Title: Lucky String
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.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.
For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:
- b: 2- c: 3,<=10- d: 4,<=8- e: 6- f: 7- z: 1,<=5,<=9- Lists of positions of letters a, g, h, ..., y are empty.
This string is lucky as all differences are lucky numbers. For letters z: 5<=-<=1<==<=4, 9<=-<=5<==<=4, for letters c: 10<=-<=3<==<=7, for letters d: 8<=-<=4<==<=4.
Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.
Find the lexicographically minimal lucky string whose length equals *n*.
Input Specification:
The single line contains a positive integer *n* (1<=β€<=*n*<=β€<=105) β the length of the sought string.
Output Specification:
Print on the single line the lexicographically minimal lucky string whose length equals *n*.
Demo Input:
['5\n', '3\n']
Demo Output:
['abcda\n', 'abc\n']
Note:
The lexical comparison of strings is performed by the < operator in modern programming languages. String *a* is lexicographically less than string *b* if exists such *i* (1ββ€β*i*ββ€β*n*), that *a*<sub class="lower-index">*i*</sub>β<β*b*<sub class="lower-index">*i*</sub>, and for any *j* (1ββ€β*j*β<β*i*) *a*<sub class="lower-index">*j*</sub>β=β*b*<sub class="lower-index">*j*</sub>. | ```python
n=int(input())
s=(n//4+1)*"abcd"
print(s[:n])
``` |
28 | Bender Problem | Title: Bender Problem
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Robot Bender decided to make Fray a birthday present. He drove *n* nails and numbered them from 1 to *n* in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods.
Help Bender to solve this difficult task.
Input Specification:
The first line contains two positive integers *n* and *m* (4<=β€<=*n*<=β€<=500,<=2<=β€<=*m*<=β€<=500, *n* is even) β the amount of nails and the amount of rods. *i*-th of the following *n* lines contains a pair of integers, denoting the coordinates of the *i*-th nail. Nails should be connected in the same order as they are given in the input. The last line contains *m* integers β the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200<=000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line.
Output Specification:
If it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output *n* numbers β *i*-th of them should be the number of rod, which fold place is attached to the *i*-th nail, or -1, if there is no such rod.
If there are multiple solutions, print any of them.
Demo Input:
['4 2\n0 0\n0 2\n2 2\n2 0\n4 4\n', '6 3\n0 0\n1 0\n1 1\n2 1\n2 2\n0 2\n3 2 3\n', '6 3\n0 0\n1 0\n1 1\n2 1\n2 2\n0 2\n2 2 3\n']
Demo Output:
['YES\n1 -1 2 -1 \n', 'YES\n1 -1 2 -1 3 -1 \n', 'NO\n']
Note:
none | ```python
def main():
n, m = map(int, input().split())
nails = []
for _ in range(n):
nails.append(tuple(map(int, input().split())))
rods = list(map(int, input().split()))
rods_count1, rods_count2 = {}, {}
for i, rod in enumerate(rods):
if rod not in rods_count1:
rods_count1[rod] = [i]
else:
rods_count1[rod].append(i)
if rod not in rods_count2:
rods_count2[rod] = [i]
else:
rods_count2[rod].append(i)
ans = []
for i in range(0, n, 2):
if i < n - 2:
rod_len = abs(nails[i][0] - nails[i + 2][0]) + abs(nails[i][1] - nails[i + 2][1])
else:
rod_len = abs(nails[i][0] - nails[0][0]) + abs(nails[i][1] - nails[0][1])
if rod_len not in rods_count1:
break
else:
ans.append(-1)
ans.append(rods_count1[rod_len].pop() + 1)
if not rods_count1[rod_len]:
del rods_count1[rod_len]
else:
print("YES")
print(' '.join(map(str, ans)))
return
last_nail = nails.pop()
nails.insert(0, last_nail)
ans = []
for i in range(0, n, 2):
if i < n - 2:
rod_len = abs(nails[i][0] - nails[i + 2][0]) + abs(nails[i][1] - nails[i + 2][1])
else:
rod_len = abs(nails[i][0] - nails[0][0]) + abs(nails[i][1] - nails[0][1])
if rod_len not in rods_count2:
break
else:
ans.append(rods_count2[rod_len].pop() + 1)
ans.append(-1)
if not rods_count2[rod_len]:
del rods_count2[rod_len]
else:
print("YES")
print(' '.join(map(str, ans)))
return
print("NO")
if __name__ == "__main__":
main()
``` |
31 | TV Game | Title: TV Game
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There is a new TV game on BerTV. In this game two players get a number *A* consisting of 2*n* digits. Before each turn players determine who will make the next move. Each player should make exactly *n* moves. On it's turn *i*-th player takes the leftmost digit of *A* and appends it to his or her number *S**i*. After that this leftmost digit is erased from *A*. Initially the numbers of both players (*S*1 and *S*2) are Β«emptyΒ». Leading zeroes in numbers *A*,<=*S*1,<=*S*2 are allowed. In the end of the game the first player gets *S*1 dollars, and the second gets *S*2 dollars.
One day Homer and Marge came to play the game. They managed to know the number *A* beforehand. They want to find such sequence of their moves that both of them makes exactly *n* moves and which maximizes their total prize. Help them.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=18). The second line contains integer *A* consisting of exactly 2*n* digits. This number can have leading zeroes.
Output Specification:
Output the line of 2*n* characters Β«HΒ» and Β«MΒ» β the sequence of moves of Homer and Marge, which gives them maximum possible total prize. Each player must make exactly *n* moves. If there are several solutions, output any of them.
Demo Input:
['2\n1234\n', '2\n9911\n']
Demo Output:
['HHMM', 'HMHM']
Note:
none | ```python
from functools import *
n,a=int(input()),[*map(int,input())]
@lru_cache(maxsize=None)
def v(h=n,m=n):
r,t=(0,''),a[-h-m]
if h:
w,q=v(h-1,m)
r=(w+t*10**(h-1),'H'+q)
if m:
w,q=v(h,m-1)
r=max(r,(w+t*10**(m-1),'M'+q))
return r
print(v()[1])
``` |
45 | Event Dates | Title: Event Dates
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
On a history lesson the teacher asked Vasya to name the dates when *n* famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [*l**i*,<=*r**i*] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such *n* dates of famous events that will fulfill both conditions. It is guaranteed that it is possible.
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=100) β the number of known events. Then follow *n* lines containing two integers *l**i* and *r**i* each (1<=β€<=*l**i*<=β€<=*r**i*<=β€<=107) β the earliest acceptable date and the latest acceptable date of the *i*-th event.
Output Specification:
Print *n* numbers β the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists.
Demo Input:
['3\n1 2\n2 3\n3 4\n', '2\n1 3\n1 3\n']
Demo Output:
['1 2 3 \n', '1 2 \n']
Note:
none | ```python
# LUOGU_RID: 111386935
from sys import stdin
from collections import defaultdict
input = stdin.readline
def get() :
return map(int,input().split())
class Node :
def __init__(self, l, r, idx) :
self.l = l
self.r = r
self.idx = idx
def __lt__(self, other) :
if self.r != other.r :
return self.r < other.r
elif self.r == other.r :
return self.l < other.l
n = int(input())
lst = []
ans = [0] * (n)
for i in range(n) :
a, b = get()
lst.append(Node(a, b, i))
lst.sort()
d = defaultdict(int)
for i in range(n) :
l, r, idx = lst[i].l, lst[i].r, lst[i].idx
for j in range(l, r + 1) :
if d[j] == 0 :
d[j] = 1
ans[idx] = j
break
for i in range(n) :
print(ans[i], end = ' ')
``` |
111 | Petya and Inequiations | Title: Petya and Inequiations
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Little Petya loves inequations. Help him find *n* positive integers *a*1,<=*a*2,<=...,<=*a**n*, such that the following two conditions are satisfied:
- *a*12<=+<=*a*22<=+<=...<=+<=*a**n*2<=β₯<=*x*- *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<=β€<=*y*
Input Specification:
The first line contains three space-separated integers *n*, *x* and *y* (1<=β€<=*n*<=β€<=105,<=1<=β€<=*x*<=β€<=1012,<=1<=β€<=*y*<=β€<=106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output Specification:
Print *n* positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Demo Input:
['5 15 15\n', '2 3 2\n', '1 99 11\n']
Demo Output:
['4\n4\n1\n1\n2\n', '-1\n', '11\n']
Note:
none | ```python
n,x,y=map(int,input().split())
n-=1
t=y-n
print(['1\n'*n+str(t),-1][t<1 or t*t+n<x])
``` |
18 | Seller Bob | Title: Seller Bob
Time Limit: 2 seconds
Memory Limit: 128 megabytes
Problem Description:
Last year Bob earned by selling memory sticks. During each of *n* days of his work one of the two following events took place:
- A customer came to Bob and asked to sell him a 2*x* MB memory stick. If Bob had such a stick, he sold it and got 2*x* berllars. - Bob won some programming competition and got a 2*x* MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it.
Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last *n* days, Bob wants to know, how much money he could have earned, if he had acted optimally.
Input Specification:
The first input line contains number *n* (1<=β€<=*n*<=β€<=5000) β amount of Bob's working days. The following *n* lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2*x* MB memory stick (0<=β€<=*x*<=β€<=2000). It's guaranteed that for each *x* there is not more than one line sell x. Line win x stands for a day when Bob won a 2*x* MB memory stick (0<=β€<=*x*<=β€<=2000).
Output Specification:
Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.
Demo Input:
['7\nwin 10\nwin 5\nwin 3\nsell 5\nsell 3\nwin 10\nsell 10\n', '3\nwin 5\nsell 6\nsell 4\n']
Demo Output:
['1056\n', '0\n']
Note:
none | ```python
n = int(input())
a = []
b = []
for i in range(n):
x = input().split()
a.append(x[0][0])
b.append(int(x[1]))
res = 0
f = [-1]*2002
for i in range(n):
if (a[i]=='w'):
f[b[i]] = res
elif f[b[i]]>=0:
res = max(res, f[b[i]]+2**b[i])
print(res)
``` |
40 | Interesting Sequence | Title: Interesting Sequence
Time Limit: 3 seconds
Memory Limit: 256 megabytes
Problem Description:
Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if *d**i* β the number of people in Berland in the year of *i*, then either *d**i*<==<=12*d**i*<=-<=2, or *d**i*<==<=13*d**i*<=-<=1<=-<=12*d**i*<=-<=2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled *A*. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of *a*1,<=*a*2,<=...,<=*a**k*. Then you have to define how many residents could be in the country during those years apart from the *A* variant. Look at the examples for further explanation.
Input Specification:
The first line contains integer *A* (1<=β€<=*A*<=<<=10300). It is guaranteed that the number doesn't contain leading zeros.
Output Specification:
On the first output line print YES, if there could be a year in which the total population of the country equaled *A*, otherwise print NO.
If the answer is YES, then you also have to print number *k* β the number of years in which the population could equal *A*. On the next line you have to output precisely *k* space-separated numbers β *a*1,<=*a*2,<=...,<=*a**k*. Those numbers have to be output in the increasing order.
On the next line you should output number *p* β how many variants of the number of people could be in the years of *a*1,<=*a*2,<=...,<=*a**k*, apart from the *A* variant. On each of the next *p* lines you have to print one number β the sought number of residents. Those number also have to go in the increasing order.
If any number (or both of them) *k* or *p* exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order.
The numbers should have no leading zeros.
Demo Input:
['2\n', '3\n', '13\n', '1729\n']
Demo Output:
['YES\n1\n1\n0\n', 'NO\n', 'YES\n1\n2\n0\n', 'YES\n1\n4\n1\n156\n']
Note:
none | ```python
import heapq
import sys
lim = 1000
a = int(input())
def gen_pow():
ans = {}
pw_x = 1
x = 0
while pw_x <= a:
ans[pw_x] = x
pw_x *= 12
x += 1
return ans
pow_map = gen_pow()
year_list = set()
for pw_x, x in pow_map.items():
pw_y = a - pw_x
if pw_y not in pow_map:
continue
y = pow_map[pw_y]
year_list.add(x + y)
if len(year_list) == 0:
print('NO')
sys.exit(0)
print('YES')
def elm(x, y):
return (12 ** x + 12 ** y, x, y)
h = []
for year in year_list:
y = year // 2
x = year - y
h.append(elm(x, y))
heapq.heapify(h)
variants = set()
while len(h) and len(variants) < lim:
(v, x, y) = heapq.heappop(h)
if v != a:
variants.add(v)
if y == 0:
continue
new_elm = elm(x + 1, y - 1)
heapq.heappush(h, new_elm)
k = min(len(year_list), lim)
print(k)
print(*sorted(map(lambda x: x + 1, year_list))[:k])
print(len(variants))
print(*sorted(variants), sep='\n')
``` |
34 | Road Map | Title: Road Map
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
There are *n* cities in Berland. Each city has its index β an integer number from 1 to *n*. The capital has index *r*1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city *i*, different from the capital, there is kept number *p**i* β index of the last city on the way from the capital to *i*.
Once the king of Berland Berl XXXIV decided to move the capital from city *r*1 to city *r*2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.
Input Specification:
The first line contains three space-separated integers *n*, *r*1, *r*2 (2<=β€<=*n*<=β€<=5Β·104,<=1<=β€<=*r*1<=β <=*r*2<=β€<=*n*) β amount of cities in Berland, index of the old capital and index of the new one, correspondingly.
The following line contains *n*<=-<=1 space-separated integers β the old representation of the road map. For each city, apart from *r*1, there is given integer *p**i* β index of the last city on the way from the capital to city *i*. All the cities are described in order of increasing indexes.
Output Specification:
Output *n*<=-<=1 numbers β new representation of the road map in the same format.
Demo Input:
['3 2 3\n2 2\n', '6 2 4\n6 1 2 4 2\n']
Demo Output:
['2 3 ', '6 4 1 4 2 ']
Note:
none | ```python
def find_new_map(n: int, old_capital: int, new_capital: int,
old_map: list) -> list:
"""
Parameters:
:n (int): number of cities
:old_capital (int): old capital's number
:new_capital (int): new capital's number
:old_map (list): old road map representation
:return: new road map representation
"""
new_map = old_map.copy()
new_map.insert(old_capital - 1, -1)
parent = -1
node = new_capital
while True:
next_node = new_map[node - 1]
new_map[node - 1] = parent
parent = node
if node == old_capital:
break
node = next_node
new_map.pop(new_capital - 1)
return new_map
n, old, new = map(int,input().split())
map = list(map(int,input().split()))
print(" ".join(str(x) for x in find_new_map(n,old,new,map)))
``` |
92 | Binary Number | Title: Binary Number
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer *x* and wants to get a number one from it. While *x* is not equal to 1, Fangy repeats the following action: if *x* is odd, then he adds 1 to it, otherwise he divides *x* by 2. Fangy knows that for any positive integer number the process ends in finite time.
How many actions should Fangy perform to get a number one from number *x*?
Input Specification:
The first line contains a positive integer *x* in a binary system. It is guaranteed that the first digit of *x* is different from a zero and the number of its digits does not exceed 106.
Output Specification:
Print the required number of actions.
Demo Input:
['1\n', '1001001\n', '101110\n']
Demo Output:
['0\n', '12\n', '8\n']
Note:
Let's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1. | ```python
s = input()
s = s[::-1]
if s.count('1')==1:
print(len(s)-1)
exit(0)
print(s.find('1')+(s.count('0')-s.find('1'))*2+s.count('1')+1)
``` |
2 | Commentator problem | Title: Commentator problem
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered.
Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.
Input Specification:
The input data consists of three lines, each of them describes the position of one stadium. The lines have the format *x*,<=<=*y*,<=<=*r*, where (*x*,<=*y*) are the coordinates of the stadium's center (<=-<=<=103<=β€<=*x*,<=<=*y*<=β€<=103), and *r* (1<=β€<=*r*<=<=β€<=103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line.
Output Specification:
Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.
Demo Input:
['0 0 10\n60 0 10\n30 30 10\n']
Demo Output:
['30.00000 0.00000\n']
Note:
none | ```python
x1,y1,r1 = map(int,input().split())
x2,y2,r2 = map(int,input().split())
x3,y3,r3 = map(int,input().split())
if r1==r2==r3:
d = ((x2-x1)*(y3-y2)-(x3-x2)*(y2-y1))*2
a = x2**2+y2**2-x1**2-y1**2
b = x3**2+y3**2-x2**2-y2**2
print(((y3-y2)*a+(y1-y2)*b)/d,((x2-x3)*a+(x2-x1)*b)/d)
else:
if r1==r2: x2,y2,r2,x3,y3,r3=x3,y3,r3,x2,y2,r2
if r2==r3: x1,y1,r1,x2,y2,r2=x2,y2,r2,x1,y1,r1
r1 **= 2; r2 **= 2; r3 **= 2
g1,g2 = r2-r1,r3-r2
x4,y4 = (r2*x1-r1*x2)/g1,(r2*y1-r1*y2)/g1
r4 = x4**2+y4**2-(r2*(x1**2+y1**2)-r1*(x2**2+y2**2))/g1
x5,y5 = (r3*x2-r2*x3)/g2,(r3*y2-r2*y3)/g2
r5 = x5**2+y5**2-(r3*(x2**2+y2**2)-r2*(x3**2+y3**2))/g2
R = (x5-x4)**2+(y5-y4)**2
if R>(r4**.5+r5**.5)**2 or r4>(R**.5+r5**.5)**2 or r5>(R**.5+r4**.5)**2: exit()
c = (r4-r5)/R
xt,yt = (x4+x5)/2+c*(x5-x4)/2,(y4+y5)/2+c*(y5-y4)/2
dd = (2*(r4+r5)/R-c**2-1)**.5/2
x6,y6 = xt+dd*(y5-y4),yt+dd*(x4-x5)
x7,y7 = xt-dd*(y5-y4),yt-dd*(x4-x5)
if (x6-x1)**2+(y6-y1)**2<(x7-x1)**2+(y7-y1)**2: print(x6,y6)
else: print(x7,y7)
``` |
42 | Strange town | Title: Strange town
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Volodya has recently visited a very odd town. There are *N* tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour β a cycle which visits every attraction exactly once β the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
Input Specification:
Input contains just one natural number (3<=β€<=*N*<=β€<=20) β the number of town attractions.
Output Specification:
Output should contain *N* rows containing *N* positive integer numbers each β the adjacency matrix of the prices graph (thus, *j*-th number in *i*-th row should be equal to the price of the road between the *j*-th and the *i*-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.
Demo Input:
['3\n']
Demo Output:
['0 3 4 \n3 0 5 \n4 5 0 \n']
Note:
none | ```python
n = int(input())
massa = [1]
i = 2
d = set()
while( len(massa) != n ):
test = True
for el in massa:
if(el + i in d):
test = False
break
if(test == True):
for el in massa:
d.add(el+i)
massa.append(i)
i=i+1
for b in massa:
ans=""
for el in massa:
ans+="0 " if b==el else str(b+el)+" "
print ( ans )
``` |
93 | Flags | Title: Flags
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted.
However, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well.
And how about you? Can you solve the problem?
The flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from *L* to *R*, if:
- a flag cannot have adjacent stripes of one color; - a flag cannot have adjacent white and yellow stripes; - a flag cannot have adjacent red and black stripes; - a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order; - symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same.
Input Specification:
The only line contains two integers *L* and *R* (1<=β€<=*L*<=β€<=*R*<=β€<=109). They are the lower and upper borders of the number of stripes on the flag.
Output Specification:
Print a single number β the number of different flags that would satisfy the condition of the problem and would have from *L* to *R* stripes, modulo 1000000007.
Demo Input:
['3 4\n', '5 6\n']
Demo Output:
['23', '64']
Note:
In the first test the following flags exist (they are listed in the lexicographical order, the letters B, R, W, Y stand for Black, Red, White and Yellow correspondingly):
3 stripes: BWB, BYB, BYR, RWR, RYR, WBW, WBY, WRW, WRY, YBY, YRY (overall 11 flags).
4 stripes: BWBW, BWBY, BYBW, BYBY, BYRW, BYRY, RWRW, RWRY, RYBW, RYBY, RYRW, RYRY (12 flags).
That's why the answer to test 1 is equal to 11β+β12β=β23. | ```python
MOD = (10**9)+7
def cal(x):
if x==0:
return 0
elif x==1:
return 4
elif x&1:
a1=11*pow(3,x//2,MOD)-7
#print(a1,x)
return a1
else:
return 19*pow(3,x//2-1,MOD)-7
def grp(x):
return (cal(x)+cal(x+1>>1))*pow(2,MOD-2,MOD)%MOD
l,r=map(int,input().strip().split())
ans=(grp(r)-grp(l-1))%MOD
print(ans)
``` |
63 | Bulls and Cows | Title: Bulls and Cows
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "*x* bulls *y* cows". *x* represents the number of digits in the experimental number that occupy the same positions as in the sought number. *y* represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input Specification:
The first input line contains an integer *n* (1<=β€<=*n*<=β€<=10) which represents the number of already made guesses. Then follow *n* lines in the form of "*a**i* *b**i* *c**i*", where *a**i* is the *i*-th experimental number, *b**i* is the number of bulls, *c**i* is the number of cows (1<=β€<=*i*<=β€<=*n*, 0<=β€<=*b**i*,<=*c**i*,<=*b**i*<=+<=*c**i*<=β€<=4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output Specification:
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Demo Input:
['2\n1263 1 2\n8103 2 1\n', '2\n1234 2 2\n1256 0 2\n', '2\n0123 1 1\n4567 1 2\n']
Demo Output:
['Need more data', '2134', 'Incorrect data']
Note:
none | ```python
from itertools import permutations
a, result = [], []
for _ in range(int(input())):
s, bull, cow = input().split()
a.append([[int(i) for i in s], int(bull), int(cow)])
for c in permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4):
ok = True
for trying in a:
bull, cow = 0, 0
for i in range(4):
x = c[i]
if trying[0].count(x) == 1:
if x == trying[0][i]:
bull += 1
else:
cow += 1
if bull != trying[1] or cow != trying[2]:
ok = False
break
if ok:
result.append(c)
l = len(result)
if l == 0:
print('Incorrect data')
elif l == 1:
print(''.join(map(str, result[0])))
else:
print('Need more data')
``` |
42 | Safe cracking | Title: Safe cracking
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Right now you are to solve a very, very simple problem β to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both by one; you may choose two adjacent even numbers and divide both by two. Nothing else. Crack the safe!
Input Specification:
The single line of the input contains four space-separated integer positive numbers not greater than 109 each β four numbers on the circle in consecutive order.
Output Specification:
The output should contain "-1" (quotes for clarity) if the safe is secure, that is it's impossible to crack it. Otherwise, output should contain the sequence of operations (one operations per line) leading to unlocking the safe. You don't have to minimize the number of operations, but it should not exceed 1000. To make things clear, assume numbers stand on positions 1 through 4. Each operation is encoded by two symbols. If the following operation is dividing then first symbol is '/'; otherwise it's '+' (addition). The second symbol is the position of the first number in pair in consecutive order. (see samples for clarification).
If there are several solutions, output any of them.
Demo Input:
['1 1 1 1\n', '1 2 4 2\n', '3 3 1 1\n', '2 1 2 4\n']
Demo Output:
['', '/2\n/3\n', '+1\n/1\n/1\n', '/3\n/4\n']
Note:
none | ```python
A=list(map(int,input().split()))
ANS=[]
while A!=[1,1,1,1]:
k=max(A)
x=A.index(k)
if A[x]%2==0 and A[x-1]%2==0:
ANS.append("/"+str((x-1)%4+1))
A[x]//=2
A[x-1]//=2
continue
if A[x]%2==0 and A[(x+1)%4]%2==0:
ANS.append("/"+str(x%4+1))
A[x]//=2
A[(x+1)%4]//=2
continue
if A[x]%2==1 and A[x-1]%2==1:
ANS.append("+"+str((x-1)%4+1))
A[x]+=1
A[x-1]+=1
continue
if A[x]%2==1 and A[(x+1)%4]%2==1:
ANS.append("+"+str(x%4+1))
A[x]+=1
A[(x+1)%4]+=1
continue
if A[x]%2==1 and A[x-1]%2==0:
ANS.append("+"+str((x-1)%4+1))
A[x]+=1
A[x-1]+=1
continue
ANS.append("+"+str((x-1)%4+1))
ANS.append("+"+str(x%4+1))
A[x]+=2
A[x-1]+=1
A[(x+1)%4]+=1
print("\n".join(ANS))
``` |
56 | Corporation Mail | Title: Corporation Mail
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
- *employee* ::= *name*. | *name*:*employee*1,*employee*2, ... ,*employee**k*. - *name* ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is *s* writes a letter to another person whose name is also *s*. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
Input Specification:
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output Specification:
Print a single number β the number of uncomfortable situations in the company.
Demo Input:
['MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...\n', 'A:A..\n', 'A:C:C:C:C.....\n']
Demo Output:
['3\n', '1\n', '6\n']
Note:
none | ```python
s = input()
a = []
cnt = 0
s = ':' + s
s1 = ''
flag = False
for i in range(len(s)):
if flag:
if s[i] != '.' and s[i] != ':' and s[i] != ',':
s1 += s[i]
continue
else:
a.append(s1)
flag = False
for j in range(len(a) - 1):
if a[j] == a[-1]:
cnt += 1
if s[i] != '.' and s[i] != ':' and s[i] != ',':
flag = True
s1 = s[i]
elif s[i] == '.':
a.pop()
print(cnt)
``` |
51 | bHTML Tables Analisys | Title: bHTML Tables Analisys
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.
A string is a bHTML table, if it satisfies the grammar:
Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.
As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.
Input Specification:
For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation *s* of the specified table. String *s* corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string *s*.
Output Specification:
Print the sizes of all the tables in the non-decreasing order.
Demo Input:
['<table><tr><td></td></tr></table>\n', '<table>\n<tr>\n<td>\n<table><tr><td></td></tr><tr><td></\ntd\n></tr><tr\n><td></td></tr><tr><td></td></tr></table>\n</td>\n</tr>\n</table>\n', '<table><tr><td>\n<table><tr><td>\n<table><tr><td>\n<table><tr><td></td><td></td>\n</tr><tr><td></td></tr></table>\n</td></tr></table>\n</td></tr></table>\n</td></tr></table>\n']
Demo Output:
['1 ', '1 4 ', '1 1 1 3 ']
Note:
none | ```python
import sys
R=str.replace
s=R(R(R(R(R(''.join(sys.stdin.readlines()),'\n',''),'</tr>',''),'<tr>',''),'><',' '),'>','').split()[1:]
def f(k):
r=0;a=[]
while s[0]!='/table':
if s[0]=='table':
s.pop(0);a+=f(k+1)
else:r+=s[0]=='td';s.pop(0)
s.pop(0)
return[r]+a
print(' '.join(map(str,sorted(f(1)))))
``` |
77 | Heroes | Title: Heroes
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.
The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: *a* for Mephisto, *b* for Diablo and *c* for Baal.
Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a of experience, rounded down, where *x* will be the amount of experience for the killed megaboss and *y* β the number of people in the team.
Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.
It is known that some heroes like others. But if hero *p* likes hero *q*, this does not mean that the hero *q* likes hero *p*. No hero likes himself.
The total amount of liking in teams is the amount of ordered pairs (*p*,<=*q*), such that heroes *p* and *q* are in the same group, and hero *p* likes hero *q* (but it is not important if hero *q* likes hero *p*). In case of heroes *p* and *q* likes each other and they are in the same group, this pair should be counted twice, as (*p*,<=*q*) and (*q*,<=*p*).
A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.
It is guaranteed that every hero is able to destroy any megaboss alone.
Input Specification:
The first line contains a single non-negative integer *n* (0<=β€<=*n*<=β€<=42) β amount of liking between the heroes. Next *n* lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p <=β <= q). Every liking is described in the input exactly once, no hero likes himself.
In the last line are given three integers *a*, *b* and *c* (1<=β€<=*a*,<=*b*,<=*c*<=β€<=2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal.
In all the pretests, except for examples from the statement, the following condition is satisfied: *a*<==<=*b*<==<=*c*.
Output Specification:
Print two integers β the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team).
When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.
Demo Input:
['3\nTroll likes Dracul\nDracul likes Anka\nSnowy likes Hexadecimal\n210 200 180\n', '2\nAnka likes Chapay\nChapay likes Anka\n10000 50 50\n']
Demo Output:
['30 3\n', '1950 2\n']
Note:
A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay. | ```python
from itertools import combinations
def main():
heroes = ("Anka", "Chapay", "Cleo", "Troll", "Dracul", "Snowy", "Hexadecimal")
sympaty = [[False] * 7 for _ in range(7)]
for _ in range(int(input())):
a, _, b = input().split()
sympaty[heroes.index(a)][heroes.index(b)] = True
a, b, c = map(int, input().split())
tmp, res = [], []
for i in range(1, 6):
for j in range(1, 7 - i):
t = (int(a / i), int(b / j), int(c / (7 - i - j)))
tmp.append((max(t) - min(t), i, j))
delta = min(tmp)[0]
for i, j in ((i, j) for x, i, j in tmp if x == delta):
for aa in combinations(range(7), i):
rest = [x for x in range(7) if x not in aa]
for bb in combinations(rest, j):
res.append(sum(sum(sympaty[x][y] for x in xy for y in xy)
for xy in (aa, bb, [x for x in rest if x not in bb])))
print(delta, max(res))
if __name__ == '__main__':
main()
``` |
67 | Partial Teacher | Title: Partial Teacher
Time Limit: 1 seconds
Memory Limit: 256 megabytes
Problem Description:
A teacher decides to give toffees to his students. He asks *n* students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.
He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.
It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
Input Specification:
The first line of input contains the number of students *n* (2<=β€<=*n*<=β€<=1000). The second line gives (*n*<=-<=1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
Output Specification:
Output consists of *n* integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
Demo Input:
['5\nLRLR\n', '5\n=RRR\n']
Demo Output:
['2 1 2 1 2\n', '1 1 2 3 4\n']
Note:
none | ```python
len = int(input())
dir = input()
res = [1] * len
for i in range(1, len):
if dir[i - 1] == 'L':
res[i] = 1
else:
res[i] = res[i - 1] + (dir[i - 1] == 'R')
for i in range(len - 2, -1, -1):
if dir[i] == 'L':
res[i] = max(res[i], res[i + 1] + 1)
elif dir[i] == '=':
res[i] = max(res[i], res[i + 1])
print(*res)
``` |
93 | Frames | Title: Frames
Time Limit: 2 seconds
Memory Limit: 256 megabytes
Problem Description:
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, *m* icons can fit in a horizontal row in any window.
Igor K.'s computer contains *n* folders in the D: disk's root catalog. The folders are numbered from 1 to *n* in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from *a* to *b* inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from *a* to *b* and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input Specification:
The only line contains four integers *n*, *m*, *a*, *b* (1<=β€<=*n*,<=*m*<=β€<=109, 1<=β€<=*a*<=β€<=*b*<=β€<=*n*). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output Specification:
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from *a* to *b*.
Demo Input:
['11 4 3 9\n', '20 5 2 20\n']
Demo Output:
['3\n', '2\n']
Note:
The images below illustrate statement tests.
The first test:
<img class="tex-graphics" src="https://espresso.codeforces.com/a0e4ba690dd16e3c68210a28afd82020b23fb605.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<img class="tex-graphics" src="https://espresso.codeforces.com/289e2666a3d8b3dfe5b22ff3d88976df711640f7.png" style="max-width: 100.0%;max-height: 100.0%;"/>
In this test we can first select all folders in the first row (2, 3, 4, 5), then β all other ones. | ```python
def solve(n, m, a, b):
a -= 1
b -= 1
ra = a // m
rb = b // m
if ra == rb:
return 1
if a % m == 0:
if b == n - 1 or b % m == m - 1:
return 1
else:
return 2
if b == n - 1 or b % m == m - 1:
return 2
if a % m == (b % m) + 1:
return 2
if ra == rb - 1:
return 2
return 3
n, m, a, b = map(int, input().split())
result = solve(n, m, a, b)
print(result)# 1698067608.3173046
``` |
11 | Increasing Sequence | Title: Increasing Sequence
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
A sequence *a*0,<=*a*1,<=...,<=*a**t*<=-<=1 is called increasing if *a**i*<=-<=1<=<<=*a**i* for each *i*:<=0<=<<=*i*<=<<=*t*.
You are given a sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 and a positive integer *d*. In each move you may choose one element of the given sequence and add *d* to it. What is the least number of moves required to make the given sequence increasing?
Input Specification:
The first line of the input contains two integer numbers *n* and *d* (2<=β€<=*n*<=β€<=2000,<=1<=β€<=*d*<=β€<=106). The second line contains space separated sequence *b*0,<=*b*1,<=...,<=*b**n*<=-<=1 (1<=β€<=*b**i*<=β€<=106).
Output Specification:
Output the minimal number of moves needed to make the sequence increasing.
Demo Input:
['4 2\n1 3 3 2\n']
Demo Output:
['3\n']
Note:
none | ```python
arr = input().split()
n = int(arr[0])
d = int(arr[1])
a = input().split()
ans = int(0)
pre = int(-1)
# a.sort()
for i in a:
i = int(i)
# print(i, end = ', ')
x = 0
if i <= pre:
x = (pre-i + d) // d
ans = ans + x
pre = i + x*d
# print(pre, end = '\n')
print(ans)
``` |
4 | Watermelon | Title: Watermelon
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
Input Specification:
The first (and the only) input line contains integer number *w* (1<=β€<=*w*<=β€<=100) β the weight of the watermelon bought by the boys.
Output Specification:
Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.
Demo Input:
['8\n']
Demo Output:
['YES\n']
Note:
For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant β two parts of 4 and 4 kilos). | ```python
if __name__ == '__main__':
weight = int(input())
print('YES' if not weight%2 and weight>2 else 'NO')
``` |
9 | Die Roll | Title: Die Roll
Time Limit: 1 seconds
Memory Limit: 64 megabytes
Problem Description:
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko β W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
Input Specification:
The only line of the input file contains two natural numbers Y and W β the results of Yakko's and Wakko's die rolls.
Output Specification:
Output the required probability in the form of irreducible fraction in format Β«A/BΒ», where A β the numerator, and B β the denominator. If the required probability equals to zero, output Β«0/1Β». If the required probability equals to 1, output Β«1/1Β».
Demo Input:
['4 2\n']
Demo Output:
['1/2\n']
Note:
Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points. | ```python
a, b = map(int, input().split())
if 6 - max(a, b) == 0 or 6 - max(a, b) == 4:
print(str(6 - max(a, b) + 1) + '/' + '6')
elif 6 - max(a, b) == 1 or 6 - max(a, b) == 3:
print(str((6 - max(a, b) + 1) // 2) + '/' + '3')
elif 6 - max(a, b) == 2:
print('1' + '/' + '2')
else:
print('1' + '/' + '1')
``` |
14 | Two Paths | Title: Two Paths
Time Limit: 2 seconds
Memory Limit: 64 megabytes
Problem Description:
As you know, Bob's brother lives in Flatland. In Flatland there are *n* cities, connected by *n*<=-<=1 two-way roads. The cities are numbered from 1 to *n*. You can get from one city to another moving along the roads.
The Β«Two PathsΒ» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).
It is known that the profit, the Β«Two PathsΒ» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
Input Specification:
The first line contains an integer *n* (2<=β€<=*n*<=β€<=200), where *n* is the amount of cities in the country. The following *n*<=-<=1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road *a**i*,<=*b**i* (1<=β€<=*a**i*,<=*b**i*<=β€<=*n*).
Output Specification:
Output the maximum possible profit.
Demo Input:
['4\n1 2\n2 3\n3 4\n', '7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n', '6\n1 2\n2 3\n2 4\n5 4\n6 4\n']
Demo Output:
['1\n', '0\n', '4\n']
Note:
none | ```python
n = int(input())
p = [[] for i in range(n + 1)]
for j in range(n - 1):
a, b = map(int, input().split())
p[a].append(b)
p[b].append(a)
def g(b, c):
x = y = d = 0
for a in p[b]:
if a != c:
s, z = g(a, b)
z, y, x = sorted([x, y, z])
d = max(d, s)
return max(d, x + y), x + 1
print(max(g(a, b)[0] * g(b, a)[0] for a in range(n + 1) for b in p[a] if b > a))
``` |