problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
nums = int(input()) coins = list(map(int, input().split())) # list of coins values coins.sort(reverse=True) # biggest to smallest #print(coins) sidelist = [] while (True): if ( (sum(coins)+1 > sum(sidelist)) ): sidelist.append(coins.pop(0)) else: break '''while ( (sum(coins) > sum(sidelist)...
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction. More specifically, in one move, he can go from coordinate x to x + D or x - D. He wants to make K moves so that the absolute value of the coordinate of the destination wil...
3
X, K, D = map(int, input().split()) X = abs(X) if X//D <= K: K -= X//D X %= D X -= D*(K%2) print(abs(X)) else: print(X - D*K)
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W. Output the list...
1
from copy import deepcopy T = input() r = 1 def getnum(index,prew,pretot,temp,c,ans): if ans: return if (c+1)/2<=pretot<=c: ans.append(deepcopy(prew)) return if index==len(temp): return if temp[index][0]+pretot<=c: prew.append(temp[index][1]) getnum(ind...
You have an integer variable x. Initially, x=0. Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`. Find the maximum value taken by x duri...
3
N = int(input()) S = input() ans = 0 x = 0 for c in S: if c == 'I': x += 1 else: x -=1 ans = max(ans, x) print(ans)
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
import re s = input() if re.search('0{7,}', s) or re.search('1{7,}', s): print('YES') else: print('NO')
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
3
buttons = int(input()) inner = buttons-1 sum = 0 for x in range(1,buttons+1): sum += x + (x-1) * inner inner -= 1 print(sum)
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
3
n=int(input()) l=[input() for _ in range(n)] m=[] for i in l: if i not in m: print('NO') m.append(i) else: print('YES')
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
a=int(input()) for i in range(0,a): b=int(input()) c=list(map(int,input())) d=c.count(0) e=c.count(1) f='' for j in range(0,b): f+=str(0) g='' for k in range(0,b): g+=str(1) if d>e: print(f) else: print(g) #submission dkle bia hbe na ।
Archith was a making noise in digital logic class.Sir was very frustrated by the behaviour of Archith. Sir asked archith to meet him in staff room. As archith reached staff room sir gave a smile and asked to complete this assignment in one day if not he will be suspended. Archith has low attendence so he has to complet...
1
def binary(decimal) : ans=0 while decimal != 0 : rem=(decimal % 2) if rem==1: ans+=1 decimal /= 2 return ans t=input() while t: n=input() r=binary(n) if r%2==0: print "even" else: print "odd" t-=1
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
""" inp_start 3 2 3 2 3 4 1 3 5 3 2 2 3 4 1 3 5 5 5 1 4 3 3 8 8 1 3 8 2 9 3 5 3 1 8 8 5 6 9 8 7 3 8 4 inp_end """ from sys import stdin input = stdin.readline from collections import Counter tcs = int(input()) for tc in range(tcs): n, m = list(map(int, input().split())) L = [] first_m = [] for i in range(n): p ...
Chef and Roma are playing a game. Rules of the game are quite simple. Initially there are N piles of stones on the table. In each turn, a player can choose one pile and remove it from the table. Each player want to maximize the total number of stones removed by him. Chef takes the first turn. Please tell Chef the max...
1
testcase = input() while testcase != 0: n = input() array = map(int, raw_input().split()) array.sort(reverse = True) sumi = 0 for i in range(0, len(array)): if i % 2 == 0: sumi += array[i] print sumi testcase -= 1
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
ch=input() a=0 b=0 c=0 for i in range(1,len(ch)): if(ord(ch[i])> 96): a=1 elif(ord(ch[i])<97): b+=1 if(len(ch)==1): if(ch.islower()): print(ch.upper()) else: print(ch.lower()) if(a==1): print(ch) elif(b!=0): if(ch[0].islower()): print(ch[0].upper()+ch[1:]...
Problem Alice and Bob are competing in the 50m dash. However, in this world, the higher the AOJ rate is, the better, so the higher the AOJ rate wins. If there is no AOJ rate on either side, there is no comparison, so there is no choice but to compete in the 50m sprint time. In this case, the one with the shorter time ...
3
#!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()]...
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()) summer,maxv=0,-1<<345 for _ in range(n): a,b=map(int,input().split()) summer-=a summer+=b maxv=max(maxv,summer) print(maxv)
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
3
n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] ans = 0 for i in range(n): for j in range(n): hor = 0 ver = 0 for k in range(n): hor += arr[i][k] ver += arr[k][j] ans += ver > hor print(ans)
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
3
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: ...
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m. Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B. For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ...
3
from sys import stdin from math import gcd, sqrt, log10, log2 def ii(): return int(stdin.readline()) def mi(): return map(int, stdin.readline().split()) def li(): return list(mi()) n=ii() a=li() m=ii() b=li() print(max(a), max(b))
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
3
s = input() flag = 1 for i in range(0 , len(s)): if(s[i] != 'a' and s[i] != 'e' and s[i] != 'i' and s[i] != 'o'and s[i] != 'u' and s[i] != 'n'): if(i == len(s) - 1 or (s[i + 1] != 'a' and s[i + 1] != 'e' and s[i + 1] != 'i' and s[i + 1] != 'o'and s[i + 1] != 'u')): flag = 0 if(flag): print("Y...
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly...
3
from copy import copy from math import * def arr_float_inp(): return [float(s) for s in input().split()] def arr_int_inp(): return [int(s) for s in input().split()] def int_inp(): return int(input()) def float_inp(): return float(input()) def comp(a): return a[0] def gcd(a, b): if b !...
HAI I HAS A TUX GIMMEH TUX I HAS A FOO ITS 0 I HAS A BAR ITS 0 I HAS A BAZ ITS 0 I HAS A QUZ ITS 1 TUX IS NOW A NUMBR IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0 I HAS A PUR GIMMEH PUR PUR IS NOW A NUMBR FOO R SUM OF FOO AN PUR ...
1
t = int(raw_input().strip()) a = b = c = 0 d = 1 for i in xrange(t): p = int(raw_input().strip()) a = a + p b = b + 1 if max(a * d, b * c) == a * d: c = a d = b print "%.12f" % (1.0 * c / d)
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
3
t = int(input()) for i in range(t): n = int(input()) a = [int(s) for s in input().split()] a.sort() d = a[1] - a[0] for j in range(n - 1): if a[j + 1] - a[j] < d: d = a[j + 1] - a[j] if d == 0: break print(d)
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. <image> The dragon has a hit p...
3
import sys try: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass input = sys.stdin.readline for tt in range(int(input())): # n = int(input()) x,n,m = map(int,input().split()) # l = list(map(int,input().split())) while n: if x<=m*10: print("YES") break else: x = ...
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...
1
n=input() if n%2==0 and n!=2: print "yes" else: print "no"
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: * Move the chip i by 2 to the left or 2 to the right for free (i.e. replace...
3
def main(): n= int(input()) arr = list(map(int, input().rstrip().split())) even,odd=0,0 for i in arr: if(i%2==0): even+=1 else: odd+=1 coin = min(odd,even) print(coin) if __name__ == "__main__": main()
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. <image> The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou...
3
n,m,k = map(int,input().split()) s = [int(i) for i in input().split()] x,y=0,0 d = s[m-1::-1] c = s[m-1:n] for i in range(len(d)-1): if d[i+1]!=0 and d[i+1]<=k: x = i+1 break for i in range(len(c)-1): if c[i+1]!=0 and c[i+1]<=k: y = i+1 break if x==0 or y==0: print(max(x,y)*10) else: print(min(x,y)*10) ...
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
n,m=list(map(int,input().split())) for i in range(n): print(['#'*m,'.'*(m-1)+'#','#'*m,'#'+'.'*(m-1)][i%4])
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≤ n ≤ ...
3
m = int(input()) n = list(map(int, input().split())) n.reverse() s = [] if len(n) == 1: s.append(n[0]) else: for i in range(len(n)): if n[i] not in s: s.insert(0, n[i]) print (len(s)) print(" ".join(map(str, s)))
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string s. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" <image>...
3
def main(): n = input() d = input() c1 = len([v for v in d if v=='1']) с0 = len(d)-c1 print("1"+"0"*с0 if c1>0 else "0") if __name__ == "__main__": main()
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbas...
3
s = input() a = ['B', 'u', 'l', 'b', 'a', 's', 'r'] b = [] for i in range(len(a)): if a[i] != 'a' and a[i] != 'u': b.append(s.count(a[i])) else: b.append(int(s.count(a[i])/2)) print(min(b))
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
3
import sys inf = 2**33 sys.setrecursionlimit(2**20) def solve(dp, wa, original, smallest): if (original == 0): return(0) if (original - smallest < 0): return(-inf) #print("reached here") if (dp[original] == -1): cuts = -inf for i in wa: if (original - i >= 0)...
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
arr = list(input().split()) for i in range(len(arr)): if not arr[i][0].isupper(): arr[i]=chr(ord(arr[i][0])-32)+arr[i][1:] print(*arr)
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where <image> Now DZY has a string s. He wants to insert k lowercase ...
3
s1=input() n=int(input()) l1=list(map(int,input().split())) index=l1.index(max(l1)) s1+=chr(97+index)*n sum1=0 for i in range (len(s1)): sum1+=l1[ord(s1[i])-97]*(i+1) print(sum1)
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
vogais = ['a','e','i','o','u','y'] string = input().lower() answer = '' for e in string: if e not in vogais: answer += '.'+e print(answer)
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu...
1
s = raw_input() n = len(s) ans = s.count("VK") s = s.replace("VK","**") print ans+1 if "VV" in s or "KK" in s else ans
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b. For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
import math import sys #sys.stdin = open("in.txt") t = int(input()) for i in range(t): n, k = map(int, input().split()) for i in range(k): if (n % 2 == 0): n += 2 * (k - i) break else: for d in range(3, 1000, 2): if (n % d == 0 or d * d > n)...
The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s. Igor is at the point x1. He should reach the point...
3
s, x1, x2 = map(int, input().split()) t1, t2 = map(int, input().split()) p, d = map(int, input().split()) ans = abs(x1 - x2) * t2 if d == -1: x1, x2 = s - x1, s - x2 p = s - p x1t = [(x1-p)*t1,(2*s-x1-p)*t1,(2*s+x1-p)*t1] x2t = [(x2-p)*t1,(2*s-x2-p)*t1,(2*s+x2-p)*t1] while x1t[0] < 0: x1t.pop(0) while x2t[0...
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...
1
n = int(raw_input()) s = raw_input() count = 0 for i in range(1, n): if s[i] == s[i-1]: count += 1 print count
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
for _ in range(int(input())): n,a,b=[int(i) for i in input().split()] l=max([int(i) for i in input().split()]) l2=max([int(i) for i in input().split()]) if l>l2: print("YES") else: print("NO")
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 — the base of the ladder; * k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
3
t=int(input()) while(t): n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) a1=a[1]-1 a2=n-2 ans=min(a1,a2) print(ans) t-=1
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po...
1
x,y=map(int,raw_input().split()) a,b=map(int,raw_input().split()) result=0 for i in xrange(0,int(raw_input())): d,r,e=map(int,raw_input().split()) if (d*x+r*y+e)*(d*a+r*b+e)<0: result+=1 print result
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0. Each heater has a va...
1
n, r = map(int, raw_input().split()) a = map(int, raw_input().split()) ones = list(filter(lambda x: a[x]==1, xrange(n)))[::-1] cov = [False]*n b = False cnt = 0 for i in xrange(n): if cov[i]: continue while len(ones) > 1 and ones[-2] - i < r: ones.pop() if len(ones) >= 1 and ones[-1] -i <r:...
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()) ans = 0 for i in range(n): if [int(i) for i in input().split(' ')].count(1) >= 2: ans+=1 print(ans)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
t=0 for i in range(int(input())): if sum(map(int,input().split()))>1: t+=1 print (t)
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
1
inp = raw_input().strip() now = 0 ans = 0 for i in range(len(inp)): if now == 5 or (i >= 1 and inp[i] != inp[i - 1]): ans += 1 now = 0 now += 1 ans += 1 print ans
Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn. Of co...
3
N=int(input()) p=[0]+list(map(int,input().split())) count=0 for i in range(len(p)-1): count+=abs(p[i+1]-p[i]) print(count)
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4. Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q...
3
n = int(input()) arr = [[0]*2 for i in range(101)] st = str(input()).split() st = [int (i) for i in st] for i in st: arr[int(i)-1][0]+=1 one=0 two=0 more=0 x=0 y=0 for i in range(101): if(arr[i][0]==1): one+=1 elif(arr[i][0]==2): #print('-----') two+=1 y+=arr[i][0] eli...
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
3
cards=input() numbers="0123456789" even = "02468" vowals="aeiou" count = 0 for s in range(len(cards)): if cards[s] in vowals: count += 1 else: if cards[s] in numbers and cards[s] not in even: count += 1 print(count)
You will be given an integer a and a string s consisting of lowercase English letters as input. Write a program that prints s if a is not less than 3200 and prints `red` if a is less than 3200. Constraints * 2800 \leq a < 5000 * s is a string of length between 1 and 10 (inclusive). * Each character of s is a lowerca...
3
a,s=open(0) print(("red",s)[int(a)>3199])
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo...
1
a,b,c,d=raw_input().split() a=float(a) b=float(b) c=float(c) d=float(d) x=sorted([a,b,c,d]) if(x[0]+x[1]>x[2] or x[1]+x[2]>x[3]): print("TRIANGLE") elif(x[0]+x[1]==x[2] or x[1]+x[2]==x[3]): print("SEGMENT") else: print("IMPOSSIBLE")
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
a=[] for i in range(1000): s=list(str(i)) if '0' in s or '1'in s or '2' in s or '3' in s or '8' in s or '5' in s or'6' in s or '9' in s : continue else: x=int("".join(s)) a.append(x) L=len(a) n=int(input()) c=0 for i in range(L): if n%a[i]==0: c=c+1 if c!=0: ...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
1
n = input() st1 = set(sorted((map(int, raw_input().split()))[1:])) st2 = set(sorted((map(int, raw_input().split()))[1:])) turns = st1.union(st2) if len(turns) == n: print "I become the guy." else: print "Oh, my keyboard!"
There is a cave. The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside. It is dark in th...
3
import queue n,m=map(int,input().split()) e=[[] for _ in range(n+1)] INF=10**18 d=[INF]*(n+1) ans=[0]*(n+1) for _ in range(m): a,b=map(int,input().split()) e[a]+=[b] e[b]+=[a] q=queue.Queue() q.put(1) d[1]=0 while not q.empty(): now=q.get() for to in e[now]: if d[to]==INF: ans[to]=now d[to]=d[...
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
1
s=raw_input() t=raw_input() if len(s) != len(t): print('No') else: f = True for i in range(len(s)): if (s[i] in "aeiou") != (t[i] in "aeiou"): print("No") f = False break if (f): print("Yes")
Petya and Vasya are competing with each other in a new interesting game as they always do. At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S. In order to win, Vasya ha...
3
n,s=map(int,input().split()) if s>=2*n: print("YES") a=[2]*(n-1) a.append(s-sum(a)) print(*a) print(1) else: print("NO")
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
3
import math def square(m, n, flagstone): if (1<= m, n, flagstone <= 10^9): possibility = math.ceil(m/flagstone) * math.ceil(n/flagstone) return(possibility) m, n, flagstone = (int(x) for x in input().split(' ')) print(square(m, n, flagstone))
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
t=int(input()) for i in range(t): ch=input() ch1=input() ch2=input() L1=[int(i)for i in ch1.split()] L2=[int(i)for i in ch2.split()] L1.sort() L2.sort() if L1[-1]>L2[-1]: print("YES") else: ...
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...
3
n,m = (int(i) for i in input().split()) l = list(map(int,input().split())) pdm = [] for i in range(m): a,b = (int(i) for i in input().split()) a-=1 b-=1 if sum(l[a:b+1])>0: pdm +=[[a,b]] ans = 0 for i in range(n): am = 0 for j in range(len(pdm)): if i<=pdm[j][1] and i >= pdm[j]...
Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly <image> hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster e...
3
z=int(input()) x=list(map(str,input())) if x.count('X')>=x.count('x'): print((z//2)-x.count('x')) b='x' a='X' else: print((z//2)-x.count('X')) b='X' a='x' for i in range((z//2)-x.count(b)): x[x.index(a)]=b print(''.join(x))
Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n). If Nikolay is currently in some room, he c...
1
t=int(raw_input()) for x in range(t): n=int(raw_input()) s=raw_input() if s.count('1')!=0: a=s.index('1') b=s[::-1].index('1') m=max(a+1,n-a,b+1,n-b) print 2*m else: print len(s)
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` ...
3
N=int(input()) s=input() for c in s: print(chr((ord(c)-65+N)%26+65),end="")
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s...
3
k,d,t=map(int,input().split()) a=d-(k%d) if(a==d): a=0 b=k+a/2 ans=0 ans+=(t//b)*(k+a) t=t%b if(t<=k): ans+=t else: ans+=k+(t-k)*2 print(ans)
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui...
3
import math n, t, k, d = list(map(int, input().split())) total_time = math.ceil(n / k) * t if total_time - t > d: print("YES") else: print("NO")
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can...
1
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time import sys import io import re import math import itertools import collections #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #mod=1777777777 pi=3.141592653589 xy=[(1,0),(-1,0),(0,1),(0,-1)] bs=[(-1,-1),(-1,1),(1,1),(1,-1...
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i. Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to: * Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change...
3
n = int(input()) a = [int(i) for i in input().split()] if n > 60: print(sum(a) - n) else : ans = 0x3f3f3f3f3f3f3f3f a.sort() nlen = int(pow(max(a), 1 / (len(a) - 1))) + 1 i = 1 while i <= nlen: t = 0 for j in range(len(a)): t += abs(a[j] - i ** j) ans = min(an...
Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total. Each Kinder Surprise can be one of three types: * it can contain a single sticker and no toy; * it can contain a single toy and no sticker; * it can contain both a sing...
3
t=int(input()) res=[] for i in range(t): n,s,t = tuple([int(x) for x in input().split()]) res.append(n-min(s,t)+1) for i in res: print(i)
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote...
1
l=lambda:map(int,raw_input().split()) n,k=l() a=l() ll=n*k f=[False]*ll d=range(1,ll+1) for i in a: f[i-1]=True cur=0 for i in range(k): c=0 while cur<ll and c<n-1: if not f[cur]: print d[cur], c+=1 cur+=1 print a[i]
You have N items and a bag of strength W. The i-th item has a weight of w_i and a value of v_i. You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W. Your objective is to maximize the total value of the selected items. Constraints * 1 ≤ N ≤ 10...
3
N,W=map(int,input().split()) L=[[]for i in range(4)] A=[] for i in range(N): w,v=map(int,input().split()) A.append([w,v]) A.sort() #print(A) L[0].append(A[0]) P=0 for i in range(1,N): if A[i][0]==A[i-1][0]: L[P].append(A[i]) else: P+=1 L[P].append(A[i]) #print(L) for i in rang...
There is always an integer in Takahashi's mind. Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1. The symbols Takahashi is going t...
3
s=input() x=s.count("-") y=s.count("+") print(y-x)
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
3
n=int(input()) b=[] for x in range(n): b+=list(map(int,input().split())) c=[] d=[] i=0 while i<n*2: c.append(b[i]) i+=2 i=1 while i<n*2: d.append(b[i]) i+=2 count=0 for x in c: for y in d: if x==y: count+=1 print(count)
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ...
3
for i in range(int(input())): x = input().split("R") long = list(map(len, x)) print(max(long)+1)
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indice...
3
from collections import Counter n = int(input()) a = [int(i) for i in input().split()] res = [] wefind = Counter(a).most_common(1)[0][0] firstindex = a.index(wefind) i = firstindex - 1 while i >= 0: if a[i] < wefind: res.append((1,i,i+1)) elif a[i] > wefind: res.append((2,i,i+1)) i -= 1 i =...
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ...
3
for _ in range(int(input())): N=int(input()) Sum=N X=0 while N!=0: X=X+N%10 N=N//10 Sum=Sum+N Sum+=X//10 Sum+=((X//10)+(X%10))//10 print(Sum)
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively. Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number: * Extension Magic: Consumes 1 MP (magic point)....
3
N,A,B,C=[int(i) for i in input().split()] l=[] for i in range(N): l.append(int(input())) def magic(cur,a,b,c): if cur==N: if a*b*c!=0: return abs(a-A)+abs(b-B)+abs(c-C)-30 else: return 10**9 r0=magic(cur+1,a,b,c) r1=magic(cur+1,a+l[cur],b,c)+10 r2=magic(cur+1,a,b+l[cur],c)+10 r3=magic(c...
Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it. The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer)....
3
n = int(input()) for i in range(50001): if int(i * 1.08) == n: print(i) exit() print(":(")
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
def solve(): a, b = list(map(int, input().split())) if a < b: a, b = b, a print((a - b + 9) // 10) ct = int(input()) while ct > 0: solve() ct -= 1
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce...
3
import sys input = lambda: sys.stdin.readline().rstrip("\r\n") Read = lambda: list(map(int, input().split())) Num = lambda: int(input()) def solve(): n, m = Read() a, b = [], [] sa, sb = 0, 0 diff = [] for _ in range(n): x, y = Read() sa += x sb += y diff.append(x -...
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
3
import sys input=sys.stdin.readline for _ in range(int(input())): n=int(input()) ar=[int(x) for x in input().split()] bit=[0]*32 dr=True for i in range(32): for j in ar: bit[i]+=1 if(1<<i & j) else 0 #print(bit) bit=bit[::-1] for i in bit: if(i%2!=0): ...
Vasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, …, d_k, such that 1 ≤ d_i ≤ 9 for all i and d_1 + d_2 + … + d_k = n. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different d...
3
n=int(input()) temp=1 for i in range(1,10): if(n%i==0): d=n/i if(i>temp): temp=i print(int(n/temp)) s=0 while(s<n): s=s+temp print(temp, end=" ")
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
t=int(input()) for j in range(t): n, a, b = map(int, input().split()) q = list(map(int, input().split())) w = list(map(int, input().split())) if max(q) > max(w): print('YES') else: print('NO')
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people c...
3
import math n = int(input()) m = int(input()) x = m arr = [] for i in range(n): arr.append(int(input())) maxx = max(arr) summ = 0 for i in range(n): if arr[i] <= maxx: if m >= maxx - arr[i]: m -= maxx - arr[i] arr[i] = maxx else: arr[i] += m m ...
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
for t in range(int(input())): n = int(input()) a = list(map(lambda x: int(x)-1, input().split())) setA = [-1]*n yes = False for i,e in enumerate(a): if setA[e] != -1 and setA[e] != i-1: yes = True break elif setA[e] == -1: setA[e] = i if yes: print("YES") else: print("NO") #v
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. Fo...
3
n = int(input()) a = list(map(int, input().split())) for i in a: if 1 <= i % 14 <= 6 and i > 14: print('YES') else: print('NO')
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider...
1
def solve(points): x_dict = {} y_dict = {} act_dict = {} for p in points: if p[0] not in x_dict: x_dict[p[0]] = 0 x_dict[p[0]] += 1 if p[1] not in y_dict: y_dict[p[1]] = 0 y_dict[p[1]] += 1 if (p[0], p[1]) not in act_dict: act_dict[(p[0], p[1])] = 0 act_dict[(p[0], p[1])] += 1 ans = 0 for...
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi). In the tournament, each team plays exactly one home game and exactly one aw...
3
import sys inf = float("inf") # sys.setrecursionlimit(10000000) # abc='abcdefghijklmnopqrstuvwxyz' # abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 2...
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
def stones_on_the_table(stones): count=0 for i in range(1,len(stones)): if stones[i]==stones[i-1]: count+=1 print(count) n1=int(input()) stones=input() stones_on_the_table(stones)
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white. Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po...
3
W,H,N = map(int,input().split()) L = 0 R = W D = 0 U = H for _ in range(N): x,y,a = map(int,input().split()) if a == 1: L = max(L,x) if a == 2: R = min(R,x) if a == 3: D = max(D,y) if a == 4: U = min(U,y) x = max(0,R-L) y = max(0,U-D) answer = x*y print(answer)
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
#------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUF...
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor. The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a pla...
3
n=int(input()) if n%2==0: print("2") else: print("1")
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
l = [] n = int(input()) s = 0 for i in range(n): f = input() l.append(f) for i in l: if(i =='Tetrahedron'): s = s+4 elif(i =='Cube'): s = s+6 elif(i =='Octahedron'): s = s+8 elif(i =='Dodecahedron'): s = s+12 else: ...
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ...
3
card_tb = input("") card_hd = input("").split(" ") tg_rank = card_tb[0] tg_suit = card_tb[1] for item in card_hd: cur_rank = item[0] cur_suit = item[1] if cur_rank == tg_rank or cur_suit == tg_suit: print("YES") exit() print("NO")
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end...
3
import re def norm(s): result = re.sub(r'(ogo)(go)*', "***", s) return result i = input() s = input() print(norm(s))
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret! A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ...
3
t=int(input()) for i in range(t): n=int(input()) list1=list(map(int,input().split())) list2=[] i=0 j=i+1 S=set(list1) if len(S)>1: print(1) else: print(n)
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
3
n=int(input()) ar=list(map(int,input().split())) ans=[ ] for i in range (0,n): k=ar[i] arr=list(map(int,input().split()))[:k] s=sum(arr)*5 + 15*k ans.append(s) print(min(ans))
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
3
n = int(input()) air = input() con = 0 home = 0 for i in range(n): road = input() if road[0:3] == air: con += 1 else: home += 1 if con > home: print('contest') else: print('home')
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
3
a,b=map(int,input().split()) i=1 c=0 while True: if i%b!=0: a-=1 c+=1 if a==0: break i+=1 print(c)
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
n,m = map(int,input().split()) line = [int(x) for x in input().split()] se = [] l = 0 se = {} dp = [] for _ in range(n): a = line.pop() try: se[a] except KeyError: se[a] = 1 l += 1 dp.append(l) ans = [] for _ in range(m): ans.append(str(dp[n-int(input())])) print('\n'.join(an...
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it. You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: fi...
3
import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(i, n, delta, delta2): inf = 2 * 10**9 dp = [[-1] * n for _ in range(1 << n)] dp[(1 << i)][i] = in...
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ...
3
n = int(input()) lst = [] for x in input().split(): lst.append(int(x)) mini = min(lst) ls = lst.index(mini) l = len(lst) for x in range(ls + 1, len(lst)): if lst[x] == mini: l = min(l, x - ls) ls = x print(l)
Recently, chef Ciel often hears about lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Ciel decides to make Ciel numbers. As you know, Ciel likes the digi...
1
count=0 for i in range(input()): p=raw_input().split() p=p[-1] c8=p.count('8') c5=p.count('5') c3=p.count('3') if(c3+c5+c8==len(p) and c8>=c5 and c5>=c3): count+=1 print count
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
import sys from collections import defaultdict as dd from collections import deque from fractions import Fraction as f from copy import * from bisect import * from heapq import * from math import * from itertools import permutations def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrecursionlimit(...