problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
1
lst = [0,0,0] def doit(string): num = int(string) lst[num%3]+=1 return 0 x=raw_input() ls = map(doit,raw_input().split(' ')) print lst[0]/2 + min(lst[1],lst[2])
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es...
3
def input_split(f): return map(f, input().split()) def main(): n, r, avg = input_split(int) ex = [] sum_a = 0 for i in range(n): ai, bi = input_split(int) sum_a += ai ex.append([bi, ai]) ex.sort() le = avg*n - sum_a res = 0 i = 0 while le > 0: bi, ai...
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa...
3
a , b = input().split() a = int(a) for i in range(a): x = input() if i % 2 == 0: d = 0 else: d = 1 for j in range(len(x)): if x[j] == '.': if d % 2 == 0: print('B' , end = '') d = d + 1 else: print('...
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
from bisect import * from collections import * for _ in range(int(input())): n=int(input()) l=list(input()) if(n<11): print('NO') continue #print(l[:(len(l)-11)+1]) if('8' in l[:(len(l)-11)+1]): print('YES') else: print('NO')
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n=int(input()) dp=[99]*(101) dp[0]=0 for i in range(1,101): dp[i]=min(dp[i-1],dp[i-5],dp[i-10],dp[i-20],dp[i-100])+1 print(dp[n%100]+n//100)
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order. Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≤ i ≤ n), that s_i < t_i, and for a...
3
from math import sqrt def FindPos(k): temp=int(sqrt(2*k))+1 if(temp-1)*temp/2<k<=(temp+1)*(temp)/2: return temp else: return temp-1 t=int(input()) res=[] for i in range(t): n,k=map(int,input().split()) Pos=FindPos(k) index1=n-Pos index2=int(n-(k-Pos*(Pos-1)/2)+1) temp='a'...
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
3
import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def solve(): n = int(input()) a = list(map(int, input().split())) ans = len(set(a)) print(ans) t = int(input()) for i in range(t): solve()
There are N blocks arranged in a row, numbered 1 to N from left to right. Each block has a weight, and the weight of Block i is A_i. Snuke will perform the following operation on these blocks N times: * Choose one block that is still not removed, and remove it. The cost of this operation is the sum of the weights of t...
3
MOD = 10 ** 9 + 7 n = int(input()) a = list(map(int, input().split())) csum_invs = [0] t = 0 for i in range(1, n + 1): t += pow(i, MOD - 2, MOD) t %= MOD csum_invs.append(t) # print(csum_invs) fact = [] t = 1 for i in range(1, n + 1): t *= i t %= MOD fact.append(t) # print(fact) ans = 0 for ...
There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below: There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"...
3
le=int(input()) for _ in range(le): str1=input() count=0 arr=[1,2,3,4,6,12] arr1=[] for num in arr: flag=False i=12//num for j in range(i): if(str1[j]=="X"): flag=True z=j while(z<12): ...
Kurohashi has never participated in AtCoder Beginner Contest (ABC). The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same. What is the earliest ABC where Kurohashi can make his debut? Constraints * 100 \leq N...
3
a=int(input()) a+=110 a//=111 a*=111 print(a)
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
count = 0 string = input() for i in range(1, len(string)) : if string[i] >= 'A' and string[i] <= 'Z' : count += 1 if count == len(string) - 1 : if string[0] >= 'a' and string[0] <= 'z' : print(string[0].upper(), end = '') else : print(string[0].lower(), end = '') for i in range(1, len...
Takahashi and Aoki will have a battle using their monsters. The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively. The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ... Here, an attack decreases ...
3
a,b,c,d=map(int,input().split()) if (-c//b)*(-1)<=(-a//d)*(-1): print('Yes') else: print('No')
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to...
3
s = input() a = 0 b = 0 for c in s: if (c >= 'a' and c <= 'z'): a = min(a, b) b = b + 1 else: a = min(a, b) + 1 print(min(a,b))
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
#A - Cards: 10 min n = int(input()) word = input() dicionario = {'o':0, 'n':0, 'e':0, 'z':0, 'e':0, 'r':0,} for e in word: dicionario[e] += 1 ans = [] while dicionario['o'] > 0 and dicionario['n'] > 0 and dicionario['e'] > 0: ans.append(1) dicionario['o'] -= 1 dicionario['n'] -= 1 dicionario['e'] -=...
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
3
from sys import stdin, stdout #import sys INF=1e11 import bisect def get_int(): return int(stdin.readline().strip()) def get_ints(): return map(int,stdin.readline().strip().split()) def get_array(): return list(map(int,stdin.readline().strip().split())) def get_string(): return stdin.readline().strip() def op(c): retu...
A sequence a_1, a_2, ..., a_k is called an arithmetic progression if for each i from 1 to k elements satisfy the condition a_i = a_1 + c ⋅ (i - 1) for some fixed c. For example, these five sequences are arithmetic progressions: [5, 7, 9, 11], [101], [101, 100, 99], [13, 97] and [5, 5, 5, 5, 5]. And these four sequence...
1
if True: n = input() arr = map(int,raw_input().split(" ")) arr2 = [i for i in arr] arr.sort() def test(arr,pos): if len(arr)<=3: return True if pos >=len(arr): return False tmp = [arr[i] for i in range(len(arr)) if i!=pos] if len(set([tmp[i]- tmp[i-1] f...
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
1
import sys s = sys.stdin.readline().split() print (len(s[0]) + 1) * 26 - len(s[0])
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n = int(input()) total = 0 ans = 0 for i in range(n): a,b = list(map(int, input().split())) total -= a total += b ans = max(total, ans) print(ans)
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
s1 = input() s2 = input() def func(s1,s2): for i,j in list(zip(s1,s2)): if i.lower() == j.lower(): continue elif i.lower() < j.lower() : return -1 else: return 1 return 0 res = func(s1,s2) print(res)
Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the Ox axis from west to east, and th...
3
class Point(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return str(self.x) + ',' + str(self.y) class Vec(): def __init__(self, x, y): self.x = x self.y = y def cross(a, b): return a.x * b.y - a.y * b.x def toVec(a,b): return Vec(b...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
a= input() if len(a) ==1 and a[0].islower(): print(a.upper()) elif a[0].islower() and a[1::].isupper(): print(a[0].upper()+a[1::].lower()) elif a[::].isupper():print(a[::].lower()) else: print(a)
In some other world, today is December D-th. Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22. Constraints * 22 \leq D \leq 25 * D is an integer. Input Input is given from Standard Input in the following format: D ...
3
D = int(input()) x = "Christmas" + (" Eve")*(25-D) print(x)
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
def solve(n, k): return n * (k // (n - 1)) + (k % (n - 1)) - (1 if k % (n - 1) == 0 else 0) cases = int(input()) for _ in range(cases): print(solve(*map(int, input().split())))
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n = int(input()) arr = [int(x) for x in input().split()] s = sum(arr) if(s == 0): print("Easy") else: print("Hard")
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
3
t=int(input()) for i in range(t): x=input().split() y=input().split() for j in range(2): x[j]=int(x[j]) y[j]=int(y[j]) if max(x)==max(y): if min(x)+min(y)==max(x): print('YES') else: print('NO') else: print('NO')
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ...
1
from sys import stdin n, a, x, b, y = map(int, stdin.readline().split()) while a != x and b != y: if a == b: print('YES') exit() a = a + 1 if a < n else 1 b = b - 1 if b > 1 else n print('YES' if a == b else 'NO')
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n=int(input()) x=0 for i in range(n): spam=input() if '++' in spam: x=x+1 if '--' in spam: x=x-1 print(x)
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells c...
3
for _ in range(int(input())): n, m = map(int, input().split()) a = [] for i in range(n): a.append(list(map(int, input().split()))) for j in range(m): if i % 2 == 0: if j % 2 == 0: if a[i][j] % 2: a[i][j] += 1 else: if a[i][j] % 2 == 0: a[i][j] += 1 else: if j % 2: if ...
You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique). Input The first line contains a single positive integer t (1 ≤ t ≤ 50) — the number of test cases in the test. Then t test cases follow. Each test case consists of ...
1
from __future__ import division, print_function from itertools import permutations import threading,bisect,math,heapq,sys # threading.stack_size(2**27) # sys.setrecursionlimit(10**4) from sys import stdin, stdout i_m=9223372036854775807 def cin(): return map(int,sin().split()) def ain(): ...
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer! Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher...
3
s1=input() s2=input() s3=input() s11='';s22='';s33='' m=[';','_','-'] p=[] for i in range(len(s1)): if s1[i] not in m: s11=s11+s1[i] s11=s11.lower() for i in range(len(s2)): if s2[i] not in m: s22=s22+s2[i] s22=s22.lower() for i in range(len(s3)): if s3[i] not in m: s33=s33+s3[i] s33...
Let's play Hit and Blow game. A imagines four numbers and B guesses the numbers. After B picks out four numbers, A answers: * The number of numbers which have the same place with numbers A imagined (Hit) * The number of numbers included (but different place) in the numbers A imagined (Blow) For example, if A imagin...
3
# -*- coding: utf-8 -*- import sys import os import math lines = sys.stdin.readlines() game_num = len(lines) // 2 for i in range(game_num): s0 = lines[2 * i].strip() s1 = lines[2 * i + 1].strip() A = list(map(int, s0.split())) B = list(map(int, s1.split())) hit = 0 blow = 0 for j in ran...
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:...
1
for _ in range(input()): n=input() a=[int(i) for i in raw_input().split()] b=sorted(a) dp=[0 for i in range(n+1)] d={} for i in range(n): d[b[i]]=i+1 for i in range(n): dp[d[a[i]]]=1+dp[d[a[i]]-1] maxx=max(dp) print n-maxx
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
3
# from bisect import bisect_left TC = int(input()) for tc in range(TC): N, K = map(int, input().split()) S = list(input()) w = 0 l = [] rw = 0 rl = 0 start = 0 for s in S: if s == 'W': if rl > 0: if w > 0: l.append(rl) ...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
arr = [str(x) for x in input().split('WUB') if len(str(x)) > 0] for i in arr: print(i, end = ' ')
This is an interactive problem. You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x. More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the int...
3
import random from sys import stdout idx_len, start_idx, x = (int(x) for x in input().split()) random.seed(153) requests = (list(range(1, idx_len + 1))) random.shuffle(requests) val_next = [(-1, start_idx)] for request in requests[:999]: print('? {}'.format(request)) stdout.flush() value, next = (int(x) ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
a = [input().lower(), input().lower()] print(0) if a[0] == a[1] else (print(1) if a[0] > a[1] else print(-1))
Let w be a string consisting of lowercase letters. We will call w beautiful if the following condition is satisfied: * Each lowercase letter of the English alphabet occurs even number of times in w. You are given the string w. Determine if w is beautiful. Constraints * 1 \leq |w| \leq 100 * w consists of lowercas...
1
y=list(raw_input()) f=0 for i in set(y): if y.count(i)%2!=0: f=1 break if f: print "No" else: print "Yes"
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha...
3
from datetime import timedelta, datetime start_time = input() end_time = input() time_format = '%H:%M' # Convert to the datetime object start = datetime.strptime(start_time, time_format) end = datetime.strptime(end_time, time_format) # Find half of delta between start and end half_seconds = (end - start)/ 2 half = ...
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
1
s=raw_input() def differentfromthesetwo(a,b): if a!='a' and b!='a': return 'a' elif a!='b' and b!='b': return 'b' return 'c' n=len(s) if n==1: print s else: news=s[0] for i in xrange(1,n): if s[i]==news[i-1]: if i<n-1: news+=differentfromthes...
In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education. One day, there was an exam where a one-year-old child must write a program that prints `Hello World`, and a two-year-old child must write a program that receives integers A, B...
3
print('Hello World') if input()=='1' else print(int(input())+int(input()))
AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to sched...
3
d=int(input()) c=list(map(int,input().split())) for i in range(d): c=list(map(int,input().split())) print(c.index(max(c))+1)
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
3
a=input() lst = input().split() max = int(lst[0]) min = int(lst[0]) count = 0 for i in lst: i=int(i) if i > max: max = i count+=1 if i < min: min = i count+=1 print(count)
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. Input The first line contains a nu...
3
x = input() alph = "" i = 0 while i < len(x) : if x[i] == '-': if x[i+1] == '.': alph += '1' elif x[i+1] == '-': alph += '2' i += 2 else: alph += '0' i += 1 print(alph)
10^9 contestants, numbered 1 to 10^9, will compete in a competition. There will be two contests in this competition. The organizer prepared N problems, numbered 1 to N, to use in these contests. When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclus...
3
#!/usr/bin/env python3 import sys sys.setrecursionlimit(10**8) # input = sys.stdin.readline n = int(input()) lr = [] for i in range(n): l, r = [int(item) for item in input().split()] lr.append((l, r)) lr.sort() al = lr[0][0]; ar = lr[0][1]; anum = ar - al + 1 bl = lr[1][0]; br = lr[1][1]; bnum = br - bl + 1 # ...
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points. At any time Andrew can visit the store where tasty buns are sold (y...
3
from math import ceil hh, mm = [int(x) for x in input().split()] h, d, c, n = [int(x) for x in input().split()] cost = 0.8 * c if hh >= 20 else c res = int(ceil(h / n)) * cost if hh < 20: diff = (20 - hh) * 60 - mm diff *= d h += diff res = min(res, int(ceil(h / n)) * 0.8 * c) print(res)
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
# cook your dish here for _ in range(int(input())): x,y,a,b=map(int,input().split()) q=(y-x)%(a+b) if(q==0): print((y-x)//(a+b)) else: print("-1")
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs). <image> Fig. 1 A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertic...
3
class Node: def __init__(self, num, children): self.num = num self.children = children self.parents = -1 self.type = None self.depth = 0 def output(self): print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(self.num, ...
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
3
for _ in range(int(input())): s=input() a=[] j=0 while j<len(s): if s[j]=="1": t=0 for k in range(j,len(s)): if s[k]=="1": j+=1 t+=1 else:break a.append(t) else: ...
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e...
3
t =int(input()) for i in range(t): n = int(input()) s = input().split(' ') a = [] for c in s: a.append(int(c)) a.reverse() for i in range(n): if i % 2 == 0: a[i] = -a[i] for i in range(n): print(a[i], end = ' ') print()
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the ar...
3
n=int(input()) a=list(map(int,input().split())) lastocc=[0]*1000006 ans=[0]*n ans[0]=1 lastocc[a[0]]=1 for i in range(1,n): ans[i]=ans[i-1]+(i+1-lastocc[a[i]]) lastocc[a[i]]=i+1 print((2*sum(ans)-n)/(n*n))
Alice and Bob have decided to play the game "Rock, Paper, Scissors". The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ...
3
a=int(input()) d,r,l=map(int,input().split(" ")) z,j,k=map(int,input().split(" ")) maxx=min(l,z)+min(d,j)+min(r,k) minn=max(0,l-(j+k))+max(0,d-(z+k))+max(0,r-(z+j)) print(minn,maxx)
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thu...
3
""" Author - Satwik Tiwari . 18th Feb , 2021 - Thursday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import Byt...
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be...
3
a,b,c,d = map(int,input().split()) t = a//b k = min((b-a%b)*c,(a%b)*d) print(k)
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t...
3
n = int(input()) votes = list(map(int, input().split())) print(max((sum(votes) * 2) // n + 1, max(votes)))
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
3
from functools import reduce import collections import math import sys class Read: @staticmethod def string(): return input() @staticmethod def int(): return int(input()) @staticmethod def list(delimiter=' '): return input().split(delimiter) @staticmethod d...
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
s = input("").split() m = int(s[0]) n = int(s[1]) mono = m*n dominoes = m*n//2 print(dominoes)
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
1
s=raw_input() t='' while len(s)>0: while s[0:3]=='WUB': s=s[3:] if len(s)>0: pos=s.find('WUB') if pos!=-1: t=t+s[:pos]+' ' s=s[pos:] else: t+=s s='' print t
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
3
s=input() ls=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] j=1 d={} for i in ls: d[i]=j j=j+1 c=0 ip='a' for i in s: x1=abs(d[i]-d[ip]) x2=26-x1 c=c+min(x1,x2) ip=i print(c)
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ...
3
n,a,x,b,y=map(int,input().split()) m = min((x-a)%n,(b-y)%n) #print(m) flag=False for i in range(1,m+1): if(a+i)%n==(b-i)%n: flag=True break print("YES" if flag else "NO")
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
1
myin = raw_input() small = 'abcdefghijklmnopqrstuvwxyz' big = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' change = True for i in range(1, len(myin)): if myin[i] in small: change = False out = '' if change == True: if myin[0] in small: temp = small.index(myin[0]) out += big[temp] myin = my...
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in...
3
n,v=map(int,input().split()) if n-1<=v: print(n-1) else: for i in range(n): if i==0: k=v else: k+=i+1 if i+v==n-1: break print(k)
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
t = int(input()) for _ in range(t): n = int(input()) if n % 2 == 1: print(int(n / 2)) else: print(int(n/2) - 1)
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
3
n = int(input()) cards = [int(i) for i in input().split()] first, second = int(), int() for i in range(len(cards)): if not len(cards): break if i % 2 == 0: if cards[0] > cards[-1]: first += cards[0] del cards[0] else: first += cards[-1] d...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
''' # Петя и строки s = input().lower() s1 = input().lower() if s > s1: print(1) elif s < s1: print(-1) else: print(0) # Футбол s = input() if '1111111' in s or '0000000' in s: print('YES') else: print('NO') # Юра и заселение n = int(input()) k = 0 for i in range(n): p, q = map(int, input().spli...
You're given an array a of length n. You can perform the following operations on it: * choose an index i (1 ≤ i ≤ n), an integer x (0 ≤ x ≤ 10^6), and replace a_j with a_j+x for all (1 ≤ j ≤ i), which means add x to all the elements in the prefix ending at i. * choose an index i (1 ≤ i ≤ n), an integer x (1 ≤ x ≤...
3
n=int(input()) a=list(map(int,input().split(' '))) print(n+1) print(1,n,10**5) for i in range(n): a[i]=a[i]+10**5 for i in range(n): k=a[i]-i print(2,i+1,k)
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
3
first = input().lower() second = input().lower() for chars in zip(first, second): if chars[0] < chars[1]: print(-1) break elif chars[0] > chars[1]: print(1) break else: print(0)
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
3
a, b, c = map(int, input().split()) d = abs(a-b) if(d <= c and c != 0): print("?") elif(d == 0): print("0") elif(a>b): print("+") else: print("-")
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
3
def get_prime_set(ub): from itertools import chain from math import sqrt if ub < 4: return ({}, {}, {2}, {2, 3})[ub] ub, ub_sqrt = ub+1, int(sqrt(ub))+1 primes = {2, 3} | set(chain(range(5, ub, 6), range(7, ub, 6))) du = primes.difference_update for n in chain(range(5, ub_sqrt, 6),...
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage. ...
1
N = input() print (N + 1) / 2
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it. ...
3
from sys import stdout,stdin from collections import defaultdict t=int(input()) for _ in range(t): n=int(input()) #n,m=map(int,input().split()) #l=list(map(int,input().split())) #b=list(map(int,input().split())) z=n//4 r=n%4 s='' for i in range(n-z-1): s+='9' if r>0: ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
1
n = input() for i in range(n): word = raw_input() if len(word) >10: print word[0] + str(len(word)-2) + word[-1] else: print word
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
def iip(): return int(input()) def sip(): return input() def mip(): return map(int,input().split()) def lip(): return list(map(int,input().split())) m,n = mip() print(m*n//2)
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ...
3
a = int(input()) b = int(input()) c = int(input()) z = min(a,b//2,c//4) print(z*7)
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands: * 'L' (Left) sets the position x: =x - 1; * 'R' (Right) sets the position x: =x + 1. Unfortunately, Mezo's controller malfunctions sometimes. ...
3
n,a=int(input()),input() print(n+1)
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with n buttons. Determine if it is fasten...
1
n=input() x=map(int,raw_input().split()) if n==1 and x[0]==1: print "YES" elif n==1 and x[0]==0: print "NO" else: c0=0 c1=0 for i in range(n): if x[i]==0: c0+=1 elif x[i]==1: c1+=1 if c0==1: print "YES" else: print "NO"
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th...
3
n = int(input()) ans = [0] * (2 * n) flag = True cnt = 1 for i in range(n): idx = (i + n) % (2 * n) if ans[i] == 0: ans[i] = cnt if flag else cnt + 1 if ans[idx] == 0: ans[idx] = cnt + 1 if flag else cnt cnt += 2 flag = not flag prev = ans[-1] - ans[-1 - n] for i in range(2 * n):...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
3
n=int(input()) s='abcd' ans=s*(n//4) ans+=s[0:n%4] print(ans)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
# your code goes here h=int(input()) count=0 for i in range(h): sum=0 r=input() x=r.split() sum = int(x[0])+int(x[1])+int(x[2]) if sum>=2: count+=1 print(count)
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
1
rd = lambda: list(map(int,raw_input().split())) z = [] for i in 'ii': a = rd() z += [a[::2], a[1::2]] for x in z: x.sort() u, v, x, y = z for i in range(u[0], u[3] + 1): for j in range(v[0], v[3] + 1): if x[0] + y[1] <= i + j <= x[3] + y[1] and y[0] - x[1] <= j - i <= y[3] - x[1]: pr...
N of us are going on a trip, by train or taxi. The train will cost each of us A yen (the currency of Japan). The taxi will cost us a total of B yen. How much is our minimum total travel expense? Constraints * All values in input are integers. * 1 \leq N \leq 20 * 1 \leq A \leq 50 * 1 \leq B \leq 50 Input Input i...
3
a,b,c = map(int,input().split()) print(c if c<a*b else a*b)
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n = int(input()) sad = n//100 n = n - sad*100 bist = n//20 n = n - bist*20 dah = n // 10 n = n - dah * 10 panj = n // 5 n = n - 5*panj yek = n print(sad+bist+dah+panj+yek)
On the way to school, Karen became fixated on the puzzle game on her phone! <image> The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col...
1
R = lambda: map(int, raw_input().split()) n, m = R() a = [R() for _ in xrange(n)] rows_first = n <= m row_name = 'row' col_name = 'col' if not rows_first: a = map(list, zip(*a)) row_name, col_name = col_name, row_name n, m = m, n state = [[0] * m for _ in xrange(n)] moves = [] for row_idx in xrange(n): ...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
L = input() N = len(L) k1 = 0 k0 = 0 for i in range (N): if L[i] == '1': k1 += 1 if k1 >= 7: break if L[i] == '0': k1 = 0 for i in range (N): if L[i] == '0': k0 += 1 if k0 >= 7: break if L[i] == '1': k0 = 0 if k1 >= 7 o...
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1". More formally, f(s) is equal to the ...
3
import sys # from itertools import # from collections import deque # import math # from bisect import bisect import io,os # input = sys.stdin.buffer.readline # input = sys.stdin.readline input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # def in1(): # return int(input()) # def in3(): # return map(in...
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, ...
3
t = int(input()) for i in range(t): n = int(input()) a= list(map(int , input().split())) a.sort(reverse=True) for j in a: print(j ,end = ' ') print()
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
3
n = int(input()) if n<=10 or n>21: print(0) elif 11<=n<=19 or n==21: print(4) else: print(15)
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re...
3
import math from collections import defaultdict a=int(input()) for i in range(a): x,k=map(int,input().split()) s=input() ans=[s[i] for i in range(len(s))] ans.sort() al=defaultdict(int) for i in range(len(s)): al[s[i]]+=1 fin=[] for i in range(k): fin.append(ans[i]) ...
You are planning to buy an apartment in a n-floor building. The floors are numbered from 1 to n from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor. Let: * a_i for all i from 1 to n-1 be the time required to go from the i-th floor...
3
# -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a...
You are given a permutation of length n. Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (n=3 but there is 4 ...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). Input The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. Output Print "YES" (without the quot...
1
st=raw_input() a1=st.find('AB') a2=st.find('BA',a1+2) b1=st.find('BA') b2=st.find('AB',b1+2) if (a1!=-1 and a2!=-1) or (b1!=-1 and b2!=-1): print 'YES' else: print 'NO'
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
3
n=int(input()) a=list(map(int,input().split(maxsplit=6))) i=0 while n>0: if i==7: i=0 n=n-a[i] i=i+1 print(i)
You are given two integers n and k. You should create an array of n positive integers a_1, a_2, ..., a_n such that the sum (a_1 + a_2 + ... + a_n) is divisible by k and maximum element in a is minimum possible. What is the minimum possible maximum element in a? Input The first line contains a single integer t (1 ≤ ...
3
from collections import defaultdict import math for _ in range(int(input())): #n=int(input()) n,k=list(map(int,input().split())) #d=defaultdict(lambda:0) if n==k: print(1) elif n<k: print(math.ceil(k/n)) else: x=int((n+k-1)/k) k=k*x print((k+n-1)//n)
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. Input The first line contai...
3
a, b = int(input()), int(input()) sizes = [int(input()) for x in range(a)] sizes = sorted(sizes)[::-1] u = 0 n = 0 while n < b: n += sizes[u] u += 1 print(u)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
1
a=raw_input() i=0 q=0 while i< len(a) : j=i+1 c=1 while j < len(a): if a[j]==a[i]: c=c+1 else: break if c>=7: print "YES" i=len(a) q=1 break j=j+1 i=i+1 if q!=1: print "NO"
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
import sys n, k = map(int, input().split()) a = map(int, input().split()) print(len([x for x in a if x + k <= 5]) // 3)
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. <image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano...
3
def mi(): return map(int, input().split()) n,k = mi() a = list(mi()) maxs = s = sum(a[:k]) index = 0 for i in range(k,n): s += a[i] s -= a[i-k] if s<maxs: maxs = s index = i-k+1 print (index+1)
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there? Here, a Shichi-Go number is a positive integer that has exactly 75 divisors. Constraints * 1 \leq N \leq 100 * N is an integer. Input Input is given from S...
3
data = int(input()) e = [0] * (data+1) for i in range(2, data+1): cur = i for j in range(2, i+1): while cur % j == 0: e[j] += 1 cur //= j def num(m): return len(list(filter(lambda x: x >= m-1, e))) print(num(75) + num(25)*(num(3)-1) + num(15)*(num(5)-1)+num(5)*(num(5)-1)*(...
Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (...
3
v,e=list(map(int,input().split())) la=v fa=e for x in range(e): if v<=0: break else: v-=2 if v<=0: kam=0 else: kam=v v=la e=fa ti=2 dim=1 for x in range(5555555): if e!=0 and v>0: if dim>=e: v-=ti break ti+=1 dim+=ti-1 else: b...
Given is a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i. Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different. Among the colo...
3
import sys input = sys.stdin.readline n = int(input()) edges = [] for id in range(n-1): a, b = map(int, input().split()) edges.append([a-1, b-1, id]) edges.sort() used = [0]*(n) ans = [0]*(n-1) num = 1 prev = 0 for edge in edges: _from, to, id = edge if _from != prev: num = 1 if used[_fr...
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1. The decoding of the lever description is ...
3
lever = input() pivot = lever.find("^") left = 0 for i in range(pivot): if lever[i] != '=': w = int(lever[i]) #print("left w: ", w, " in ", i) left += (w * (pivot - i)) right = 0 for i in range(pivot+1, len(lever)): if lever[i] != '=': w = int(lever[i]) #print("right w: ", w, " in ", i) right += (w * (i...