problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa...
1
import random from bisect import* from collections import defaultdict import re def it() : return tuple(map(int,raw_input().split())) def il(): return map(int, raw_input().split()) def fl(): return map(float, raw_input().split()) def sl(): return raw_input().split() # fh = open("inB.txt") n,m = it() num = il() s = ...
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()) notes = (100, 20, 10, 5, 1) result = 0 for i in notes: result += n // i n %= i print(result)
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one ...
1
def reverseBinary(c): val = ord(c) b = '{0:08b}'.format(val) br = b[::-1] return int(br, 2) s = raw_input() prev = 0 for i in range(len(s)): print (prev - reverseBinary(s[i])) % 256 prev = reverseBinary(s[i])
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...
3
def main(): s = input() vowels = ["a","e","i","o","y","u","Y","A","E","I","O","U"] ans = "" for i in range(len(s)): if s[i] in vowels: pass else: ans += "."+s[i].lower() print(ans) if __name__ == '__main__': main()
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string. A Bitlandish string is a string made only of characters "0" and "1". BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish ...
3
a = input() b = input() if len(a) != len(b): print('NO') elif (a.count('1') > 0) ^ (b.count('1') > 0): print('NO') else: print('YES')
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote. Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions o...
3
from collections import deque n = int(input()) s = input() s = list(s) D = deque([]) R = deque([]) cnt = 1 for i in range(n): if s[i] == "D": D.append(i) else: R.append(i) while True: if len(D) == 0 or len(R) == 0: break a = D.popleft() b = R.popleft() if a < b: D...
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
# -*- coding: utf-8 -*- # @Date : 2019-05-26 21:23:56 # @Author : raj lath (oorja.halt@gmail.com) # @Link : link # @Version : 1.0.0 import sys sys.setrecursionlimit(10**5+1) inf = int(10 ** 20) max_val = inf min_val = -inf RW = lambda : sys.stdin.readline().strip() RI = lambda : int(RW()) RMI = lambd...
Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g...
3
import sys from math import trunc # How to multiply matrices in 32 bit python? # Solution: Use doubles with homemade mult and mod. # This should be around 6-10 times faster than using int # and close to the speed you'd get in 64 bit python. MOD = 10**9 + 7 MODF = float(MOD) MODF_inv = 1.0/MODF FLOAT_PREC = float(2**52...
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
3
class Solver: def main(self): _ = input() flights = input().strip() print(['No', 'Yes'][int(flights.count('SF') > flights.count('FS'))]) Solver().main()
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}. There are 2n students, the i-th student has...
3
for t in range(int(input())): n=int(input()) a=list(map(int,input().split())) a.sort() print(abs(a[n]-a[n-1]))
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
1
n=int(input()) s=raw_input() l=s.split() for i in range(n): l[i]=int(l[i]) l.sort() k=l[n-1]-l[0] if k>0: a=l.count(l[n-1]) b=l.count(l[0]) c=a*b else: c=(len(l)*(len(l)-1))/2 l=[str(k),str(c)] s=' '.join(l) print(s)
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
number_of_problems = int(input()) solutions = 0 for i in range(number_of_problems): lis = list() Petya_Soln, Vasya_Soln, Tonya_Soln = map(int, input().split()) lis.append(Petya_Soln) lis.append(Vasya_Soln) lis.append(Tonya_Soln) if lis[0]+lis[1]+lis[2] >=2: solutions +=1 print(solutions)
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check ...
3
N, arr = int(input()), [int(x) for x in input().split()] arr.sort() for i in range(1, N - 1): if(arr[i] + arr[i - 1] > arr[i + 1]): print("YES") break else: print("NO")
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will defin...
3
n, m, k = map(int,input().split()) a = list(map(int,input().split())) a.sort() vis = [] for i in range(n): vis.append(0) ans = l = r = 0 cnt = 1 while(r < n): while(a[r]-a[l]+1 > m): if(vis[l] == 0): cnt -= 1 l += 1 if cnt >= k: ans += 1 vis[r] = 1; cnt -= 1 r += ...
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
string = input().split(" ") n = int(string[0]) k = int(string[1]) red = -(-(n*8)//k) green = -(-(n*5)//k) blue = -(-(n*2)//k) print(str(red +green + blue))
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n. You can successively perform the following move any number of times (possibly, zero): * swap any two adjacent (neighboring) characters of s (i.e. for any i = ...
3
n=int(input()) s=list(map(str,input())) t=list(map(str,input())) ggg=True nnn=[] nn=t[:] a=" " for ii in s: if ii in nn: nn.pop(nn.index(ii)) else: ggg=False break if ggg==True: for i in range(n-1,0,-1): if t[i]!=s[i]: a=s.index(t[i]) for j in range(a,...
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to d...
3
n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): x, y, z = map(int, input().split()) g[x] += (y, z), g[y] += (x, z), def go(x, f): ret = 0 for y, z in g[x]: if y != f: ret = max(ret, z + go(y, x)) return ret print(go(0, -1))
It is winter now, and Max decided it's about time he watered the garden. The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ...
1
for _ in range(int(raw_input())): n,k = map(int,raw_input().split()) g = map(int,raw_input().split()) p = [1 if i+1 in g else 0 for i in range(n)] t = 1 while sum(p) < n: p_ = [0]*n for i in range(n): if p[i]: p_[i] = 1 if i > 0: p_[i-1] = 1 if i < n-1: p_[i+1] = 1 t += 1 p = p_ ...
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness. The choice of candies has a direc...
1
n, k = map(int, raw_input().split()) if k == 1: print n else: mini = 1 while mini <= n: mini *= 2 print mini-1
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is xi kilos of raspberry. Unfortunately, the b...
3
n,c=map(int,input().split()) a=list(map(int,input().split())) s=0 for i in range(n-1): if a[i]>a[i+1]: s=max(s,a[i]-a[i+1]-c) print(s)
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()) a=[0]*n b=[0]*n capacity = 0 max_capacity = 0 for i in range(n): a[i], b[i] = input().split(' ') capacity = capacity - int(a[i]) + int(b[i]) if capacity > max_capacity: max_capacity = capacity print(max_capacity)
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the ...
3
n = int(input()) a = [*map(int, input().split())] print(sum(a) if sum(a) % 2 == 0 else sum(a) - min([*filter(lambda x: x % 2 == 1, a)]))
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
from sys import stdin import math inp = stdin.readline t = int(inp().strip()) while t: t -= 1 # n = int(inp().strip()) line = [] for i in range(9): line.append(list(inp().strip())) line[0][0] = line[0][1] line[1][4] = line[1][5] line[2][8] = line[2][6] line[3][1] = line[3][2] ...
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
# import numpy as np def solution(): numbers = array_to_int(input().split(" ")) max = numbers[0] if numbers[0] > numbers[1] else numbers[1] print(to_mixed_frac((6 - max + 1), 6)) def to_mixed_frac(first, second): while True: for i in range(2, first+1): if first % i == 0 and second...
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
1
m,r=map(int,raw_input().split()) flg=False i=1 while True: if (m*i)%10==r or (m*i)%10==0 : print i flg=True if flg: break i+=1
Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise. You are given Smeke's current rating, x. Print `ABC` if Smeke will participate in ABC, and print `ARC` otherwise. Constraints * 1 ≦ x ≦ 3{,}000 * x i...
3
import math a=int(input()) print("ABC" if a<1200 else "ARC")
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ...
3
n = int(input()) a = [int(e) for e in input().split()] def is_extremum(i, arr): return i > 0 and \ i < len(arr) - 1 and \ ((arr[i - 1] < arr[i] and arr[i] > arr[i + 1]) or (arr[i - 1] > arr[i] and arr[i] < arr[i + 1])) print(sum([1 for i,_ in enumerate(a) if is_extremum(i, a)])...
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi...
1
n = int(raw_input()) print (n/2) while (n>0): if n == 3: t=3; else: t=2; n -= t; print t,
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
str1=input() str2=str1[0] str2=str2.upper() del_string=str1[1 : :] print(str2+del_string)
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
3
def swap(arr,i,j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def gcd(a,b): if (b == 0): return a return gcd(b, a%b) t = int(input()) for i in range(t): size = int(input()) arr = [int(n) for n in input().split()] maxi = arr[0] idx = 0 for j in range(1,size):...
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanc...
3
dp = {} input() sum = 0 ans = 0 dp[0] = -1 for i, c in enumerate(input()): if c == "0": sum += 1 else: sum -= 1 if sum in dp: ans = max(ans, i - dp[sum]) else: dp[sum] = i print(ans)
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
3
import sys t = int(input()) while t > 0: n = int(input()) ones = int(n / 2) if n % 2 == 1: sys.stdout.write("7") ones -= 1 while ones > 0: sys.stdout.write("1") ones -= 1 print() t -= 1
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
3
from math import sqrt # region fastio 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 self...
According to Gregorian Calendar, it was Monday on the date 01/01/2001. If any year is input, Write a program to display what is the day on the 1st January of this year. Input The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer year. Output Display th...
1
test=raw_input() ntest=int(test) lst=list() case=0 while case<ntest: y=raw_input() yn=int(y) lst.append(yn) case+=1 '''a=raw_input() year=int(a)''' nleap=0 n=0 cent=0 leapcent=0 spl=0 days=list() for day in ('monday','tuesday','wednesday','thursday','friday','saturday','sunday','monday'): days.appen...
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
name = set([c for c in input()]) if len(name) % 2 == 1: print('IGNORE HIM!') else: print('CHAT WITH HER!')
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...
1
import sys range = xrange input = raw_input h1,m1 = [int(x) for x in input().split(':')] h2,m2 = [int(x) for x in input().split(':')] t = (h1+h2)*60 + (m1+m2) t//=2 h3 = t//60 m3 = t%60 print ('%2i:%2i' %(h3,m3)).replace(" ","0")
We have N cards numbered 1, 2, ..., N. Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side. Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up. Determine whether it is ...
3
import bisect N = int(input()) A = list(map(int,input().split())) B = list(map(int,input().split())) ans = 10**9+7 for i in range(2**N): card = [[],[]] num = [] iii = i for j in range(N): if i&1: num.append(B[j]) card[(j+1)%2].append(j) else: num.appen...
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
import sys input=sys.stdin.readline print=sys.stdout.write y,b,r=map(int,input().split()) print(str(3*min(y+1,b,r-1)))
You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center o...
1
class Point(object): def __init__(self,x,y): self.x,self.y = x,y __mul__ = lambda self, f:Point(self.x*f,self.y*f) __add__ = lambda self, other: Point(self.x+other.x,self.y+other.y) __str__ = lambda self: '{x} {y}'.format(x = self.x,y = self.y) readPair = lambda : (int(s) for s in raw_input().sp...
For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0...
3
import sys input = sys.stdin.readline from operator import itemgetter sys.setrecursionlimit(10000000) def dijkstra(n, start, nbl): """n: 頂点数, start: 始点, nbl: 隣接リスト""" import heapq WHITE = 1<<5 GRAY = 1<<10 BLACK = 1<<15 INF = 1<<20 color = [WHITE] * n distance = [INF] * n parent = [...
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
oy = input() noy = int(oy) nny = noy + 1 while True: if len(set(str(nny))) >= len(str(nny)): print(nny) break else: nny += 1
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
3
import sys cases = int(input()) for case in range(cases): size = int(input()) if (size/2)%2 == 0: print("YES") amt = int(size/2) evenArray = 0 for y in range(1,amt+1): sys.stdout.write(str(y*2) + " ") evenArray += y*2 for z in range(1,amt): sys.stdout.write(str(z*2-1) + " ") ...
N friends of Takahashi has come to a theme park. To ride the most popular roller coaster in the park, you must be at least K centimeters tall. The i-th friend is h_i centimeters tall. How many of the Takahashi's friends can ride the roller coaster? Constraints * 1 \le N \le 10^5 * 1 \le K \le 500 * 1 \le h_i \le 5...
3
(N,M) = (int(i) for i in input().split(" ")) print(sum([int(i)>=M for i in input().split()]))
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
3
n = int(input()) for i in range(n): raw_in = input().split() querry = [int(x) for x in raw_in] sum_querry = sum(querry) print(sum_querry//2)
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
3
a='AEIOUY' n=input() b=[0] c=1 flag=0 for i in range(len(n)): if n[i] not in a: c+=1 else: b.append(c) c=1 print(max(max(b),c))
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
M = 0 def update_M(j, s): global M #print(M, s, j) if j == M + 1: M = j if j in s: s.remove(j) # sorted_s = sorted(s) z = 1 while True: if j + z in s: M += 1 s.remove(j + z) z += 1 el...
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
3
n = int(input()) if(n%2==0): print(4,n-4) if(n%2!=0): print(9,n-9) #1 2 3 4 5 6 7 #1 3 5 7 2 4 6
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj. Input The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — ...
3
import bisect n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() #b.sort() for i in range(m): try: #for j# in range(0,n+1): l=bisect.bisect_right(a,b[i],lo=0,hi=n) # t=l-i #ans= max(ans,b[t]+tb) print(l) except: ...
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
3
import sys, math, string, fractions, functools, collections, copy sys.setrecursionlimit(10**7) RI=lambda x=' ': list(map(int,input().rstrip().split(x))) RS=lambda x=' ': input().rstrip().split(x) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] mod=int(1e9+7) eps=1e-14 MAX=1010 ##############################...
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
3
for _ in range(int(input())): n = int(input()) a = [*map(int, input().split())] for i in range(n): if a[i] >= 2:break print('First' if i%2==0 else 'Second')
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
3
import sys input = sys.stdin.buffer.readline T = int(input()) def f(x,y): dg = 10**6 if x == 0: return y elif x < dg: if x > y: return y*dg + x else: return x*dg + y else: xs,xf = divmod(x,dg) if xs < y: xs = y else: ...
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result ...
3
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # import math # from itertools import * # import random # import calendar # import datetime # import webbrowser n, m = map(int, input().split()) n = str(n) count = 0 ans = 0 for i in range(len(n) - 1, -1, -1): if n[i] != "0": ans += 1 if count == m: ...
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
n = int(input()) colors=[] for i in range(n): x=input() colors.append(x) meaning={"Power":"purple", "Time":"green", "Space":"blue", "Reality":"red", "Soul":"orange", "Mind":"yellow"} count=0 final=[] for i in meaning: if(meaning[i] in colors): continue else: ...
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
s1=input() s2=input() s=input() l=list(s) if len(s1)+len(s2)==len(s): for ch in s1: if ch in l: l.remove(ch) for ch in s2: if ch in l: l.remove(ch) if len(l)==0: print("YES") else: print("NO") else: print("NO")
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: * Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. ...
3
t=int(input()) while (t): t-=1 s = input() if(len(s)>=3): cnt = 0 cot = 0 one=[] ans=1001 for i in range(len(s)): if(s[i]=='1'): cnt+=1 one.append(cnt) else: cot+=1 one.append(cnt) for i in range(len(s)): ans=min(ans, i-one[i]+cnt-one[i]+1) ans=min(ans, one[i]+(len(s)-i)-(cnt-...
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
3
ANS = "" for i in range(int(input())): n = int(input()) a = [int(s) for s in input().split()] b = [int(s) for s in input().split()] p, o, ans = 0, 0, "YES" for i in range(n): if (a[i] == 1): p += 1 if (a[i] == -1): o += 1 for j in range(n): i = n -...
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice). Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M...
3
n = int(input()) for _ in range(n): print(int(input()) // 2)
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
n,m,a=map(int,input().split()) if m%a==0 : ans1 = m//a else: ans1 = m//a+1 if n%a==0 : ans2 = n//a else: ans2 = n//a+1 print(ans1*ans2)
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
3
n = int(input()) a = [] b = [] for i in range(n): b.insert(i,0) value = input() j = 0 for i in map(int, value.split()): a.insert(j,i) j+=1 a.insert(n//2+1, 0) k = 0 for i in range(n//2): b[i] = k b[n-1-i] = a[i]-k if b[n-1-i] < a[i+1]-k: k+=(a[i+1]-k) - b[n-1-i] s = '' for i in range(n...
Recently n students from city S moved to city P to attend a programming camp. They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea. i-th stude...
3
from collections import deque t = int(input()) for i in range(t): k = int(input()) a = deque([] for i in range(k)) for j in range(k): a[j].append(j) a[j].append([int(x) for x in input().split()]) t1 = a.popleft() d = deque([t1]) ans = [0] * k s = t1[1][0] while d or a: ...
The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town. There are n+1 checkpoints on the trail. They are numbered by 0, 1, ..., n. A runner must start at checkpoint 0 and finish at checkpoint n. No checkpoint...
3
def main(): class PriorityQueue: class Reverse: def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __repr__(self): return repr(self.val) def __init__(self, a=None, des...
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array...
3
import sys # from collections import deque # from collections import Counter from math import sqrt # from math import log from math import ceil # alpha=['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'] # mod=10**9+7 # mod=998244353 fast_...
There is an array with n elements a1, a2, ..., an and the number x. In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the [bitwise and](https://en.wikipedia.org/wiki/Bitwise_operation#AND) operation. You want the array to have at least two equal elements after appl...
1
s=raw_input().split(' ') n=int(s[0]) m=int(s[1]) lt=raw_input().split() ar=[] for i in range(0,n): ar.append(int(lt[i])) dic={} f=0 for i in range(0,n): if ar[i] not in dic: dic[ar[i]]=1 else: dic[ar[i]]+=1 if dic[ar[i]]>=2: f=1 if f==1: print(0) else: d2={} k=0 c=-1 for i in range(0,n): l=(ar[i]&m...
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map. <image> Figure B-1: A marine area map You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two ar...
3
import sys sys.setrecursionlimit(2500) def dfs(v): y, x = v checked[y][x] = 1 ret = 1 for dy, dx in directions: if y+dy>=h or y+dy<0 or x+dx>=w or x+dx<0: continue elif Map[y+dy][x+dx]==0: continue if not checked[y+dy][x+dx]: ret += dfs((y+dy...
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells. So, user tncks0121 has ...
3
n,t=[int(i) for i in input().split()] a=input().split() b=[] if t==1: print('YES') if t!=1: i=0 while i<=n-2: i=i+int(a[i]) b.append(i) if (t-1) in b: print('YES') else: print('NO')
Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorde...
3
class Node: def __init__(self, key): self.key = key self.left = None self.right = None self.p = None def insert(z,root): y = None x = root while x != None: y = x if z.key < x.key: x = x.left else: x = x.right z.p = y ...
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()); sum = 0; for i in range(n): a, b ,c = map(int, input().split()) if(a+b+c>1): sum+=1 print(sum)
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
d = { 'purple': 'Power', 'green': 'Time', 'blue': 'Space', 'orange': 'Soul', 'red': 'Reality', 'yellow': 'Mind' } n = int(input()) a = set(d.keys()) for _ in range(n): a.remove(input()) print(len(a)) print(*map(d.get, a), sep='\n')
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
n, k = [int(x) for x in input().split()] h = [int(x) for x in input().split()] last = 0 for i in range(k): last += h[i] answer = last index = 0 for i in range(k, n): next = last + h[i] - h[i - k] if next < answer: answer = next index = i - k + 1 last = next print(index + 1)
Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon...
3
b = int(input()) a = list(map(int,input().split())) print(max(a))
Petya has a rectangular Board of size n × m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column. In one action, Petya can move all the chips to the left, right, down or up by 1 cell. If the chip was in the (x, y) cell, then after the oper...
3
m, n, k = [int(i) for i in input().split()] ans = "" ans += "L"*(n-1) + "U"*(m-1) for i in range(2*k): input() for i in range(m): if i % 2: ans += "L"*(n-1) else: ans += "R"*(n-1) ans += "D" print(n*m + n - 1 + m - 1) print(ans)
This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the...
3
import sys input = sys.stdin.readline def ask(i): print(f"? {i + 1}", flush=True) return list(map(int, input().split())) def main(): n = int(input()) ans = [] dlst = ask(0) odd = [] even = [] for i, d in enumerate(dlst): if d % 2 == 0: even.append(i) else: ...
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()) z=0 count=0 for i in range(0,n): d=[int(x) for x in raw_input().split()] z=d.count(1) if z>1: count+=1 print(count)
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different. In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec...
3
from math import * def gcd(a,b) : if b < pi/100: return a return gcd(b, fmod(a, b)) x = [] for i in range(3): x.append(list(map(float, input().split()))) A, B, C = x dist = lambda x, y: sqrt((y[1] - x[1])**2 + (y[0] - x[0])**2) a, b, c = dist(B, C), dist(A, C), dist(A, B) s = (a + b + c) / 2 k ...
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N. On this sequence, Snuke can perform the following operation: * Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements....
3
M, N =map(int, input().split()) print(-(-(M-1)//(N-1)))
There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total? Constraints * 1≦N≦100 Input The input is given from Standard Inpu...
3
N=int(input()) X=(N*(N+1))//2 print(X)
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
######### ## ## ## #### ##### ## # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # # # # # ##### # # # # ### # # # # # # # # ##### # # # # # # # # # # # # # # # # # # #########...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th...
3
n, m = map(int, input().split()) i = 1 a = 0 b = 0 count = 0 while i <= n: a = a + i * 5 i += 1 b = a + m if b <= 240: count += 1 print(count) #V
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
1
t=input() from collections import defaultdict for i in range(t): n=input() d=defaultdict(list) l=[] for j in range(n): x,y=map(int,raw_input().split()) d[x].append(y) l.append(x) l=list(set(l)) l.sort() a=True for j in range(len(l)-1): if max(d[l[j]])>min(...
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks. An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick. In the grid shown be...
3
arr = [int(x) for x in input().split()] n = arr[0] m = arr[1] min_stick = min(n,m) if min_stick %2 != 0: print("Akshat") else: print("Malvika")
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
3
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split(" "))) mx = 0 for x in a: if(x>mx): mx = x possible = False for x in a: if(x!=mx): possible = True if(not possible): print("-1") else: for i in range(n): if(a[i]==mx and ((i<n-1 and a[i+1]!=mx) or (i>0 and a[i-1]!=mx...
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
1
import sys n, x = [int(i) for i in sys.stdin.readline().split()] count = 0 for i in xrange(1, n + 1): if(x % i == 0 and x / i <= n): count += 1 print count
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ...
3
n = int(input()) x = n total = 0 for i in range(1,n//2+1): if i == 1: total+=1 elif (x-i)%i==0: total+=1 print(total)
You have a board represented as a grid with 2 × n cells. The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black. You have w white dominoes (2 × 1 tiles, both cells are colored in white) and b black dominoes (2 × 1 tiles, both cells are col...
3
from math import ceil,floor,log import sys,threading from heapq import heappush,heappop from collections import Counter,defaultdict,deque import bisect input=lambda : sys.stdin.readline().strip() c=lambda x: 10**9 if(x=="?") else int(x) def rec(a,l,r,m,i,l1): # print(l,r) if(l==r): l1[l]=i retur...
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the...
3
k=int(input()) m={} for i in range (1,k+1): n=int(input()) ar=list(map(int,input().split())) s=sum(ar) for j in range(0,n): if s-ar[j] in m and m[s-ar[j]][0] != i: print("YES") print(i,j+1) print(m[s-ar[j]][0],m[s-ar[j]][1]) exit() else: ...
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
3
from collections import defaultdict t=int(input()) for tc in range(t): n=int(input()) a=str(input()) arr=list(a) b=str(input()) charray=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"] flag=0 for i in range(n): if a[i]>b[i]: print("-1") ...
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
3
n, k, l, c, d, p, nl, np = map(int,input().split()) a = k*l x = a//nl y = c*d z = p//np print (min(x,y,z)//n)
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t...
3
n, a, b, c = (int(x) for x in input().split()) nd = 4 - n % 4 if n % 4 == 0: print(0) elif nd == 1: print(min(a, b + c, 3 * c, c + 3 * b)) elif nd == 2: print(min(2 * a, b, 2 * c)) else: print(min(3 * a, min(a + b, c)))
Food contains three nutrients called "protein", "fat" and "carbohydrate", which are called three major nutrients. It is calculated that protein and carbohydrate are 4 kcal (kilocalories) and fat is 9 kcal per 1 g (gram). For example, according to the table below, the number 1 cake contains 7 g of protein, 14 g of fat a...
3
while 1: n=int(input()) if n==0:break a=[list(map(int,input().split())) for _ in range(n)] p,q,r,c=map(int,input().split()) b=[x[0] for x in a if x[1]<=p and x[2]<=q and x[3]<=r and 4*(x[1]+x[3])+9*x[2]<=c] if len(b):print(*b,sep='\n') else:print('NA')
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7. The Little Elephant has K favorite lucky strings A1, A2, ..., AK. He thinks that the lucky string S is good if either |S| ≥ 47 or for some j from 1 to K we have that Aj is a substring of S. The ...
1
from sys import stdin k,n=map(int,stdin.readline().split()) l=[] for i in range(0,k): s=raw_input() l.append(s) for i in range(0,n): s=raw_input() for x in l: if s.__len__()>=47 or s.__contains__(x): print "Good" break else: print "Bad"
Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones. Each time she can do one of two operations: 1. take one stone from the first heap and two stones from the second heap (...
3
for i in range(int(input())): a, b, c = map(int, input().split()) res = 0 while True: if b >= 1 and c >= 2: res += 3 c -= 2 b -= 1 elif a >= 1 and b >= 2: res += 3 a -= 1 b -= 2 else: print(res) ...
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
for _ in range(int(input())): a,b,n,s = list(map(int,input().split())) if s%n>b: print('NO') continue if a*n+b<s: print('NO') else: print('YES')
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds. Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb...
3
for __ in range(int(input())): n, m = list(map(int, input().split())) ar = [] ans = 0 for i in range(n): ar.append(list(map(int, input().split()))) for i in range(n // 2): for j in range(m // 2): lol = [ar[i][j], ar[n - i - 1][j], ar[i][m - j - 1], ar[n - i - 1][m - j - 1...
DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a ...
3
n, m = map(int, input().split(" ")) val = list(map(int, input().split(" "))) ans = 0 for i in range(m): x, y, z = map(int, input().split(" ")) ans = max(ans, (val[x-1]+val[y-1])/z) print(ans)
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
3
import math ###################################################### # ps template def mi(): return map(int, input().split()) def ii(): return int(input()) def li(): return list(map(int, input().split())) def si(): return input().split() ####################################################### t = ii() for _ in range(t):...
Write a program which prints small/large/equal relation of given two integers a and b. Constraints * -1000 ≤ a, b ≤ 1000 Input Two integers a and b separated by a single space are given in a line. Output For given two integers a and b, print a < b if a is less than b, a > b if a is greater than b, and a...
3
a, b=map(int,input().split()) if a<b: print("a < b") elif a>b: print("a > b") elif a==b: print("a == b") else: pass
Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested fo...
1
files = [] while True: try: path = raw_input() files.append(path[:2] + path[3:]) except EOFError: break roots = list(set([f.split("\\", 1)[0] for f in files])) # folder count folder_count = dict([(r, set([])) for r in roots]) for f in files: path = f.rsplit("\\", 1)[0] root ...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
a = int(input()) mas = list(input()) n = mas[0] h = 0 for i in range(1,a): if n == mas[i]: h += 1 n = mas[i] else: n = mas[i] print(h)
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
1
n = int(raw_input()) array = map(int,raw_input().split()) array2 = [] for i in xrange(len(array)): array2.append(0) maxi = array[0] for i in xrange(len(array)): if array[i] > maxi: maxi = array[i] aux = 1 while maxi >= 0: cout = 0 for i in xrange(len(array)): if array[i] == maxi and a...
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c. You h...
3
lis=list(map(int,input().split())) res=max(lis) f=[] for i in range(len(lis)): if lis[i]!=res: f.append(res-lis[i]) for i in f: print(i,end=' ')