contestId
int64
0
1.01k
name
stringlengths
2
54
prompt
stringlengths
297
7.35k
response
stringlengths
32
43.6k
10
Power Consumption Calculation
Title: Power Consumption Calculation Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes *P*1 watt per minute. *T*1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to *P*2 watt per minute. Finally, after *T*2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes *P*3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into *n* time periods [*l*1,<=*r*1],<=[*l*2,<=*r*2],<=...,<=[*l**n*,<=*r**n*]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [*l*1,<=*r**n*]. Input Specification: The first line contains 6 integer numbers *n*, *P*1, *P*2, *P*3, *T*1, *T*2 (1<=≤<=*n*<=≤<=100,<=0<=≤<=*P*1,<=*P*2,<=*P*3<=≤<=100,<=1<=≤<=*T*1,<=*T*2<=≤<=60). The following *n* lines contain description of Tom's work. Each *i*-th of these lines contains two space-separated integers *l**i* and *r**i* (0<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=1440, *r**i*<=&lt;<=*l**i*<=+<=1 for *i*<=&lt;<=*n*), which stand for the start and the end of the *i*-th period of work. Output Specification: Output the answer to the problem. Demo Input: ['1 3 2 1 5 10\n0 10\n', '2 8 4 2 5 10\n20 30\n50 100\n'] Demo Output: ['30', '570'] Note: none
```python n,p1,p2,p3,T1,T2=map(int,input().split()) total,previousTime=0,-1 for k in range(n): start,finish=map(int,input().split()) if previousTime<0: previousTime=start total +=p1*(finish-start) timeIdle=start-previousTime if timeIdle>T1+T2: total +=(timeIdle-T1-T2)*p3 timeIdle=T1+T2 if timeIdle>T1: total +=(timeIdle-T1)*p2 timeIdle=T1 total +=timeIdle*p1 previousTime=finish print(total) ```
9
Running Student
Title: Running Student Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point (0,<=0), he got on a minibus and they drove along a straight line, parallel to axis *OX*, in the direction of increasing *x*. Poor Student knows the following: - during one run the minibus makes *n* stops, the *i*-th stop is in point (*x**i*,<=0) - coordinates of all the stops are different - the minibus drives at a constant speed, equal to *v**b* - it can be assumed the passengers get on and off the minibus at a bus stop momentarily - Student can get off the minibus only at a bus stop - Student will have to get off the minibus at a terminal stop, if he does not get off earlier - the University, where the exam will be held, is in point (*x**u*,<=*y**u*) - Student can run from a bus stop to the University at a constant speed *v**s* as long as needed - a distance between two points can be calculated according to the following formula: - Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University. Input Specification: The first line contains three integer numbers: 2<=≤<=*n*<=≤<=100, 1<=≤<=*v**b*,<=*v**s*<=≤<=1000. The second line contains *n* non-negative integers in ascending order: coordinates *x**i* of the bus stop with index *i*. It is guaranteed that *x*1 equals to zero, and *x**n*<=≤<=105. The third line contains the coordinates of the University, integers *x**u* and *y**u*, not exceeding 105 in absolute value. Output Specification: In the only line output the answer to the problem — index of the optimum bus stop. Demo Input: ['4 5 2\n0 2 4 6\n4 1\n', '2 1 1\n0 100000\n100000 100000\n'] Demo Output: ['3', '2'] Note: As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.
```python def dist(a,b,c,d): return (((a-c)**2)+((b-d)**2))**0.5 n,vb,vs=map(int,input().split()) x=list(map(int,input().split()))[1::] xx,yy=map(int,input().split()) mintime=-1 lol=0 for i in range(n-1): time=(x[i]/vb)+dist(x[i],0,xx,yy)/vs if mintime==-1: mintime=time elif time<mintime: mintime=time lol=i elif time==mintime: if dist(x[lol],0,xx,yy)>dist(x[i],0,xx,yy): lol=i print(lol+2) ```
5
Chat Servers Outgoing Traffic
Title: Chat Servers Outgoing Traffic Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands. Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends *l* bytes to each participant of the chat, where *l* is the length of the message. As Polycarp has no time, he is asking for your help in solving this problem. Input Specification: Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following: - +&lt;name&gt; for 'Add' command. - -&lt;name&gt; for 'Remove' command. - &lt;sender_name&gt;:&lt;message_text&gt; for 'Send' command. &lt;name&gt; and &lt;sender_name&gt; is a non-empty sequence of Latin letters and digits. &lt;message_text&gt; can contain letters, digits and spaces, but can't start or end with a space. &lt;message_text&gt; can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive. Output Specification: Print a single number — answer to the problem. Demo Input: ['+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate\n', '+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate\n'] Demo Output: ['9\n', '14\n'] Note: none
```python count=0 count1=0 while(1): try: s = input() if(s[0]=="+"): count+=1 elif(s[0]=="-"): count-=1 else: for i in range(0,len(s)): if(s[i]==":"): p=i break len1 = len(s)-1-p count1+=len1*count except: print(count1) break ```
3
Shortest path of the king
Title: Shortest path of the king Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square *t*. As the king is not in habit of wasting his time, he wants to get from his current position *s* to square *t* in the least number of moves. Help him to do this. In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to). Input Specification: The first line contains the chessboard coordinates of square *s*, the second line — of square *t*. Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8. Output Specification: In the first line print *n* — minimum number of the king's moves. Then in *n* lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD. L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them. Demo Input: ['a8\nh1\n'] Demo Output: ['7\nRD\nRD\nRD\nRD\nRD\nRD\nRD\n'] Note: none
```python start = list(input()) end = list(input()) rows = ['a','b','c','d','e','f','g','h'] colomns = list(range(1,9)) rmove = rows.index(end[0])-rows.index(start[0]) cmove = colomns.index(int(end[1]))-colomns.index(int(start[1])) if rmove >= 0: x = 'R' else: x = 'L' if cmove >= 0: y = 'U' else: y = 'D' rmove = abs(rmove) cmove = abs(cmove) move = abs(min(rmove, cmove)) count = 0 steps = [] for i in range(move): move = f'{x}{y}' steps.append(move) count += 1 if rmove > cmove: for i in range(rmove-cmove): steps.append(x) count += 1 else: for i in range(cmove-rmove): steps.append(y) count += 1 print(count) for step in steps: print(step) ```
2
Winner
Title: Winner Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to *m*) at the end of the game, than wins the one of them who scored at least *m* points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. Input Specification: The first line contains an integer number *n* (1<=<=≤<=<=*n*<=<=≤<=<=1000), *n* is the number of rounds played. Then follow *n* lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. Output Specification: Print the name of the winner. Demo Input: ['3\nmike 3\nandrew 5\nmike 2\n', '3\nandrew 3\nandrew 2\nmike 5\n'] Demo Output: ['andrew\n', 'andrew\n'] Note: none
```python ''' ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓█████▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬ ▓▓ ▓▓ ╬╬ ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ########################### // •︿• \\ /\\ //\ /\\ //\ /\\//\ ########################### ''' import sys input = lambda : sys.stdin.readline().strip() import math as mt from math import ceil as cl from math import log2 as l2 mod = 10**9 + 7 def ii(): return int(input()) def lii(): return list(map(int, input().split())) def ss(): return input() def lss(): return list(map(str, input().split())) def yes(): print("YES") def no(): print("NO") ''' ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ''' rounds = list() scores = dict() for i in range(ii()): name, score = ss().split() scores[name] = scores.get(name, 0)+int(score) rounds.append(name+' '+str(scores[name])) maxscr = max(scores.values()) for r in rounds: name, score = r.split() if int(score)>=maxscr and scores[name]>=maxscr: print (name); break ```
39
C*++ Calculations
Title: C*++ Calculations Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (*expression* is the main term): - *expression* ::= *summand* | *expression*<=+<=*summand* | *expression*<=-<=*summand* - *summand* ::= *increment* | *coefficient***increment* - *increment* ::= a++ | ++a - *coefficient* ::= 0|1|2|...|1000 For example, "5*a++-3*++a+a++" is a valid expression in C*++. Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1. The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then — multiplied by the coefficient. The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value. Input Specification: The first input line contains an integer *a* (<=-<=1000<=≤<=*a*<=≤<=1000) — the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation. Output Specification: Output a single number — the maximal possible value of the expression. Demo Input: ['1\n5*a++-3*++a+a++\n', '3\na+++++a\n'] Demo Output: ['11\n', '8\n'] Note: Consider the second example. Initially *a* = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of *a* is increased by 1. At the calculation of the second summand *a* is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
```python a = int(input()) s = '+'+input() t = [] p = 0 n = len(s) while p < n : pa = s.find('a', p) if pa >= p + 3 and s[pa - 2 : pa] == '++' : np = pa + 1 else : np = pa + 3 t.append(s[p : np]) p = np coef = [] for s in t : if s[-1] == 'a' : pre = True else : pre = False v = 1 if len(s) > 4 : v = int(s[:-4]) elif s[0] == '-' : v = -1 coef.append((v, pre)) coef.sort() ans = 0 for (v, pre) in coef : if pre : a += 1 ans += v * a if not pre : a += 1 print(ans) ```
7
Line
Title: Line Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: A line on the plane is described by an equation *Ax*<=+<=*By*<=+<=*C*<==<=0. You are to find any point on this line, whose coordinates are integer numbers from <=-<=5·1018 to 5·1018 inclusive, or to find out that such points do not exist. Input Specification: The first line contains three integers *A*, *B* and *C* (<=-<=2·109<=≤<=*A*,<=*B*,<=*C*<=≤<=2·109) — corresponding coefficients of the line equation. It is guaranteed that *A*2<=+<=*B*2<=&gt;<=0. Output Specification: If the required point exists, output its coordinates, otherwise output -1. Demo Input: ['2 5 3\n'] Demo Output: ['6 -3\n'] Note: none
```python def gcd(a,b): if b==0: return (1,0,a) else: x,y,g=gcd(b, a%b) return (y,x-(a//b)*y,g) a,b,c=map(int,input().split()) if a>b: x,y,g=gcd(max(a,b),min(a,b)) else: y,x,g=gcd(max(a,b),min(a,b)) if abs(c)%g!=0: print(-1) else: print(-x*(c//g),-y*(c//g)) ```
29
Ant on the Tree
Title: Ant on the Tree Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are *n* vertexes in the tree, and they are connected by *n*<=-<=1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex. The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant. Input Specification: The first line contains integer *n* (3<=≤<=*n*<=≤<=300) — amount of vertexes in the tree. Next *n*<=-<=1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains *k* integers, where *k* is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once. Output Specification: If the required route doesn't exist, output -1. Otherwise, output 2*n*<=-<=1 numbers, describing the route. Every time the ant comes to a vertex, output it's index. Demo Input: ['3\n1 2\n2 3\n3\n', '6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 6 3\n', '6\n1 2\n1 3\n2 4\n4 5\n4 6\n5 3 6\n'] Demo Output: ['1 2 3 2 1 ', '1 2 4 5 4 6 4 2 1 3 1 ', '-1\n'] Note: none
```python def ni(): return int(input()) def ia(): return list(map(int, input().split())) def pod(g, root=0): n = len(g) par = [-1 for _ in range(n)] odr = [-1 for _ in range(n)] dep = [-1 for _ in range(n)] vis = [False for _ in range(n)] odr[root] = 0 dep[root] = 0 ptr = 1 for i in range(n): cur = odr[i] vis[cur] = True for nex in g[odr[i]]: if not vis[nex]: par[nex] = cur odr[ptr] = nex dep[nex] = dep[cur] + 1 ptr += 1 return par, odr, dep def is_subsequence(arr1, arr2): i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: i += 1 j += 1 return i == len(arr1) def dfs(g, cur, vis, cost, ans): vis[cur] = True ans.append(cur + 1) for nex in sorted(g[cur], key=lambda x: cost[x]): if not vis[nex]: dfs(g, nex, vis, cost, ans) ans.append(cur + 1) n = ni() g = [[] for _ in range(n)] for i in range(n - 1): x, y = ia() g[x - 1].append(y - 1) g[y - 1].append(x - 1) leaves = ia() cost = [10000 for _ in range(n)] for idx, leaf in enumerate(leaves): cost[leaf - 1] = idx par, odr, dep = pod(g) for node in odr[::-1]: for nex in g[node]: if nex != par[node]: cost[node] = min(cost[nex], cost[node]) ans = [] dfs(g, 0, [False for _ in range(n)], cost, ans) print(" ".join(map(str, ans)) if is_subsequence(leaves, ans) else -1) ```
65
Harry Potter and the History of Magic
Title: Harry Potter and the History of Magic Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates. So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes. Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. Input Specification: The first input line contains an integer *n* (1<=≤<=*n*<=≤<=1000). It represents the number of dates in Harry's notes. Next *n* lines contain the actual dates *y*1, *y*2, ..., *y**n*, each line contains a date. Each date is a four-digit integer (1000<=≤<=*y**i*<=≤<=9999). Output Specification: Print *n* numbers *z*1, *z*2, ..., *z**n* (1000<=≤<=*z**i*<=≤<=2011). They are Ron's resulting dates. Print each number on a single line. Numbers *z**i* must form the non-decreasing sequence. Each number *z**i* should differ from the corresponding date *y**i* in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). Demo Input: ['3\n1875\n1936\n1721\n', '4\n9999\n2000\n3000\n3011\n', '3\n1999\n5055\n2000\n'] Demo Output: ['1835\n1836\n1921\n', '1999\n2000\n2000\n2011\n', 'No solution\n'] Note: none
```python n = int(input()) values = [ 1000, 100, 10, 1 ] ranges = [ [1, 2], range(10), range(10), range(10) ] def attempt(previous, digits, x): least = None for i in range(4): for d in ranges[i]: y = x + (d - digits[i]) * values[i] if y <= 2011 and y >= previous and (least == None or y < least): least = y return least previous = 0 result = [] for i in range(n): s = input() digits = list(map(int, list(s))) x = int(s) y = attempt(previous, digits, x) if y == None: print('No solution') import sys; sys.exit() result.append(y) previous = y print('\n'.join(map(str, result))) ```
23
Tree
Title: Tree Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree. Input Specification: The first input line contains integer number *n* (1<=≤<=*n*<=≤<=700) — amount of vertices in the tree. The following *n*<=-<=1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*). It's guaranteed that the graph described in the input is a tree. Output Specification: Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges. Demo Input: ['5\n1 2\n2 3\n3 4\n4 5\n', '8\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n6 8\n', '3\n1 2\n1 3\n'] Demo Output: ['6', '18', '3'] Note: none
```python n = int(input()) edges = [[] for i in range(n)] ch = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 edges[a].append(b) edges[b].append(a) dp = [1 for i in range(n)] prod = [1 for i in range(n)] def dfs(v, pr): prod[v] = 1 for to in edges[v]: if to != pr: dfs(to, v) ch[v].append(to) prod[v] *= dp[to] ch[v].sort(key = lambda i : dp[i] / prod[i]) dp[v] = prod[v] now = prod[v] cnt = 1 for to in ch[v]: cnt += 1 now //= dp[to] now *= prod[to] dp[v] = max(dp[v], now * cnt) for to in ch[v]: now = prod[v] // dp[to] * prod[to] cnt = 2 for gr in ch[to]: cnt += 1 now //= dp[gr] now *= prod[gr] dp[v] = max(dp[v], now * cnt) dfs(0, -1) print(dp[0]) ```
31
Schedule
Title: Schedule Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, *n* groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect. The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=5000) — amount of groups, which have lessons in the room 31. Then *n* lines follow, each of them contains two integers *l**i* *r**i* (1<=≤<=*l**i*<=&lt;<=*r**i*<=≤<=106) — starting and finishing times of lesson of the *i*-th group. It is possible that initially no two lessons intersect (see sample 1). Output Specification: Output integer *k* — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output *k* numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. Demo Input: ['3\n3 10\n20 30\n1 3\n', '4\n3 10\n20 30\n1 3\n1 39\n', '3\n1 5\n2 6\n3 7\n'] Demo Output: ['3\n1 2 3 ', '1\n4 ', '0\n'] Note: none
```python """ CP 2.B - Schedule Allan Lago Vjudge Username: alago1 """ n = int(input().strip()) lessons = [] keypoints = [] for i in range(n): s, e = tuple(int(x) for x in input().strip().split()) lessons.append((s, e)) keypoints.append((s, 1)) keypoints.append((e, -1)) keypoints.sort() k, start, end = (0,)*3 for t, dk in keypoints: k += dk if k > 2: print('0') exit(0) if k == 2: start = t if not start else start end = t out = [] for i, lesson in enumerate(lessons): ls, le = lesson if not start or start >= ls and end < le: out.append(i+1) print(len(out)) print(*out) ```
53
Physical Education
Title: Physical Education Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the height of the *i*-th student in the line and *n* is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: *b*1,<=*b*2,<=...,<=*b**n*, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: *a*1,<=*a*2,<=...,<=*a**n*. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=300) which is the number of students. The second line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=109) which represent the height of the student occupying the *i*-th place must possess. The third line contains *n* space-separated integers *b**i* (1<=≤<=*b**i*<=≤<=109) which represent the height of the student occupying the *i*-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. *a* and *b* coincide as multisets. Output Specification: In the first line print an integer *k* (0<=≤<=*k*<=≤<=106) which is the number of moves. It is not required to minimize *k* but it must not exceed 106. Then print *k* lines each containing two space-separated integers. Line *p**i*, *p**i*<=+<=1 (1<=≤<=*p**i*<=≤<=*n*<=-<=1) means that Vasya should swap students occupying places *p**i* and *p**i*<=+<=1. Demo Input: ['4\n1 2 3 2\n3 2 1 2\n', '2\n1 100500\n1 100500\n'] Demo Output: ['4\n2 3\n1 2\n3 4\n2 3\n', '0\n'] Note: none
```python def vasya_and_physcult(count, a_str, b_str): size = int(count) a = list(map(int, a_str.split())) b = list(map(int, b_str.split())) changes_count = 0 result = "" for i in range(size): current_index = i for j in range(i,size): if b[j] == a[i]: current_index = j break while current_index>i: b[current_index], b[current_index-1] = b[current_index-1], b[current_index-1] result += "\n" + f"{current_index} {current_index+1}" changes_count+=1 current_index-=1 return str(changes_count) + result count = input() a = input() b = input() print(vasya_and_physcult(count, a, b)) ```
68
Energy exchange
Title: Energy exchange Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the *i*-th accumulator has *a**i* units of energy. Energy can be transferred from one accumulator to the other. Every time *x* units of energy are transferred (*x* is not necessarily an integer) *k* percent of it is lost. That is, if *x* units were transferred from one accumulator to the other, amount of energy in the first one decreased by *x* units and in other increased by units. Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers. Input Specification: First line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=10000,<=0<=≤<=*k*<=≤<=99) — number of accumulators and the percent of energy that is lost during transfers. Next line contains *n* integers *a*1,<=*a*2,<=... ,<=*a**n* — amounts of energy in the first, second, .., *n*-th accumulator respectively (0<=≤<=*a**i*<=≤<=1000,<=1<=≤<=*i*<=≤<=*n*). Output Specification: Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10<=-<=6. Demo Input: ['3 50\n4 2 1\n', '2 90\n1 11\n'] Demo Output: ['2.000000000\n', '1.909090909\n'] Note: none
```python (n, k), t = map(int, input().split()), [0] + sorted(list(map(int, input().split()))) i, d, s = 1, t[1], sum(t) while i < n: i += 1 d += t[i] if 100 * (s - t[i] * n) < k * (s - d - t[i] * (n - i)): d -= t[i] i -= 1 break print(t[i] + (100 * (s - t[i] * n) - k * (s - d - t[i] * (n - i))) / (100 * n - k * (n - i))) ```
52
123-sequence
Title: 123-sequence Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There is a given sequence of integers *a*1,<=*a*2,<=...,<=*a**n*, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=106). The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=3). Output Specification: Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal. Demo Input: ['9\n1 3 2 2 2 1 1 2 3\n'] Demo Output: ['5\n'] Note: In the example all the numbers equal to 1 and 3 should be replaced by 2.
```python n=int(input()) a=input() print(n-max(a.count(x)for x in '123')) ```
62
Wormhouse
Title: Wormhouse Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from 1 to *n*. All the corridors are bidirectional. Arnie wants the new house to look just like the previous one. That is, it should have exactly *n* rooms and, if a corridor from room *i* to room *j* existed in the old house, it should be built in the new one. We know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors. However, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm. Input Specification: The first line contains two integers *n* and *m* (3<=≤<=*n*<=≤<=100,<=3<=≤<=*m*<=≤<=2000). It is the number of rooms and corridors in Arnie's house correspondingly. The next line contains *m*<=+<=1 positive integers that do not exceed *n*. They are the description of Arnie's old path represented as a list of rooms he visited during the gnawing. It is guaranteed that the last number in the list coincides with the first one. The first room described in the list is the main entrance, that's why Arnie should begin gnawing from it. You may assume that there is no room which is connected to itself and there is at most one corridor between any pair of rooms. However, it is possible to find some isolated rooms which are disconnected from others. Output Specification: Print *m*<=+<=1 positive integers that do not exceed *n*. Those numbers are the description of the new path, according to which Arnie should gnaw out his new house. If it is impossible to find new path you should print out No solution. The first number in your answer should be equal to the last one. Also it should be equal to the main entrance. Demo Input: ['3 3\n1 2 3 1\n', '3 3\n1 3 2 1\n'] Demo Output: ['1 3 2 1 ', 'No solution'] Note: none
```python n,m = map(int,input().split()) m+=1 p = list(map(lambda x:int(x)-1,input().split())) a = [0]*m q = [[False]*n for i in range(n)] d = [[] for i in range(n)] for i in range(1,m): d[p[i]].append(p[i-1]) d[p[i-1]].append(p[i]) for i in range(n): d[i].sort() s = [(p[0],True,p[0])] l = 0 while s: v,f,vv = s[-1] if f is None: s.pop() l-=1 q[vv][v]=q[v][vv]=False continue q[vv][v]=q[v][vv]=True s[-1]=(v,None,vv) a[l]=v l+=1 if l==m: if f: continue else: break for u in reversed(d[v]): if f and u<p[l]: continue if q[u][v]: continue s.append((u,f and u==p[l],v)) if s: print(' '.join(map(lambda x:str(x+1),a))) else: print("No solution") ```
89
Widget Library
Title: Widget Library Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget *a* is packed in the widget *b* if there exists a chain of widgets *a*<==<=*c*1,<=*c*2,<=...,<=*c**k*<==<=*b*, *k*<=≥<=2, for which *c**i* is packed directly to *c**i*<=+<=1 for any 1<=≤<=*i*<=&lt;<=*k*. In Vasya's library the situation when the widget *a* is packed in the widget *a* (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0<=×<=0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. Input Specification: The first line contains an integer *n* — the number of instructions (1<=≤<=*n*<=≤<=100). Next *n* lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. - "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. - "HBox [name]" — create a new widget [name] of the type HBox. - "VBox [name]" — create a new widget [name] of the type VBox. - "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. - "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. - "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. Output Specification: For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator) Demo Input: ['12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)\n', '15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dummy)\ny.set_border(5)\ny.set_spacing(55)\ndummy.set_border(10)\ndummy.set_spacing(20)\nx.set_border(10)\nx.set_spacing(10)\nx.pack(pack)\nx.pack(dummy)\nx.pack(pack)\nx.set_border(0)\n'] Demo Output: ['brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20\n', 'dummy 0 0\npack 10 10\nx 40 10\ny 10 10\n'] Note: In the first sample the widgets are arranged as follows:
```python #bobwish(md) import re def size(name): global d if len(d[name]) == 4: type, children, border, spacing = d[name] if not children: d[name] = (0, 0) else: ww, hh = zip(*map(size, children)) b, s = 2 * border, spacing * max(0, len(children) - 1) if type == 'VBox': d[name] = (b + max(ww), b + s + sum(hh)) else: d[name] = (b + s + sum(ww), b + max(hh)) return d[name] d = {} for _ in range(int(input())): line = input().strip() s = re.split("[ (,).]", line) if len(s) == 5: type, name, width, height, _ = s d[name] = (int(width), int(height)) elif len(s) == 2: type, name = s d[name] = [type, [], 0, 0] else: name, op, arg, _ = s if op == 'pack': d[name][1].append(arg) elif op == 'set_border': d[name][2] = int(arg) elif op == 'set_spacing': d[name][3] = int(arg) for name in sorted(d): w, h = size(name) print(name, w, h) ```
13
Numbers
Title: Numbers Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number *A* written in all bases from 2 to *A*<=-<=1. Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10. Input Specification: Input contains one integer number *A* (3<=≤<=*A*<=≤<=1000). Output Specification: Output should contain required average value in format «X/Y», where X is the numerator and Y is the denominator. Demo Input: ['5\n', '3\n'] Demo Output: ['7/3\n', '2/1\n'] Note: In the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
```python def readln(): return tuple(map(int, input().split())) a, = readln() ch = zn = 0 for os in range(2, a): t = a while t: ch += t % os t //= os zn += 1 def gcd(a, b): while a: a, b = b % a, a return b g = gcd(ch, zn) print('%d/%d' % (ch // g, zn // g)) ```
10
Digital Root
Title: Digital Root Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Not long ago Billy came across such a problem, where there were given three natural numbers *A*, *B* and *C* from the range [1,<=*N*], and it was asked to check whether the equation *AB*<==<=*C* is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root *d*(*x*) of the number *x* is the sum *s*(*x*) of all the digits of this number, if *s*(*x*)<=≤<=9, otherwise it is *d*(*s*(*x*)). For example, a digital root of the number 6543 is calculated as follows: *d*(6543)<==<=*d*(6<=+<=5<=+<=4<=+<=3)<==<=*d*(18)<==<=9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. *d*(*xy*)<==<=*d*(*d*(*x*)*d*(*y*)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes. Input Specification: The first line contains the only number *N* (1<=≤<=*N*<=≤<=106). Output Specification: Output one number — the amount of required *A*, *B* and *C* from the range [1,<=*N*]. Demo Input: ['4\n', '5\n'] Demo Output: ['2\n', '6\n'] Note: For the first sample the required triples are (3, 4, 3) and (4, 3, 3).
```python n=int(input()) d=[0]*10 res=0 for i in range(1,n+1): res-=n//i d[i%9]+=1 for i in range(10): for j in range(10): res+=d[i]*d[j]*d[(i*j)%9] print(res) ```
57
Array
Title: Array Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of *n*, containing only integers from 1 to *n*. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions: - each elements, starting from the second one, is no more than the preceding one - each element, starting from the second one, is no less than the preceding one Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last. Input Specification: The single line contains an integer *n* which is the size of the array (1<=≤<=*n*<=≤<=105). Output Specification: You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007. Demo Input: ['2\n', '3\n'] Demo Output: ['4\n', '17\n'] Note: none
```python def fact(n): k = 1 for i in range(n): k *= i+1 return k def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m n = int(input()) k = 1 for i in range(n-1): k *= i+(n+1) k = k % 1000000007 l = 1 for i in range(n-1): l *= i+1 l = l % 1000000007 print((2*k*modinv(l, 1000000007)-n) % 1000000007) ```
95
Lucky Numbers
Title: Lucky Numbers 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*<=≤<=10100000). This number doesn't have leading zeroes. Output Specification: Output the least super lucky number that is more than or equal to *n*. Demo Input: ['4500\n', '47\n'] Demo Output: ['4747\n', '47\n'] Note: none
```python def f(i,c,n4,n7):return s[:i]+c+'4'*n4+'7'*n7 P=print;s=input();n=len(s);n4=n7=n//2;z=(0,'4',n4,n7+1) if n&1==1:exit(P(f(*z))) for i,c in enumerate(s): if c>'7':break if c == "7": if n7 == 0:break n7 -= 1;continue if n7 > 0:z = (i, "7", n4, n7 - 1) if c > "4":break if c == "4": if n4 == 0:break n4 -= 1;continue if n4 > 0:z = (i, "4", n4 - 1, n7) break else:z=(n,'',0,0) P(f(*z)) ```
89
Robbery
Title: Robbery Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has *n* cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to *n* from the left to the right. Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works. Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an *n*<=-<=1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered. Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than *m* times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check. In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only *k* minutes left before morning, and on each of these *k* minutes he can perform no more than *m* operations. All that remains in Joe's pocket, is considered his loot. Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning. Input Specification: The first line contains integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=104, 1<=≤<=*m*,<=*k*<=≤<=109). The next line contains *n* numbers. The *i*-th number is equal to the amount of diamonds in the *i*-th cell — it is an integer from 0 to 105. Output Specification: Print a single number — the maximum number of diamonds Joe can steal. Demo Input: ['2 3 1\n2 3\n', '3 2 2\n4 1 3\n'] Demo Output: ['0', '2'] Note: In the second sample Joe can act like this: The diamonds' initial positions are 4 1 3. During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket. By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off. During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket. By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off. Now Joe leaves with 2 diamonds in his pocket.
```python n, m, k = map(int, input().split()) a = list(map(int, input().split())) if n % 2 == 0: print('0') else: print(min(m // (n // 2 + 1) * k, min(a[::2])))# 1691197711.423217 ```
37
Old Berland Language
Title: Old Berland Language Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Berland scientists know that the Old Berland language had exactly *n* words. Those words had lengths of *l*1,<=*l*2,<=...,<=*l**n* letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol. Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves. Input Specification: The first line contains one integer *N* (1<=≤<=*N*<=≤<=1000) — the number of words in Old Berland language. The second line contains *N* space-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000. Output Specification: If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next *N* lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any. Demo Input: ['3\n1 2 3\n', '3\n1 1 1\n'] Demo Output: ['YES\n0\n10\n110\n', 'NO\n'] Note: none
```python #!/usr/bin/python3 counts = [0]*1024 for x in range(len(counts)): counts[x] = [] N = int(input()) x = [int(t) for t in input().strip().split()] for i,t in enumerate(x): counts[t].append(i) curr = 0 ans = [0]*N for i in range(1,1024): while len(counts[i]) > 0: x = bin(curr)[2:] if len(x) > i: print("NO") exit(0) else: x = "0"*(i-len(x)) + x ans[counts[i].pop()] = x curr += 1 curr = 2*curr print("YES") print("\n".join(ans)) ```
34
Collisions
Title: Collisions Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: On a number line there are *n* balls. At time moment 0 for each ball the following data is known: its coordinate *x**i*, speed *v**i* (possibly, negative) and weight *m**i*. The radius of the balls can be ignored. The balls collide elastically, i.e. if two balls weighing *m*1 and *m*2 and with speeds *v*1 and *v*2 collide, their new speeds will be: Your task is to find out, where each ball will be *t* seconds after. Input Specification: The first line contains two integers *n* and *t* (1<=≤<=*n*<=≤<=10,<=0<=≤<=*t*<=≤<=100) — amount of balls and duration of the process. Then follow *n* lines, each containing three integers: *x**i*, *v**i*, *m**i* (1<=≤<=|*v**i*|,<=*m**i*<=≤<=100,<=|*x**i*|<=≤<=100) — coordinate, speed and weight of the ball with index *i* at time moment 0. It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;*t*]). Output Specification: Output *n* numbers — coordinates of the balls *t* seconds after. Output the numbers accurate to at least 4 digits after the decimal point. Demo Input: ['2 9\n3 4 5\n0 7 8\n', '3 10\n1 2 3\n4 -5 6\n7 -8 9\n'] Demo Output: ['68.538461538\n44.538461538\n', '-93.666666667\n-74.666666667\n-15.666666667\n'] Note: none
```python import sys from math import isclose EPSILON = 1e-9 def main(): n, t = map(float, input().split()) n = int(n) data = [] for _ in range(n): x, v, m = map(float, input().split()) data.append([x, v, m]) while True: tmin = 999999 for i in range(n): for j in range(n): if (not isclose(data[i][0], data[j][0], rel_tol=EPSILON) and not isclose(data[i][1], data[j][1], rel_tol=EPSILON)): temp = (data[i][0] - data[j][0]) / (data[j][1] - data[i][1]) if temp > 0 and temp < tmin: tmin = temp if tmin >= t: break t -= tmin for i in range(n): data[i][0] += tmin * data[i][1] for i in range(n): for j in range(i): if isclose(data[i][0], data[j][0], rel_tol=EPSILON): vi = ((data[i][2] - data[j][2]) * data[i][1] + 2 * data[j][2] * data[j][1]) / (data[i][2] + data[j][2]) vj = ((data[j][2] - data[i][2]) * data[j][1] + 2 * data[i][2] * data[i][1]) / (data[i][2] + data[j][2]) data[i][1] = vi data[j][1] = vj for i in range(n): data[i][0] += t * data[i][1] for i in range(n): print("{:.9f}".format(data[i][0])) if __name__ == "__main__": main()# 1692009658.9190907 ```
59
Title
Title: Title Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first *k* Latin letters and not containing any other ones. Also, the title should be a palindrome, that is it should be read similarly from the left to the right and from the right to the left. Vasya has already composed the approximate variant of the title. You are given the title template *s* consisting of lowercase Latin letters and question marks. Your task is to replace all the question marks by lowercase Latin letters so that the resulting word satisfies the requirements, described above. Each question mark should be replaced by exactly one letter, it is not allowed to delete characters or add new ones to the template. If there are several suitable titles, choose the first in the alphabetical order, for Vasya's book to appear as early as possible in all the catalogues. Input Specification: The first line contains an integer *k* (1<=≤<=*k*<=≤<=26) which is the number of allowed alphabet letters. The second line contains *s* which is the given template. In *s* only the first *k* lowercase letters of Latin alphabet and question marks can be present, the length of *s* is from 1 to 100 characters inclusively. Output Specification: If there is no solution, print IMPOSSIBLE. Otherwise, a single line should contain the required title, satisfying the given template. The title should be a palindrome and it can only contain the first *k* letters of the Latin alphabet. At that, each of those *k* letters must be present at least once. If there are several suitable titles, print the lexicographically minimal one. The lexicographical comparison is performed by the standard &lt; operator in modern programming languages. The line *a* is lexicographically smaller than the line *b*, if exists such an *i* (1<=≤<=*i*<=≤<=|*s*|), that *a**i*<=&lt;<=*b**i*, and for any *j* (1<=≤<=*j*<=&lt;<=*i*) *a**j*<==<=*b**j*. |*s*| stands for the length of the given template. Demo Input: ['3\na?c\n', '2\na??a\n', '2\n?b?a\n'] Demo Output: ['IMPOSSIBLE\n', 'abba\n', 'abba\n'] Note: none
```python #def computeGCD(x, y): import math from collections import Counter k = int(input()) #n=int(input()) #stirng s = (input()) flag = False if len(s)%2==0: l = len(s)//2-1 r = len(s)//2 else: l=r=len(s)//2 dic = Counter(s) alpha = [] for i in range(97,97+k): if chr(i) in dic: k-=1 else: alpha.append(chr(i)) s = [i for i in s] while l>-1 and r<len(s): # print(s[l],s[r]) if s[l]!='?' and s[r]!='?' and s[l]!=s[r]: flag = True break elif s[l]=='?' and s[r]!='?': s[l] = s[r] elif s[r]=='?' and s[l]!='?': s[r] = s[l] elif s[l] == '?' and s[r] == '?': if alpha: s[l] = s[r] = alpha.pop() k-=1 else: s[l] = s[r] = 'a' l-=1 r+=1 if k == 0 and not flag: print(''.join(s)) else: print("IMPOSSIBLE") ```
0
none
Title: none 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 import itertools hero = { "Anka": 0, "Chapay": 1, "Cleo": 2, "Troll": 3, "Dracul": 4, "Snowy": 5, "Hexadecimal": 6, } partitions = [ (1, 1, 5), (1, 2, 4), (1, 3, 3), (2, 2, 3), ] def likes(group): return sum(g[i][j] for i in group for j in group) g = [[0] * 7 for _ in range(7)] for _ in range(int(input())): x, y = input().split(" likes ") g[hero[x]][hero[y]] = 1 a, b, c = sorted(map(int, input().split())) best_diff = float("inf") best_partitions = [] for p in partitions: exp = (a // p[0], b // p[1], c // p[2]) diff = max(exp) - min(exp) if diff == best_diff: best_partitions.append(p) elif diff < best_diff: best_diff = diff best_partitions = [p] best_likes = max( likes(h[:x]) + likes(h[x : x + y]) + likes(h[x + y :]) for x, y, _ in best_partitions for h in itertools.permutations(range(7)) ) print(best_diff, best_likes) ```
22
Bargaining Table
Title: Bargaining Table Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room *n*<=×<=*m* meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office. Input Specification: The first line contains 2 space-separated numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=25) — the office room dimensions. Then there follow *n* lines with *m* characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free. Output Specification: Output one number — the maximum possible perimeter of a bargaining table for Bob's office room. Demo Input: ['3 3\n000\n010\n000\n', '5 4\n1100\n0000\n0000\n0000\n0000\n'] Demo Output: ['8\n', '16\n'] Note: none
```python def main(): n, m = map(int, input().split()) prev_row = [0 for _ in range(m)] max_perimeter = 4 for _ in range(n): current = input() current_row = [] for j in range(m): if current[j] == '1': current_row.append(0) else: current_row.append(prev_row[j] + 1) max_height = 100 for k in range(j, -1, -1): if current_row[k] == 0: break max_height = min(max_height, current_row[k]) max_perimeter = max(max_perimeter, (max_height + (j - k + 1)) * 2) prev_row = current_row print(max_perimeter) if __name__ == "__main__": main() ```
45
Goats and Wolves
Title: Goats and Wolves Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Vasya needed to transport *m* goats and *m* wolves from riverbank to the other as quickly as possible. The boat can hold *n* animals and Vasya, in addition, he is permitted to put less than *n* animals in the boat. If in one place (on one of the banks or in the boat) the wolves happen to strictly outnumber the goats, then the wolves eat the goats and Vasya gets upset. When Vasya swims on the boat from one shore to the other, he must take at least one animal to accompany him, otherwise he will get bored and he will, yet again, feel upset. When the boat reaches the bank, first all the animals get off simultaneously, and then the animals chosen by Vasya simultaneously get on the boat. That means that at the moment when the animals that have just arrived have already got off and the animals that are going to leave haven't yet got on, somebody might eat someone. Vasya needs to transport all the animals from one river bank to the other so that nobody eats anyone and Vasya doesn't get upset. What is the minimal number of times he will have to cross the river? Input Specification: The first line contains two space-separated numbers *m* and *n* (1<=≤<=*m*,<=*n*<=≤<=105) — the number of animals and the boat's capacity. Output Specification: If it is impossible to transport all the animals so that no one got upset, and all the goats survived, print -1. Otherwise print the single number — how many times Vasya will have to cross the river. Demo Input: ['3 2\n', '33 3\n'] Demo Output: ['11\n', '-1\n'] Note: The first sample match to well-known problem for children.
```python m, n = map(int, input().split()) def solve(): global m global n f = 0 res = 0 if n == 1: print(-1) return # 特判 if (m == 3 and n == 2) or (m == 5 and n == 3): print(11) return while True: if n >= 2*m: print(res+1) return elif n >= m: if n == m: print(res+5) else: print(res+3) return elif not f: m -= n-2 res = 4 f = 1 else: if n//2 == 1: print(-1) return else: m -= n//2-1 res += 2 solve() ```
18
Platforms
Title: Platforms Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: In one one-dimensional world there are *n* platforms. Platform with index *k* (platforms are numbered from 1) is a segment with coordinates [(*k*<=-<=1)*m*,<=(*k*<=-<=1)*m*<=+<=*l*], and *l*<=&lt;<=*m*. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly *d* units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down. Input Specification: The first input line contains 4 integer numbers *n*, *d*, *m*, *l* (1<=≤<=*n*,<=*d*,<=*m*,<=*l*<=≤<=106,<=*l*<=&lt;<=*m*) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers *m* and *l* needed to find coordinates of the *k*-th platform: [(*k*<=-<=1)*m*,<=(*k*<=-<=1)*m*<=+<=*l*]. Output Specification: Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down. Demo Input: ['2 2 5 3\n', '5 4 11 8\n'] Demo Output: ['4\n', '20\n'] Note: none
```python n, d, m, l = [int(w) for w in input().split()] for k in range(n): t = (k * m + l) % d if d - t < m - l: print(k * m + l + d - t) exit(0) target = (n - 1) * m + l result = target + d - (target % d ) while result <= target: result += d print(result) ```
98
Help King
Title: Help King Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive. Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast. Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage. The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be *n* noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1<=/<=*n*). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task. Input Specification: The first line contains a single integer *n* from the problem's statement (1<=≤<=*n*<=≤<=10000). Output Specification: Print the sought expected number of tosses as an irreducible fraction in the following form: "*a*/*b*" (without the quotes) without leading zeroes. Demo Input: ['2\n', '3\n', '4\n'] Demo Output: ['1/1\n', '8/3\n', '2/1\n'] Note: none
```python """ 1/n = sum c_k 2^{-k} としたとき、n * sum kc_k2^{-k} が答 """ from fractions import Fraction def f(N): n = 0 while N % 2 == 0: N//=2 n+=1 if N==1: return Fraction(n,1) C = [] x = 1 while True: x = 2 * x C.append(x//N) x %= N if x == 1: break P = len(C) C = C[::-1] a = b = 0 for k, x in enumerate(C): a += x<<k b += ((P-k)*x)<<k x = Fraction(P*a,((1<<P)-1)**2) y = Fraction(b,(1<<P)-1) ANS = (x + y) * N ANS += n return ANS N = int(input()) ANS = f(N) print(f"{ANS.numerator}/{ANS.denominator}") ```
26
Parquet
Title: Parquet Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Bob decided to lay a parquet floor in his living room. The living room is of size *n*<=×<=*m* metres. Bob had planks of three types: *a* planks 1<=×<=2 meters, *b* planks 2<=×<=1 meters, and *c* planks 2<=×<=2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input Specification: The first input line contains 5 space-separated integer numbers *n*, *m*, *a*, *b*, *c* (1<=≤<=*n*,<=*m*<=≤<=100,<=0<=≤<=*a*,<=*b*,<=*c*<=≤<=104), *n* and *m* — the living room dimensions, *a*, *b* and *c* — amount of planks 1<=×<=2, 2<=×<=1 и 2<=×<=2 respectively. It's not allowed to turn the planks. Output Specification: If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room — output *n* lines with *m* lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Demo Input: ['2 6 2 2 1\n', '1 1 100 100 100\n', '4 4 10 10 10\n'] Demo Output: ['aabcca\naabdda\n', 'IMPOSSIBLE\n', 'aabb\naabb\nbbaa\nbbaa\n'] Note: none
```python n, m, a, b, c = map(int, input().split()) mat = [0]*n for i in range(n): mat[i] = [0] * m n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] z = ['d', 'e', 'f', 'g'] z1 = ['m', 'n', 'u', 'o'] z2 = ['p', 'q', 'r', 'w'] #print(n1) def fill(h, w): if h <= 0 or w <= 0: return True i = 0; j = 0 for k in range(3): while n1[k] > 0: #print(i, j, h, w) if k == 0: if i%4 and j%4: o = 3 elif i%4 and not j%4: o = 2 elif not i%4 and j%4: o = 1 else: o = 0 mat[i][j] = mat[i+1][j] = mat[i][j+1] = mat[i+1][j+1] = z[o]; if p[k] == 'a': if j%4: o = 2 else: o = 0 mat[i][j] = mat[i][j+1] = z1[o] mat[i+1][j] = mat[i+1][j+1] = z1[o+1]; elif p[k] == 'b': if i%4: o = 0 else: o = 2 mat[i][j] = mat[i+1][j] = z2[o] mat[i][j+1] = mat[i+1][j+1] = z2[o+1]; if k == 0: n1[k] -= 1 else: n1[k] -= 2 j += 2 if j >= w: i += 2 j = 0 if i >= h: return True return False def pmat(): for i in range(n): for j in range(m): print(mat[i][j], end='') print('\n', end='') def even(h, w): k1 = 0; k2 = 0 if n1[1] %2 == 1: n1[1] -= 1; k1 = 1 if n1[2] %2 == 1: n1[2] -= 1; k2 = 1 if fill(h, w): n1[1] += k1 n1[2] += k2 return True else: n1[1] += k1 n1[2] += k2 return False if n*m % 2 == 0: if n%2 == 0 and m%2 == 0: if even(n, m): pmat() else: print('IMPOSSIBLE') elif n%2 == 0 and m%2 != 0: n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] f = 'b' if even(n, m-1): for i in range(0, n, 2): mat[i][m-1] = f; mat[i+1][m-1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 else: if n1[2] >= 0: pmat() else: print('IMPOSSIBLE') else: print('IMPOSSIBLE') else: n1 = [min(n*m//4, c), min(n//2 * m, b), min(m//2 * n, a)] p = ['c', 'b', 'a'] f = 'a' if even(n-1, m): for i in range(0, m, 2): mat[n-1][i] = f; mat[n-1][i+1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 else: if n1[2] >= 0: pmat() else: print('IMPOSSIBLE') else: print('IMPOSSIBLE') elif n*m % 2 != 0: print('IMPOSSIBLE') ```
89
Space mines
Title: Space mines Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once upon a time in the galaxy of far, far away... Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star. When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — space mines. Let's describe a space mine's build. Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius *r* with the center in the point *O*. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point *P*, such that (transporting long-spiked mines is problematic), where |*OP*| is the length of the segment connecting *O* and *P*. It is convenient to describe the point *P* by a vector *p* such that *P*<==<=*O*<=+<=*p*. The Death Star is shaped like a ball with the radius of *R* (*R* exceeds any mine's radius). It moves at a constant speed along the *v* vector at the speed equal to |*v*|. At the moment the rebels noticed the Star of Death, it was located in the point *A*. The rebels located *n* space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines. Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed). Input Specification: The first input data line contains 7 integers *A**x*,<=*A**y*,<=*A**z*,<=*v**x*,<=*v**y*,<=*v**z*,<=*R*. They are the Death Star's initial position, the direction of its movement, and its radius (<=-<=10<=≤<=*v**x*,<=*v**y*,<=*v**z*<=≤<=10, |*v*|<=&gt;<=0, 0<=&lt;<=*R*<=≤<=100). The second line contains an integer *n*, which is the number of mines (1<=≤<=*n*<=≤<=100). Then follow *n* data blocks, the *i*-th of them describes the *i*-th mine. The first line of each block contains 5 integers *O**ix*,<=*O**iy*,<=*O**iz*,<=*r**i*,<=*m**i*, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0<=&lt;<=*r**i*<=&lt;<=100,<=0<=≤<=*m**i*<=≤<=10). Then follow *m**i* lines, describing the spikes of the *i*-th mine, where the *j*-th of them describes the *i*-th spike and contains 3 integers *p**ijx*,<=*p**ijy*,<=*p**ijz* — the coordinates of the vector where the given spike is directed (). The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that *R*<=&gt;<=*r**i* for any 1<=≤<=*i*<=≤<=*n*. For any mines *i*<=≠<=*j* the following inequality if fulfilled: . Initially the Death Star and the mines do not have common points. Output Specification: If the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast. If the Death Star will not touch a mine, print "-1" (without quotes). For the answer the absolute or relative error of 10<=-<=6 is acceptable. Demo Input: ['0 0 0 1 0 0 5\n2\n10 8 0 2 2\n0 -3 0\n2 2 0\n20 0 0 4 3\n2 4 0\n-4 3 0\n1 -5 0\n', '8 8 4 4 4 2 6\n1\n-2 -2 -1 3 0\n', '30 30 2 1 2 1 20\n3\n0 0 40 5 1\n1 4 4\n-10 -40 -5 7 0\n100 200 95 8 1\n-10 0 0\n'] Demo Output: ['10.0000000000', '-1', '74.6757620881'] Note: none
```python import sys, math def dist(a,b): return pow((a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2,0.5) def vxv(v1,v2): x = -v1[2] * v2[1] + v1[1] * v2[2] y = -v1[0] * v2[2] + v1[2] * v2[0] z = -v1[1] * v2[0] + v1[0] * v2[1] return (x,y,z) readline = sys.stdin.readline s1,s2,s3,v1,v2,v3,R = map(int,readline().split()) n = int(readline()) pm = [] p = [] for _ in range(n): o1,o2,o3,r,m = map(int,readline().split()) p.append((o1,o2,o3,r)) for _ in range(m): pm1,pm2,pm3 = map(int,readline().split()) pm.append((pm1 + o1, pm2 + o2, pm3 + o3)) nv = (v1,v2,v3) m = (s1,s2,s3) distance = [] for x in pm: tp = (x[0] - m[0], x[1] - m[1], x[2] - m[2]) tp1 = vxv(tp,nv) d = dist(tp1,(0,0,0))/dist(nv,(0,0,0)) if d <= R: dd = pow(dist(x,m)**2-d**2,0.5) dnv = dist(nv, (0, 0, 0)) nnv = (dd * nv[0] / dnv + m[0], dd * nv[1] / dnv + m[1], dd * nv[2] / dnv + m[2]) if dist(nnv, x) < dist(x, m): distance.append(dd - pow(R**2 - d**2,0.5)) for i in range(len(p)): pi =(p[i][0],p[i][1],p[i][2]) tp = (pi[0] - m[0], pi[1] - m[1], pi[2] - m[2]) tp1 = vxv(tp,nv) d = dist(tp1,(0,0,0))/dist(nv,(0,0,0)) if d - p[i][3] <= R: dd = pow(dist(pi,m)**2-d**2,0.5) dnv = dist(nv,(0,0,0)) nnv = (dd * nv[0]/dnv + m[0], dd * nv[1]/dnv + m[1],dd * nv[2]/dnv + m[2]) if dist(nnv,p[i]) < dist(p[i],m): dr = pow((R + p[i][3])**2 - d**2,0.5) distance.append(dd - dr) if len(distance): distance.sort() print(distance[0]/dist(nv,(0,0,0))) else: print(-1)# 1692608648.734028 ```
24
Broken robot
Title: Broken robot Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of *N* rows and *M* columns of cells. The robot is initially at some cell on the *i*-th row and the *j*-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost (*N*-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row. Input Specification: On the first line you will be given two space separated integers *N* and *M* (1<=≤<=*N*,<=*M*<=≤<=1000). On the second line you will be given another two space separated integers *i* and *j* (1<=≤<=*i*<=≤<=*N*,<=1<=≤<=*j*<=≤<=*M*) — the number of the initial row and the number of the initial column. Note that, (1,<=1) is the upper left corner of the board and (*N*,<=*M*) is the bottom right corner. Output Specification: Output the expected number of steps on a line of itself with at least 4 digits after the decimal point. Demo Input: ['10 10\n10 4\n', '10 14\n5 14\n'] Demo Output: ['0.0000000000\n', '18.0038068653\n'] Note: none
```python from functools import cache N, M = [int(w) for w in input().split()] r, c = [int(w) for w in input().split()] # print(N, M, r, c) # @cache def calc(r: int, c: int) -> float: if r == N: return 0 e, a, b = [0.] * M, [0.] * M, [0.] * M for l in range(N - 1, r - 1, -1): a[0], b[0] = 0.5, 0.5*(3 + e[0]) for k in range(1, M -1): a[k] = 1 / (3 - a[k - 1]) b[k] = a[k] * (b[k - 1] + 4 + e[k]) e[-1] = (3 + b[-2] + e[-1])/(2 - a[-2]) for k in range(M - 2, -1, -1): e[k] = a[k] * e[k + 1] + b[k] return e[c] if M == 1: print(2.0 * (N - r)) else: print(calc(r, c - 1)) ```
45
Planting Trees
Title: Planting Trees Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into *n*<=×<=*m* squares and decided to plant a forest there. Vasya will plant *nm* trees of all different heights from 1 to *nm*. For his forest to look more natural he wants any two trees growing in the side neighbouring squares to have the absolute value of difference in heights to be strictly more than 1. Help Vasya: make the plan of the forest planting for which this condition is fulfilled. Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100) — the number of rows and columns on Vasya's field Output Specification: If there's no solution, print -1. Otherwise, print *n* lines containing *m* numbers each — the trees' planting plan. In every square of the plan the height of a tree that should be planted on this square should be written. If there are several solutions to that problem, print any of them. Demo Input: ['2 3\n', '2 1\n'] Demo Output: ['3 6 2\n5 1 4\n', '-1\n'] Note: none
```python n, m = map(int, input().split()) def solve0(n, m): swapped = False if n < m: n, m = m, n swapped = True ret = solve(n, m) new_ret = [[0 for i in range(n)] for j in range(m)] if swapped and ret != -1: for i in range(m): for j in range(n): new_ret[i][j] = ret[j][i] ret = new_ret return ret def solve(n, m): if m == 1 and n == 4: return [[3], [1], [4], [2]] if m == 2 and n == 3: return [[5, 3], [1, 6], [4, 2]] field = [[0 for i in range(m)] for j in range(n)] def adv(i, j): j += 1 if j == m: j = 0 i += 1 return i, j def arrange(vals0, vals1): i, j = 0, 0 for val in vals0: field[i][j] = val i, j = adv(i, j) for val in vals1: field[i][j] = val i, j = adv(i, j) good = True for i in range(n): for j in range(m): if i + 1 < n: good &= abs(field[i + 1][j] - field[i][j]) > 1 if j + 1 < m: good &= abs(field[i][j + 1] - field[i][j]) > 1 return good all_odd = list(range(1, n * m + 1, 2)) all_even = list(range(2 , n * m + 1, 2)) g = arrange(all_odd, all_even) if g: return field all_odd = all_odd[::-1] if g: return field all_even = all_even[::-1] if g: return field all_odd = all_odd[::-1] if g: return field return -1; ret = solve0(n, m) if ret == -1: print(ret) else: for x in ret: print(' '.join(map(str, x))) ```
106
Buns
Title: Buns Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Lavrenty, a baker, is going to make several buns with stuffings and sell them. Lavrenty has *n* grams of dough as well as *m* different stuffing types. The stuffing types are numerated from 1 to *m*. Lavrenty knows that he has *a**i* grams left of the *i*-th stuffing. It takes exactly *b**i* grams of stuffing *i* and *c**i* grams of dough to cook a bun with the *i*-th stuffing. Such bun can be sold for *d**i* tugriks. Also he can make buns without stuffings. Each of such buns requires *c*0 grams of dough and it can be sold for *d*0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking. Find the maximum number of tugriks Lavrenty can earn. Input Specification: The first line contains 4 integers *n*, *m*, *c*0 and *d*0 (1<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=10, 1<=≤<=*c*0,<=*d*0<=≤<=100). Each of the following *m* lines contains 4 integers. The *i*-th line contains numbers *a**i*, *b**i*, *c**i* and *d**i* (1<=≤<=*a**i*,<=*b**i*,<=*c**i*,<=*d**i*<=≤<=100). Output Specification: Print the only number — the maximum number of tugriks Lavrenty can earn. Demo Input: ['10 2 2 1\n7 3 2 100\n12 3 1 10\n', '100 1 25 50\n15 5 20 10\n'] Demo Output: ['241', '200'] Note: To get the maximum number of tugriks in the first sample, you need to cook 2 buns with stuffing 1, 4 buns with stuffing 2 and a bun without any stuffing. In the second sample Lavrenty should cook 4 buns without stuffings.
```python import sys N = 1010 a = [0]*N b = [0]*N c = [0]*N d = [0]*N f = [0]*N n, m, x, y = map(int, sys.stdin.readline().split()) for i in range(1, m+1): a[i], b[i], c[i], d[i] = map(int, sys.stdin.readline().split()) m += 1 a[m] = 10**9 b[m] = 1 c[m] = x d[m] = y for i in range(1, m+1): for j in range(n, 0, -1): for k in range(min(j // c[i], a[i] // b[i])+1): f[j] = max(f[j], f[j - k * c[i]] + k * d[i]) print(f[n]) ```
111
Petya and Spiders
Title: Petya and Spiders Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Petya loves training spiders. Petya has a board *n*<=×<=*m* in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second. Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=40,<=*n*·*m*<=≤<=40) — the board sizes. Output Specification: In the first line print the maximum number of cells without spiders. Demo Input: ['1 1\n', '2 3\n'] Demo Output: ['0\n', '4\n'] Note: In the first sample the only possible answer is: s In the second sample one of the possible solutions is: s denotes command "stay idle", l, r, d, u denote commands "crawl left", "crawl right", "crawl down", "crawl up", correspondingly.
```python maxn = 7 d = [[-1 for _ in range(1 << (2 * maxn))] for _ in range(57)] nbits = [0] * 100500 def ok(x, x3): x2 = (x & ((1 << m) - 1)) x >>= m x1 = x x = 0 x |= x1 x |= x2 x |= (x2 << 1) x |= (x2 >> 1) x |= x3 return (x & ((1 << m) - 1)) == ((1 << m) - 1) for i in range(1 << (2 * maxn)): x, y = i, 0 while x: y += x % 2 x //= 2 nbits[i] = y n, m = map(int, input().split()) if n < m: n, m = m, n for mask in range(1 << m): d[0][mask] = m - nbits[mask] for i in range(n - 1): for mask in range(1 << (2 * m)): if d[i][mask] == -1: continue for nm in range(1 << m): if ok(mask, nm): x = d[i][mask] + m - nbits[nm] msk = ((mask & ((1 << m) - 1)) << m) + nm d[i + 1][msk] = max(d[i + 1][msk], x) res = 0 for i in range(1 << (2 * m)): if d[n - 1][i] != -1 and ok(i, 0): res = max(res, d[n - 1][i]) print(res)# 1691433031.1881988 ```
85
Domino
Title: Domino Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: We all know the problem about the number of ways one can tile a 2<=×<=*n* field by 1<=×<=2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes. You are given a 4<=×<=*n* rectangular field, that is the field that contains four lines and *n* columns. You have to find for it any tiling by 1<=×<=2 dominoes such that each of the *n*<=-<=1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2<=×<=1 as well as 1<=×<=2 dominoes. Write a program that finds an arbitrary sought tiling. Input Specification: The input contains one positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of the field's columns. Output Specification: If there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing *n* characters each — that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling. Demo Input: ['4\n'] Demo Output: ['yyzz\nbccd\nbxxd\nyyaa\n'] Note: none
```python import sys input = sys.stdin.readline n = int(input()) if n % 2: x1 = ('aacc' * n)[:n-1] x2 = ('ccaa' * n)[:n-1] x3 = ('bbdd' * n)[:n-1] x4 = ('ddbb' * n)[:n-1] print(x1+'e') print(x2+'e') print('f'+x3) print('f'+x4) else: x1 = ('aacc' * n)[:n] x2 = ('ccaa' * n)[:n] x3 = ('bbdd' * n)[:n-2] x4 = ('ddbb' * n)[:n-2] print(x1) print(x2) print('e'+x3+'f') print('e'+x4+'f') ```
9
Hexadecimal's Numbers
Title: Hexadecimal's Numbers Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of *n* different natural numbers from 1 to *n* to obtain total control over her energy. But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully. Input Specification: Input data contains the only number *n* (1<=≤<=*n*<=≤<=109). Output Specification: Output the only number — answer to the problem. Demo Input: ['10\n'] Demo Output: ['2'] Note: For *n* = 10 the answer includes numbers 1 and 10.
```python class solve: def __init__(self): n=int(input()) ans=0 for i in range(1,2**10-1): b=int(bin(i).replace("0b",'0')) if b<=n: ans+=1 else: break print(ans) obj=solve() ```
11
Jumping Jack
Title: Jumping Jack Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point *x*. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach *x*. Input Specification: The input data consists of only one integer *x* (<=-<=109<=≤<=*x*<=≤<=109). Output Specification: Output the minimal number of jumps that Jack requires to reach *x*. Demo Input: ['2\n', '6\n', '0\n'] Demo Output: ['3\n', '3\n', '0\n'] Note: none
```python n = int(input()) if not n: print(0); exit() n = abs(n) a = int(((8*n-7)**.5-1)/2)+1 while (a*(a+1)//2-n)&1: a += 1 print(a) ```
3
Tic-tac-toe
Title: Tic-tac-toe Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3<=×<=3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced. You are given a 3<=×<=3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below: - illegal — if the given board layout can't appear during a valid game; - the first player won — if in the given board layout the first player has just won; - the second player won — if in the given board layout the second player has just won; - draw — if the given board layout has just let to a draw. Input Specification: The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero). Output Specification: Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw. Demo Input: ['X0X\n.0.\n.X.\n'] Demo Output: ['second\n'] Note: none
```python a,b,c=input(),input(),input() players=["first","second"] nx=(a+b+c).count('X') no=(a+b+c).count('0') d=nx-no s=[a,b,c,a[0]+b[1]+c[2],a[2]+b[1]+c[0]]+list(map(''.join,zip(a,b,c))) w=('XXX' in s)+2*('000' in s)-1 if(d not in (0,1)) or w>1 or d==w: print('illegal') elif(w>=0): print('the '+players[w]+' player won') elif nx+no==9: print('draw') else: print(players[d]) ```
7
Memory Manager
Title: Memory Manager Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: - alloc n — to allocate *n* bytes of the memory and return the allocated block's identifier *x*; - erase x — to erase the block with the identifier *x*; - defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of *m* bytes, numbered for convenience from the first to the *m*-th. The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of *n* successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL. The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT. The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order. In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration. You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands. Input Specification: The first line of the input data contains two positive integers *t* and *m* (1<=≤<=*t*<=≤<=100;1<=≤<=*m*<=≤<=100), where *t* — the amount of operations given to the memory manager for processing, and *m* — the available memory size in bytes. Then there follow *t* lines where the operations themselves are given. The first operation is alloc n (1<=≤<=*n*<=≤<=100), where *n* is an integer. The second one is erase x, where *x* is an arbitrary 32-bit integer numerical token. The third operation is defragment. Output Specification: Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks. Demo Input: ['6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n'] Demo Output: ['1\n2\nNULL\n3\n'] Note: none
```python t, m =map(int, input().split()) alocuente = [0]*m ind =1 for i in range(t): op=input().split() if op[0]=='alloc': pos=0 for j in range(m): if alocuente[j]==0: pos += 1 if pos == int(op[1]): alocuente[j-int(op[1])+1:j+1]=[ind]*int(op[1]) print(ind) ind+=1 break else: pos=0 else: print("NULL") if op[0]=='erase': pos=0 if int(op[1]) not in alocuente or int (op[1])==0: print('ILLEGAL_ERASE_ARGUMENT') else: for j in range(m): if int(op[1])>0 and alocuente[j]==int(op[1]): alocuente[j]=0 if op[0] =="defragment": cnt=0 cnt=alocuente.count(0) alocuente=[j for j in alocuente if j !=0] for j in range(cnt): alocuente.append(0) ```
5
Follow Traffic Rules
Title: Follow Traffic Rules Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of *a* km/h2, and has maximum speed of *v* km/h. The road has the length of *l* km, and the speed sign, limiting the speed to *w* km/h, is placed *d* km (1<=≤<=*d*<=&lt;<=*l*) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input Specification: The first line of the input file contains two integer numbers *a* and *v* (1<=≤<=*a*,<=*v*<=≤<=10000). The second line contains three integer numbers *l*, *d* and *w* (2<=≤<=*l*<=≤<=10000; 1<=≤<=*d*<=&lt;<=*l*; 1<=≤<=*w*<=≤<=10000). Output Specification: Print the answer with at least five digits after the decimal point. Demo Input: ['1 1\n2 1 3\n', '5 70\n200 170 40\n'] Demo Output: ['2.500000000000\n', '8.965874696353\n'] Note: none
```python a,v=map(int,input().split()) l,d,w=map(int,input().split()) def p(v0,v,w,d,a): b=2*a*d+w**2 S=(b-v0**2)/4/a r=[[0,d],[0,0,0],v] V1=(2*a*S+v0**2)**.5 if S < d and v >= V1: return([(V1-v0+V1-w)/a],w) else: S=(v**2-v0**2)/2/a if S <= d: r[0][0]=S r[1][0]=(v-v0)/a else: V1=(2*a*d+v0**2)**.5 return ([(V1-v0)/a],V1) S=(b-v**2)/2/a if S < d: r[0][1]=S r[1][2]=(v-w)/a r[2]=w r[1][1]=(r[0][1]-r[0][0])/v return([r[1],r[2]]) c=p(0, v, w, d, a) print(sum(c[0]+p(c[1],v,v,l-d,a)[0])) ```
9
How many trees?
Title: How many trees? Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game... For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this. However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User. This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with *n* nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to *n*. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf). In Hexadecimal's game all the trees are different, but the height of each is not lower than *h*. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you? Input Specification: The input data contains two space-separated positive integer numbers *n* and *h* (*n*<=≤<=35, *h*<=≤<=*n*). Output Specification: Output one number — the answer to the problem. It is guaranteed that it does not exceed 9·1018. Demo Input: ['3 2\n', '3 3\n'] Demo Output: ['5', '4'] Note: none
```python def solve(n, h): v = [[0] * 40 for _ in range(40)] for i in range(n + 1): v[0][i] = 1 for i in range(1, n + 1): for j in range(1, n + 1): for k in range(i): v[i][j] += v[k][j - 1] * v[i - k - 1][j - 1] print(v[n][n] - v[n][h - 1]) def main(): n, h = map(int, input().split()) solve(n,h) main() ```
32
Hide-and-Seek
Title: Hide-and-Seek Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Victor and Peter are playing hide-and-seek. Peter has hidden, and Victor is to find him. In the room where they are playing, there is only one non-transparent wall and one double-sided mirror. Victor and Peter are points with coordinates (*x**v*,<=*y**v*) and (*x**p*,<=*y**p*) respectively. The wall is a segment joining points with coordinates (*x**w*,<=1,<=*y**w*,<=1) and (*x**w*,<=2,<=*y**w*,<=2), the mirror — a segment joining points (*x**m*,<=1,<=*y**m*,<=1) and (*x**m*,<=2,<=*y**m*,<=2). If an obstacle has a common point with a line of vision, it's considered, that the boys can't see each other with this line of vision. If the mirror has a common point with the line of vision, it's considered, that the boys can see each other in the mirror, i.e. reflection takes place. The reflection process is governed by laws of physics — the angle of incidence is equal to the angle of reflection. The incident ray is in the same half-plane as the reflected ray, relative to the mirror. I.e. to see each other Victor and Peter should be to the same side of the line, containing the mirror (see example 1). If the line of vision is parallel to the mirror, reflection doesn't take place, and the mirror isn't regarded as an obstacle (see example 4). Victor got interested if he can see Peter, while standing at the same spot. Help him solve this problem. Input Specification: The first line contains two numbers *x**v* and *y**v* — coordinates of Victor. The second line contains two numbers *x**p* and *y**p* — coordinates of Peter. The third line contains 4 numbers *x**w*,<=1, *y**w*,<=1, *x**w*,<=2, *y**w*,<=2 — coordinates of the wall. The forth line contains 4 numbers *x**m*,<=1, *y**m*,<=1, *x**m*,<=2, *y**m*,<=2 — coordinates of the mirror. All the coordinates are integer numbers, and don't exceed 104 in absolute value. It's guaranteed, that the segments don't have common points, Victor and Peter are not on any of the segments, coordinates of Victor and Peter aren't the same, the segments don't degenerate into points. Output Specification: Output YES, if Victor can see Peter without leaving the initial spot. Otherwise output NO. Demo Input: ['-1 3\n1 3\n0 2 0 4\n0 0 0 1\n', '0 0\n1 1\n0 1 1 0\n-100 -100 -101 -101\n', '0 0\n1 1\n0 1 1 0\n-1 1 1 3\n', '0 0\n10 0\n100 100 101 101\n1 0 3 0\n'] Demo Output: ['NO\n', 'NO\n', 'YES\n', 'YES\n'] Note: none
```python xv,yv=list(map(int,input().split())) xp,yp=list(map(int,input().split())) xw1,yw1,xw2,yw2=list(map(int,input().split())) xm1,ym1,xm2,ym2=list(map(int,input().split())) def a(x1,y1,x2,y2,x3,y3,x4,y4): if x1==x2: if x3==x4: return False else: k2=(y3-y4)/(x3-x4) b2=y3-k2*x3 return min(y3,y4)<=k2*x1+b2<=max(y3,y4) and min(y1,y2)<=k2*x1+b2<=max(y1,y2) and min(x3,x4)<=x1<=max(x3,x4) and min(x1,x2)<=x1<=max(x1,x2) else: if x3==x4: k1=(y1-y2)/(x1-x2) b1=y1-k1*x1 return min(y3,y4)<=k1*x3+b1<=max(y3,y4) and min(y1,y2)<=k1*x3+b1<=max(y1,y2) and min(x3,x4)<=x3<=max(x3,x4) and min(x1,x2)<=x3<=max(x1,x2) else: k1=(y1-y2)/(x1-x2) b1=y1-k1*x1 k2=(y3-y4)/(x3-x4) b2=y3-k2*x3 if k1==k2: return b1==b2 and min(x1,x2)<=min(x3,x4)<=max(x1,x2) and min(y1,y2)<=min(y3,y4)<=max(y1,y2) x=(b2-b1)/(k1-k2) y=k1*x+b1 return min(y3,y4)<=y<=max(y3,y4) and min(y1,y2)<=y<=max(y1,y2) and min(x3,x4)<=x<=max(x3,x4) and min(x1,x2)<=x<=max(x1,x2) def b(xm1,xm2,ym1,ym2,x,y): if ym1==ym2: xi=x yi=2*ym1-y elif xm1==xm2: yi=y xi=2*xm1-x else: k1=-(xm1-xm2)/(ym1-ym2) b1=y-k1*x k2=(ym1-ym2)/(xm1-xm2) b2=ym1-k2*xm1 x1=(b2-b1)/(k1-k2) xi=2*x1-x yi=k1*xi+b1 return [xi,yi] xw3,yw3=b(xm1,xm2,ym1,ym2,xw1,yw1) xw4,yw4=b(xm1,xm2,ym1,ym2,xw2,yw2) if a(xv,yv,xp,yp,xw1,yw1,xw2,yw2) or a(xv,yv,xp,yp,xm1,ym1,xm2,ym2): xip,yip=b(xm1,xm2,ym1,ym2,xp,yp) if [xip,yip]!=[xv,yv] and a(xv,yv,xip,yip,xm1,ym1,xm2,ym2) and not(a(xv,yv,xip,yip,xw1,yw1,xw2,yw2)) and not(a(xv,yv,xip,yip,xw3,yw3,xw4,yw4)): print('YES') else: print('NO') else: print('YES') ```
74
Chessboard Billiard
Title: Chessboard Billiard Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving. More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed. It is considered that one billiard ball *a* beats another billiard ball *b* if *a* can reach a point where *b* is located. You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard *n*<=×<=*m* in size. Input Specification: The first line contains two integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=106). Output Specification: Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator). Demo Input: ['3 4\n', '3 3\n'] Demo Output: ['2', '3'] Note: none
```python import math x, y = map(int, input().split()) x -= 1; y -= 1 print(math.gcd(x, y)+1) ```
49
Disposition
Title: Disposition Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya bought the collected works of a well-known Berland poet Petya in *n* volumes. The volumes are numbered from 1 to *n*. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers *i* such that for at least one *j* (1<=≤<=*j*<=≤<=*n*) is true both: *j* *mod* *i*<==<=0 and at the same time *p*(*j*) *mod* *i*<==<=0, where *p*(*j*) is the number of the tome that stands on the *j*-th place and *mod* is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume. Help Vasya — find the volume disposition with the minimum number of divisors. Input Specification: The first line contains number *n* (1<=≤<=*n*<=≤<=100000) which represents the number of volumes and free places. Output Specification: Print *n* numbers — the sought disposition with the minimum divisor number. The *j*-th number (1<=≤<=*j*<=≤<=*n*) should be equal to *p*(*j*) — the number of tome that stands on the *j*-th place. If there are several solutions, print any of them. Demo Input: ['2\n', '3\n'] Demo Output: ['2 1 \n', '1 3 2 \n'] Note: none
```python import sys input = sys.stdin.readline n = int(input()) print(str(n) + ' ' + ' '.join([str(i) for i in range(1, n)])) ```
8
Train and Peter
Title: Train and Peter Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input Specification: The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Specification: Output one of the four words without inverted commas: - «forward» — if Peter could see such sequences only on the way from A to B; - «backward» — if Peter could see such sequences on the way from B to A; - «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; - «fantasy» — if Peter could not see such sequences. Demo Input: ['atob\na\nb\n', 'aaacaaa\naca\naa\n'] Demo Output: ['forward\n', 'both\n'] Note: It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
```python # LUOGU_RID: 119299363 w = input() a = input() b = input() v = n = 0 if (w.find(a)!=-1 and w.find(a) <= w.rfind(b)-len(a)): v = 1 w = w[::-1] if (w.find(a)!=-1 and w.find(a) <= w.rfind(b)-len(a)): n = 1 if v and n: print("both") elif v: print("forward") elif n: print("backward") else: print("fantasy") ```
54
Writing a Song
Title: Writing a Song Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names. The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song! The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first *K* letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word). The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name *P*, the length *N* of the required word, the given positions of the occurrences of the name *P* in the desired word and the alphabet's size *K*. Note that the occurrences of the name can overlap with each other. Input Specification: The first line contains numbers *N* and *K* which are the length of the required string and the alphabet size accordingly. The limitations are: 1<=≤<=*N*<=≤<=100, 2<=≤<=*K*<=≤<=26. The second line contains the name *P* which is a non-empty string whose length does not exceed *N* characters. The string consists only of the first *K* lowercase symbols of an English alphabet. The third line contains the string of length *N*<=-<=*length*(*P*)<=+<=1, consisting only of numbers zero and one. A number one in the *i*-th position means that an occurrence of the name *P* should start from *i*-th position of the desired word, while a zero means that there is no occurrence starting here. Output Specification: Print the desired word *S*. If there are several answers, print any of them. If there is no solution, then print "No solution". Demo Input: ['5 2\naba\n101\n', '5 2\na\n10001\n', '6 2\nabba\n101\n'] Demo Output: ['ababa', 'abbba', 'No solution'] Note: none
```python n, k = map(int, input().split()) p = input() a = input() res = ['0'] * n def m(tmp): return chr(ord('a') + k // 2) if tmp == 'a' else 'a' for i in range(len(a)): if a[i] == '1': l = i for j in range(len(p)): res[l] = p[j] l += 1 for i in range(len(a)): if a[i] == '1': l = i for j in range(len(p)): if res[l] != p[j]: print("No solution") exit() l += 1 for i in range(len(a)): if a[i] == '0': l = i ok = False cnt = 0 for j in range(len(p)): if res[l] == '0': res[l] = m(p[j]) ok = True break else: if res[l] != p[j]: ok = True break else: cnt += 1 l += 1 if not ok and cnt == len(p): print("No solution") exit() x = 'b' if p[0] == 'a' else 'a' print(''.join([x if c == '0' else c for c in res])) ###from Jasnah bobb31 ###from Jasnah bobb31 ###from Jasnah bobb31 ###from Jasnah bobb31 ```
5
Center Alignment
Title: Center Alignment Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input Specification: The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. Output Specification: Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. Demo Input: ['This is\n\nCodeforces\nBeta\nRound\n5\n', 'welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck\n'] Demo Output: ['************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************\n', '****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************\n'] Note: none
```python from sys import stdin lines = [] for line in stdin: lines.append(line.strip()) n = max(len(line) for line in lines) print('*' * (n+2)) f = 0 for line in lines: print('*', end='') if len(line) % 2 == n % 2: print(' ' * ((n - len(line))//2), line, ' ' * ((n - len(line))//2), '*', sep='') elif f: print(' ' * ((n - len(line))//2 + 1), line, ' ' * ((n - len(line))//2), '*', sep='') f = 0 else: print(' ' * ((n - len(line))//2), line, ' ' * ((n - len(line))//2 + 1), '*', sep='') f = 1 print('*' * (n+2)) ```
65
Harry Potter and the Sorting Hat
Title: Harry Potter and the Sorting Hat Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter. At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones — to Ravenclaw, the persistent and honest ones — to Hufflepuff and the clever and cunning ones — to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far. Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione. Input Specification: The first input line contains an integer *n* (1<=≤<=*n*<=≤<=10000). It is the number of students who are in the list before Hermione. The next line contains *n* symbols. If all the relatives of a student used to study in the same house, then the *i*-th character in the string coincides with the first letter of the name of this house. Otherwise, the *i*-th symbol is equal to "?". Output Specification: Print all the possible houses where Hermione can be sent. The names of the houses should be printed in the alphabetical order, one per line. Demo Input: ['11\nG????SS???H\n', '2\nH?\n'] Demo Output: ['Gryffindor\nRavenclaw\n', 'Gryffindor\nRavenclaw\nSlytherin\n'] Note: Consider the second example. There are only two students before Hermione. The first student is sent to Hufflepuff. The second disciple is given the choice between the houses where the least number of students has been sent, i.e. Gryffindor, Slytherin and Ravenclaw. If he chooses Gryffindor, Hermione is forced to choose between Ravenclaw and Slytherin, if he chooses Ravenclaw, Hermione will choose between Gryffindor and Slytherin, if he chooses Slytherin, Hermione will choose between Gryffindor and Ravenclaw. In the end, the following situation is possible (it depends on the choice of the second student and Hermione). Hermione will end up 1) in Gryffindor, 2) in Ravenclaw, 3) in Slytherin. Note that, despite the fact that in neither case Hermione will be given a choice between all the three options, they are all possible and they should all be printed in the answer. Hermione will not, under any circumstances, end up in Hufflepuff.
```python n = input() inputs = input() first_letter_to_index = { 'G': 0, 'H': 1, 'R': 2, 'S': 3 } pos = {(0, 0, 0, 0)} # call possibilities for first_letter in inputs: size = len(pos) new_pos = [] if first_letter in first_letter_to_index: idx = first_letter_to_index[first_letter] for p in pos: clone = list(p) clone[idx] += 1 new_pos.append(tuple(clone)) else: for p in pos: least = min(p) index_least = [i for i, x in enumerate(p) if x == least] for index in index_least: clone = list(p) clone[index] += 1 new_pos.append(tuple(clone)) pos = set(new_pos) res = set() for p in pos: least = min(p) index_least = [i for i, x in enumerate(p) if x == least] res.update(index_least) full_houses = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'] print('\n'.join([full_houses[idx] for idx in sorted(list(res))])) ```
13
Sequence
Title: Sequence Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of *N* integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence *a* is called non-decreasing if *a*1<=≤<=*a*2<=≤<=...<=≤<=*a**N* holds, where *N* is the length of the sequence. Input Specification: The first line of the input contains single integer *N* (1<=≤<=*N*<=≤<=5000) — the length of the initial sequence. The following *N* lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value. Output Specification: Output one integer — minimum number of steps required to achieve the goal. Demo Input: ['5\n3 2 -1 2 11\n', '5\n2 1 1 1 1\n'] Demo Output: ['4\n', '1\n'] Note: none
```python import heapq input() ans=0 a=[] inf=10**9 for x in map(int,input().split()): x=inf-x heapq.heappush(a,x) ans+=a[0]-x heapq.heappop(a) heapq.heappush(a,x) print(-ans) ```
37
Computer Game
Title: Computer Game Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place. While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level: 1) The boss has two parameters: *max* — the initial amount of health and *reg* — regeneration rate per second. 2) Every scroll also has two parameters: *pow**i* — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than *pow**i* percent of health the scroll cannot be used); and *dmg**i* the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts *dmg**i* of damage per second upon him until the end of the game. During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates *reg* of health (at the same time he can’t have more than *max* of health), then the player may use another scroll (no more than one per second). The boss is considered to be defeated if at the end of a second he has nonpositive (<=≤<=0) amount of health. Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it. Input Specification: The first line contains three integers *N*, *max* and *reg* (1<=≤<=*N*,<=*max*,<=*reg*<=≤<=1000) –– the amount of scrolls and the parameters of the boss. The next *N* lines contain two integers *pow**i* and *dmg**i* each — the parameters of the *i*-th scroll (0<=≤<=*pow**i*<=≤<=100, 1<=≤<=*dmg**i*<=≤<=2000). Output Specification: In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated. Demo Input: ['2 10 3\n100 3\n99 1\n', '2 100 10\n100 11\n90 9\n'] Demo Output: ['NO\n', 'YES\n19 2\n0 1\n10 2\n'] Note: none
```python n, max_val, reg = map(int, input().split()) pow_vals = [0] * (n + 1) dmg_vals = [0] * (n + 1) for i in range(1, n + 1): pow_vals[i], dmg_vals[i] = map(int, input().split()) used = [False] * (n + 1) cur = max_val tot = 0 ans = -1 m = 0 a = [0] * (n + 1) b = [0] * (n + 1) for it in range(10001): cur = cur - tot + reg if cur <= 0: ans = it break if cur > max_val: cur = max_val mn = 0 km = 0 for i in range(1, n + 1): if not used[i] and cur * 100 <= pow_vals[i] * max_val: if dmg_vals[i] > mn: mn = dmg_vals[i] km = i if km > 0: m += 1 a[m] = it b[m] = km tot += mn used[km] = True if ans == -1: print('NO') else: print('YES') print(ans, m) for i in range(1, m + 1): print(a[i], b[i])# 1691499045.4562871 ```
102
Clothes
Title: Clothes Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap. Overall the shop sells *n* clothing items, and exactly *m* pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend. Input Specification: The first input file line contains integers *n* and *m* — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the prices of the clothing items in rubles. Next *m* lines each contain a pair of space-separated integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=*u**i*<=≠<=*v**i*). Each such pair of numbers means that the *u**i*-th and the *v**i*-th clothing items match each other. It is guaranteed that in each pair *u**i* and *v**i* are distinct and all the unordered pairs (*u**i*,<=*v**i*) are different. Output Specification: Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes). Demo Input: ['3 3\n1 2 3\n1 2\n2 3\n3 1\n', '3 2\n2 3 4\n2 3\n2 1\n', '4 4\n1 1 1 1\n1 2\n2 3\n3 4\n4 1\n'] Demo Output: ['6\n', '-1\n', '-1\n'] Note: In the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles. The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1. In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) G = [[0] * (n + 1) for _ in range(n + 1)] a = [0] + list(map(int, input().split())) for _ in range(m): u, v = map(int, input().split()) G[u][v] = 1 G[v][u] = 1 inf = pow(10, 9) + 1 ans = inf for i in range(1, n + 1): for j in range(i + 1, n + 1): if not G[i][j]: continue s = a[i] + a[j] if s > ans: continue for k in range(j + 1, n + 1): if G[i][k] and G[j][k]: ans = min(ans, s + a[k]) ans = (ans + 1) % (inf + 1) - 1 print(ans) ```
87
Vasya and Types
Title: Vasya and Types Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Programmer Vasya is studying a new programming language &amp;K*. The &amp;K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages. There is a very powerful system of pointers on &amp;K* — you can add an asterisk to the right of the existing type *X* — that will result in new type *X*<=*<=. That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of *X*, which is a pointer, you can add an ampersand — that will result in a type &amp;*X*, to which refers *X*. That is called a dereference operation. The &amp;K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof. - The operator "typedef *A* *B*" defines a new data type *B*, which is equivalent to *A*. *A* can have asterisks and ampersands, and *B* cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.- The operator "typeof *A*" returns type of *A*, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**. An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*<==<=&amp;errtype<==<=errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype. Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change. Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &amp;*T*<=*<= is always equal to *T*. Note, that the operators are executed consecutively one by one. If we have two operators "typedef &amp;void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &amp;void* = void (see sample 2). Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of operators. Then follow *n* lines with operators. Each operator is of one of two types: either "typedef *A* *B*", or "typeof *A*". In the first case the *B* type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands. All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10. Output Specification: For every typeof operator print on the single line the answer to that operator — the type that the given operator returned. Demo Input: ['5\ntypedef void* ptv\ntypeof ptv\ntypedef &amp;&amp;ptv node\ntypeof node\ntypeof &amp;ptv\n', '17\ntypedef void* b\ntypedef b* c\ntypeof b\ntypeof c\ntypedef &amp;b b\ntypeof b\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\ntypedef &amp;b* c\ntypeof c\ntypedef &amp;void b\ntypeof b\ntypedef b******* c\ntypeof c\ntypedef &amp;&amp;b* c\ntypeof c\n'] Demo Output: ['void*\nerrtype\nvoid\n', 'void*\nvoid**\nvoid\nvoid**\nerrtype\nvoid\nerrtype\nerrtype\nerrtype\n'] Note: Let's look at the second sample. After the first two queries typedef the b type is equivalent to void*, and с — to void**. The next query typedef redefines b — it is now equal to &amp;b = &amp;void* = void. At that, the с type doesn't change. After that the с type is defined as &amp;&amp;b* = &amp;&amp;void* = &amp;void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &amp;void* = void. Then the b type is again redefined as &amp;void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &amp;void******* = void******. The same happens in the last typedef.
```python from collections import * import sys,re lines = [i[:-1] for i in sys.stdin.readlines()] n = int(lines[0]) lines = lines[1:] typeof = defaultdict(lambda:'errtype') typeof['void'] = 'void' def simplify(s): global typeof l,r = s.count('&'),s.count('*') result = typeof[s[l:len(s)-r]] #print(l,r,result,s[l:len(s)-r]) if(result == 'errtype'): return result for i in range(r): result = result+'*' for i in range(l): if(result[-1] == '*'): result = result[:-1] else: return 'errtype' return result #print(simplify('void*')) typeof['ptv'] = simplify('void*') #print(typeof['ptv']) #print(simplify('ptv')) #exit() for line in lines: commands = line.split() if(commands[0] == 'typeof'): print(simplify(commands[1])) else: typeof[commands[2]] = simplify(commands[1]) #print(typeof['ptv']) ```
53
Dead Ends
Title: Dead Ends Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are *n* junctions and *m* two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to *n*<=-<=1 roads and it were still possible to get from each junction to any other one. Besides, the mayor is concerned with the number of dead ends which are the junctions from which only one road goes. There shouldn't be too many or too few junctions. Having discussed the problem, the mayor and his assistants decided that after the roads are closed, the road map should contain exactly *k* dead ends. Your task is to count the number of different ways of closing the roads at which the following conditions are met: - There are exactly *n*<=-<=1 roads left. - It is possible to get from each junction to any other one. - There are exactly *k* dead ends on the resulting map. Two ways are considered different if there is a road that is closed in the first way, and is open in the second one. Input Specification: The first line contains three integers *n*, *m* and *k* (3<=≤<=*n*<=≤<=10,<=*n*<=-<=1<=≤<=*m*<=≤<=*n*·(*n*<=-<=1)<=/<=2,<=2<=≤<=*k*<=≤<=*n*<=-<=1) which represent the number of junctions, roads and dead ends correspondingly. Then follow *m* lines each containing two different integers *v*1 and *v*2 (1<=≤<=*v*1,<=*v*2<=≤<=*n*,<=*v*1<=≠<=*v*2) which represent the number of junctions connected by another road. There can be no more than one road between every pair of junctions. The junctions are numbered with integers from 1 to *n*. It is guaranteed that it is possible to get from each junction to any other one along the original roads. Output Specification: Print a single number — the required number of ways. Demo Input: ['3 3 2\n1 2\n2 3\n1 3\n', '4 6 2\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n', '4 6 3\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n'] Demo Output: ['3\n', '12\n', '4\n'] Note: none
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) adj = [[] for _ in range(n)] dp = [[0] * (1 << n) for _ in range(1 << n)] for u, v in (map(int, input().split()) for _ in range(m)): u, v = u - 1, v - 1 adj[u].append(v) adj[v].append(u) dp[(1 << u) | (1 << v)][(1 << u) | (1 << v)] = 1 for v_set in range(1, 1 << n): leaf_set = v_set while leaf_set: for new_v in range(n): if (1 << new_v) & v_set: continue for bridge in adj[new_v]: if (1 << bridge) & v_set == 0: continue new_leaf_set = (leaf_set | (1 << new_v)) & ~(1 << bridge) if (((1 << new_v) - 1) & new_leaf_set) == 0: dp[v_set | (1 << new_v)][new_leaf_set] += dp[v_set][leaf_set] leaf_set = (leaf_set - 1) & v_set ans = 0 bit = (1 << k) - 1 while bit < (1 << n): ans += dp[-1][bit] x = bit & -bit y = bit + x bit = (((bit & ~y) // x) >> 1) | y print(ans) ```
82
Sets
Title: Sets Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose *n* non-empty sets in such a way, that no two of them have common elements. One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on *n*·(*n*<=-<=1)<=/<=2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order. For example, if *n*<==<=4, and the actual sets have the following form {1,<=3}, {5}, {2,<=4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: - 2,<=7,<=4. - 1,<=7,<=3; - 5,<=4,<=2; - 1,<=3,<=5; - 3,<=1,<=2,<=4; - 5,<=7. Then Vasya showed the pieces of paper to his friends, but kept the *n* sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper? Input Specification: The first input file line contains a number *n* (2<=≤<=*n*<=≤<=200), *n* is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on *n*·(*n*<=-<=1)<=/<=2 lines. Each set starts with the number *k**i* (2<=≤<=*k**i*<=≤<=200), which is the number of numbers written of the *i*-th piece of paper, and then follow *k**i* numbers *a**ij* (1<=≤<=*a**ij*<=≤<=200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from *n* non-intersecting sets. Output Specification: Print on *n* lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them. It is guaranteed that there is a solution. Demo Input: ['4\n3 2 7 4\n3 1 7 3\n3 5 4 2\n3 1 3 5\n4 3 1 2 4\n2 5 7\n', '4\n5 6 7 8 9 100\n4 7 8 9 1\n4 7 8 9 2\n3 1 6 100\n3 2 6 100\n2 1 2\n', '3\n2 1 2\n2 1 3\n2 2 3\n'] Demo Output: ['1 7 \n2 2 4 \n2 1 3 \n1 5 \n', '3 7 8 9 \n2 6 100 \n1 1 \n1 2 \n', '1 1 \n1 2 \n1 3 \n'] Note: none
```python n=int(input()) L=[] for i in range((n*(n-1))//2): A=input().split() L.append(A[1:]) x=L[0][0] Set=list(L[0]) Set.remove(x) for i in range(1,(n*(n-1))//2): if(x in L[i]): for item in L[i]: if(item in Set): Set.remove(item) break x=Set[0] Sets=[] Sets.append(list(Set)) for i in range((n*(n-1))//2): if(x in L[i]): Sets.append(list(L[i])) for item in Set: Sets[-1].remove(item) for item in Sets: print(len(item),end="") for z in item: print(" "+str(z),end="") print() ```
10
LCIS
Title: LCIS Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: This problem differs from one which was on the online contest. The sequence *a*1,<=*a*2,<=...,<=*a**n* is called increasing, if *a**i*<=&lt;<=*a**i*<=+<=1 for *i*<=&lt;<=*n*. The sequence *s*1,<=*s*2,<=...,<=*s**k* is called the subsequence of the sequence *a*1,<=*a*2,<=...,<=*a**n*, if there exist such a set of indexes 1<=≤<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*<=≤<=*n* that *a**i**j*<==<=*s**j*. In other words, the sequence *s* can be derived from the sequence *a* by crossing out some elements. You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=500) — the length of the first sequence. The second line contains *n* space-separated integers from the range [0,<=109] — elements of the first sequence. The third line contains an integer *m* (1<=≤<=*m*<=≤<=500) — the length of the second sequence. The fourth line contains *m* space-separated integers from the range [0,<=109] — elements of the second sequence. Output Specification: In the first line output *k* — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any. Demo Input: ['7\n2 3 1 6 5 4 6\n4\n1 3 5 6\n', '5\n1 2 0 2 1\n3\n1 0 1\n'] Demo Output: ['3\n3 5 6 \n', '2\n0 1 \n'] Note: none
```python # -*- coding: utf-8 -*- # @project : 《Atcoder》 # @Author : created by bensonrachel on 2021/10/18 # @File : 28.LCIS.py # 求 find their longest common increasing subsequence最长公共递增子序列。 def output(w,pre_k): if(w != -1): output(pre_k[w],pre_k) print(b[w-1],end=" ") def dp_solve(): dp = [[0]*(m+1) for _ in range(n+1)] pre_k = [-1] * (m+1) for i in range(1,n+1): max_k = 0 k = -1 for j in range(1,m+1): if a[i-1]!=b[j-1]: dp[i][j] = dp[i-1][j] if a[i-1]>b[j-1] and max_k < dp[i-1][j] : max_k = dp[i-1][j] k = j else: dp[i][j] = max_k + 1 pre_k[j] = k ans = 0 w = 0 for index,value in enumerate(dp[-1]): if(value > ans): ans = value w = index print(ans) if(ans): output(w,pre_k) if __name__ == '__main__': n = int(input()) a = [int(i) for i in input().split()] m = int(input()) b = [int(i) for i in input().split()] ans = dp_solve() ```
1
Spreadsheet
Title: Spreadsheet Time Limit: 10 seconds Memory Limit: 64 megabytes Problem Description: In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc. The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example. Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system. Input Specification: The first line of the input contains integer number *n* (1<=≤<=*n*<=≤<=105), the number of coordinates in the test. Then there follow *n* lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 . Output Specification: Write *n* lines, each line should contain a cell coordinates in the other numeration system. Demo Input: ['2\nR23C55\nBC23\n'] Demo Output: ['BC23\nR23C55\n'] Note: none
```python import sys input = sys.stdin.readline # from math import gcd as gcd, isqrt # from collections import deque # import bisect #-->For bisect.bisect_left=lower_bound and bisect_right=upper_bound t = 1 t = int(input()) for _ in range(t): s = input().strip() if (s[1].isdigit() and 'R' in s and 'C' in s): start = end = "" i = 1 while (s[i] != 'C'): i += 1 end = s[1:i] col = int(s[i+1:]) while (col > 0): x = col % 26 if (x): start = chr(x + 64) + start else: start = 'Z' + start col -= 26 col //= 26 print(start + end) else: start = "R" col = 0 s1 = "" for i in s: if (i.isdigit()): start += i else: s1 += i for i in s1: col *= 26 col += ord(i) - 64 print(start + "C" + str(col)) ```
47
Safe
Title: Safe Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Vasya tries to break in a safe. He knows that a code consists of *n* numbers, and every number is a 0 or a 1. Vasya has made *m* attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses. Input Specification: The first input line contains two integers *n* and *m* (6<=≤<=*n*<=≤<=35,<=1<=≤<=*m*<=≤<=10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow *m* lines, each containing space-separated *s**i* and *c**i* which correspondingly indicate Vasya’s attempt (a line containing *n* numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively). Output Specification: Print the single number which indicates how many possible code variants that do not contradict the *m* system responses are left. Demo Input: ['6 2\n000000 2\n010100 4\n', '6 3\n000000 2\n010100 4\n111100 0\n', '6 3\n000000 2\n010100 4\n111100 2\n'] Demo Output: ['6\n', '0\n', '1\n'] Note: none
```python from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) pow2 = [1] for _ in range(20): pow2.append(2 * pow2[-1]) n1, n2 = n // 2, (n + 1) // 2 x, y, z = [], [], [] for _ in range(m): s, c = list(input().rstrip().decode().split()) x0, y0 = [], [] for i in range(n1): x0.append(ord(s[i]) - 48) for i in range(n1, n): y0.append(ord(s[i]) - 48) x.append(x0) y.append(y0) z.append(int(c)) cnt = defaultdict(lambda : 0) u = [0] * n1 for i in range(pow2[n1]): c = [] for j in range(n1): u[j] = 1 if i & pow2[j] else 0 for j in range(m): v = n1 for k, l in zip(u, x[j]): v -= k ^ l if v > z[j]: break c.append(z[j] - v) if len(c) == m: cnt[tuple(c)] += 1 ans = 0 u = [0] * n2 for i in range(pow2[n2]): c = [] for j in range(n2): u[j] = 1 if i & pow2[j] else 0 for j in range(m): v = n2 for k, l in zip(u, y[j]): v -= k ^ l if v > z[j]: break c.append(v) if len(c) == m: c = tuple(c) if c in cnt: ans += cnt[c] print(ans) ```
77
Falling Anvils
Title: Falling Anvils Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height *p* of the potential victim vary in the range [0;*a*] and the direction of the wind *q* vary in the range [<=-<=*b*;*b*]. *p* and *q* could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the *p* and *q* coefficients are chosen equiprobably and independently in their ranges. Input Specification: The first line contains integer *t* (1<=≤<=*t*<=≤<=10000) — amount of testcases. Each of the following *t* lines contain two space-separated integers *a* and *b* (0<=≤<=*a*,<=*b*<=≤<=106). Pretests contain all the tests with 0<=&lt;<=*a*<=&lt;<=10,<=0<=≤<=*b*<=&lt;<=10. Output Specification: Print *t* lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10<=-<=6. Demo Input: ['2\n4 2\n1 2\n'] Demo Output: ['0.6250000000\n0.5312500000\n'] Note: none
```python for i in range(int(input())): a, b = map(int, input().split()) print(0.5 + a / (b << 4) if 4 * b > a else 1 - b / a if a else 1) ```
10
Cinema Cashier
Title: Cinema Cashier Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: All cinema halls in Berland are rectangles with *K* rows of *K* seats each, and *K* is an odd number. Rows and seats are numbered from 1 to *K*. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of *M* people, who come to watch a movie, want necessarily to occupy *M* successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for *M* seats comes, the program should determine the row number *x* and the segment [*y**l*,<=*y**r*] of the seats numbers in this row, where *y**r*<=-<=*y**l*<=+<=1<==<=*M*. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say, — the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number *x* is lower). If the variants are still multiple, it should choose the one with the minimum *y**l*. If you did not get yet, your task is to simulate the work of this program. Input Specification: The first line contains two integers *N* and *K* (1<=≤<=*N*<=≤<=1000,<=1<=≤<=*K*<=≤<=99) — the amount of requests and the hall size respectively. The second line contains *N* space-separated integers *M**i* from the range [1,<=*K*] — requests to the program. Output Specification: Output *N* lines. In the *i*-th line output «-1» (without quotes), if it is impossible to find *M**i* successive seats in one row, otherwise output three numbers *x*,<=*y**l*,<=*y**r*. Separate the numbers with a space. Demo Input: ['2 1\n1 1\n', '4 3\n1 2 3 1\n'] Demo Output: ['1 1 1\n-1\n', '2 2 2\n1 1 2\n3 1 3\n2 1 1\n'] Note: none
```python __author__ = 'Darren' def solve(): n, k = map(int, input().split()) group = map(int, input().split()) available = [[k, 1][:] for _ in range(k+1)] center = (k + 1) // 2 for m in group: closest, best_row, best_col = 10000, -1, -1 for row in range(1, k+1): col = 0 if available[row][0] < m and k - available[row][1] + 1 < m: continue if available[row][0] == k: col = center - m // 2 elif center - available[row][0] <= available[row][1] - center: col = available[row][0] - m + 1 else: col = available[row][1] distance = calc_distance(center, row, col, m) if distance < closest: closest = distance best_row = row best_col = col if closest == 10000: print(-1) else: print(best_row, best_col, best_col+m-1) available[best_row][0] = min(available[best_row][0], best_col-1) available[best_row][1] = max(available[best_row][1], best_col+m) def calc_distance(center, row, col, num): end_col = col + num - 1 distance = abs(center - row) * num if col >= center: distance += (col - center) * num + (num - 1) * num // 2 elif end_col <= center: distance += (center - end_col) * num + (num - 1) * num // 2 else: distance += ((center - col) * (center - col + 1) // 2 + (end_col - center) * (end_col - center + 1) // 2) return distance if __name__ == '__main__': solve() ```
81
Plug-in
Title: Plug-in Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input Specification: The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Specification: Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Demo Input: ['hhoowaaaareyyoouu\n', 'reallazy\n', 'abacabaabacabaa\n'] Demo Output: ['wre', 'rezy', 'a'] Note: none
```python def get_remaining_balls(sequence): ball_stack = [] for ball in sequence: if ball_stack and ball_stack[-1] == ball: ball_stack.pop() else: ball_stack.append(ball) remaining_balls = ''.join(ball_stack) return remaining_balls sequence = input() remaining_balls = get_remaining_balls(sequence) print(remaining_balls) ```
52
Right Triangles
Title: Right Triangles Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You are given a *n*<=×<=*m* field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input Specification: The first line contains two positive integer numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000). The following *n* lines consist of *m* characters each, describing the field. Only '.' and '*' are allowed. Output Specification: Output a single number — total number of square triangles in the field. 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\n**\n*.\n', '3 4\n*..*\n.**.\n*.**\n'] Demo Output: ['1\n', '9\n'] Note: none
```python n,m=map(int,input().split()) z=[] zn=[0]*n zm=[0]*m for i in range(n): s=input() z.append(s) for j in range(m): if s[j]=='*': zm[j]+=1 zn[i]=s.count('*') k=0 for i in range(n): for j in range(m): if z[i][j]=='*': k+= (zm[j]-1) * (zn[i]-1) print(k) ```
5
Longest Regular Bracket Sequence
Title: Longest Regular Bracket Sequence Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well. Input Specification: The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106. Output Specification: Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1". Demo Input: [')((())))(()())\n', '))(\n'] Demo Output: ['6 2\n', '0 1\n'] Note: none
```python def solve(): s = input() n = len(s) l, r, maxLen, cnt, maxCnt = 0, 0, 0, 0, 0 for i in range(n): if s[i] == '(': l += 1 else: r += 1 if l == r: if 2 * r > maxLen: maxLen = 2 * r cnt = 1 elif 2 * r == maxLen: cnt += 1 elif r > l: l, r = 0, 0 maxCnt = max(maxCnt, cnt) l, r, cnt = 0, 0, 0 for i in range(n-1, -1, -1): if s[i] == '(': l += 1 else: r += 1 if l == r: if 2 * l > maxLen: maxLen = 2 * l cnt = 1 elif 2 * l == maxLen: cnt += 1 elif l > r: l, r = 0, 0 maxCnt = max(maxCnt, cnt) if maxLen != 0: print(str(maxLen) + ' '+ str(maxCnt)) else: print('0 1') if __name__ == "__main__": solve() ```
113
Petr#
Title: Petr# Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the *s**begin* and ending with the *s**end* (it is possible *s**begin*<==<=*s**end*), the given string *t* has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him! Input Specification: The input file consists of three lines. The first line contains string *t*. The second and the third lines contain the *s**begin* and *s**end* identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters. Output Specification: Output the only number — the amount of different substrings of *t* that start with *s**begin* and end with *s**end*. Demo Input: ['round\nro\nou\n', 'codeforces\ncode\nforca\n', 'abababab\na\nb\n', 'aba\nab\nba\n'] Demo Output: ['1\n', '0\n', '4\n', '1\n'] Note: In the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab. In the fourth sample identificators intersect.
```python def calc_lcp(s, sa): rank = [0 for _ in range(len(s))] for i in range(len(s)): rank[sa[i]] = i lcp = [0 for _ in range(len(s) - 1)] h = 0 for i in range(len(s)): if rank[i] < len(s) - 1: while max(i, sa[rank[i] + 1]) + h < len(s) and s[i + h] == s[sa[rank[i] + 1] + h]: h += 1 lcp[rank[i]] = h if h > 0: h -= 1 return lcp, rank def suffix_array(s): s += chr(0) n = len(s) na = max(n, 256) sa = [0 for _ in range(n)] top = [0 for _ in range(na)] rank = [0 for _ in range(n)] sa_new = [0 for _ in range(n)] rank_new = [0 for _ in range(n)] for i in range(n): rank[i] = ord(s[i]) top[rank[i]] += 1 for i in range(1, na): top[i] += top[i - 1] for i in range(n): top[rank[i]] -= 1 sa[top[rank[i]]] = i k = 1 while k < n: for i in range(n): j = sa[i] - k if j < 0: j += n sa_new[top[rank[j]]] = j top[rank[j]] += 1 rank_new[sa_new[0]] = 0 top[0] = 0 cnt = 0 for i in range(1, n): if rank[sa_new[i]] != rank[sa_new[i - 1]] or rank[sa_new[i] + k] != rank[sa_new[i - 1] + k]: cnt += 1 top[cnt] = i rank_new[sa_new[i]] = cnt sa, sa_new = sa_new, sa rank, rank_new = rank_new, rank if cnt == n - 1: break k *= 2 return sa[1:] def kmp(s, p): pi = [0 for _ in range(len(p))] k = 0 for i in range(1, len(p)): while k > 0 and p[k] != p[i]: k = pi[k - 1] if p[k] == p[i]: k += 1 pi[i] = k k = 0 resp = [] for i in range(len(s)): while k > 0 and p[k] != s[i]: k = pi[k - 1] if p[k] == s[i]: k += 1 if k == len(p): resp.append(i - len(p) + 1) k = pi[k - 1] return resp def lower_bound(list, value): left = 0 right = len(list) while left < right: mid = int((left + right) / 2) if list[mid] < value: left = mid + 1 else: right = mid return left s = input() start = input() end = input() indStart = kmp(s, start) indEnd = kmp(s, end) if len(indStart) == 0 or len(indEnd) == 0: print(0) else: sa = suffix_array(s) lcp, rank = calc_lcp(s, sa) ind = rank[indStart[0]] for st in indStart: ind = min(ind, rank[st]) resp = len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, len(start) - len(end))) while ind < len(lcp) and lcp[ind] >= len(start): ind += 1 resp += len(indEnd) - lower_bound(indEnd, sa[ind] + max(0, max(lcp[ind - 1] + 1, len(start)) - len(end))) print(resp) ```
30
Shooting Gallery
Title: Shooting Gallery Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him. The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates *x**i*, and *y**i*, by the time of it's appearance *t**i* and by the number *p**i*, which gives the probability that Copa hits this target if he aims at it. A target appears and disappears instantly, so Copa can hit the target only if at the moment *t**i* his gun sight aimed at (*x**i*,<=*y**i*). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — amount of targets in the shooting gallery. Then *n* lines follow, each describing one target. Each description consists of four numbers *x**i*, *y**i*, *t**i*, *p**i* (where *x**i*, *y**i*, *t**i* — integers, <=-<=1000<=≤<=*x**i*,<=*y**i*<=≤<=1000,<=0<=≤<=*t**i*<=≤<=109, real number *p**i* is given with no more than 6 digits after the decimal point, 0<=≤<=*p**i*<=≤<=1). No two targets may be at the same point. Output Specification: Output the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10<=-<=6. Demo Input: ['1\n0 0 0 0.5\n', '2\n0 0 0 0.6\n5 0 5 0.7\n'] Demo Output: ['0.5000000000\n', '1.3000000000\n'] Note: none
```python import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) T=[tuple(map(float,input().split())) for i in range(n)] T.sort(key=itemgetter(2)) DP=[0]*n for i in range(n): x,y,t,p=T[i] DP[i]=p for j in range(i): x2,y2,t2,p2=T[j] if (x2-x)**2+(y2-y)**2<=(t2-t)**2: DP[i]=max(DP[i],DP[j]+p) print(max(DP)) ```
98
Help Victoria the Wise
Title: Help Victoria the Wise Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube) Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem. Input Specification: The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} — they are the colors of gems with which the box should be decorated. Output Specification: Print the required number of different ways to decorate the box. Demo Input: ['YYYYYY\n', 'BOOOOB\n', 'ROYGBV\n'] Demo Output: ['1\n', '2\n', '30\n'] Note: none
```python from collections import deque import itertools import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) while q: i = q.popleft() p1 = [(i // pow6[j]) % 6 for j in range(6)] for v0 in v: for _ in range(3): p1[v0[0]], p1[v0[1]], p1[v0[2]], p1[v0[3]] = p1[v0[1]], p1[v0[2]], p1[v0[3]], p1[v0[0]] u = 0 for j in range(6): u += p1[j] * pow6[j] if not visit[u]: visit[u] = 1 q.append(u) return s = list(input().rstrip()) d = {"R":0, "O":1, "Y":2, "G":3, "B":4, "V":5} pow6 = [1] for _ in range(6): pow6.append(6 * pow6[-1]) p = [d[i] for i in s] n = pow6[6] visit = [0] * n ans = 0 v = [(0, 1, 2, 3), (0, 4, 2, 5), (1, 4, 3, 5)] for p0 in itertools.permutations(p): u = 0 for i in range(6): u += p0[i] * pow6[i] if visit[u]: continue ans += 1 bfs(u) print(ans) ```
83
Magical Array
Title: Magical Array Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide. He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements. Input Specification: The first line of the input data contains an integer *n* (1<=≤<=*n*<=≤<=105). The second line contains an array of original integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109). Output Specification: Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). Demo Input: ['4\n2 1 1 4\n', '5\n-2 -2 -2 0 1\n'] Demo Output: ['5\n', '8\n'] Note: Notes to sample tests: Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end. In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3]. In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
```python n = int(input()) jum = 0 now = "p" cnt = 0 a = input().split() for x in a: if(x == now): cnt += 1 else: if(cnt != 0): jum += cnt*(cnt+1)//2 cnt = 1 now = x jum += cnt*(cnt+1)//2 print(jum) ```
41
Pawn
Title: Pawn Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its *k* brothers, the number of peas must be divisible by *k*<=+<=1. Find the maximal number of peas it will be able to collect and which moves it should make to do it. The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas. Input Specification: The first line contains three integers *n*, *m*, *k* (2<=≤<=*n*,<=*m*<=≤<=100,<=0<=≤<=*k*<=≤<=10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow *n* lines containing each *m* numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row. Output Specification: If it is impossible to reach the highest row having collected the number of peas divisible by *k*<=+<=1, print -1. Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by *k*<=+<=1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of *n*<=-<=1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them. Demo Input: ['3 3 1\n123\n456\n789\n', '3 3 0\n123\n456\n789\n', '2 2 10\n98\n75\n'] Demo Output: ['16\n2\nRL\n', '17\n3\nLR\n', '-1\n'] Note: none
```python n,m,k=map(int,input().split()) MAP=[list(map(int,list(input().strip()))) for i in range(n)] DP=[[[-1]*(k+1) for i in range(m)] for j in range(n)] FROM=[[["L"]*(k+1) for i in range(m)] for j in range(n)] for i in range(m): DP[n-1][i][MAP[n-1][i]%(k+1)]=MAP[n-1][i] for i in range(n-1,0,-1): for j in range(m): for c in range(k+1): if DP[i][j][c]==-1: continue now=DP[i][j][c] if j-1>=0: p=MAP[i-1][j-1] if now+p>DP[i-1][j-1][(now+p)%(k+1)]: DP[i-1][j-1][(now+p)%(k+1)]=now+p FROM[i-1][j-1][(now+p)%(k+1)]="L" if j+1<m: p=MAP[i-1][j+1] if now+p>DP[i-1][j+1][(now+p)%(k+1)]: DP[i-1][j+1][(now+p)%(k+1)]=now+p FROM[i-1][j+1][(now+p)%(k+1)]="R" ANS=-1 ind=-1 for j in range(m): if ANS<DP[0][j][0]: ANS=DP[0][j][0] ind=j if ANS==-1: print(-1) exit() else: print(ANS) AIND=[] xc=0 for y in range(n-1): if FROM[y][ind][xc]=="L": AIND.append("L") xc=(xc-MAP[y][ind])%(k+1) ind+=1 else: AIND.append("R") xc=(xc-MAP[y][ind])%(k+1) ind-=1 print(ind+1) print("".join(AIND)[::-1]) ```
38
Let's Go Rolling!
Title: Let's Go Rolling! Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: On a number axis directed from the left rightwards, *n* marbles with coordinates *x*1,<=*x*2,<=...,<=*x**n* are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number *i* is equal to *c**i*, number *c**i* may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: - the sum of the costs of stuck pins; - the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible. Input Specification: The first input line contains an integer *n* (1<=≤<=*n*<=≤<=3000) which is the number of marbles. The next *n* lines contain the descriptions of the marbles in pairs of integers *x**i*, *c**i* (<=-<=109<=≤<=*x**i*,<=*c**i*<=≤<=109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions. Output Specification: Output the single number — the least fine you will have to pay. Demo Input: ['3\n2 3\n3 4\n1 2\n', '4\n1 7\n3 1\n5 10\n6 1\n'] Demo Output: ['5\n', '11\n'] Note: none
```python import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) M=[tuple(map(int,input().split())) for i in range(n)] M.sort(key=itemgetter(0)) DP=[1<<60]*n DP[0]=M[0][1] for i in range(1,n): x,c=M[i] MIN=1<<60 for j in range(i): MIN=min(MIN,DP[j]) DP[j]+=abs(x-M[j][0]) DP[i]=MIN+c print(min(DP)) ```
42
Game of chess unfinished
Title: Game of chess unfinished Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", — Volodya said and was right for sure. And your task is to say whether whites had won or not. Pieces on the chessboard are guaranteed to represent a correct position (every piece occupies one cell, no two pieces occupy the same cell and kings cannot take each other). Thus, your task is only to decide whether whites mate blacks. We would remind you that it means that the black king can be taken by one of the opponent's pieces at the moment and also it cannot move to an unbeaten position. A rook moves vertically or horizontally by any number of free cells (assuming there are no other pieces on its path), a king — to the adjacent cells (either by corner or by side). Certainly, pieces cannot leave the board. The black king might be able to take opponent's rooks at his turn (see sample 3). Input Specification: The input contains 4 space-separated piece positions: positions of the two rooks, the white king and the black king. Each position on 8<=×<=8 chessboard is denoted by two symbols — ('a' - 'h') and ('1' - '8') — which stand for horizontal and vertical coordinates of the cell occupied by the piece. It is guaranteed, that no two pieces occupy the same cell, and kings cannot take each other. Output Specification: Output should contain one word: "CHECKMATE" if whites mate blacks, and "OTHER" otherwise. Demo Input: ['a6 b4 c8 a8\n', 'a6 c4 b6 b8\n', 'a2 b1 a3 a1\n'] Demo Output: ['CHECKMATE\n', 'OTHER\n', 'OTHER\n'] Note: none
```python import sys b = 'sabcdefgh' a1,a2,a3,a4 = map(str,input().split()) x1 = b.index(a1[0])-1 y1 = int(a1[1]) -1 x2 = b.index(a2[0])-1 y2 = int(a2[1]) -1 x3 = b.index(a3[0])-1 y3 = int(a3[1]) -1 x4 = b.index(a4[0])-1 y4 = int(a4[1]) -1 c = [] for i in range(8): c.append([0]*8) pr = 0 pr1 = 0 pr4 = 0 pr3 = 0 for i in range(1,8): if y1 - i > -1 and pr == 0: if (y1 - i == y2 and x1 == x2) or (y1 - i == y3 and x1 == x3): c[x1][y1 - i] = 1 pr = 1 else: c[x1][y1 - i] = 1 if y1 + i < 8 and pr1 == 0: if (y1 + i == y2 and x1 == x2) or (y1 + i == y3 and x1 == x3): c[x1][y1 + i] = 1 pr1 = 1 else: c[x1][y1 + i] = 1 if y2 - i > -1 and pr3 == 0: if (y2 - i == y1 and x1 == x2) or (y2 - i == y3 and x2== x3): c[x2][y2 - i] = 1 pr3 = 1 else: c[x2][y2 - i] = 1 if y2 + i < 8 and pr4 == 0: if (y3 + i == y1 and x1 == x2) or (y2 + i == y3 and x2 == x3): c[x2][y2 + i] = 1 pr4 = 1 else: c[x2][y2 + i] = 1 pr = 0 pr1 = 0 pr2 = 0 pr3 = 0 for i in range(1,8): if x1 - i > -1 and pr == 0: if (x1 - i == x2 and y1 == y2) or (x1 - i == x3 and y1 == y3): c[x1 - i][y1] = 1 pr = 1 else: c[x1 - i][y1] = 1 if x2 - i > -1 and pr1 == 0: if (x2 - i == x1 and y1 == y2) or (x2 - i == x3 and y2 == y3): c[x2 - i][y2] = 1 pr1 = 1 else: c[x2 - i][y2] = 1 if x1 + i < 8 and pr2 == 0: if (x1 + i == x2 and y1 == y2) or (x1 + i == x3 and y1 == y3): c[x1 + i][y1] = 1 pr2 = 1 else: c[x1 + i][y1] = 1 if x2 + i < 8 and pr3 == 0: if (x2 + i == x1 and y1 == y2) or (x2 + i == x3 and y2 == y3): c[x2 + i][y2] = 1 pr3= 1 else: c[x2 + i][y2] = 1 for i in range(-1,2): for j in range(-1,2): if x3 + i < 8 and x3 + i > -1 and y3 + j < 8 and y3 + j > -1: c[x3 + i][y3+j] = 1 for i in range(-1,2): for j in range(-1,2): if x4 + i < 8 and x4 + i > -1 and y4 + j < 8 and y4 + j > -1: if c[x4 + i][y4+j] == 0: print("OTHER") sys.exit() print("CHECKMATE") ```
40
Berland Square
Title: Berland Square Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1,<=2,<=...,<=*K* and the center in the point (*z*,<=0) a (*K*,<=*z*)-set. Thus, on the square were painted a (*N*,<=*x*)-set and a (*M*,<=*y*)-set. You have to find out how many parts those sets divided the square into. Input Specification: The first line contains integers *N*,<=*x*,<=*M*,<=*y*. (1<=≤<=*N*,<=*M*<=≤<=100000,<=<=-<=100000<=≤<=*x*,<=*y*<=≤<=100000,<=*x*<=≠<=*y*). Output Specification: Print the sought number of parts. Demo Input: ['1 0 1 1\n', '1 0 1 2\n', '3 3 4 7\n'] Demo Output: ['4\n', '3\n', '17\n'] Note: Picture for the third sample:
```python def readGen(trans): while 1: for x in input().split(): yield(trans(x)) readint=readGen(int) [N,x,M,y]=(next(readint) for i in range(4)) d=abs(y-x) def interval(a,b): return range(a,b+1) def case1(N,M,d): # d>=N ans=0 for r in interval(1, min(M,d-N)): ans+=1 if (M<=d-N): return ans for r in interval(d-N+1, min(M,d)): ans+=2*(N+r-d) if (M<=d): return ans for r in interval(d+1,min(M,d+N)): ans+=2*(d+N-r+1) if (M<=d+N): return ans for r in interval(d+N+1,M): ans+=1 return ans def partA(N,M,d): ans=0 for r in interval(1,min(M,d)): ans+=2*r-1 if (M<d+1): return ans for r in interval(d+1,min(M,2*d)): ans+=2*(2*d-r)+1 return ans def partB(N,M,d): ans=0 bound1=min(2*d,N-d) for r in interval(1,min(M,bound1)): ans+=2*(r-1)+1 if (M<=bound1): return ans if (2*d<=N-d): for r in interval(bound1+1,min(M,N-d)): ans+=4*d if (M<=N-d): return ans if (2*d>N-d): for r in interval(bound1+1,min(M,2*d)): ans+=2*(N-d)+1 if (M<=2*d): return ans bound2=max(2*d,N-d) for r in interval(bound2+1,min(M,d+N)): ans+=2*(d+N-r)+2 if (M<=d+N): return ans for r in interval(d+N+1,M): ans+=1 return ans def case2(N,M,d): # d<N return partA(N,M,d)+partB(N,M,d) def remain(N,M,d): if (M>=d+N): return 1 if (M>d): return d+N-M+1 if (M<=d): return N+1 def calc(N,M,d): if (N<=d): return remain(N,M,d)+case1(N,M,d) else: return remain(N,M,d)+case2(N,M,d) print(calc(N,M,d)) ```
63
Sweets Game
Title: Sweets Game Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward. The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses. Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake. Input Specification: The input data contains 5 lines, containing 19 words consisting of one symbol. The word "O" means that the cell contains a chocolate and a "." stands for an empty cell. It is guaranteed that the box contains at least one chocolate. See the examples for better understanding. Output Specification: If Karlsson gets the cake, print "Karlsson" (without the quotes), otherwise print "Lillebror" (yet again without the quotes). Demo Input: ['. . .\n . . O .\n. . O O .\n . . . .\n . . .\n', '. . .\n . . . O\n. . . O .\n O . O .\n . O .\n'] Demo Output: ['Lillebror', 'Karlsson'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline pow2 = [1] for _ in range(19): pow2.append(2 * pow2[-1]) x = [[] for _ in range(15)] z, c = 0, 0 for i in range(5): s = list(input().rstrip()) for j in s: if j == 32: continue x[i].append(pow2[c]) z ^= (j & 1) * pow2[c] c += 1 for i in range(5): u = x[i] v = u[::-1] l = max(i - 2, 0) r = l + len(u) for j in range(l, r): x[j + 5].append(u[j - l]) x[j + 10].append(v[j - l]) s = set() for u in x: v = [0] for i in u: v.append(v[-1] ^ i) for i in v: for j in v: s.add(i ^ j) s.remove(0) n = pow2[19] dp = [0] * n for i in range(n): if dp[i]: continue for j in s: if i & j: continue dp[i ^ j] = 1 ans = "Karlsson" if dp[z] else "Lillebror" print(ans) ```
54
First Digit Law
Title: First Digit Law Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are *N* random variables, the *i*-th of which can take any integer value from some segment [*L**i*;*R**i*] (all numbers from this segment are equiprobable). It means that the value of the *i*-th quantity can be equal to any integer number from a given interval [*L**i*;*R**i*] with probability 1<=/<=(*R**i*<=-<=*L**i*<=+<=1). The Hedgehog wants to know the probability of the event that the first digits of at least *K*% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD — most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least *K* per cent of those *N* values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one. Input Specification: The first line contains number *N* which is the number of random variables (1<=≤<=*N*<=≤<=1000). Then follow *N* lines containing pairs of numbers *L**i*,<=*R**i*, each of whom is a description of a random variable. It is guaranteed that 1<=≤<=*L**i*<=≤<=*R**i*<=≤<=1018. The last line contains an integer *K* (0<=≤<=*K*<=≤<=100). All the numbers in the input file are integers. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d). Output Specification: Print the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10<=-<=9. Demo Input: ['1\n1 2\n50\n', '2\n1 2\n9 11\n50\n'] Demo Output: ['0.500000000000000', '0.833333333333333'] Note: none
```python #Problem E import sys input = lambda: sys.stdin.readline()[:-1] get_int = lambda: int(input()) get_int_iter = lambda: map(int,input().split()) get_int_list = lambda: list(map(int,input().split())) N = get_int() p = [0]*(N+1) p[0] = 1 for i in range(N): L,R = get_int_iter() L_D,R_D = len(str(L)),len(str(R)) curr_p = 0 if L_D == R_D: if R >= 2*10**(L_D-1): curr_p = max(2*10**(L_D-1)-L,0)/(R-L+1) else: curr_p = 1 else: curr_p = max(2*10**(L_D-1)-L,0) for j in range(L_D+1,R_D): curr_p += 10**(j-1) if R >= 2*10**(R_D-1): curr_p += 10**(R_D-1) else: curr_p += R-10**(R_D-1) + 1 curr_p /= R-L+1 #print(curr_p) p_next = [0]*(N+1) for k in range(N): p_next[k] += p[k] * (1-curr_p) p_next[k+1] += p[k] * curr_p p = p_next #print(p) K = get_int() win_p = 0 for i in range(N+1): if i*100 >= N*K: win_p += p[i] print(win_p) ```
39
Inverse Function
Title: Inverse Function Time Limit: 5 seconds Memory Limit: 64 megabytes Problem Description: Petya wrote a programme on C++ that calculated a very interesting function *f*(*n*). Petya ran the program with a certain value of *n* and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of *n* the program was run. Help Petya, carry out the inverse function! Mostly, the program consists of a function in C++ with the following simplified syntax: - *function* ::= int f(int n) {*operatorSequence*}- *operatorSequence* ::= *operator* | *operator* *operatorSequence*- *operator* ::= return *arithmExpr*; | if (*logicalExpr*) return *arithmExpr*;- *logicalExpr* ::= *arithmExpr*<=&gt;<=*arithmExpr* | *arithmExpr*<=&lt;<=*arithmExpr* | *arithmExpr* == *arithmExpr*- *arithmExpr* ::= *sum*- *sum* ::= *product* | *sum*<=+<=*product* | *sum*<=-<=*product*- *product* ::= *multiplier* | *product*<=*<=*multiplier* | *product*<=/<=*multiplier*- *multiplier* ::= n | *number* | f(*arithmExpr*)- *number* ::= 0|1|2|... |32767 The whitespaces in a *operatorSequence* are optional. Thus, we have a function, in which body there are two kinds of operators. There is the operator "return *arithmExpr*;" that returns the value of the expression as the value of the function, and there is the conditional operator "if (*logicalExpr*) return *arithmExpr*;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language — cycles, assignment operators, nested conditional operators etc, and other variables except the *n* parameter are used in the function. All the constants are integers in the interval [0..32767]. The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations "&gt;" (more), "&lt;" (less) and "==" (equals) also have standard meanings. Now you've got to pay close attention! The program is compiled with the help of 15-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo 32768 (if the result of subtraction is negative, then 32768 is added to it until the number belongs to the interval [0..32767]). Division "/" is a usual integer division where the remainder is omitted. Examples of arithmetical operations: Guaranteed that for all values of *n* from 0 to 32767 the given function is performed correctly. That means that: 1. Division by 0 never occures. 2. When performing a function for the value *n*<==<=*N* recursive calls of the function *f* may occur only for the parameter value of 0,<=1,<=...,<=*N*<=-<=1. Consequently, the program never has an infinite recursion. 3. As the result of the sequence of the operators, the function always returns a value. We have to mention that due to all the limitations the value returned by the function *f* is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of *n* parameter. That's why the *f* function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of *n* from the interval [0..32767] and a value of *f*(*n*) from the same interval. Given the value of *f*(*n*), and you should find *n*. If the suitable *n* value is not unique, you should find the maximal one (from the interval [0..32767]). Input Specification: The first line has an integer *f*(*n*) from the interval [0..32767]. The next lines have the description of the function *f*. In the description can be found extra spaces and line breaks (see the examples) which, of course, can’t break key words int, if, return and numbers. The size of input data can’t exceed 100 bytes. Output Specification: Output a single number — the answer to the problem. If there’s no answer, output "-1" (without quotes). Demo Input: ['17\nint f(int n)\n{\nif (n &lt; 100) return 17;\nif (n &gt; 99) return 27;\n}\n', '13\nint f(int n)\n{\nif (n == 0) return 0;\nreturn f(n - 1) + 1;\n}\n', '144\nint f(int n)\n{\nif (n == 0) return 0;\nif (n == 1) return n;\nreturn f(n - 1) + f(n - 2);\n}'] Demo Output: ['99\n', '13', '24588\n'] Note: none
```python import sys y = int(input()) lines = sys.stdin.read() mod = 32768 p1 = lines.find('{') + 1 p2 = lines.find('}') lines = lines[p1:p2].strip().replace('\n', '').split(';') mp = {} cmd = "def f(n):\n" for line in lines: line = line.strip() if line == "": continue cmd += "\tif n in mp:\n\t\treturn mp[n]\n" items = line.split("return") pre, ex = "", items[-1].strip() if "if" in line: cmd += "\t" + items[0].strip() + ":\n" pre = "\t" cmd += pre + "\tmp[n] = " + ex + "\n" cmd += pre + "\tmp[n] %= mod \n" cmd += pre + "\treturn mp[n] \n" cmd = cmd.replace("/", "% mod //") exec(cmd) ans = -1 for x in range(mod): if f(x) == y: ans = x print(ans) ```
65
Harry Potter and the Golden Snitch
Title: Harry Potter and the Golden Snitch Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (*x*0,<=*y*0,<=*z*0), (*x*1,<=*y*1,<=*z*1), ..., (*x**n*,<=*y**n*,<=*z**n*). At the beginning of the game the snitch is positioned at the point (*x*0,<=*y*0,<=*z*0), and then moves along the polyline at the constant speed *v**s*. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (*P**x*,<=*P**y*,<=*P**z*) and his super fast Nimbus 2011 broom allows him to move at the constant speed *v**p* in any direction or remain idle. *v**p* is not less than the speed of the snitch *v**s*. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=10000). The following *n*<=+<=1 lines contain the coordinates *x**i*, *y**i*, *z**i*, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities *v**p* and *v**s*, the last line contains *P**x*, *P**y*, *P**z*, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that *v**s*<=≤<=*v**p*. Output Specification: If Harry Potter can catch the snitch while it is moving along the polyline (including the end (*x**n*,<=*y**n*,<=*z**n*)), print "YES" in the first line (without the quotes). Print in the second line *t*, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers *X*, *Y*, *Z*, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10<=-<=6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". Demo Input: ['4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25\n', '4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50\n', '1\n1 2 3\n4 5 6\n20 10\n1 2 3\n'] Demo Output: ['YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000\n', 'NO\n', 'YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000\n'] Note: none
```python import math, sys eps = 1e-8 n = int(input()) al = [list(map(int, input().split())) for _ in range(n + 1)] vp, vs = map(int, input().split()) px, py, pz = map(int, input().split()) al = [(x - px, y - py, z - pz) for x, y, z in al] d3 = lambda x, y, z: x*x + y*y + z*z t0 = 0 rt, pt = None, 0 ts = 0 def tsol(t): global rt, pt if t0 - eps < t < te + eps and (rt is None or rt > t): rt, pt = t, [(x + a * t) / l for x, a in zip(s, v)] for i in range(n): c = [y - x for x, y in zip(al[i], al[i + 1])] ll = d3(*c) l = ll ** 0.5 ts += l te = ts / vs v = [vs * x for x in c] s = [l * x - a * t0 for x, a in zip(al[i], v)] a = d3(*v) - vp * vp * ll b = 2 * sum(x * i for x, i in zip(s, v)) c = d3(*s) d = b * b - 4 * a * c fa = abs(a) < eps if fa: if abs(b) > eps: tsol(-c / b) elif d > -eps: if d < eps: d = 0 a *= 2.0 d **= 0.5 tsol((-b + d) / a) tsol((-b - d) / a) t0 = te if rt is None: print("NO") else: print("YES") print("%.10f" % rt) print("%.10f" % (pt[0] + px), "%.10f" % (pt[1] + py), "%.10f" % (pt[2] + pz)) ```
35
Warehouse
Title: Warehouse Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse. The warehouse has one set of shelving. It has *n* shelves, each of which is divided into *m* sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught. After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you. The process of counting contains two types of query messages: - «+1 x y id» (where *x*, *y* are integers, 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m*, and *id* is a string of lower case Latin letters — from 1 to 10 characters long). That query means that the warehouse got a box identified as *id*, which should be put in the section *y* on the shelf *x*. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query. - «-1 id» (where *id* is a string of lower case Latin letters — from 1 to 10 characters long). That query means that a box identified as *id* is removed from the warehouse. You have to answer this query (see output format). Input Specification: The first input line contains integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=30, 1<=≤<=*k*<=≤<=2000) — the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following *k* lines the queries are given in the order of appearance in the format described above. Output Specification: For each query of the «-1 id» type output two numbers in a separate line — index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output «-1 -1» without quotes. Demo Input: ['2 2 9\n+1 1 1 cola\n+1 1 1 fanta\n+1 1 1 sevenup\n+1 1 1 whitekey\n-1 cola\n-1 fanta\n-1 sevenup\n-1 whitekey\n-1 cola\n', '2 2 8\n+1 1 1 cola\n-1 cola\n+1 1 1 fanta\n-1 fanta\n+1 1 1 sevenup\n-1 sevenup\n+1 1 1 whitekey\n-1 whitekey\n'] Demo Output: ['1 1\n1 2\n2 1\n2 2\n-1 -1\n', '1 1\n1 1\n1 1\n1 1\n'] Note: none
```python import sys sys.stdin = open('input.txt') sys.stdout = open('output.txt', 'w') [row_num, col_num, query_num] = list(map(int, input().split())) rows = [] for r in range(row_num+1): rows.append((col_num+1)*[None]) location = {} for query_index in range(query_num): tokens = input().split() id = tokens.pop() integers = list(map(int, tokens)) if integers[0] == -1: if id in location: r, c = location[id] del location[id] rows[r][c] = None print("%d %d" % (r, c)) else: print("-1 -1") else: r, c = integers[1:3] while rows[r][c]: c += 1 if c > col_num: c = 1 r += 1 if r > row_num: break if r <= row_num: location[id] = [r, c] rows[r][c] = id ```
47
Crossword
Title: Crossword Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical. The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification. Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order. Input Specification: Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters. Output Specification: If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the &lt; operator in the modern programming languages. Demo Input: ['NOD\nBAA\nYARD\nAIRWAY\nNEWTON\nBURN\n', 'AAA\nAAA\nAAAAA\nAAA\nAAA\nAAAAA\n', 'PTC\nJYNYFDSGI\nZGPPC\nIXEJNDOP\nJJFS\nSSXXQOFGJUZ\n'] Demo Output: ['BAA...\nU.I...\nR.R...\nNEWTON\n..A..O\n..YARD\n', 'AAA..\nA.A..\nAAAAA\n..A.A\n..AAA\n', 'JJFS....\nY..S....\nN..X....\nY..X....\nF..Q....\nD..O....\nS..F....\nG..G....\nIXEJNDOP\n...U...T\n...ZGPPC\n'] Note: none
```python from itertools import permutations v = [] for p in permutations(input() for i in range(6)): if len(p[1]) != len(p[0]) + len(p[2]) - 1 or len(p[4]) != len(p[3]) + len(p[5]) - 1: continue elif p[0][0] != p[3][0] or p[0][-1] != p[4][0]: continue elif p[1][0] != p[3][-1] or p[1][len(p[0]) - 1] != p[4][len(p[3]) - 1] or p[1][-1] != p[5][0]: continue elif p[2][0] != p[4][-1] or p[2][-1] != p[5][-1]: continue else: x, y, c = '.' * (len(p[1]) - len(p[0])), '.' * \ (len(p[1]) - len(p[2])), [] c.append(p[0] + x) for i in range(1, len(p[3]) - 1): c.append(p[3][i] + '.' * (len(p[0]) - 2) + p[4][i] + x) c.append(p[1]) for i in range(1, len(p[5]) - 1): c.append(y + p[4][len(p[3]) + i - 1] + '.' * (len(p[2]) - 2) + p[5][i]) c.append(y + p[2]) v.append(c) print('\n'.join(sorted(v)[0]) if v else 'Impossible') ```
27
Unordered Subsequence
Title: Unordered Subsequence Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The sequence is called ordered if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. Input Specification: The first line of the input contains one integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers — the given sequence. All numbers in this sequence do not exceed 106 by absolute value. Output Specification: If the given sequence does not contain any unordered subsequences, output 0. Otherwise, output the length *k* of the shortest such subsequence. Then output *k* integers from the range [1..*n*] — indexes of the elements of this subsequence. If there are several solutions, output any of them. Demo Input: ['5\n67 499 600 42 23\n', '3\n1 2 3\n', '3\n2 3 1\n'] Demo Output: ['3\n1 3 5\n', '0\n', '3\n1 2 3\n'] Note: none
```python def main(): n = int(input()) a = list(map(int, input().split())) p1, p2 = True, True for i in range(1, n): if a[i] > a[i - 1]: p1 = False if a[i] < a[i - 1]: p2 = False if not (p1 or p2): print("3") print(1, i, i + 1) return print("0") if __name__ == "__main__": main()# 1690811174.1351662 ```
23
Party
Title: Party Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: *n* people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2,<=3,<=...,<=*n*<=-<=1 friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of people that could stay at the party in the end? Input Specification: The first input line contains one number *t* — amount of tests (1<=≤<=*t*<=≤<=105). Each of the following *t* lines contains one integer number *n* (1<=≤<=*n*<=≤<=105). Output Specification: For each test output in a separate line one number — the maximum amount of people that could stay in the end. Demo Input: ['1\n3\n'] Demo Output: ['1\n'] Note: none
```python import sys input = lambda: sys.stdin.readline().rstrip() for _ in range(int(input())): N = int(input()) print(max(0,N-2)) ```
108
Datatypes
Title: Datatypes Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has *n* unsigned integer datatypes of sizes (in bits) *a*1,<=*a*2,<=... *a**n*. The *i*-th datatype have size *a**i* bits, so it can represent every integer between 0 and 2*a**i*<=-<=1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer *x*, such that *x* fits in some type *i* (in *a**i* bits) and *x*·*x* does not fit in some other type *j* (in *a**j* bits) where *a**i*<=&lt;<=*a**j*, then Tuftuf will stop using Gava. Your task is to determine Tuftuf's destiny. Input Specification: The first line contains integer *n* (2<=≤<=*n*<=≤<=105) — the number of Gava's unsigned integer datatypes' sizes. The second line contains a single-space-separated list of *n* integers (1<=≤<=*a**i*<=≤<=109) — sizes of datatypes in bits. Some datatypes may have equal sizes. Output Specification: Print "YES" if Tuftuf will stop using Gava, and "NO" otherwise. Demo Input: ['3\n64 16 32\n', '4\n4 2 1 3\n'] Demo Output: ['NO\n', 'YES\n'] Note: In the second example, *x* = 7 (111<sub class="lower-index">2</sub>) fits in 3 bits, but *x*<sup class="upper-index">2</sup> = 49 (110001<sub class="lower-index">2</sub>) does not fit in 4 bits.
```python n=int(input()) a=sorted(list(map(int,input().split()))) for i in range(n-1): if a[i]<a[i+1] and a[i]*2>a[i+1]: print("YES") exit() print("NO") ```
33
Wonderful Randomized Sum
Title: Wonderful Randomized Sum Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of *n* numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by <=-<=1. The second operation is to take some suffix and multiply all numbers in it by <=-<=1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations? Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — amount of elements in the sequence. The second line contains *n* integers *a**i* (<=-<=104<=≤<=*a**i*<=≤<=104) — the sequence itself. Output Specification: The first and the only line of the output should contain the answer to the problem. Demo Input: ['3\n-1 -2 -3\n', '5\n-4 2 0 5 0\n', '5\n-1 10 -5 10 -2\n'] Demo Output: ['6\n', '11\n', '18\n'] Note: none
```python n = int(input()) values = list(map(int, input().split())) best_infix = infix = 0 for x in values: infix = max(0, infix + x) best_infix = max(best_infix, infix) print(2 * best_infix - sum(values)) ```
75
Modified GCD
Title: Modified GCD Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor *d* between two integers *a* and *b* that is in a given range from *low* to *high* (inclusive), i.e. *low*<=≤<=*d*<=≤<=*high*. It is possible that there is no common divisor in the given range. You will be given the two integers *a* and *b*, then *n* queries. Each query is a range from *low* to *high* and you have to answer each query. Input Specification: The first line contains two integers *a* and *b*, the two integers as described above (1<=≤<=*a*,<=*b*<=≤<=109). The second line contains one integer *n*, the number of queries (1<=≤<=*n*<=≤<=104). Then *n* lines follow, each line contains one query consisting of two integers, *low* and *high* (1<=≤<=*low*<=≤<=*high*<=≤<=109). Output Specification: Print *n* lines. The *i*-th of them should contain the result of the *i*-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query. Demo Input: ['9 27\n3\n1 5\n10 11\n9 11\n'] Demo Output: ['3\n-1\n9\n'] Note: none
```python def solve(): left=0 right=len(arr)-1 ant=-1 while left<=right: mid=left+right>>1 if arr[mid]<l: left=mid+1 elif arr[mid]>r: right=mid-1 else: ant=mid left=mid+1 return ant from math import * a,b=map(int,input().split()) n=int(input()) k=gcd(a,b) arr=[] for i in range(1,int(sqrt(k))+1): if k%i==0: arr.append(i) arr.append(k//i) arr.sort() for i in range(n): l,r=map(int,input().split()) ant=solve() if ant!=-1: print(arr[ant]) else:print(-1) ```
88
Keyboard
Title: Keyboard Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has *n* rows of keys containing *m* keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase. Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed *x*. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys. Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than *x*. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips. You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand. Input Specification: The first line contains three integers *n*, *m*, *x* (1<=≤<=*n*,<=*m*<=≤<=30,<=1<=≤<=*x*<=≤<=50). Next *n* lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly *m* keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol. Then follow the length of the text *q* (1<=≤<=*q*<=≤<=5·105). The last line contains the text *T*, which consists of *q* symbols, which are uppercase and lowercase Latin letters. Output Specification: If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes). Demo Input: ['2 2 1\nab\ncd\n1\nA\n', '2 2 1\nab\ncd\n1\ne\n', '2 2 1\nab\ncS\n5\nabcBA\n', '3 9 4\nqwertyuio\nasdfghjkl\nSzxcvbnmS\n35\nTheQuIcKbRoWnFOXjummsovertHeLazYDOG\n'] Demo Output: ['-1\n', '-1\n', '1\n', '2\n'] Note: In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard. In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard. In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m, x = map(int, input().split()) s = [] for _ in range(n): s0 = list(input().rstrip()) for i in s0: s.append(i) inf = pow(10, 9) + 1 dist = [inf] * 150 for u in range(n * m): su = s[u] if su ^ ord("S"): dist[su] = 0 continue i, j = u % m, u // m for v in range(n * m): sv = s[v] if not sv ^ ord("S"): continue d = pow(abs(i - v % m), 2) + pow(abs(j - v // m), 2) dist[sv - 32] = min(dist[sv - 32], d) x *= x x += 1 for i in range(150): if dist[i] ^ inf: dist[i] = min(1, dist[i] // x) q = int(input()) t = list(input().rstrip()) ans = 0 for i in t: ans += dist[i] if ans >= inf: ans = -1 break print(ans) ```
43
Journey
Title: Journey Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The territory of Berland is represented by a rectangular field *n*<=×<=*m* in size. The king of Berland lives in the capital, located on the upper left square (1,<=1). The lower right square has coordinates (*n*,<=*m*). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king. Input Specification: The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100,<=2<=≤<= *n* · *m*) — the field size. The upper left square has coordinates (1,<=1), and the lower right square has coordinates of (*n*,<=*m*). Output Specification: On the first line output integer *k* — the minimum number of teleporters. Then output *k* lines each containing 4 integers *x*1 *y*1 *x*2 *y*2 (1<=≤<=*x*1,<=*x*2<=≤<=*n*,<=1<=≤<=*y*1,<=*y*2<=≤<=*m*) — the coordinates of the square where the teleporter is installed (*x*1,<=*y*1), and the coordinates of the square where the teleporter leads (*x*2,<=*y*2). Then print *nm*<=+<=1 lines containing 2 numbers each — the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1,<=1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time. Demo Input: ['2 2\n', '3 3\n'] Demo Output: ['0\n1 1\n1 2\n2 2\n2 1\n1 1\n', '1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1\n'] Note: none
```python def d(a, b): print(a+1, b) return (a+1, b) def u(a, b): print(a-1, b) return (a-1, b) def l(a, b): print(a, b-1) return (a, b-1) def r(a, b): print(a, b+1) return (a, b+1) a, b = map(int, input().split(' ')) if a == 1: if b == 2: print(0) else: print(1) print(a, b, 1, 1) for i in range(1, b+1): print(1, i) print(1, 1) quit() if b == 1: if a == 2: print(0) else: print(1) print(a, b, 1, 1) for i in range(1, a+1): print(i, 1) print(1, 1) quit() if a%2==1 and b%2==1: print(1) print(a, b, 1, 1) for i in range(1, a+1): if i%2 == 1: for j in range(1, b+1): print(i, j) else: for j in range(b, 0, -1): print(i, j) print(1, 1) quit() if a%2==0 and b%2==0: print(0) x, y = 1, 1 print(x, y) for i in range(a-1): x, y = d(x, y) k=True while 1: if x == 2 and y == b: break if k: x, y = r(x, y) for i in range(a-2): x, y = u(x, y) else: x, y = r(x, y) for i in range(a-2): x, y = d(x, y) k = not k x, y = u(x, y) for i in range(b-1): x, y = l(x, y) if a%2==0 and b%2==1: print(0) x, y = 1, 1 print(x, y) for i in range(a-1): x, y = d(x, y) k=True while 1: if x == a and y == b-2: break if k: x, y = r(x, y) for i in range(a-2): x, y = u(x, y) else: x, y = r(x, y) for i in range(a-2): x, y = d(x, y) k = not k x, y = r(x, y) k = True while 1: if x == 1 and y == b: break if k: x, y = r(x, y) x, y = u(x, y) else: x, y = l(x, y) x, y = u(x, y) k = not k for i in range(b-1): x, y = l(x, y) if a%2==1 and b%2==0: print(0) x, y = 1, 1 print(x, y) for i in range(b-1): x, y = r(x, y) k=True while 1: if x == a-2 and y == b: break if k: x, y = d(x, y) for i in range(b-2): x, y = l(x, y) else: x, y = d(x, y) for i in range(b-2): x, y = r(x, y) k = not k x, y = d(x, y) k = True while 1: if x == a and y == 1: break if k: x, y = d(x, y) x, y = l(x, y) else: x, y = u(x, y) x, y = l(x, y) k = not k for i in range(a-1): x, y = u(x, y) # Made By Mostafa_Khaled ```
8
Two Friends
Title: Two Friends Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than *t*1, and the distance covered by Bob should not differ from the shortest one by more than *t*2. Find the maximum distance that Alan and Bob will cover together, discussing the film. Input Specification: The first line contains two integers: *t*1,<=*t*2 (0<=≤<=*t*1,<=*t*2<=≤<=100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building. Output Specification: In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places. Demo Input: ['0 2\n0 0\n4 0\n-3 0\n', '0 0\n0 0\n2 0\n1 0\n'] Demo Output: ['1.0000000000\n', '2.0000000000\n'] Note: none
```python #!/usr/bin/env python ''' ' Author: Cheng-Shih Wong ' Email: [email protected] ' Date: 2017-08-26 ''' def main(): import math from itertools import combinations, chain EPS = 1e-12 def fcomp(x): return -1 if x < -EPS else int(x>EPS) def dist(A, B): return math.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2) def root(a, b, c): if fcomp(b**2-4*a*c) >= 0: sq = math.sqrt(b**2-4*a*c) if b**2-4*a*c > 0 else 0 return ((-b+sq)/(2*a), (-b-sq)/(2*a)) return None def circle_intersect(A, r1, B, r2): if fcomp(dist(A, B)-(r1+r2)) <= 0: if fcomp(dist(A, B)+r2-r1)<=0 or fcomp(dist(A, B)+r1-r2)<=0: return True, None else: a, b = A c, d = B r = r1 s = r2 e = c - a f = d - b p = math.sqrt(e**2+f**2) k = (p**2 + r**2 - s**2)/(2*p) if fcomp(r**2-k**2)<=0: r = k intsec = ( (a+e*k/p+(f/p)*math.sqrt(r**2-k**2), b+f*k/p-(e/p)*math.sqrt(r**2-k**2)), (a+e*k/p-(f/p)*math.sqrt(r**2-k**2), b+f*k/p+(e/p)*math.sqrt(r**2-k**2)) ) return True, intsec else: return False, None def check(CA, CB, CC): intsec = [] if CA[1]<=0 or CB[1]<=0 or CC[1]<=0: return False # print(CA) # print(CB) # print(CC) for pair in combinations([CA, CB, CC], 2): ret, ip = circle_intersect(*pair[0], *pair[1]) # print(ret, ip) if not ret: return False intsec.append(ip) # print(intsec) if None not in intsec: for p in chain.from_iterable(intsec): if fcomp(dist(p, CA[0])-CA[1])<=0 and \ fcomp(dist(p, CB[0])-CB[1])<=0 and \ fcomp(dist(p, CC[0])-CC[1])<=0: return True return False return True def bisec(l, r): nonlocal A, B, C, T1, T2 while fcomp(r-l) > 0: mid = (l+r)/2 # print('(L, M, R) =', l, mid, r) if check((A, mid), (B, T2-mid), (C, T1-dist(B, C)-mid)): l = mid else: r = mid return l # input t1, t2 = map(float, input().split()) A, B, C = [tuple(map(float, input().split())) for _ in range(3)] # init T1 = dist(A, C)+dist(C, B)+t1 T2 = dist(A, B)+t2 if T2 >= dist(A, C)+dist(C, B): print('{0:6f}'.format(min(T1, T2))) else: print('{0:6f}'.format(bisec(0, min(T1, T2)))) if __name__ == '__main__': import sys, os from time import time if len(sys.argv)>1 and os.path.exists(sys.argv[1]): sys.stdin = open(sys.argv[1], 'rb') st = time() main() print('----- Run {:.6f} seconds. -----'.format(time()-st), file=sys.stderr) ```
48
Permutations
Title: Permutations Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: A permutation is a sequence of integers from 1 to *n* of length *n* containing each number exactly once. For example, (1), (4,<=3,<=5,<=1,<=2), (3,<=2,<=1) are permutations, and (1,<=1), (4,<=3,<=1), (2,<=3,<=4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). The next line contains the mixed array of *n* integers, divided with a single space. The numbers in the array are from 1 to 105. Output Specification: If this array can be split into several permutations so that every element of the array belongs to exactly one permutation, print in the first line the number of permutations. The second line should contain *n* numbers, corresponding to the elements of the given array. If the *i*-th element belongs to the first permutation, the *i*-th number should be 1, if it belongs to the second one, then its number should be 2 and so on. The order of the permutations’ numbering is free. If several solutions are possible, print any one of them. If there’s no solution, print in the first line <=-<=1. Demo Input: ['9\n1 2 3 1 2 1 4 2 5\n', '4\n4 3 2 1\n', '4\n1 2 2 3\n'] Demo Output: ['3\n3 1 2 1 2 2 2 3 2\n', '1\n1 1 1 1 ', '-1\n'] Note: In the first sample test the array is split into three permutations: (2, 1), (3, 2, 1, 4, 5), (1, 2). The first permutation is formed by the second and the fourth elements of the array, the second one — by the third, the fifth, the sixth, the seventh and the ninth elements, the third one — by the first and the eigth elements. Clearly, there are other splitting variants possible.
```python from sys import stdin, stdout input = stdin.readline MAX_ARR = 100001 def main(): input() arr = list(map(int, input().split())) dct = [0] * MAX_ARR result = list() for i in arr: dct[i] += 1 # result = result + str(dct[i]) + " " result.append(str(dct[i])) pre = MAX_ARR for i in range(1, MAX_ARR): if dct[i] > pre: print("-1") return else: pre = dct[i] print("%s\n" % dct[1]) print(" ".join(result)) if __name__ == '__main__': main() ```
19
Checkout Assistant
Title: Checkout Assistant Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Bob came to a cash &amp; carry store, put *n* items into his trolley, and went to the checkout counter to pay. Each item is described by its price *c**i* and time *t**i* in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant. Input Specification: The first input line contains number *n* (1<=≤<=*n*<=≤<=2000). In each of the following *n* lines each item is described by a pair of numbers *t**i*, *c**i* (0<=≤<=*t**i*<=≤<=2000,<=1<=≤<=*c**i*<=≤<=109). If *t**i* is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item *i*. Output Specification: Output one number — answer to the problem: what is the minimum amount of money that Bob will have to pay. Demo Input: ['4\n2 10\n0 20\n1 5\n1 3\n', '3\n0 1\n0 10\n0 100\n'] Demo Output: ['8\n', '111\n'] Note: none
```python n=int(input()) ar=[float('inf')]*(n+1) ar[0]=0 for i in range(n): t,c=map(int,input().split()) for j in range(n-1,-1,-1): w=min(j+t+1,n) ar[w]=min(ar[w],ar[j]+c) print(ar[n]) ```
39
Spelling Check
Title: Spelling Check Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete? Input Specification: The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one. Output Specification: In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0. Demo Input: ['abdrakadabra\nabrakadabra\n', 'aa\na\n', 'competition\ncodeforces\n'] Demo Output: ['1\n3\n', '2\n1 2\n', '0\n'] Note: none
```python import sys input = sys.stdin.readline print = sys.stdout.write s = input().strip() t = input().strip() i = 0 while i < len(t) : if s[i] != t[i] : break i += 1 if i == len(t) : while i >= 0 and s[-1] == s[i] : i -= 1 print(str(len(t)-i)+'\n') for j in range(i+2,len(s)+1) : print(str(j)+' ') else : j = k = i while i < len(t) : if s[i+1] != t[i] : break i += 1 if i < len(t) : print('0') else : while j > 0 and s[j] == s[j-1] : j -= 1 print(str(k-j+1)+'\n') for a in range(j+1,k+2) : print(str(a)+' ') ```
30
King's Problem?
Title: King's Problem? Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom. King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are *n* cities in the kingdom at points with coordinates (*x*1,<=0),<=(*x*2,<=0),<=...,<=(*x**n*,<=0), and there is one city at point (*x**n*<=+<=1,<=*y**n*<=+<=1). King starts his journey in the city number *k*. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*<=+<=1) — amount of cities and index of the starting city. The second line contains *n*<=+<=1 numbers *x**i*. The third line contains *y**n*<=+<=1. All coordinates are integers and do not exceed 106 by absolute value. No two cities coincide. Output Specification: Output the minimum possible length of the journey. Your answer must have relative or absolute error less than 10<=-<=6. Demo Input: ['3 1\n0 1 2 1\n1\n', '3 1\n1 0 2 1\n1\n', '4 5\n0 5 -1 -5 2\n3\n'] Demo Output: ['3.41421356237309490000', '3.82842712474619030000', '14.24264068711928400000'] Note: none
```python import sys readline = sys.stdin.readline N, K = [int(w) for w in readline().split()] poses = [int(w) for w in readline().split()] xk = poses[K - 1] xn, yn = poses.pop(), int(readline()) poses.sort() dist = [((x - xn)**2 + yn ** 2) ** 0.5 for x in poses] if K == N + 1: print(poses[-1] - poses[0] + min(dist[0], dist[-1])) exit(0) k = poses.index(xk) x_min = poses[0] x_max = poses[-1] l, r = max(0, k - 1), min(len(poses) - 1, k + 1) xl, xr = poses[l], poses[r] result = dist[0] + dist[-1] + x_max - x_min - max(xr - xk, xk - xl) result = min(result, dist[0] + x_max - x_min + x_max - xk) result = min(result, dist[-1] + x_max - x_min + xk - x_min) for i, xi in enumerate(poses): l, r = max(0, i - 1), min(len(poses) - 1, i + 1) xl, xr = poses[l], poses[r] result = min(result, min([ dist[-1] + dist[l] + abs(xk - xi) + x_max - xi + xl - x_min, dist[0] + dist[r] + abs(xi - xk) + xi - x_min + x_max - xr, # dist[l] + dist[i] + x_max - xi + xl - x_min + min([x_max - xk, xk - x_min]), dist[r] + dist[i] + x_max - xr + xi - x_min + min([x_max - xk, xk - x_min])])) print(result) ```
44
Hyperdrive
Title: Hyperdrive Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In a far away galaxy there are *n* inhabited planets, numbered with numbers from 1 to *n*. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number 1 a hyperdrive was invented. As soon as this significant event took place, *n*<=-<=1 spaceships were built on the planet number 1, and those ships were sent to other planets to inform about the revolutionary invention. Paradoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of *s* hyperyears in *s* years). When the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make *n*<=-<=2 identical to it ships with a hyperdrive and send them to other *n*<=-<=2 planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new *n*<=-<=2 ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues. However the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy! Your task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet. Input Specification: The first line contains a number *n* (3<=≤<=*n*<=≤<=5000) — the number of inhabited planets in the galaxy. The next *n* lines contain integer coordinates of the planets in format "*x**i* *y**i* *z**i*" (<=-<=104<=≤<=*x**i*,<=*y**i*,<=*z**i*<=≤<=104). Output Specification: Print the single number — the solution to the task with an absolute or relative error not exceeding 10<=-<=6. Demo Input: ['4\n0 0 0\n0 0 1\n0 1 0\n1 0 0\n'] Demo Output: ['1.7071067812\n'] Note: none
```python import sys from math import sqrt, inf from functools import cache readline = sys.stdin.readline planets = [] def read(): N = int(readline().strip()) for _ in range(N): planets.append(tuple([int(w) for w in readline().split()])) def solve() -> float: @cache def dist(a: list, b: list) ->float: v = 0 for x1, x2 in zip(a, b): v += (x1 - x2) ** 2 return sqrt(v) base = planets[0][:] planets.sort(key = lambda x: dist(base, x)) d1, d2, d3 = 0.0, 0.0, 0.0 result = inf for i in range(1, len(planets)): d1 = dist(base, planets[i]) if d1 * 2 > result: break for j in range(i + 1, len(planets)): d2 = dist(base, planets[j]) d3 = dist(planets[j], planets[i]) if d1 + d2 > result: break # print(d1, d2, d3, d1 + d2 + d3) if abs(d1 - d2 - d3) < 1e-6 or abs(d2 - d1 - d3) < 1e-6: return 0.0 result = min(result, d1 + d2 + d3) return result read() print(solve()/2) ```
37
Lesson Timetable
Title: Lesson Timetable Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with *M* classrooms numbered from 1 to *M*, situated along it. All the students of Petya’s year are divided into *N* groups. Petya has noticed recently that these groups’ timetable has the following peculiarity: the number of the classroom where the first lesson of a group takes place does not exceed the number of the classroom where the second lesson of this group takes place. Once Petya decided to count the number of ways in which one can make a lesson timetable for all these groups. The timetable is a set of 2*N* numbers: for each group the number of the rooms where the first and the second lessons take place. Unfortunately, he quickly lost the track of his calculations and decided to count only the timetables that satisfy the following conditions: 1) On the first lesson in classroom *i* exactly *X**i* groups must be present. 2) In classroom *i* no more than *Y**i* groups may be placed. Help Petya count the number of timetables satisfying all those conditionsю As there can be a lot of such timetables, output modulo 109<=+<=7. Input Specification: The first line contains one integer *M* (1<=≤<=*M*<=≤<=100) — the number of classrooms. The second line contains *M* space-separated integers — *X**i* (0<=≤<=*X**i*<=≤<=100) the amount of groups present in classroom *i* during the first lesson. The third line contains *M* space-separated integers — *Y**i* (0<=≤<=*Y**i*<=≤<=100) the maximal amount of groups that can be present in classroom *i* at the same time. It is guaranteed that all the *X**i*<=≤<=*Y**i*, and that the sum of all the *X**i* is positive and does not exceed 1000. Output Specification: In the single line output the answer to the problem modulo 109<=+<=7. Demo Input: ['3\n1 1 1\n1 2 3\n', '3\n1 1 1\n1 1 1\n'] Demo Output: ['36\n', '6\n'] Note: In the second sample test the first and the second lessons of each group must take place in the same classroom, that’s why the timetables will only be different in the rearrangement of the classrooms’ numbers for each group, e.g. 3! = 6.
```python import sys from functools import cache MOD = 10**9 + 7 def make_comb_matrix(n: int) -> list: comb = [[1] * (n + 1) for i in range(n + 1)] for i in range(2, n + 1): for j in range(1, i): comb[i][j] = (comb[i - 1][j] + comb[i - 1][j -1]) % MOD return comb readline = sys.stdin.readline M = int(readline()) xs = [int(w) for w in readline().split()] ys = [int(w) for w in readline().split()] N = sum(xs) comb = make_comb_matrix(N) result = 1 total = N for i in range(M): result *= comb[total][xs[i]] total -= xs[i] result %= MOD # second pre = 0 dp = [0] * (N+1) dp[0] = 1 for i in range(M) : ndp = [0] * (N + 1) for j in range(pre + 1) : res = pre + xs[i] - j for k in range(min(res + 1, ys[i] + 1)) : ndp[j + k] += dp[j] * comb[res][k] ndp[j + k] %= MOD pre += xs[i] dp = ndp print(result * dp[-1] % MOD) ```
58
Trees
Title: Trees Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: On Bertown's main street *n* trees are growing, the tree number *i* has the height of *a**i* meters (1<=≤<=*i*<=≤<=*n*). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the *n*-th one) should be equal to each other, the heights of the 2-nd and the (*n*<=-<=1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) which is the number of trees. The second line contains integers *a**i* (1<=≤<=*a**i*<=≤<=105) which are the heights of the trees. Output Specification: Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful. Demo Input: ['3\n2 2 2\n', '4\n1 2 2 1\n'] Demo Output: ['1\n', '0\n'] Note: none
```python n = int(input()) a = list(map(int, input().split())) x = [n]*100001 for i in range(n): x[a[i]-min(n-i-1, i)]-=1 print(min(x[1:])) ```
38
Smart Boy
Title: Smart Boy Time Limit: 4 seconds Memory Limit: 256 megabytes Problem Description: Once Petya and Vasya invented a new game and called it "Smart Boy". They located a certain set of words — the dictionary — for the game. It is admissible for the dictionary to contain similar words. The rules of the game are as follows: first the first player chooses any letter (a word as long as 1) from any word from the dictionary and writes it down on a piece of paper. The second player adds some other letter to this one's initial or final position, thus making a word as long as 2, then it's the first player's turn again, he adds a letter in the beginning or in the end thus making a word as long as 3 and so on. But the player mustn't break one condition: the newly created word must be a substring of a word from a dictionary. The player who can't add a letter to the current word without breaking the condition loses. Also if by the end of a turn a certain string *s* is written on paper, then the player, whose turn it just has been, gets a number of points according to the formula: where - is a sequence number of symbol *c* in Latin alphabet, numbered starting from 1. For example, , and . - is the number of words from the dictionary where the line *s* occurs as a substring at least once. Your task is to learn who will win the game and what the final score will be. Every player plays optimally and most of all tries to win, then — to maximize the number of his points, then — to minimize the number of the points of the opponent. Input Specification: The first input line contains an integer *n* which is the number of words in the located dictionary (1<=≤<=*n*<=≤<=30). The *n* lines contain the words from the dictionary — one word is written on one line. Those lines are nonempty, consisting of Latin lower-case characters no longer than 30 characters. Equal words can be in the list of words. Output Specification: On the first output line print a line "First" or "Second" which means who will win the game. On the second line output the number of points of the first player and the number of points of the second player after the game ends. Separate the numbers by a single space. Demo Input: ['2\naba\nabac\n', '3\nartem\nnik\nmax\n'] Demo Output: ['Second\n29 35\n', 'First\n2403 1882\n'] Note: none
```python import sys from collections import defaultdict readline = sys.stdin.readline def score_word(word: str, subs: dict, graph:defaultdict): tmp = {} for i in range(len(word)): v, m = 0, 0 for j in range(i, len(word)): val = ord(word[j]) - ord('a') + 1 v += val m = max(val, m) sub = word[i:j + 1] graph[sub[:-1]].add(sub) graph[sub[1:]].add(sub) tmp[sub] = v * m for sub in tmp: if sub in subs: subs[sub][0] += 1 else: subs[sub] = [1, tmp[sub]] subs = {} graph = defaultdict(set) def score(word:str) -> int: if word in subs: return sum(subs[word]) return 0 N = int(readline()) inputs = [] for _ in range(N): word = readline().strip() inputs.append(word) score_word(word, subs, graph) cache = {} def dfs(word:str) ->tuple: if word in cache: return cache[word] result = (0, 0, 0) for nword in graph[word]: w, score1, score2 = dfs(nword) result = max(result, (1 - w, - score2 + score(nword), - score1)) cache[word] = result return result dfs('') if cache[''][0] == 1: print('First') else: print('Second') print(cache[''][1], - cache[''][2]) ```
91
Newspaper Headline
Title: Newspaper Headline Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word *s*2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters. For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac". Which least number of newspaper headings *s*1 will Fangy need to glue them, erase several letters and get word *s*2? Input Specification: The input data contain two lines. The first line contain the heading *s*1, the second line contains the word *s*2. The lines only consist of lowercase Latin letters (1<=≤<=|*s*1|<=≤<=104,<=1<=≤<=|*s*2|<=≤<=106). Output Specification: If it is impossible to get the word *s*2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings *s*1, which Fangy will need to receive the word *s*2. Demo Input: ['abc\nxyz\n', 'abcd\ndabc\n'] Demo Output: ['-1\n', '2\n'] Note: none
```python # 子序列自动机 s1 = input() s2 = input() n = len(s1) nxt = [[-1]*26 for _ in range(n + 1)] for i in range(n - 1,-1,-1): for j in range(26): nxt[i][j] = nxt[i + 1][j] nxt[i][ord(s1[i]) - ord('a')] = i + 1 ans = 1 cur = 0 for ch in s2: if nxt[0][ord(ch) - ord('a')] == -1: print(-1) exit() else: if nxt[cur][ord(ch) - ord('a')] == -1: cur = nxt[0][ord(ch) - ord('a')] ans += 1 else: cur = nxt[cur][ord(ch) - ord('a')] print(ans) ```
98
Help Shrek and Donkey
Title: Help Shrek and Donkey Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds *m* cards and the Donkey holds *n* cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall *m*<=+<=*n*<=+<=1 cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can: - Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins.- Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that. Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner. Input Specification: The first line contains space-separated integers *m* and *n* (0<=≤<=*m*,<=*n*<=≤<=1000). Output Specification: Print space-separated probabilities that Shrek wins and Donkey wins correspondingly; the absolute error should not exceed 10<=-<=9. Demo Input: ['0 3\n', '1 0\n', '1 1\n'] Demo Output: ['0.25 0.75\n', '1 0\n', '0.5 0.5\n'] Note: none
```python N, M = map(int, input().split()) K = max(N, M) dp = [[-1e8 for j in range(K + 1)] for i in range(K + 1)] for i in range(K + 1): dp[0][i] = 1 / (1 + i) dp[i][0] = 1 for s in range(2, 2 * K + 1): n, m = 1, s - 1 while n < s: if not (K < n or K < m): assert dp[m - 1][n] != -1e8 assert dp[m][n - 1] != -1e8 a = m / (m + 1) * (1 - dp[m - 1][n]) c = 1 / (m + 1) b = c + a d = 1 - dp[m][n - 1] p = (d - 1) / (a - 1 + d - b) dp[n][m] = a * p + 1 - p n += 1 m -= 1 print(dp[N][M], 1 - dp[N][M]) ```
22
System Administrator
Title: System Administrator Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Bob got a job as a system administrator in X corporation. His first task was to connect *n* servers with the help of *m* two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index *v* fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers. Input Specification: The first input line contains 3 space-separated integer numbers *n*, *m*, *v* (3<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105,<=1<=≤<=*v*<=≤<=*n*), *n* — amount of servers, *m* — amount of direct connections, *v* — index of the server that fails and leads to the failure of the whole system. Output Specification: If it is impossible to connect the servers in the required way, output -1. Otherwise output *m* lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any. Demo Input: ['5 6 3\n', '6 100 1\n'] Demo Output: ['1 2\n2 3\n3 4\n4 5\n1 3\n3 5\n', '-1\n'] Note: none
```python n, m, v = map(int, input().split()) def main(n, m, v): if m < n - 1 or m > (n - 3) * (n - 2) // 2 + n - 1: print(-1) return for i in range(1, n+1): if i == v: continue print(i, v) edges = n - 1 for i in range(1, n): if i == v: continue for j in range(1, i): if j == v: continue if edges == m: return print(i, j) edges += 1 main(n, m, v) ```
69
Dot
Title: Dot Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules: - On the checkered paper a coordinate system is drawn. A dot is initially put in the position (*x*,<=*y*). - A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line *y*<==<=*x*. - Anton and Dasha take turns. Anton goes first. - The player after whose move the distance from the dot to the coordinates' origin exceeds *d*, loses. Help them to determine the winner. Input Specification: The first line of the input file contains 4 integers *x*, *y*, *n*, *d* (<=-<=200<=≤<=*x*,<=*y*<=≤<=200,<=1<=≤<=*d*<=≤<=200,<=1<=≤<=*n*<=≤<=20) — the initial coordinates of the dot, the distance *d* and the number of vectors. It is guaranteed that the initial dot is at the distance less than *d* from the origin of the coordinates. The following *n* lines each contain two non-negative numbers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=200) — the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different. Output Specification: You should print "Anton", if the winner is Anton in case of both players play the game optimally, and "Dasha" otherwise. Demo Input: ['0 0 2 3\n1 1\n1 2\n', '0 0 2 4\n1 1\n1 2\n'] Demo Output: ['Anton', 'Dasha'] Note: In the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move — to reflect relatively to the line *y* = *x*. Dasha will respond to it with the same move and return the dot in position (2;3).
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') x, y, n, d = map(int, input().split()) vector = [list(map(int, input().split())) for _ in range(n)] dp = [[-1] * (d * 2 + 1) for _ in range(d * 2 + 1)] for i in range(d * 2 + 1): for j in range(d * 2 + 1): if (i - d) ** 2 + (j - d) ** 2 > d**2: dp[i][j] = 1 def solve(x, y): if dp[x][y] != -1: return dp[x][y] for dx, dy in vector: if 0 <= x + dx <= 2 * d and 0 <= y + dy <= 2 * d and solve(x + dx, y + dy) == 0: dp[x][y] = 1 return 1 dp[x][y] = 0 return 0 if solve(x + d, y + d): print('Anton') else: print('Dasha') ```
33
String Problem
Title: String Problem Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character *A**i* in one of the strings into arbitrary character *B**i*, but he has to pay for every move a particular sum of money, equal to *W**i*. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input Specification: The first input line contains two initial non-empty strings *s* and *t*, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer *n* (0<=≤<=*n*<=≤<=500) — amount of possible changings. Then follow *n* lines, each containing characters *A**i* and *B**i* (lower case Latin letters) and integer *W**i* (0<=≤<=*W**i*<=≤<=100), saying that it's allowed to change character *A**i* into character *B**i* in any of the strings and spend sum of money *W**i*. Output Specification: If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Demo Input: ['uayd\nuxxd\n3\na x 8\nx y 13\nd c 3\n', 'a\nb\n3\na b 2\na b 3\nb a 5\n', 'abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0\n'] Demo Output: ['21\nuxyd\n', '2\nb\n', '-1\n'] Note: none
```python import sys import math import collections from heapq import heappush, heappop input = sys.stdin.readline ints = lambda: list(map(int, input().split())) s = input().strip() t = input().strip() n = int(input()) adj = [[math.inf for _ in range(26)] for _ in range(26)] distances = [[math.inf for _ in range(26)] for _ in range(26)] for _ in range(n): line = input().split() u = ord(line[0]) - ord('a') v = ord(line[1]) - ord('a') adj[u][v] = min(adj[u][v], int(line[2])) for i in range(26): for j in range(26): if i == j: distances[i][j] = 0 elif adj[i][j] != math.inf: distances[i][j] = adj[i][j] for k in range(26): for i in range(26): for j in range(26): distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j]) res = [] ans = 0 flag = True for i in range(min(len(s), len(t))): u = ord(s[i]) - ord('a') v = ord(t[i]) - ord('a') mn, letter = math.inf, "" for j in range(26): if distances[u][j] + distances[v][j] < mn: mn = distances[u][j] + distances[v][j] letter = chr(j + ord('a')) if letter == "": flag = False break res.append(letter) ans += mn if not flag or len(s) != len(t): print("-1") else: print(ans) print("".join(res)) ```
68
Synchrophasotron
Title: Synchrophasotron Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: For some experiments little Petya needs a synchrophasotron. He has already got the device, all that's left is to set the fuel supply. Fuel comes through a system of nodes numbered from 1 to *n* and connected by pipes. Pipes go from every node with smaller number to every node with greater number. Fuel can only flow through pipes in direction from node with smaller number to node with greater number. Any amount of fuel can enter through the first node and the last node is connected directly to the synchrophasotron. It is known that every pipe has three attributes: the minimum amount of fuel that should go through it, the maximum amount of fuel that can possibly go through it and the cost of pipe activation. If *c**ij* units of fuel (*c**ij*<=&gt;<=0) flow from node *i* to node *j*, it will cost *a**ij*<=+<=*c**ij*2 tugriks (*a**ij* is the cost of pipe activation), and if fuel doesn't flow through the pipe, it doesn't cost anything. Only integer number of units of fuel can flow through each pipe. Constraints on the minimal and the maximal fuel capacity of a pipe take place always, not only if it is active. You may assume that the pipe is active if and only if the flow through it is strictly greater than zero. Petya doesn't want the pipe system to be overloaded, so he wants to find the minimal amount of fuel, that, having entered the first node, can reach the synchrophasotron. Besides that he wants to impress the sponsors, so the sum of money needed to be paid for fuel to go through each pipe, must be as big as possible. Input Specification: First line contains integer *n* (2<=≤<=*n*<=≤<=6), which represents the number of nodes. Each of the next *n*(*n*<=-<=1)<=/<=2 lines contains five integers *s*,<=*f*,<=*l*,<=*h*,<=*a* that describe pipes — the first node of the pipe, the second node of the pipe, the minimum and the maximum amount of fuel that can flow through the pipe and the the activation cost, respectively. (1<=≤<=*s*<=&lt;<=*f*<=≤<=*n*,<=0<=≤<=*l*<=≤<=*h*<=≤<=5,<=0<=≤<=*a*<=≤<=6). It is guaranteed that for each pair of nodes with distinct numbers there will be exactly one pipe between them described in the input. Output Specification: Output in the first line two space-separated numbers: the minimum possible amount of fuel that can flow into the synchrophasotron, and the maximum possible sum that needs to be paid in order for that amount of fuel to reach synchrophasotron. If there is no amount of fuel that can reach synchrophasotron, output "-1 -1". The amount of fuel which will flow into synchrophasotron is not neccessary positive. It could be equal to zero if the minimum constraint of every pipe is equal to zero. Demo Input: ['2\n1 2 1 2 3\n', '3\n1 2 1 2 3\n1 3 0 0 0\n2 3 3 4 5\n', '4\n1 2 0 2 1\n2 3 0 2 1\n1 3 0 2 6\n1 4 0 0 1\n2 4 0 0 0\n3 4 2 3 0\n', '3\n1 2 0 2 1\n1 3 1 2 1\n2 3 1 2 1\n'] Demo Output: ['1 4\n', '-1 -1\n', '2 15\n', '2 6\n'] Note: In the first test, we can either pass 1 or 2 units of fuel from node 1 to node 2. The minimum possible amount is 1, it costs *a*<sub class="lower-index">12</sub> + 1<sup class="upper-index">2</sup> = 4. In the second test, you can pass at most 2 units from node 1 to node 2, and at you have to pass at least 3 units from node 2 to node 3. It is impossible. In the third test, the minimum possible amount is 2. You can pass each unit of fuel through two different paths: either 1-&gt;2-&gt;3-&gt;4 or 1-&gt;3-&gt;4. If you use the first path twice, it will cost *a*<sub class="lower-index">12</sub> + 2<sup class="upper-index">2</sup> + *a*<sub class="lower-index">23</sub> + 2<sup class="upper-index">2</sup> + *a*<sub class="lower-index">34</sub> + 2<sup class="upper-index">2</sup>=14. If you use the second path twice, it will cost *a*<sub class="lower-index">13</sub> + 2<sup class="upper-index">2</sup> + *a*<sub class="lower-index">34</sub> + 2<sup class="upper-index">2</sup>=14. However, if you use each path (allowing one unit of fuel go through pipes 1-&gt;2, 2-&gt;3, 1-&gt;3, and two units go through 3-&gt;4) it will cost *a*<sub class="lower-index">12</sub> + 1<sup class="upper-index">2</sup> + *a*<sub class="lower-index">23</sub> + 1<sup class="upper-index">2</sup> + *a*<sub class="lower-index">13</sub> + 1<sup class="upper-index">2</sup> + *a*<sub class="lower-index">34</sub> + 2<sup class="upper-index">2</sup>=15 and it is the maximum possible cost. Also note that since no fuel flows from node 1 to node 4, activation cost for that pipe is not added to the answer.
```python import sys from functools import cache # input N, graph = 0, [] # output flow, total_cost = -1, -1 def read_input(): global N, graph, in_degree, out_degree readline = sys.stdin.readline N = int(readline().rstrip()) graph = [[] for _ in range(N + 1)] m = N * (N - 1) // 2 for _ in range(m): u, v, l, h, a = [int(w) for w in readline().split()] graph[u].append([v, l, h, a]) for i in range(1, N + 1): graph[i].sort() @cache def groupby(num: int, groups: int) -> list: if groups == 1: return [(num, )] result = [] for i in range(0, num + 1): subs = groupby(num - i, groups - 1) for sub in subs: result.append((i, ) + sub) return result def solve(): global flow, total_cost def dfs(node: int, pattern: tuple, cost: int)->bool: global flow, total_cost if node == N: if flow < 0 or sum(pattern) <= flow: flow = sum(pattern) total_cost = max(cost, total_cost) return True # if pattern[node] == 0: # return dfs(node + 1, pattern, cost) if pattern[node] > high_limits[node] or pattern[node] < low_limits[node]: return False result = False for sub in groupby(pattern[node], N - node): can_go = True act_cost = 0 flow_cost = 0 # print(f'node = {node}, sub = {sub}, pattern={pattern}') for i in range(len(sub)): if sub[i] == 0 and graph[node][i][1] == 0: continue if sub[i] < graph[node][i][1] or sub[i] > graph[node][i][2]: can_go = False break act_cost += graph[node][i][-1] flow_cost += sub[i] * sub[i] if not can_go: continue npattern = list(pattern) for i in range(len(sub)): npattern[node + i + 1] += sub[i] npattern[node] = 0 result |= dfs(node + 1, tuple(npattern), cost + act_cost + flow_cost) # print(f'result = {result}') return result high_limits = [0] * (N + 1) low_limits = [0] * (N + 1) for u in range(1, N + 1): for v, l, h, a in graph[u]: high_limits[u] += h low_limits[u] += l for i in range(max(low_limits), high_limits[1] + 1): temp = [0] * (N + 1) temp[1] = i if dfs(1, tuple(temp), 0): break def write_output(): # print(f"mininal flow = {flow}, max_cost = {total_cost}") print(flow, total_cost) read_input() # print(graph) solve() write_output() ```
15
Industrial Nim
Title: Industrial Nim Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: There are *n* stone quarries in Petrograd. Each quarry owns *m**i* dumpers (1<=≤<=*i*<=≤<=*n*). It is known that the first dumper of the *i*-th quarry has *x**i* stones in it, the second dumper has *x**i*<=+<=1 stones in it, the third has *x**i*<=+<=2, and the *m**i*-th dumper (the last for the *i*-th quarry) has *x**i*<=+<=*m**i*<=-<=1 stones in it. Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses. Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik». Input Specification: The first line of the input contains one integer number *n* (1<=≤<=*n*<=≤<=105) — the amount of quarries. Then there follow *n* lines, each of them contains two space-separated integers *x**i* and *m**i* (1<=≤<=*x**i*,<=*m**i*<=≤<=1016) — the amount of stones in the first dumper of the *i*-th quarry and the number of dumpers at the *i*-th quarry. Output Specification: Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise. Demo Input: ['2\n2 1\n3 2\n', '4\n1 1\n1 1\n1 1\n1 1\n'] Demo Output: ['tolik\n', 'bolik\n'] Note: none
```python import sys N = int(sys.stdin.readline().split()[0]) def ff(a: int) -> int: return [0, a - 1, 1, a][a & 3] result = 0 for _ in range(N): x, m = tuple(map(int, sys.stdin.readline().split())) result ^= ff(x) ^ ff(x + m) if result == 0: print('bolik') else: print('tolik') ```