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 f...
```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 ...
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 direct...
```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<mi...
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 fr...
```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 ...
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 ...
```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...
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...
```python ''' ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ╬╬ β–“β–“ β–“β–“ ╬╬ ╬╬ β–“β–“ β–“β–“ ╬╬ ╬╬ β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“ ╬╬ ╬╬ β–“β–“ β–“β–“ ╬╬ ╬╬ β–“β–“ β–“β–“ ╬╬ ╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬ ########################### // β€’οΈΏβ€’ \\ /\\ //\ /\\ //\ /\\//\ #########################...
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 a...
```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 = ...
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 ex...
```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...
```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...
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 lectur...
```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 == N...
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 compon...
```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 i...
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 ...
```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 ...
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,<=....
```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]: ...
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 ...
```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 -...
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...
```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 th...
```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 wh...
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 el...
```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(chi...
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 su...
```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 stud...
```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 dr...
```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 Excep...
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 n...
```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": ...
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 t...
```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 qui...
```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) ...
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 col...
```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 ...
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...
```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: ...
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 ...
```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] ...
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 ...
```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: ...
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...
```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) ...
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 j...
```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 awa...
```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) ...
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...
```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...
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 r...
```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,v...
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 r...
```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] =...
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 differen...
```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...
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*...
```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): ...
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 hum...
```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) fo...
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...
```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 = ...
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 ...
```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 ...
```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 ...
```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]+' p...
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 relea...
```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]=[i...
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. T...
```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 ...
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 ...
```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...
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...
```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-x...
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...
```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 minim...
```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...
```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("backw...
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 th...
```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 ...
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 ...
```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), '*...
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 alphabe...
```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] ...
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. ...
```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 ...
```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):...
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 ...
```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, ...
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 language...
```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(...
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 ...
```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,...
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 ...
```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=[] Se...
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 sub...
```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(): ...
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 n...
```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 ...
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 n...
```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(in...
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 an...
```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 a...
```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): ...
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...
```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...
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. ...
```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]...
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 exp...
```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 = ...
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* ...
```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[ran...
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. T...
```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...
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 ...
```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]],...
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 re...
```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. O...
```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): ...
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 ...
```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,D...
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!", β€” Vol...
```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...
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...
```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): re...
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 ...
```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 ...
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 oth...
```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(s...
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...
```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...
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 al...
```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 = ...
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. ...
```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...
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 r...
```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]...
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. Y...
```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, ...
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 ...
```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 wr...
```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 cultivat...
```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 ...
```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()) ...
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 ...
```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 s...
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...
```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...
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...
```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.s...
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. The...
```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(d...
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 thi...
```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 ...
```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+...
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 ju...
```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(d...
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 num...
```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: lis...
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* classr...
```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....
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...
```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...
```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 ...
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...
```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: pr...
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...
```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...
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 oth...
```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: ...
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...
```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...
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 mak...
```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 ...
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. Pipe...
```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 ran...
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,...
```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') ```