problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0. Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he...
3
n=int(input()) ans=n a=1234567 b=123456 c=1234 ch=True count_a=n//a count_b=n//b count_c=n//c for i in range(count_a+1): n=ans n=n-i*a ans2=n for j in range(count_b+1): n=ans2 n=n-j*b if n<0: break elif n%c==0: ...
A permutation of length n 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 in the array). Consider a permutation p of length ...
3
import os import sys from io import BytesIO, IOBase # region fastio 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 self.write = self.buffer.wr...
Requirements * All inputs are of non-negative integer value. * T_{\text{max}} = 10000 * 200 \leq |V| \leq 400 * 1.5 |V| \leq |E| \leq 2 |V| * 1 \leq u_{i}, v_{i} \leq |V| (1 \leq i \leq |E|) * 1 \leq d_{u_i, v_i} \leq \lceil 4\sqrt{2|V|} \rceil (1 \leq i \leq |E|) * The given graph has no self-loops / multiple edges a...
3
for i in range(10000): print(-1)
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round. You are a new applicant for his company. Boboniu will test you with the following chess question: Consider a n× m grid (rows are numbered from 1 to n, and columns are nu...
3
n,m,x,y=[int(i) for i in input().split()] ans=[] x=x-1 y=y-1 down=n-1-x up=n-1 d=[[-1 for i in range(m)]for i in range(n)] done=[] pos=y while(n>0): if -1 in d[x]: n-=1 d[x][pos]=0 ans.append(((x+1),(pos+1))) while(-1 in d[x]): pos=d[x].index(-1) ...
Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest. In this game, an honest player always tells the truth, and an dishonest player always tell lies. You are given two characters a and b as the input. Each of them is either `H` or `D`, and carries the following information: If a=`H`, AtCoDe...
3
a,b = map(str,input().split()) print('H') if a == b else print('D')
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them. Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 ...
1
import sys from math import atan2 from fractions import Fraction range = xrange inp = [int(x) for x in sys.stdin.read().split()] ind = 0 n = inp[ind] ind += 1 X = inp[ind:2*n+ind:2] Y = inp[ind+1:2*n+ind:2] ind += 2*n # Sort using floating point numbers def anglesort(index): return sorted(index, key=lambda i: ...
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
3
arr = "qwertyuiopasdfghjkl;zxcvbnm,./" dic = {"q":["","w"],"/":[".",""]} for i in range(1,len(arr)-1): dic[arr[i]] = [arr[i-1],arr[i+1]] shift = input() word = input() ans = [] if shift == "L": for e in word: ans.append(dic[e][1]) else: for e in word: ans.append(dic[e][0]) print("".join(ans)...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
def main(): n = int(input()) s = [int(i) for i in input().split()] reqTaxi = 0 count1= 0 count2 = 0 count3 = 0 for i in s: if i is 4: reqTaxi += 1 elif i is 3: count3 += 1 elif i is 2: count2 += 1 else: count1 += 1 count1 = count1 - count3 reqTaxi += count3 reqTaxi += (2*count2)//4 if...
There are N empty boxes arranged in a row from left to right. The integer i is written on the i-th box from the left (1 \leq i \leq N). For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it. We say a set of choices to put a ball or not in the boxes is good when the following con...
3
n=int(input()) A=[0]+list(map(int,input().split())) for i in range(n,0,-1): if sum(A[::i])%2!=A[i]: A[i]^=1 print(sum(A)) for i,a in enumerate(A): if a==1:print(i)
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
3
a = input() u = input() v = ["a","e", "i","o", "u"] def main(): if len(a) != len(u): return("No") for i in range(len(a)): if (a[i] in v and u[i] in v) or (a[i] not in v and u[i] not in v): continue else: return("No") return("Yes") print(...
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
x = input() y = len(set(x)-set(' {},')) print(y)
Joisino is planning to open a shop in a shopping street. Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those ...
3
n = int(input()) f = [] for _ in range(n): s = 0 l = list(map(int, input().split())) for i in range(10): s += l[i]<<i f.append(s) p = [list(map(int, input().split())) for _ in range(n)] b = [] for i in range(1,1024): w = 0 for j in range(n): idx = format(i & f[j], 'b').count('1')...
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
1
data = map(int, raw_input().split()) scalar = data[0] init = data[1] banana = data[2] moneyneed = scalar*(banana)*(banana+1)/2 if moneyneed>init: print moneyneed-init else: print '0'
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100)...
3
from math import sqrt def szuk_podz(liczba, a = 1): for x in range(2, int(sqrt(liczba)) + 1): if liczba % x == 0 and x != a: return x return -1 for _ in range(int(input())): n = int(input()) a, b, c = szuk_podz(n), 0, 0 x = n // a if a == -1: print("NO") conti...
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t...
3
n = int(input()) front = list(map(int,input().split())) m = int(input()) rear = list(map(int,input().split())) integers = [] for i in front: for k in rear: if int(k/i)==k/i: integers.append(int(k/i)) print(integers.count(max(integers)))
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once. A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character...
3
def countChar(d): for ch in d.values(): if ch == 0: return False return True for i in range(int(input())): arr = input() n = len(arr) f = 0 l = 0 c = 0 d = {"1":0,"2":0,"3":0} x = n+1 while f<=l and l<n: if f == c: char = arr[l] ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n,k = list(map(int, input().split(" "))) cont = list(map(int, input().split(" "))) adv = [1 if (c >= cont[k-1] and c > 0) else 0 for c in cont] print(sum(adv))
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
x, y, z = list(map(int, input().split())) if x - y - z > 0: print('+') exit() if y - x - z > 0: print('-') exit() if x == y and z == 0: print('0') exit() print('?')
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum. For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for t values of n. Input The first line of...
3
for t in range(int(input())): x=int(input()) a=len(bin(x))-2 b=((2**a)-1) print(x*(x+1)//2-2*b)
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate. The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each...
3
n, m = map(int, input().split()) a = n * [0] for i in range(m): x = list(map(int, input().split())) a[x.index(max(x))] += 1 print(a.index(max(a)) + 1)
We have N weights indexed 1 to N. The mass of the weight indexed i is W_i. We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be th...
3
N=int(input()) W=list(map(int, input().split())) ans=1000 for t in range(1,N+1): ans=min(ans,abs(sum(W[:t])-sum(W[t:]))) print(ans)
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
a, b = input().split() a, b = int(a), int(b) for n in range(b): if a%10 == 0: a=int(a/10) else: a=a-1 print(a)
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
3
""" This template is made by Satwik_Tiwari. python programmers can use this template :)) . """ #=============================================================================================== #importing some useful libraries. import sys import bisect import heapq from math import * from collections import Cou...
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
3
n=int(input()) ansx=[] ansy=[] m=1 x=1 y=1 ansx.append(1) ansy.append(1) for i in range(1, n): if x<=y: x+=1 ansx.append(x) ansy.append(y) else: y+=1 ansx.append(x) ansy.append(y) if x<=y: m=y else: m=x print(m) for i in range(n): print(ansx[i], ansy[i...
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard. Initially, you have an empty string. Until you type the whole string, you may perform the following operation: * add a character to the end of the string. Besides, at most once you may perform one...
1
n=input() st=raw_input() c=1 f=1 for i in range(1,n/2+1): if st[0:2*i]==st[0:i]*2: f=i print n-f+1
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()) lst = map(int, input().split()) if len(list(filter(lambda x: x > 0, lst))) > 0: print("HARD") else: print("EASY")
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...
3
a = int(input()) for i in range(a): b=input() if len(b)>10: cent=len(b)-2 ans=b[0]+str(cent)+b[len(b)-1] print (ans) else: print(b)
You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K. a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K? Constraints * All input values are integers. * 1 ≤ N ≤ 2 ...
3
def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] def input(): return sys.stdin.readline().rstrip() def rand_N(ran1, ran2): return random.randint(ran1,...
...Mike the TV greets you again! Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you! This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other...
1
ver = ['000 000 000','000 010 000','001 000 100','001 010 100','101 000 101','101 010 101','101 101 101'] gor = ['000 000 000','000 010 000','100 000 001','100 010 001','101 000 101','101 010 101','111 000 111'] for i in range(len(gor)): gor[i] = gor[i].replace(' ','') ver[i] = ver[i].replace(' ','') g = set(...
This is an easier version of the problem. In this version n ≤ 1000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ...
3
from math import log2 class Sparse: def __init__(self, a): self.a = a self.n = len(a) self.k = int(log2(self.n)) + 1 self.lookup = [[0]*self.k for x in range(self.n)] self.process() def process(self): for i in range(self.n): self.lookup[i][0] = self...
Ashish has n elements arranged in a line. These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i. He can perform the following operation any number of t...
3
z,zz=input,lambda:list(map(int,z().split())) zzz=lambda:[int(i) for i in stdin.readline().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collections import * from math import * fro...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
def AStringTask(string): out = "" string = string.lower() for x in string: if (x != "a" and x != "o" and x != "y" and x != "e" and x != "u" and x != "i"): out += "."+x print out string = raw_input() AStringTask(string)
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them. Constraints * $1 \leq n \leq 100,000$ * $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$ * Two parallel segments never overlap or touch. * The number of intersections $\leq 1,000,000$ Input In the fi...
3
import sys import bisect readline = sys.stdin.readline n = int(readline()) EP = [] l = -1000000001 u = 1000000001 vs_x = set() h_num = 0 for _ in [0] * n: x1, y1, x2, y2 = (map(int, readline().split())) if x1 == x2: if y1 < y2: EP.append((y1, l, x1)) EP.append((y2, u, x1)) ...
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
3
k = int(input()) l = int(input()) m = int(input()) n = int(input()) d = int(input()) s=0 y=1 for i in range(d): if y%k==0: s+=1 y+=1 elif y%l==0: s+=1 y+=1 elif y%m==0: s+=1 y+=1 elif y%n==0: s+=1 y+=1 else: s=s+0 y+=1...
In a company an emplopyee is paid as under: If his basic salary is less than Rs. 1500, then HRA = 10% of base salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the Employee's salary is input, write a program to find his gross sa...
1
t=int(input()) for i in range (t): salary= input() gross = 0 if (salary<1500): gross =2*salary else: gross= salary+(0.98*salary+500) print "{0:g}".format(gross)
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains. Mountains are described by a sequence of heights...
3
class Solution: def solve(self, n, k, a): peak = [0 for i in range(0, n)] total = [0 for i in range(0, n)] for i in range(1, n): if i + 1 < n and a[i] > a[i - 1] and a[i] > a[i + 1]: peak[i] = 1 total[i] = total[i - 1] + peak[i] largest, pos = ...
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
n=int(input()) for i in range(n): k=int(input()) l=set(map(int,input().split())) print(len(l))
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
3
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] # def LF(): return [float(x) for x in s...
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre...
3
import math # import bisect import sys # from collections import Counter input = sys.stdin.readline def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s)-1]) def invr(): return(map(int,input().split())) def print_fract(p,q): g = math.gcd(p,q) ...
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
3
t = int(input()) for i in range(0, t): n = int(input()) arr = [int(x) for x in input().split()] for j in range(0, n): if j % 2 == 0: arr[j] = abs(arr[j]) else: arr[j] = -abs(arr[j]) print(' '.join([str(x) for x in arr]))
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers. LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6. O...
3
import math as m n=int(input()) k=int(n**(0.5)) a=0;b=0;c=100000000000000; for i in range(1,k+1): if(n%i==0): if(m.gcd(i,n//i)==1): if(max(i,n//i)<c): c=max(i,n//i); a=i; b=n//i; print(a,b)
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
3
n = int(input()) arr = list(map(int, input().split())) even = 0 ev = [] od = [] odd = 0 for i in range(n): if arr[i] % 2 == 0: even += 1 ev.append(arr[i]) else: odd += 1 od.append(arr[i]) ev.sort() od.sort() if abs(even - odd) == 0 or abs(even - odd) == 1: print(0) else: ...
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}. Less for...
3
n = int(input()) a = list(map(int,input().split())) c = [0] for i in range(len(a)): c.append(c[-1]+a[i]) q = int(input()) for _ in range(q): l,r = map(int,input().split()) print((c[r]-c[l-1])//10)
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n = input() s = str(input()) a=d =0 for i in s: if i =='A': a+=1 else: d+=1 if a>d: print("Anton") elif(d>a): print('Danik') else: print('Friendship')
You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score. You want to in...
1
def comp_rest(a,b): if a[0] > b[0]: return True elif a[0] < b[0]: return False elif a[0] == b[0]: return a[1] < b[1] def solve(): N = int(raw_input()) SP = [] for i in range(N): SiPi = raw_input().split() Si = SiPi[0] Pi = int(SiPi[1]) SP...
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
from collections import defaultdict import math def ncr(x): return (x*(x-1))//2 x=int(input()) count=defaultdict(lambda:0) for i in range(x): a=input() count[a[0]]+=1 ans=0 for i in count.keys(): ans+=ncr(count[i]//2) ans+=ncr(count[i]-(count[i]//2)) print(ans)
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 100). Output Print a singl...
3
import math prime=[2,3,5,7,11];d={} def GeneratePrimes(): for i in range(12,1010): for j in prime: if i%j==0: break if j*j>i: prime.append(i) break else: prime.append(i) #for i in range(1,len(prime)+1): ...
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
x = 0 count = int(input()) for i in range(count): taskStr = input() taskList = [] for i in taskStr: taskList.append(i) if taskList[0] == "+" and taskList[1] == "+" or taskList[1] == "+" and taskList[2] == "+": x += 1 if taskList[0] == "-" and taskList[1] == "-" or taskList[1] == "-" ...
The Easter Rabbit laid n eggs in a circle and is about to paint them. Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied: * Each of the seven colors should be used to paint at least one egg. * Any four eggs lying ...
3
# key not available "" n = int(input()) s1 = "ROYGBIV" s = "ROYGBIV" s2 = "GBIV" x = n // 7 rem = n % 7 if x > 0: s = s * x else: s = "" if rem <= 3: for i in range(rem): s += s2[i] else: for i in range(rem): s += s1[i] print(s)
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December. ...
3
d = [31,28,31,30,31,30, 31, 31, 30, 31, 30, 31] d1 = [31,29,31,30,31,30, 31, 31, 30, 31, 30, 31] da = d + d + d + d1 + d +d + d1+ d + d n = int(input()) a = list(map(int, input().split())) found = False for i in range(n): for s in range(len(da)-n): if a == da[s:s+n]: print('YES') ...
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies. Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ...
3
#!/usr/bin/env python3 from itertools import * def read_ints(): return map(int, input().strip().split()) n, m = read_ints() a = read_ints() queue = list(enumerate(a)) last = None while queue: next_queue = [] for (ch, can) in queue: last = ch if can > m: next_queue.append((c...
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
1
from __future__ import division from collections import Counter as ctr from math import ceil, log, factorial # reads a line of input and converts into a list of ints # 1 1 3 => [1, 1, 3] def rl(): return [int(i) for i in raw_input().split()] # reads n lines of input (if n defined) and returns a list of strings # w...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
username = input('') char_list = list() for i in username: char_list.append(i) char_dict = dict() for i in char_list: char_dict[i] = char_dict.get(i, 0) + 1 distinct = len(char_dict) if distinct % 2 != 0 : print("IGNORE HIM!") else: print("CHAT WITH HER!")
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
t=int(input()) for i in range(t): x1=input() x2=input() x3=input() x4=input() x5=input() x6=input() x7=input() x8=input() x9=input() print(x1.replace(x1[6],x1[5])) print(x2.replace(x2[1],x2[0])) print(x3.replace(x3[5],x3[8])) print(x4.replace(x4[8],x4[5])) print...
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
#import sys #sys.stdin=open("input.txt","r") s=input() a=s.split("+") a.sort() y="+".join(a) print(y)
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
3
n,k =map(int,input().split()) s = list(input()) # print(s) c =0 for i in set(s): if s.count(i)>k: c+=1 if c!=0: print("NO") else: print("YES")
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....
1
n = int(raw_input()) problems = 0 for _ in range(n): a, b, c = map(int , raw_input().split()) if a + b + c >= 2: problems += 1 print problems
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno...
3
#! /usr/bin/env python3 ''' Author: krishna Created: Fri Jan 19 20:09:55 2018 IST File Name: a.py USAGE: a.py Description: ''' import sys, os def has7(i): if (i % 10 == 7): return 1 i /= 10 if (i % 10 == 7): return 1 return 0 def main(): ''' The Main ''' ...
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly...
3
from sys import stdin t=int(stdin.readline()) while t: A=input() B=input() C=input() a,b,c=list(A),list(B),list(C) n=len(a) ans='YES' for i in range(n): if a[i]!=b[i]: if c[i]==b[i]: a[i]=b[i] elif c[i]==a[i]: b[i]=a[i]...
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
for _ in range(int(input())): n, k = map(int, input().split()) a = sorted([*map(int, input().split())],reverse=True) b = sorted([*map(int, input().split())]) ans = 0 for i in range(k): if a[-1] < b[n - 1 - i]: ans += b[n-1-i] a.pop() else: break ...
You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above. The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner? Constraints * -40 \leq X \leq 40 * X is an integer. Input Input is given from Standard Input in the follo...
3
N=int(input()) print("Yes" if N>=30 else "No")
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc....
3
a = list(input()) b = list(input()) a.reverse() if(a==b): print('YES') else: print('NO')
There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of road...
3
#最小全域木 プリム法 n = int(input()) x = [] for i in range(0,n): X,Y = [int(_x) for _x in input().split()] x.append((i,X,Y)) x = sorted(x, key=lambda x:x[1]) y = sorted(x, key=lambda x:x[2]) g = [[] for _ in range(n)] for j in range(1, len(x)): _i, _xx, _yy = x[j-1] i, xx, yy = x[j] dis1 = abs(_xx - xx) ...
Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she ...
1
test = input() for t in range(test): j = raw_input() s = raw_input() c = 0 for i in s: if(i in j): c += 1 print c
Input The input contains a single integer a (1 ≤ a ≤ 30). Output Output a single integer. Example Input 3 Output 27
3
n=int(input()) sieve=[] for i in range(10001): sieve.append(1) sieve[0]=sieve[1]=0 for i in range(2,10000): j=2 while i*j<=10000: sieve[i*j]=0 j+=1 def sumdig(x): ans=0 for i in x: ans+=int(i) return ans def primeFactors(x): pf=[] for i in range(2,x//2+1): while sieve[i]==1 and x%i==0: x//=i pf.ap...
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 = [int(s[0])] n = len(s) i = 1 while i<n: if s[i]!=s[i-1]: a+=int(s[i]), else: a[-1]+=int(s[i]) i+=1 a = [x for x in a if x] a.sort(reverse=True) print(sum(a[::2]))
Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. ...
1
r = int(raw_input()) g = int(raw_input()) k = 2*g - r print k
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
3
x = int(input()) a = list(map(int, input().split())) y = 0 for i in range(x): y += a[i] print(float(y/x))
One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend. Find the following: <image> Constraints * 1 ≦ N ≦ 200,000 * (a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N). Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print th...
3
def main(): N = int(input()) a = list(map(int, input().split())) l = [-1] * N s = [] for i, v in enumerate(a): while s and s[-1][0] > v: s.pop() if s: l[i] = s[-1][1] s.append((v, i)) r = [N] * N s = [] for i, v in (enumerate(reversed(a)))...
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi. To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem...
3
from sys import stdin from string import ascii_uppercase #stdin = open("sum.in", 'r') hat = stdin.readlines() n, m = map(int, hat[0].split()) a = sorted([int(x) for x in hat[1].split()]) b = sorted([int(x) for x in hat[2].split()]) counter = 0 for i in range(len(a)): flag = False for j in range(len(b)): ...
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
numStatemnets = int(input()) x = 0 res = 0 for i in range(numStatemnets): stm = input() if '+' in stm : res = res + x + 1 else : res = res + x - 1 print(res)
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
lucky = [4,7,44,77,47,74,447,474,477,444,744,747,774,777] n = int(input()) if n < 4: print('NO') else: for i in lucky: if n % i == 0: print('YES') break else: print('NO')
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
str = input() arr = str.split(' ') i1 = int(arr[0]) i2 = int(arr[1]) i3 = int(arr[2]) if (i1>10**9)or(i2>10**9)or(i3>10**9): print('The numbers are out of range.') else: print(((i1+i3-1)//i3)*((i2+i3-1)//i3))
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property. Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=...
3
t=int(input()) for i in range(0,t): s=input() p=0 if(len(s)==1): print(s) else: for i in range(1,len(s)): if(s[0]==s[i]): continue else: p=1 break if(p==0): print(s) else: ans=...
Write a program which calculates the area and perimeter of a given rectangle. Constraints * 1 ≤ a, b ≤ 100 Input The length a and breadth b of the rectangle are given in a line separated by a single space. Output Print the area and perimeter of the rectangle in a line. The two integers should be separated by a si...
3
a,b=map(int,input().split()) sum = a+b print(a*b,sum * 2)
Write a program which reverses a given string str. Input str (the size of str ≤ 20) is given in a line. Output Print the reversed str in a line. Example Input w32nimda Output admin23w
3
s = str(input()) s_new = s[::-1] print(s_new)
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi...
1
limit = 10**6+55578 frequency = [0]*limit n = input() weights = map(int,raw_input().split()) for i in weights: frequency[i] += 1 ans = 0 for i in range(10**6+55577): ans += frequency[i]%2 frequency[i + 1] += frequency[i]/2 print ans
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
1
""" Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. * Readability counts * // Author : raj1307 - Raj Singh // Date...
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b. The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part. Constraints * 0 ≤ a, b ≤ 20000 * No divisions by zero are given. Input The input c...
1
while True: a,op,b = map(str,raw_input().split()) a=int(a) b=int(b) if(op=='?'): break if(op=='+'): print a+b elif(op=='-'): print a-b elif(op=='*'): print a*b elif(op=='/'): print a/b
Zane the wizard is going to perform a magic show shuffling the cups. There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i. The problematic bone is initially at the position x = 1. Zane will confuse the audience b...
3
n,m,k=list(map(int,input().split())) a=list(map(int,input().rstrip().split())) a.insert(0,0) c=[False]*(10**6+1) for i in range(1,m+1): c[a[i]]=True initial=1 ans=1 for i in range(k): f,d=list(map(int,input().split())) if c[initial]==True: ans=initial break elif initial==f: initi...
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
3
num = int(input()) c = input().split() if int(c[0]) % 2 == 0 and int(c[1]) % 2 == 0: k = 0 elif int(c[0]) % 2 == 1 and int(c[1]) % 2 == 1: k = 1 else: k = int(c[2])%2 for i in c: if int(i)%2 != k: print(c.index(i)+1) break
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each ot...
3
temp = list(map(int,input().split())) a = temp[0] b = temp[1] highest = max(temp) for x in range(0,highest + 2): if (a < 0 or b < 0): break if (x % 2 == 1): a -= x else: b -= x if (a < 0): print('Vladik') elif(b < 0): print('Valera')
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≤ x ≤ r_i, and ((x mod a) mod b) ≠ ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
3
import sys import math def getValue(x, maxm, lcm): ans = x // lcm * (lcm - maxm) + max(0, x % lcm - maxm + 1) return ans for _ in range(int(sys.stdin.readline())): a, b, q = map(int, input().split()) lcm = (a * b) // math.gcd(a, b) ans = [] maxm = max(a, b) for i in range(q): l, r = ...
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...
3
def way(a): n=len(a) if(n<=10): return a else: return ''.join([a[0],str(n-2),a[n-1]]) if __name__ == "__main__": n=int(input()) for i in range(n): a=input() print(way(a))
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t=int(input()) while t: a1,k=list(map(int,input().split())) l=[] a1=str(a1) l.append(a1) z=0 while min(a1)!='0': k-=1 if k==0: z=1 print(l[-1]) break else: a1=str(int(a1)+int(min(a1))*(int(max(a1)))) l.append(a1) if z==0: print(l[-1]) t-=1
Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≤ a, b ≤ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest comm...
3
x,y = map(int, input().split()) def gcd(x,y): return y, x%y while y !=0: x,y = gcd(x,y) print(x)
For a positive integer X, let f(X) be the number of positive divisors of X. Given a positive integer N, find \sum_{K=1}^N K\times f(K). Constraints * 1 \leq N \leq 10^7 Input Input is given from Standard Input in the following format: N Output Print the value \sum_{K=1}^N K\times f(K). Examples Input 4 O...
3
N = int(input()) ans = 0 for i in range(1, N+1): y = N//i ans += i*y*(y+1)//2 print(ans)
Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number ...
3
l=input().split() n=int(l[0]) m=int(l[1]) l=input().split() li=[int(i) for i in l] poss=1 for i in range(m): if(n-i<li[i]): poss=0 break z=sum(li) maxa=[0 for i in range(m)] maxa[-1]=n-li[-1]+1 for i in range(m-2,-1,-1): maxa[i]=min(maxa[i+1]-1,n-li[i]+1) if(poss==0 or z<n): print(-1) else: ...
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an...
3
n = int(input()) num = list(map(int, input().split())) o = 0 a = 0 b = sum(num) for i in range(n - 1): a += num[i] b -= num[i] if a == b: o += 1 print(o)
You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 ≤ a_2 ≤ a_3 ≤ ... ≤ a_n holds). To make the sequence sorted, you may perform the following operation any number of times you want (possibly ...
3
import sys input = sys.stdin.readline for _ in range(int(input())): n,x = list(map(int,input().split())) arr = list(map(int,input().split())) ans = 0 for i in range(1,len(arr)): if arr[i]<arr[i-1]: index = i-1 while index>=0 and arr[index]>x: index-=1 ...
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what i...
3
def qsort(array): """Sort the array by using quicksort.""" less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x >...
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret! A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ...
3
a = int(input()) i = 0 while i < a : b = int(input()) s = 0 m = 0 c = input().split(" ") f = c[0] while s < b : if f == c[s] : m = m + 1 s = s + 1 if (m == b) : print(b) else : print(1) i = i + 1
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe ...
3
n,l,s=int(input()),[],0 for i in range(n):l+=[int(input())] l.sort() for i in range(n//2): s+=2*l[i]*l[-1-i] if n%2:s+=l[n//2]**2 print(s%10007)
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
n=int(input()) count=0 for i in range (n): x,y,z=map(int,input().split()) if x+y+z>1: count=count+1 print(count)
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a...
1
#!/usr/bin/env python from collections import defaultdict def rmZeros(num): num = str(num) num = num.translate(None, '0') return int(num) import sys data = sys.stdin.readlines() num1 = int(data[0].strip()) num2 = int(data[1].strip()) summ = num1 + num2 if rmZeros(num1) + rmZeros(num2) == rmZeros(summ): print 'YE...
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
3
N=int(input()) *A,=sorted(map(int,input().split())) s=[0]*N for i in A: s[i-1]+=1 for t in s: print(t)
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
3
x=int(input());a=list(map(int,input().split()));b={} for i in range(x): tem=a[i] if tem-i in b.keys(): b[tem-i]+=tem else: b[tem-i]=tem print(max(b.values()))
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly...
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...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
3
n, m, a, b = map(int, input().split()) ans1 = n // m * b + min((n - n // m * m) * a, b) ans2 = n * a # print(ans1, ans2) print(min(ans1, ans2))
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem...
1
n = input() c = 0 k = n%2 if n==1 or n==2: print 1 else: z = n/3 if n%3==0: print 2*z else: print 2*z+1