problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in th...
3
from collections import deque # palindrome all letter sums must be even and 0 or 1 odd sum allowed s = input() cnt = [0]*26 for letter in s: cnt[ord(letter) - ord('a')] += 1 # find number of odd counts odd = [] for letter in range(26): if cnt[letter] % 2: odd.append(letter) # swap odds (all if even or l...
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ...
3
a=int(input()) d={} for _ in " "*a: z=input() d[z]=d.get(z,0)+1 print(max(d.values()))
Nezzar loves the game osu!. osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees. <image> Points A,B,...
3
import sys #import re #sys.stdin=open('forest.in','r') #sys.stdout=open('forest.out','w') #import math #import queue #import random #sys.setrecursionlimit(int(1e6)) input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inara(): return...
All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the respon...
3
''' Jana Goodman6 10B Cinema Cashier ''' import math #import time #import random SPACE = ' ' MX = 10 ** 16 class Seat: def __init__(self, x, y, rem): self.x = x self.y = y self.remoteness = rem self.empty = True class Row: def __init__(self, max_seat, x, xc): self.m...
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
t = int(input()) for _ in range(t): a, b, n = list(map(int, input().split())) if b < a: a, b = b, a i = 0 while b <= n: a += b a, b = min(a, b), max(a, b) i += 1 print(i)
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
3
n, l, x, lx, r, res = 0,0,0,0,0,0 n = int(input().split()[0]) a = list(map(int, input().split())) x=a[0] lx=x 1==1 for i in range(1, n): x=a[i] if x == lx: if r != l: if 2*min(i-r, r-l) > res: res = 2*min(i-r, r-l) l = r lx=3-lx r=i eli...
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
n = int(input()) ans = "" for i in range(1,n): if i % 2 == 1: ans += "I hate that " else: ans += "I love that " if n % 2 == 1: ans += "I hate it" else: ans += "I love it" print(ans)
There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage...
3
# Danny Garcia # 7/18/2020 MAT_SIZE = 3 lock = [input() for row in range(MAT_SIZE)] symetric = "YES" for row in range(MAT_SIZE): for column in range(MAT_SIZE): if lock[row][column] != lock[MAT_SIZE - row - 1][MAT_SIZE - column - 1]: symetric = "NO" break print(symetric)
Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it: * pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range; * stick some of the elements together in the same order they were in the array; ...
3
import random import bisect import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n,q = map(int,input().split()) arr = list(map(int,input().split())) freindex = [[] for i in range(n+1)] for i in range(n): freindex[arr[i]].append(i) #print(freindex) for i in range(q): l,r = map(...
Marut is now a well settled person. Impressed by the coding skills of Marut, N girls wish to marry him. Marut will consider marriage proposals of only those girls who have some special qualities. Qualities are represented by positive non-zero integers. Marut has a list of M qualities which he wants in a girl. He can a...
1
n = input() marut_desire = map(int, raw_input().strip().split()) girls = input() answer = 0 for i in range(girls): girl_qualities = map(int, raw_input().strip().split()) matchs = 0 for desire in marut_desire: if desire not in girl_qualities: break matchs += 1 if matchs == n: ...
There are S sheep and W wolves. If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep. If the wolves will attack the sheep, print `unsafe`; otherwise, print `safe`. Constraints * 1 \leq S \leq 100 * 1 \leq W \leq 100 Input Input is given from Standard Input in the fol...
3
s,w = map(int,input().split()) ans = "safe" if w < s else "unsafe" print(ans)
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
3
l = input().split() i = int(l[0])+int(l[1])+int(l[2])+int(l[3])+int(l[4]) if i % 5 == 0 and l != ['0','0','0','0','0']: print(i//5) else: print(-1)
Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: SelectionSort(A) 1 for i = 0 to A.length-1 2 mini = i 3 for j = i to A.length-1 4 if A[j] < A[mini] 5 mini = j 6 swap A[i] and A[mini]...
1
N = int(raw_input()) nums = map(int, raw_input().split(" ")) count = 0 for i in range(0, len(nums)): mini = i for j in range(i, len(nums)): if nums[mini] > nums[j]: mini = j if i != mini: count += 1 temp = nums[i] nums[i] = nums[mini] nums[mini] = temp nums = map(s...
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting o...
3
''' Author : thekushalghosh Team : CodeDiggers ''' import sys,math input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) a.sort() q = list(a[:len(a) // 2]) w = list(a[len(a) // 2:]) print((sum(q) ** 2) + (sum(w) ** 2))
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i. You are now at town 1, and you want to visit all the ...
3
n,a,b = map(int, input().split()) x = list(map(int, input().split())) ans = 0 for i in range(0,n-1): ans += min(a*(x[i+1]-x[i]),b) print(ans)
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
1
def main(): n = input("") arr = map(int, raw_input().split(" ")) min_cur = 0 max_cur = 0 i = 0 while i < len(arr): if arr[i] > arr[max_cur]: max_cur = i if arr[i] < arr[min_cur]: min_cur = i i+=1 print max(max(abs(min_cur-0), abs(n-min_cur-1)),max(abs(max_cur-0), abs(n-max_cur-1))) #print ar...
Takahashi has decided to work on K days of his choice from the N days starting with tomorrow. You are given an integer C and a string S. Takahashi will choose his workdays as follows: * After working for a day, he will refrain from working on the subsequent C days. * If the i-th character of S is `x`, he will not wor...
1
N, K, C = map(int, raw_input().split()) S = raw_input() T1 = [0]*N T1[-1] = int(S[-1]=="o") for i in range(N-1)[::-1]: if S[i]=="o": T1[i] = max(T1[i+1], 1+(T1[i+C+1] if i+C+1<N else 0)) else: T1[i] = T1[i+1] c = 0 p = -1 for i in range(N): if S[i]=="o": if c+(T1[i+1] if i+1<N else 0)<K: print...
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
3
s=list(input()) n=len(s) s.append("z") for i in range(1,n): if s[i]==s[i-1]: k=ord(s[i])-97 while chr(k+97)==s[i-1] or chr(k+97)==s[i+1]: k=(k+1)%26 s[i]=chr(k+97) for i in range(n): print(s[i],end="")
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
3
x1,y1,x2,y2=map(int, input().split()) if x1==x2: d=y1-y2 print(x1+d,y1,x2+d,y2) elif y1==y2: d=x1-x2 print(x1,y1+d,x2,y2+d) elif abs(x1-x2)==abs(y1-y2): print(x2,y1,x1,y2) else: print(-1)
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()) i = 0 while n >= 100: n = n - 100 i = i + 1 while n >= 20: n = n - 20 i = i + 1 while n >= 10: n = n - 10 i = i + 1 while n >= 5: n = n - 5 i = i + 1 while n >= 1: n = n - 1 i = i + 1 print(i)
You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974". Constraints * 0 \leq N_1, N_2, N_3, N_4 \leq 9 * N_1, N_2, N_3 and N_4 are integers. Input Input is given from Standard Input in the following format: N_1 N_2 N_3 N_4 Output If N_1, N_2, N_3 ...
3
print("YNEOS"[set(input())!=set("1974 ")::2])
We have a string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly: * Insert a letter `x` to any position in s of his choice, including the beginning and end of s. Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is ...
1
s = raw_input() replaced = s.replace('x', '') l = len(replaced) halfl = int(l / 2) if l > 1 and replaced[:halfl] != replaced[-halfl:][::-1]: print "-1" exit() xset = {} i = 0 for c in s: if c == 'x': d = min(i, l-i) if i != l-i: xset[d] = xset.get(d, 0) + [-1, 1][i < l-i] else: i += 1 ans ...
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or...
3
n, m, k = map(int, input().split()) if (k == -1 and (n % 2 != m % 2)): print(0) else: ans = pow(2, (n - 1) * (m- 1), 1000000007) print(ans)
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ...
1
import sys; sys.setrecursionlimit(1010) n = int(raw_input()) p = [None] + map(int, raw_input().split()) answer = [] global memo def find_last(k): global memo if memo[k] == 1: return k memo[k] = 1 return find_last(p[k]) for i in xrange(1, n+1): memo = [0 for j in xrange(n+1)] answer.append(str(fi...
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n = int(input()) a = list(map(int, input().split())) a.sort() ans = [] i = 0 while(len(ans) != n): ans.append(a[n-i-1]) if(len(ans)!= n): ans.append(a[i]) i += 1 print((n-1)//2) print(*ans)
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it...
1
n = input() a = raw_input().split() ans = a[0] for i in xrange(n): a[i] = int(a[i]) if n > 1: ans = a[0] + a[n - 1] for i in xrange(n - 2): if a[i + 1] == 1: ans += 1 elif a[i + 1] == 0 and a[i] == 1 and a[i + 2] == 1: ans += 1 print ans
This contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters. Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way. You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtai...
3
s=input() if "C"in s and "F"in s: if s.find("C")<s.rfind("F"):print("Yes") else:print("No") else:print("No")
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfect...
3
# Problem from Codeforces # http://codeforces.com/contest/37/problem/C import sys class input_tokenizer: __tokens = None def has_next(self): return self.__tokens != [] and self.__tokens != None def next(self): token = self.__tokens[-1] self.__tokens.pop() return token ...
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'...
1
import sys import math i = '' for line in sys.stdin: i = line.split(' ') break print int(math.ceil(float(i[0]) / float(i[2]) )) * int(math.ceil(float(i[1]) / float(i[2]) ))
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt...
3
n,m,k = map(int,input().split()) a = list(map(int,input().split())) a.sort(reverse = True) sum1 = k if(k>= m): print(0) exit() i=0 while(i<n and sum1<m): sum1 += a[i] - 1 i+=1 if(sum1>=m): print(i) else: print(-1)
And where the are the phone numbers? You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t. It's guaranteed that the answ...
1
'''input 1 2 3 4 5 6 7 8 45 9 ''' # What doesn't challenge you, makes you weaker. import sys # pow2 = pow # for modular expo pow2(base, n, mod) # from math import * # from time import time # from collections import defaultdict # from bisect import bisect_right, bisect_left # from string import ascii_lowe...
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
3
def minutes(): for _ in range(n): *a, = [int(x) for x in input().split()] yield 60*(23-a[0])+(60-a[1]) if __name__ == '__main__': n= int(input()) ans = minutes() print(*ans,sep='\n')
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
3
if __name__ == "__main__": n = int(input()) strengths = [int(s) for s in input().split()] maximum = max(strengths) minimum = min(strengths) count = 0 for s in strengths: if minimum < s < maximum: count += 1 print(count)
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
3
polyhedrons = { "Tetrahedron":4, "Cube":6, "Octahedron":8, "Dodecahedron":12, "Icosahedron":20 } res = 0 for _ in range(int(input())): res += polyhedrons[input()] print(res)
Student Dima from Kremland has a matrix a of size n × m filled with non-negative integers. He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him! Formally, he wants to choose an integers sequence c_1, c_2, …...
3
import sys import os from io import BytesIO, IOBase ######################### # imgur.com/Pkt7iIf.png # ######################### # returns the list of prime numbers less than or equal to n: '''def sieve(n): if n < 2: return list() prime = [True for _ in range(n + 1)] p = 3 while p * p <= n: i...
You are given an array a of length n consisting of integers. You can apply the following operation, consisting of several steps, on the array a zero or more times: * you select two different numbers in the array a_i and a_j; * you remove i-th and j-th elements from the array. For example, if n=6 and a=[1, 6,...
1
from __future__ import division import sys input = sys.stdin.readline import math from math import sqrt, floor, ceil from collections import Counter from copy import deepcopy as dc ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().spli...
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage. There is at most one checkpoint on each stage, and there is always a checkp...
3
def solve(k): if k % 2 == 1: print(-1) return ans = [] left = k while left > 0: q = 0 while (pow(2, q+2) - 2) <= left: q += 1 q -= 1 left -= pow(2, q+2) - 2 ans.append(1) while q > 0: ans.append(0) q -= 1...
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
3
n, k, t = map(int, input().split(' ')) if t <= k: print(t) elif t<=n: print(k) elif k-abs(n-t)>0: print(k-abs(n-t)) else: print(0)
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
3
num = int(input()) for i in range(1, num+2): for j in range(num - i+1): print(' ' , end = '') for k in range(i): if k == 0: print(k , end = '') else: print(f' {k}' , end = '') for l in range(k-1 , -1 , -1): print(f' {l}' , end='') print() for i...
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...
3
import sys import math import itertools as it import operator as op import fractions as fr n = int(sys.stdin.readline().strip()) r = (n//3) * 2 if n%3: r+=1 print(r)
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
str1="First" str2="Second" def solve(): n=int(input()) cnt=0 mas=list(map(int,input().split())) if(sum(mas)==n): if (n%2==1): print(str1) else: print(str2) return for num in mas: if(num==1): cnt+=1 else: break if(cnt%2==0): print(str1) else: print(str2) def main(): t=int(input...
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row. The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as ...
1
n = int(raw_input()) string = raw_input().strip('S') n = len(string) streaks = [] if string == "S"*n: print 0 else: j = 0 while(j < n): count = 0 while(j < n and string[j] == 'G'): count += 1 j += 1 j += 1 streaks.append(count) #print streaks ...
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
n = int(input()) row = input() a = 0 ris = 0 while a < len(row)-1: if row[a] != row[a+1]: a += 1 else: row = row[0:a]+row[a+1:] ris += 1 print(ris)
Snuke is buying a bicycle. The bicycle of his choice does not come with a bell, so he has to buy one separately. He has very high awareness of safety, and decides to buy two bells, one for each hand. The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively. Find the m...
3
a,b,c = map(int,input().split());print((a+b+c)-max(a,b,c))
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now. Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per cocon...
3
x,y,z=map(int,input().split()) sum=(x+y)//z i1=x//z i2=y//z x=x%z y=y%z current=i1+i2 nu=0 if current==sum: print(sum,end=' ') print(nu) else: if x>y: h=x else: h=y current=sum-current current=current*z nu=current-h print(sum, end=' ') print(nu)
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
#!/usr/bin/env python def main(): lst = input().split() for i in range(len(lst)): lst[i] = int(lst[i]) if (lst[0] <= 1) and (lst[1] <= 1): print(0) else: if lst[0] == 2: print(lst[1]) elif lst[1] == 2: print(lst[0]) else: print(...
In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month. Constraints * Both 2019-M_1-D_1 and 20...
3
a, b = map(int, input().split()) c, d = map(int, input().split()) print(int(c!=a))
You are given a string S. Each character of S is uppercase or lowercase English letter. Determine if S satisfies all of the following conditions: * The initial character of S is an uppercase `A`. * There is exactly one occurrence of `C` between the third character from the beginning and the second to last character (i...
1
alpha = [str(chr(i)) for i in range(97,97+26)] def main(): S = list(raw_input()) if S[0] != 'A': return 'WA' S.remove('A') flag = True for i in S[1:-1]: if i == 'C': flag = False S.remove('C') break; if flag: return 'WA' for i in S...
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
# Program to solve Code Forces problem vanaya and fence def road_width(friends_height: list, fence_height: int) -> int: needed_road_width = 0 for value in friends_height: if value > fence_height: needed_road_width += 2 else: needed_road_width += 1 return needed_road...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
1
x=y=z=0 for i in xrange(input()): x1,y1,z1=map(int,raw_input().split()) x+=x1;y+=y1;z+=z1 print ["NO","YES"][x==y==z==0]
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it. Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all custo...
3
q = int(input()) for _ in range(q): n, m = map(int, input().split()) tlh = [tuple(map(int, input().split())) for i in range(n)] m_t = m M_t = m flag = True prev = 0 for t, l, h in tlh: m_t -= (t - prev) M_t += (t - prev) prev = t if (m_t <= l and l <= M_t) or ...
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
3
# -*- coding: utf-8 -*- """Untitled66.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/12YhN9dhFFOftGWZfnAyHeunhpLDz40ze """ def sum_number(n): s=str(n) sum=0 for i in s: sum+=int(i) return sum n=int(input()) flag=0 while flag!=1: t=...
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in ...
3
for _ in range(int(input())): n = int(input()) seq = sorted((int(x) for x in input().split())) lst = [seq[-1] - val for val in seq] s = sum(lst) ans = 0 for i in range(n): get_to_max = s-lst[i] req = get_to_max - seq[i] if req >= 0: ans = max(ans, req) ...
You are given N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given f...
3
import sys read = sys.stdin.read n, *a = map(int, read().split()) a.sort() x = 2*sum(a[(n+1)//2:]) - 2*sum(a[:(n+1)//2]) y = 2*sum(a[n//2:]) - 2*sum(a[:n//2]) if n % 2 == 1: x += a[n//2-1] + a[n//2] y -= a[n//2] + a[n//2+1] else: x -= a[n//2] - a[n//2-1] y -= a[n//2] - a[n//2-1] y print(max(x, y))...
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
3
a=input() flag=0 for i in range(len(a)-7+1): if a[i:i+7]=="1111111" or a[i:i+7]=="0000000": flag=1 break if flag==0: print("NO") else: print("YES")
Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit...
3
# Light switches i = 0 j = 0 q = [] for k in range(3): q.append([]) for l in range(3): q[k].append(0) while True: try: t = input().split(' ') for j in range(3): r = int(t[j]) q[i][j] += r if (i-1) > -1: q[i-1][j] += r ...
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
1
def choose(n): return (n**2-n)/2 N, M = map(int, raw_input().strip().split()) maxFriends = choose(N-M+1) if N-M > 0 else 0 low = N/M low_num = M - N % M high = low + 1 high_num = M - low_num minFriends = low_num*choose(low) + high_num*choose(high) print minFriends, maxFriends
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills). So, about the teams. Firstly, these two teams should have the s...
3
from collections import Counter for _ in range(int(input())): n=int(input()) l=list(map(int, input().split())) d=Counter(l) m=max(list(d.values())) dis=len(Counter(l)) if(n==1): print(0) continue elif(n==2 or dis==n): print(1) continue dis=dis-1 if(dis>=m): print(m) elif(dis<m): if(m-dis==1): p...
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
3
def find_sequence(zeros, ones): sequence = "" if zeros <= ones: if zeros< 0: return -1 double_one_sequence = ones - zeros single_one_sequence = zeros - double_one_sequence if double_one_sequence <= zeros: sequence = "011"*double_one_sequence elif d...
I have a plan to go on a school trip at a school. I conducted a questionnaire survey for that purpose. Students have student numbers from 1 to n, and the locations of travel candidates are represented by numbers from 1 to m, and where they want to go ○ , Mark the places you don't want to go with a cross and submit. At...
1
while True: n, m = map(int, raw_input().split()) if n==0 and m==0: break c = {i:0 for i in range(m)} for i in range(n): a = map(int, raw_input().split()) for j in range(m): c[j] += a[j] ans=[k[0]+1 for k in sorted(c.items(),key=lambda x:x[1],reverse=True)] print " "....
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ...
1
n = int(raw_input()) s = raw_input() ret = "" for c in s: v = (ord(c) + n) if v > ord('Z'): v = (v - ord('Z')) + ord('A') - 1 ret += chr(v) print ret
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
import math t = int(input()) while t: t -= 1 a, b, c, d = map(int, input().split()) inc = c-d ans = 0 res = a if(a <= b): print(b) else: ans += b res -= b if(inc <= 0): print(-1) else: if(res % inc == 0): print(a...
Snuke is giving cookies to his three goats. He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins). Your task is to determine whether Snuke can give cookies to his three goats so that each of them ca...
1
N = raw_input().split() ans = "" for i in range(2): if int(N[i]) % 3 == 0: ans = "Possible" if int((N[0] + N[1])) % 3 == 0 : ans = "Possible" if ans == "Possible": print ans else: print "Impossible"
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
import sys parametrs = list(map(int, input().split())) n = parametrs[0] m = parametrs[1] a = parametrs[2] b = parametrs[3] variants = [] if(n % m == 0): n_abonements = n // m else: n_abonements = n // m + 1 min_price = 10000000 for trip in range(0, n+1, 1): for abonement in range(0, n_abonements+1, 1): tri...
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97. Alice is given a sequence of n composite numbers a_1,a_2,…,a_n. She wants to choos...
3
def func(): n = int(input()) arr = [int(x) for x in input().split()] primes = [[2,False],[3,False],[5,False],[7,False],[11,False],[13,False],[17,False],[19,False],[23,False],[29,False],[31,False]] k = 0 ans = [] for i in arr: for j in range(len(primes)): if( i % primes[j][0] ...
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player sp...
3
print(int(input())*3>>1)
«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
a=[] for i in range(4): x=int(input()) a.append(x) n=int(input()) v=[] for i in range(n+1): v.append(0) for i in range(4): aux=a[i] while a[i]<n+1: v[a[i]]=1 a[i]+=aux nr=0 for i in range(1,n+1): if v[i]==1: nr+=1 print(nr)
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
n = int(input()) string = [] for i in range(0,n): string.append(int(input())) for i in range(0,n): print(string[i])
Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a ...
3
count = 0 sum=0 while (True): count += 1 a=int(input()) sum=sum+a if(count==10): print(sum) break
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
s1=input() s2=input() s="" for i in range(len(s1)): if(s1[i]==s2[i]): s+="0" else: s+="1" print(s)
The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city. For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crim...
3
def main(): n, t, c = map(int, input().split()) a = b = 0 for x in map(int, input().split()): if x <= t: b += 1 a += b >= c else: b = 0 print(a) if __name__ == '__main__': main()
There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. □ | □ | □ | □ | □ | □ | □ | □ --- | --- | --- | --- | --- | --- | --- | --- □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □...
3
def get_input(): while True: try: yield ''.join(input()) except EOFError: break N = list(get_input()) board = [[0 for i in range(11)] for j in range(11)] for l in range(0, len(N), 9): for i in range(l, l+8): for j in range(len(N[i])): board[i-l][j] =...
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 = [int(x) for x in input().split()] if abs(x-y) > z or z == 0: if x > y: print("+") elif x == y: print("0") else: print("-") else: print("?")
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m...
3
n = int(input()) s = list(map(int, input().split())) t = 0 while len(s) > 0: ls = len(s) s1 = s.index(s[0], 1) sn = s.index(s[-1]) if s1 < ls - sn-1: s = s[1:s1]+s[s1+1:] t += s1-1 else: t += ls-sn-2 s = s[:sn] + s[sn+1:ls-1] print(t)
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
def f(): s = input().split(' ') a = int(s[0]) b = int(s[1]) if a % b == 0: print(0) else: print(b * (a // b + 1) - a) t = int(input()) for i in range(t): f()
You are given three strings A, B and C. Check whether they form a word chain. More formally, determine whether both of the following are true: * The last character in A and the initial character in B are the same. * The last character in B and the initial character in C are the same. If both are true, print `YES`....
3
a,b,c=input().strip().split() if a[-1]==b[0] and b[-1]==c[0]: print("YES") else: print("NO")
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set S containing very important number...
3
# python3 q2.py < test.txt t = int(input()) for i in range(t): n = int(input()) a = [int(j) for j in input().split()] ok = False for k in range(1, max(a) * 2 + 1): if ok == True: break s = set() for j in range(n): temp = a[j] ^ k if temp not...
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous. Input The first line cont...
3
a=int(input()) b=list(map(int,input().split())) x=int(1) r=[] k=int(0) while x<a: if b[x]>b[x-1]: k=k+1 else: r.append(k+1) k=0 x=x+1 r.append(k+1) print(max(r))
It's now the season of TAKOYAKI FESTIVAL! This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i. As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points. There are \frac{N...
3
n = int(input()) d = list(map(int, input().split())) s = sum(d) ans = 0 for i in d: s -= i ans += s * i print(ans)
You are given an integer number n. The following algorithm is applied to it: 1. if n = 0, then end algorithm; 2. find the smallest prime divisor d of n; 3. subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. Input The only line contains a single integer n (2 ≤...
3
n=int(input()) ans=0 if n%2!=0: i=3 while n%i!=0 and i*i<n:i+=2 if n%i!=0:i=n n-=i ans=1 ans+=n//2 print(ans)
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
x = str(input()) if (len(x) > 0 and x[0].islower()): print(x[0].upper() + x[1:]) else: print(x)
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
3
def solve(L, v, l, r): return L//v - r//v + (l-1)//v if __name__ == '__main__': ans = [] n = int(input()) for i in range(n): L, v, l, r = map(int, input().split(' ')) ans.append(solve(L, v, l, r)) for a in ans: print(a)
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S. It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S? Input The only line of the input contains two integers n and S ...
3
import math n,s=input().split() n,s=[int(n),int(s)] ans=math.ceil(s/n) print(ans)
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
matrix = [] for i in range(5): matrix.insert(i, input()) for i in range(5): for j in range(9): if matrix[i][j] == '1': locJ = j - j/2 locI = i posJ = abs(locJ - 2) posI = abs(locI - 2) totPos = posJ + posI print(int(totPos), end="")
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
1
n, m = map(int, raw_input().split()) mi = min(n, m) + 1 print mi for x in range(mi): print x, mi-x-1
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n × m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
import sys # sys.stdin = open(r'input/A.txt') t = int(input()) inp = [line.strip().split() for line in reversed(sys.stdin.readlines())] ans = [] while t: n, m = map(int, inp.pop()) t -= 1 # print(n, m) if n * m % 2 == 1: for i in range(n): line = [] for j in range(m): ...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
n =input() li = list(map(int,n.split(" "))) i=1 while i<=max(li[0],li[1]): if(li[0]*3**i>li[1]*2**i): print(i) break i=i+1
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain posi...
3
def sumDigits(x) : return sum(list(map(int, str(x)))) n = int(input()) counter = 0 theNumbers = [] digits = len(str(n)) for i in range (max( n - digits *9, 0), n) : if i+sumDigits(i)==n: theNumbers.append(i) counter += 1 print (counter) for j in range(len(theNumbers)): print(theNumbers[j])
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input(...
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob. Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight. Limak eats a lot and his weight is tripled after every year, while Bob's weight...
3
i,e = list(map(lambda e : int(e), (input()).split(' '))) cnt = 0 while(i<=e): i *= 3 e *= 2 cnt += 1 print(cnt)
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
## necessary imports import sys import random from math import log2, log, ceil input = sys.stdin.readline # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp ## gcd function def gcd(a,b): if a > 0: return gcd(b%a, a) return b ## prime factorization d...
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ...
3
from sys import stdin def dfs(index, adj, visited): visited[index] = True for nb in adj[index]: if not visited[nb]: dfs(nb, adj, visited) def main(): n = int(stdin.readline()) vertex = [] adj = [] for _ in range(n): tt, tx, ty = map(int, stdin.readline().split()) ...
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct str...
3
from collections import Counter for i in range(int(input())): n=int(input()) s1=list(input()) s2=list(input()) C=Counter(s1+s2) f=False for i in C: if C[i]%2==1: f=True break if f: print("No") continue ans=[] for i in range(n): #s1 ...
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides). That's why Mister B decided to use this polygon. Now Mister B must find ...
1
n, a = map(int, raw_input().split()) start = 0 mid = 1 end = 2 best = 10**10 best_ind = -1 while n-end > 0: angle = ((n - float(end)) * 180) / n if abs(angle - a) < best: best = abs(angle-a) best_ind = end end += 1 print start+1, mid+1, best_ind+1
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
t=5 y=[] while t>0: x=[] x=[int(x) for x in input().split()] y.append(x) t-=1 row=0 for i in range(5): if y[i].count(1)==1: row=i+1 else:continue place=0 col=0 for item in y[row-1]: if item==1: place+=1 col=place else: place+=1 if row>3: s1=r...
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1. Note that all computa...
3
from math import gcd def to_base(b, x): ans = 0 while x > 0: ans += (x % b) x //= b return ans def main(): a = int(input()) num, den = 0, 0 for b in range(2, a): num += to_base(b, a) den += 1 d = gcd(num, den) print('{}/{}'.format(num // d, den // d)) ...
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
pontoamigo = int(input()) if pontoamigo % 5 == 0: c = pontoamigo//5 else: c = (pontoamigo//5)+1 print(c)
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
for i in range(int(input())): n=int(input()) a=[int(i) for i in input().split()] c=1 go=True for i in range(1,n): if a[-(i+1)]>=a[-i] and go: c+=1 continue else: go=False if a[-(i+1)]<=a[-i]: c+=1 go = False else: break print(n-c)
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
from sys import stdin, stdout, maxsize; # mod = int(1e9 + 7);#import re # can use multiple splits #input = stdin.buffer.readline tup = lambda: map(int, stdin.readline().split()) I = lambda: int(stdin.readline()) lint = lambda: [int(x) for x in stdin.readline().split()] S = lambda: stdin.readline().replace('\n', '').s...
You are given an array a of length n. You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions. Your task is to determine if it is poss...
3
from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5)...