problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | 1 | # -*- coding: utf-8 -*-
import itertools
if __name__ == '__main__':
n = int(raw_input())
emails = map(int, raw_input().split())
stripped_emails = map(int, ''.join(map(str, emails)).strip('0'))
result = 0
for key, group in itertools.groupby(stripped_emails):
group = list(group)
i... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 | def orange():
n = int(input())
if n != 0:
a = list(map(int,input().strip().split()))[:n]
s = sum(a)
res = float(s/n)
return res
else:
return 0.0
print(orange()) |
The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.
According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situat... | 3 | n, y = map(int, input().split())
for a in range(n+1):
for b in range(n+1-a):
if 10000*a + 5000*b + 1000*(n-a-b) == y:
print(a, b, n-a-b)
exit(0)
print("-1 -1 -1") |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 1 | for x in range(int(raw_input())):
word = raw_input()
print word[0] + str(len(word[1:-1])) + word[-1] if len(word) > 10 else word |
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only ope... | 1 | n = int(raw_input())
weights = map(int, raw_input().split())
alternatives = {None: 0}
for i in xrange(n):
s_cur = raw_input()
s_cur_rev = ''.join(reversed(s_cur))
new_alternatives = {}
for s_prev, weight_sum in alternatives.iteritems():
if s_prev <= s_cur:
new_alternatives[s_cur] = ... |
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 | import sys
def main():
s = sys.stdin.read().strip()
return ('NO', 'YES')[s == s[::-1]]
print(main())
|
There are N integers, A_1, A_2, ..., A_N, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.
Find the maximum possible greatest common divisor of the N integers on the blackboard afte... | 3 | N = int(input())
A = list(map(int,input().split()))
A.sort()
w_min = A[1]
for i in range(w_min,0,-1):
count = 0
for j in A:
if j%i != 0:
count = count + 1
if count > 1:
break
if count < 2:
print(i)
break |
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.
Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He... | 3 | t=int(input())
for i in range(t):
s,a,b,c=map(int,input().split())
q=s//c
w=(q//a)*b
print(q+w)
|
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.
Help Kurt find the maximum possible product of digits among all integers from 1 to n.
Input
The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9).
Output
Print the... | 3 | def cal(k):
if (k == 0):
return 1
if (k < 10):
return k
return max(cal(k // 10) * (k % 10), cal(k // 10 - 1) * 9)
def main():
answer = input()
answer = int(answer)
print(cal(answer))
main()
|
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 | weight = int(input())
if weight%2 == 0:
if weight == 2:
print('no')
else:
print('yes')
else:
print('no')
|
There are N people numbered 1 to N. Each person wears a red hat or a blue hat.
You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.
Determine if there are more people wearing a red hat than people wearing a blue hat.
Constraints
* 1 \l... | 3 | N = int(input())
s = input()
if s.count('R')>N/2:
print('Yes')
else:
print('No') |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | for i in range(int(input())):
l=[]
n=int(input())
l=[1]
k=2
t=1
while True:
l.append(k)
t+=1
if n%sum(l)==0:
print(int(n//sum(l)))
break
k=pow(2,t)
|
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | def brackets(n,s):
i=0
op=0
clo=0
onlyclo=0
arr=[]
while i<len(s):
if op-clo==0 and s[i]==')':
onlyclo+=1
elif s[i]=='(':
op+=1
else:
clo+=1
i+=1
print(onlyclo)
for _ in range(int(input())):
n=int(input())
s... |
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it.
If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells c... | 3 | import math
for _ in range(int(input())):
n,m = map(int,input().split())
mat = []
for i in range(n):
temp = list(map(int,input().split()))
mat.append(temp)
for i in range(n):
for j in range(m):
if mat[i][j]%2 != (i+j)%2:
mat[i][j] +=1
for i ... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 1 | import sys
lines = -1
total = 0
for line in sys.stdin:
if lines == -1:
lines = int(line.rstrip())
else:
certainties = map((lambda x: int(x)), line.rstrip().split(" "))
if sum(certainties) >= 2:
total += 1
print total
|
Navi is a counter strike pro. He always say how good he is at counter strike. After being tired of Navi, his friends decided to test his skills at shooting. They put M targets on a X-Y plane, each target is denoted by (X, Y) where X is x-coordinate and Y is y-coordinate. His friends also gave him N locations on X-Y pl... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
for t in range(input()):
n, m, d = [int(x) for x in raw_input().split()]
req = m / 2
pos = []
for i in range(n):
... |
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | 3 | x, y, z = map(int, input().split())
a, b, c = map(int, input().split())
exitcounter = 0
a -= x
if a < 0:
exitcounter += 1
if not ((a+b) >= y and (a+b-y)+c >= z):
exitcounter += 1
if exitcounter:
print('NO')
else:
print('YES')
|
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.
One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by... | 1 | a, b, n = map(int,raw_input().split())
if a % b == 0:
for i in xrange(n):
a *= 10
print a
else:
count = 0
imprimir = ""
for i in xrange(0,10,1):
imprimir = str(a) + str(i)
if int(imprimir) % b == 0:
count = 1
break
if count == 0:
print "-1"
else:
imprimir = int(imprimir)
for i in xrange(n-1):... |
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 |
import math as mt
def mostFrequent(arr, n):
# Insert all elements in Hash.
Hash = dict()
for i in range(n):
if arr[i] in Hash.keys():
Hash[arr[i]] += 1
else:
Hash[arr[i]] = 1
# find the max frequency
max_count = 0
res = -1
for i in Hash:... |
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there ... | 3 | import sys
from collections import defaultdict, namedtuple
readLine = lambda : sys.stdin.readline()
readInt = lambda : int(sys.stdin.readline())
readInts = lambda : [int(x) for x in sys.stdin.readline().split(" ")]
task = namedtuple('Task', ('Vertex', 'Action'))
def dfs(adjList, visited, tin, tout):
count = 0
... |
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).
<image> Examples of convex regular polygons
Your task is to say if it is poss... | 3 | t=int(input())
for u in range(t) :
temp=list(map(int,input().rstrip().split()))
m=temp[0]
n=temp[1]
if m%n==0 :
print("Yes")
else :
print("No")
|
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 3 | for _ in range(int(input())):
n = int(input())
if n == 1:
print(-1)
else:
print('2' + ('3' * (n - 1)))
|
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least nu... | 3 | # revisiting this one
mov = {-1:'RU',1:'LD'}
s,t = input(),input()
x,y,x1,y1 = ord(s[0])-96,int(s[1]),ord(t[0])-96,int(t[1])
v,h = abs(x-x1),abs(y-y1)
if x==x1 or y==y1:
temp = (x-x1)//abs(x-x1) if x-x1 else (y-y1)//abs(y-y1) if y-y1 else 0
if temp == 0: print(0); exit()
jmp = max(abs(x-x1),abs(y-y1))
... |
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem... | 1 |
if __name__ == "__main__":
N, K = map(int, raw_input().split())
res = []
val = 1000000000
if(N/2 > K or N == 1 and K != 0):
print "-1"
elif(N == 1 and K == 0):
print "1"
else:
for i in range(0, N-3, 2):
K -= 1
res += [val, val-1... |
Little Red Riding Hood inherited an enormously large number of Candies from her father's Candy factory. Now she wants to divide these candies equally among her and her horse Hood. After the division, both Red and Hood get an equal, integral number of candies. Your task is to find out whether this is possible or not.
... | 1 | N=input()
if N%2==0 and N!=0:
print 'YES'
else:
print 'NO' |
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 | n, h = map(int, input().split())
a = list(map(int, input().split()))
width = list()
for i in a:
width.append(2 if i > h else 1)
print(sum(width)) |
The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities:
* the cities of Byteland,
* the cities of Berland,
* disputed cities.
Recent... | 3 | #!/usr/bin/env python3
M = 4 * 10**9 + 1
n = int(input().strip())
f = lambda t: (int(t[0]), t[1])
# read and add far P points at both ends
xcis = [(-M, 'P')] + [f(input().strip().split()) for _ in range(n)] + [(M, 'P')]
iPs = [i for i in range(len(xcis)) if (xcis[i][1] == 'P')]
iRs = [i for i in range(len(xcis)) if ... |
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | 3 | for case in range(int(input())):
n, m = [int(x) for x in input().split()]
scores = [int(x) for x in input().split()]
if n == 1:
print(scores[0])
else:
current = scores[0]
rest = scores[1:]
rest_sum = sum(rest)
print(min(m, current+rest_sum)) |
Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.
Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):
* There exists a non-negative integer p such that X= a_k \times (p+0.5).
Find the number of semi-co... | 3 | from fractions import gcd
lcm = lambda a, b: a * b // gcd(a, b)
N, M, *A = map(int, open(0).read().split())
Y = A[0]
for a in A[1:]:
Y = lcm(Y, a)
if Y > 2 * M:
print(0)
quit()
print(M // (Y // 2) - (M // Y) if all((Y // a) % 2 for a in A) else 0) |
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 | ans = 0
for _ in range(int(input())):
a,b,c = map(int,input().split())
if a==1:
if b|c:
ans+=1
else:
if b&c:
ans+=1
print(ans)
|
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the progr... | 1 | def hash_value(x,y):
return (x,y)
xy = 10**9
x+=xy
y+=xy
return (x*xy*xy) + y
def is_abc(a,b,c):
dab = ((a[0]-b[0])**2)+((a[1]-b[1])**2)
dbc = ((c[0]-b[0])**2)+((c[1]-b[1])**2)
dca = ((c[0]-a[0])**2)+((a[1]-c[1])**2)
ds = [dab,dbc,dca]
ds.sort()
if(ds[0]+ds[1]==ds[2]):
... |
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int,input().split()))
b = a[0]
k = 0
if a.count(b) == len(a):
print(-1)
else:
for j in range(len(a)):
if a[j] > b:
k = j
b = a[j]
q = a.count(a[k])
if q ... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 1 | n=input()
s=list()
i=0
while i<n:
s=s+[raw_input()]
if len(s[i])>10:
s[i]=s[i][0]+str(len(s[i])-2)+s[i][-1]
i=i+1
i=0
while i<n:
print s[i]
i=i+1 |
I decided to do bowling as a recreation of the class. Create a program that inputs the pitching information for each participant and outputs the grade information in descending order of score. If there is a tie, output in ascending order of student ID number. However, it is assumed that the number of participants is 3 ... | 1 | while 1:
n=input()
if n==0:break
games=[map(int,raw_input().split()) for i in range(n)]
ls=[]
for game in games:
score,thrw=0,1
for flame in range(10):
if game[thrw]==10:
score+=sum(game[thrw:thrw+3])
thrw+=1
elif game[thrw]+game[thrw+1]==10:
score+=10+game[thrw+2]
thrw+=2
else:
sc... |
On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in... | 1 | from sys import stdin, stdout
def main():
n = int(stdin.readline())
l = [[] for _ in xrange(n + 1)]
for i, x in enumerate(map(int, stdin.readline().split())):
l[x].append(i)
i = 0
r = n
ans = []
while r:
while l[i]:
ans.append(l[i].pop() + 1)
i += 1
... |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | from bisect import *
from math import *
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
arr.sort(reverse = True)
arr = [str(j) for j in arr]
ans = " ".join(arr)
print(ans) |
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times:
* mul x: multiplies n by x (where x is an arbitrary positive integer).
* sqrt: replaces n with √... | 3 | n=int(input())
ans=1
temp=n
ans=1
c=0
for i in range(2,n+1):
if(n%i==0):
ans*=i
while(n%i==0):
n/=i
ans2=ans
while(ans%temp>0):
ans*=ans
c+=1
if ans>temp:
c+=1
print(ans2,c)
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 1 | print('+'.join(sorted(raw_input().split('+'))));#........................................
|
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... | 3 | c=0,0,0
for i in [0]*int(input()):
c=[*map(sum, zip(c,map(int,input().split())))]
print("YNEOS"[c!=[0,0,0]::2]) |
You are given an integer N.
For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.
For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.
Find the minimum value of F... | 3 | n=int(input())
import math
for i in range (int(math.sqrt(n)),0,-1):
if n%i==0:
print(max(len(str(i)),len(str(n//i))))
quit()
|
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | __author__ = 'Utena'
s=input()
if "H" in s or "Q"in s or "9"in s:
print('YES')
else:print("NO") |
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec... | 3 | for _ in range(int(input())):
a,b=map(int,input().split())
c,d=map(int,input().split())
f=0
if a==c and b+d==a:
f=1
elif a==d and b+c==a:
f=1
elif b==c and a+d==b:
f=1
elif b==d and a+c==b:
f=1
print(["No","Yes"][f==1]) |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | line = input()
n = int(line.split()[0])
t = int(line.split()[1])
line1 = [int(i) for i in input().split()]
line2 = list(range(1,n+1))
a = 1
b = 1
for i in range(n):
a += line1[b-1]
b = line2[a-1]
if a < t:
continue
if a == t:
print('YES')
break
if a > t:
print('NO')
... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | s = input()
for i in s.split('WUB'):
print(i , end=' ') |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 1 | n,t = map(int,raw_input().strip().split(" "))
a = map(int,raw_input().strip().split(" "))
t-=1
f = 0
i = 0
while i<n:
if i>t:
break
if i+a[i]==t or i==t:
f=1
print "YES"
break
else:
i+=a[i]
if f==0:
print "NO"
|
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | q = int(input())
while(q>0):
q=q-1
count=0
s= int(input())
if(s>10 or s==1):
while(s>10):
count=count+1
s = s//10
answer = (s-1)*10 +((count+1)*(count+2)/2)
else:
answer = (s-1)*10 + 1
print(int(answer)) |
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... | 3 | __author__ = 'Admin'
n = int(input())
m = list(map(int, input().split()))
t = 1
ans = 1
while m[0] == 0:
if len(m) == 1 and m[0] == 0:
ans = 0
break
else:
m.pop(0)
while m[len(m) - 1] == 0:
m.pop(len(m) - 1)
if len(m) == 0:
ans = 0
break
for i in range(len(m)):
... |
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n... | 3 | """
Code of Ayush Tiwari
Codeforces: servermonk
Codechef: ayush572000
"""
import sys
input = sys.stdin.buffer.readline
def solution():
for _ in range(int(input())):
# This is the main code
n=int(input())
l=list(map(int,input().split()))
l.sort()
a=[]
for i ... |
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then... | 1 | n=input()
d={}
for i in range(0,n):
s=str(raw_input())
d[s]=i
l=[]
for i in d:
l.append((d[i],i))
l.sort(reverse=True)
for i in l:
print i[1] |
This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to th... | 3 | from collections import defaultdict as dd, deque
import sys
n = int(input())
A = [int(x) for x in input().split()]
C = dd(int)
CC = dd(int)
for a in A:
C[a] += 1
for c in C:
CC[C[c]] += 1
for a in reversed(A):
if len(CC) == 2:
aa,bb = sorted(list(CC.items()))
k1,v1 = aa
k2,v2 = ... |
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:
* a < b < c;
* a divides b, b divides c.
Naturally, Xenia wants... | 3 | S = sorted
M = lambda : map(int,input().split())
n = int(input())
x = list(M())
a, b, c, d, e = x.count(1), x.count(2), x.count(3), x.count(4), x.count(6)
if d>b or d+e!=a or b+c!=a or a*3!=n:
print(-1)
else:
for i in range(a):
print(1, 2 if i < b else 3, 4 if i < d else 6)
|
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | word = raw_input()
word = word.lower()
for vowel in ['a', 'o', 'i', 'u', 'e', 'y']:
word = word.translate(None,vowel)
answer = ""
for letter in word:
answer += "."
answer += letter
print answer |
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?
Note, that you can't keep bags for yourself or thro... | 3 | a=list(map(int,input().split()))
a.sort()
if a[0]+a[3]==a[1]+a[2] or a[3]==a[0]+a[1]+a[2]:
print("YES")
else:
print("NO")
|
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | for i in range(int(input())):
n,a,b,c,d = map(int,input().split())
if c + d < (a - b) * n or (a + b) * n < c - d:
print("NO")
else:
print("YES") |
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that c... | 1 | from sys import stdin,stdout,setrecursionlimit,maxint,exit
#setrecursionlimit(2*10**5)
def listInput():
return map(long,stdin.readline().split())
def printBS(li):
if not li: return
for i in xrange(len(li)-1):
stdout.write("%d "%li[i])
stdout.write("%d\n"%li[-1])
def sin():
return stdin.readline().rstrip()
n,s=li... |
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to... | 3 | s = input()
n = len(s)
d = [[0]*2 for _ in range(0,n+1)]
if((ord(s[0]) >= ord('A')) and (ord(s[0]) <= ord('Z'))):
d[0][0] = 0
d[0][1] = 1
else:
d[0][0] = 1
d[0][1] = 0
for i in range(1,n):
if((ord(s[i]) >= ord('A')) and (ord(s[i]) <= ord('Z'))):
d[i][0] = d[i-1][0]
d[i][1] = mi... |
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 1 | n = int(raw_input())
police = 0
ans = 0
for event in map(int, raw_input().split()):
if event >= 0:
police += event
else:
if police == 0:
ans += 1
else:
police -= 1
print ans
|
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 ≤ i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated).
For example, if you have the ar... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
if a[-1]>a[0]:
print("YES")
else:
print("NO") |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = [int(x) for x in input().split()]
# print(a)
d = set()
for i, x in enumerate(a):
if x == -1:
if i > 0:
d.add(a[i-1])
if i < len(a) - 1:
d.add(a[i+1])
# print(list(d))
d =... |
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 | t=int(input())
for _ in range(t):
a,b=map(int,input().split())
print ((abs(a-b)//10) if abs(a-b)%10==0 else abs(a-b)//10+1) |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | n, k = map(int, input().split())
sp = list(map(int, input().split()))
sp.sort()
if n / 3 < 1:
print(0)
else:
s = 0
i = 0
while i < n-2:
if max(sp[i]+k, sp[i+1]+k, sp[i+2]+k) <= 5:
s += 1
i += 3
else:
i += 1
print(s) |
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays... | 3 | from bisect import bisect_left as pos
n, m = map(int, input().split())
track = [0]
for i in range(1, n + 1):
c, t = map(int, input().split())
track.append(c * t + track[i - 1])
moment = map(int, input().split())
ans = []
for i in moment:
ans.append(pos(track, i))
print(*ans, sep='\n')
|
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.
Constra... | 3 | S = str(input())
ans = S[0:3]
print(ans) |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high... | 3 | t = int(input())
for case in range(1,t+1):
n = int(input())
a = [int(x) for x in input().split()]
assert len(a) == n
caps = []
for i, x in enumerate(a):
if x == -1:
if i > 0 and a[i-1] != -1:
caps.append(a[i-1])
if i < n-1 and a[i+1] != -1:
... |
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 1 | a=map(int,raw_input().split())
cnt=0
if a[1]!=a[0]: cnt+=1
if a[2]!=a[1] and a[2]!=a[0]: cnt+=1
if a[3]!=a[1] and a[3]!=a[0] and a[3]!=a[2]: cnt+=1
print 3-cnt |
Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge.
n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridg... | 3 | n = int(input())
for nn in range(n):
val = [int(x) for x in input().split(" ")]
n,m = val[0], val[1]
chains = [int(x) for x in input().split(" ")]
failed = False
if n == 2:
failed = True
if m < n:
failed = True
if failed:
print("-1")
if not failed:
fi... |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | # For taking integer inputs.
import math
def inp():
return(int(input()))
# For taking List inputs.
def inlist():
return(list(map(int, input().split())))
# For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings a... |
The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100.... | 3 | n, m = map(int, input().split())
D = dict()
arr = list(map(int, input().split()))
for el in arr:
if el in D.keys():
D[el] += 1
else:
D[el] = 1
maxx = -1
for key in D.keys():
if D[key] > maxx:
maxx = D[key]
#print(maxx)
a = maxx // m
if maxx % m > 0:
a += 1
summ = a * m
ans = 0
#p... |
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.
There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st... | 3 | n = int(input())
res = list()
for i in range(n):
a = list(input().split(' '))
a = list(int(x) for x in a)
cur_sum = 0
for item in a:
cur_sum += item
res.append((cur_sum, i+1))
res = sorted(sorted(res, key = lambda x: x[1]), key = lambda x: x[0], reverse=True)
for i in range(n):
if res[i]... |
G, a college student living in a certain sky city, has a hornworm, Imotaro. He disciplined Imotaro to eat all the food in order with the shortest number of steps. You, his friend, decided to write a program because he asked me to find out if Imotaro was really disciplined.
Input
H W N
area
Input is given in H + ... | 3 | from collections import deque
def main():
h, w, n = map(int, input().split())
mp = [list("#" * (w + 2))] + [list("#" + input() + "#") for _ in range(h)] + [list("#") * (w + 2)]
init_body = [None] * 4
for y in range(1, h + 1):
for x in range(1, w + 1):
if mp[y][x] == "S":
... |
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 | d = {'Tetrahedron':4,'Cube':6,'Octahedron':8,'Dodecahedron':12,'Icosahedron':20}
e = 0
for _ in range(int(input())):
e+=d[input()]
print(e)
|
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 ... | 3 | n=int(input())
a=input().split()
b=input().split()
x=a[1:]+b[1:]
level=set(x)
num=0
for i in range(1,n+1):
if str(i) in level:
num+=1
if num==n:
print("I become the guy.")
else:
print("Oh, my keyboard!") |
Let's call left cyclic shift of some string t_1 t_2 t_3 ... t_{n - 1} t_n as string t_2 t_3 ... t_{n - 1} t_n t_1.
Analogically, let's call right cyclic shift of string t as string t_n t_1 t_2 t_3 ... t_{n - 1}.
Let's say string t is good if its left cyclic shift is equal to its right cyclic shift.
You are given str... | 3 | import math
import sys
import bisect
#input=sys.stdin.readline
t=int(input())
#t=1
for _ in range(t):
#n,k,z=map(int,input().split())
#l=list(map(int,input().split()))
s=input()
d={}
for i in range(10):
d[i]=[]
for i in range(len(s)):
d[int(s[i])].append(i)
maxi=0
for i i... |
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i.
Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?
* The i-th (1 \leq i \leq M) restriction... | 3 | import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
n = int(input())
graph = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append((b, i))
graph[b].append((a, i))
def dfs(v, v_p, target):
if v == target:
return True... |
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an... | 3 | def solve(n, cups, medals):
cupsum=sum(cups)
medalsum=sum(medals)
cupneed=int(cupsum/5)
medalneed=int(medalsum/10)
if cupsum%5 !=0:
cupneed+=1
if medalsum%10!=0:
medalneed+=1
if cupneed+medalneed<=n:
return "YES"
else:
return "NO"
cups = map(int, i... |
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 3 | a = int(input())
s = input().split()
for i in range(a):
s[i]=int(s[i])
mat=[]
for i in range(a):
mat.append(0)
hooks=1
res=0
point=9999
while True:
if point>max(s):
res+=hooks
mat[s.index(max(s))]=res
point=max(s)
s[s.index(max(s))]=-1
hooks=1
else:
hooks+... |
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 | s=input()
if len(s)<7:
print('NO')
else:
flag=0
for i in range(len(s)-6):
if s[i]=='0':
if s[i+1:i+7]=='000000':
flag=1
break
elif s[i]=='1':
if s[i+1:i+7]=='111111':
flag=1
break
if flag==0:
... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 1 | import re
s = raw_input()
print 'YES' if re.search(r'.*h.*e.*l.*l.*o.*', s) else 'NO' |
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 | from sys import stdin,stdout
LI=lambda:list(map(int,input().split()))
MAP=lambda:map(int,input().split())
IN=lambda:int(input())
S=lambda:input()
import math
def p(a):print(" ".join(list(map(str,a))))
from collections import Counter
def solve():
s=S()
o=s.count('0')
one=s.count('1')
m=min(o,one)
if... |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 1 | t = int(raw_input())
for _ in xrange(t):
n = int(raw_input())
m = map(int, raw_input().split())
s = sum(m)
l = min(m)
r = max(m)
while l <= r:
mid = (l+r)/2
if mid * n == s:
l = mid
break
if mid * n < s:
l = mid+1
else:
... |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | t=int(input())
for _ in range(t):
n=int(input())
x=str(input())
b=[]
bc=0
r=[]
rc=0
if n==1:
if int(x)%2==0:
print(2)
else:
print(1)
else:
for i in range(1,n+1):
if i%2==0:
b.append(int(x[i-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 | for _ in range(int(input())):
n,m=map(int,input().split())
for i in range(0,n-1):
for j in range(0,m):
if (i+j)%2 == 0:
print("B",end="")
else:
print("W",end="")
print()
if (n%2 != 0 )and (m%2 != 0) :
for i in range(0,m... |
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers c... | 3 |
k = int(input())
n = list(map(int, list(input())))
n.sort()
sum_ = sum(n)
for cnt, elem in enumerate(n):
if sum_ >= k:
print(cnt)
break
sum_ += 9 - elem
else:
print(len(n))
"""
k = int(input())
n = list(input())
sum = 0
for i in range (len(n)):
n[i] = int(n[i])
sum += n[i]
... |
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the b... | 1 | import sys
n, c = map(int,sys.stdin.readline().split())
arr = map(int,sys.stdin.readline().split())
i = 0
profit = [0]
while(i < n-1):
profit.append(arr[i]-arr[i+1]-c)
i += 1
print max(profit)
|
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is on... | 3 | ###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ... |
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.
The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr... | 3 | s=input()
Single=[0]*26
Double=[[0]*26 for _ in range(26)]
for i in range(len(s)):
c=ord(s[i])-ord('a')
for j in range(26):
Double[j][c]+=Single[j]
Single[c]+=1
res=0
for x in Single:
res=max(res,x)
for x in Double:
for y in x:
res=max(res,y)
print(res)
|
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 | word=input()
u=word.upper()
t=word.title()
if word==u:
print(word.swapcase())
elif word.swapcase()==t:
print(word.swapcase())
else:
print(word) |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | def main():
n,k = map(int,input().split())
if 2 <= n <= pow(10,9) and 1 <= k <= 50:
for i in range(k):
if n % 10 != 0: n -= 1
else: n /= 10
print(int(n))
main() |
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names... | 1 | N, S = raw_input().split()
N, S = int(N), int(S)
index = 0
names_index = [-1] * N
G = raw_input().split()
#print G
for i in range(len(G)):
#print i, G[i], names_index
begin_g = i
end_g = begin_g + S
if G[i] == 'YES':
#print begin_g, end_g
for i in range(begin_g, end_g):
if... |
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire strin... | 3 | n, x, y = [int(i) for i in input().split()]
v = 1
s = list(input())
cnt = 0
for digit in s:
if digit == '0' and v == 1:
cnt += 1
v = 0
if digit == '1':
v = 1
if cnt == 0:
print(0)
exit(0)
ans = min(cnt * y, (cnt - 1) * x + y)
print(ans) |
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | 3 | '''
def main():
from sys import stdin,stdout
if __name__=='__main__':
main()
'''
# Journey to moon
'''
def main():
from sys import stdin,stdout
import collections
N,I =map(int,stdin.readline().split())
visited=list(0 for x in range(N))
G=collections.defaultdict(list)
groups=[0]
for _ in range(I):
a,b=map(int... |
— Hey folks, how do you like this problem?
— That'll do it.
BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows:
1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j.
2. All candies from pile i are... | 3 | def main():
n, k = map(int, input().split())
a = list(sorted(map(int, input().split())))
ans = 0
small = a[0]
for i in range(1, n):
ans += ((k-a[i])//small)
print(ans)
# main()
for _ in range(int(input())):
main() |
In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.
The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0).
Aoki, an explorer, conducted a survey to identify the center ... | 3 | n = int(input())
list1 = [list(map(int,input().split())) for i in range(n)]
#高さは一意に求まるので、どれをとっても良い、
#わけではないh=0のとき一意に求まらない。
for i in list1:
if i[2] != 0:
a,b,c = i
break
#highについてのループ
for y in range(101):
for x in range(101):
h = c + abs(a-x) + abs(b-y) #頂点の座標
if all(h_ == max(h-abs(x-i)-abs(y-j),0... |
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | 3 | s=list(input())
n=len(s)
if '0' in s:
s.remove('0')
print(''.join(s))
else:
s.remove('1')
print(''.join(s)) |
Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.
We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integer... | 1 | n=int(raw_input())
try:
s=[]
rs=[]
ff=0
for x in raw_input().split():
# print x,s,rs
if ff==1 and len(s)==0:
raise Exception("shit")
ff=1
if x=="pair":
rs.append("pair<")
s.append(">")
s.append(",")
else:
... |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | def check(bruh):
tmp = 0
for i in range(0,len(bruh)):
if bra[i] == ')':
tmp += -1
elif bra[i] == '(':
tmp += 1
if tmp < 0:
return 0
return 1
t = int(input())
for _ in range(0,t):
# n = bra 길이
n = int(input())
bra = input()
result = ... |
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
... | 3 | n = int(input())
c = [input() for _ in range(n)]
colors = ["purple", "green", "blue", "orange", "red", "yellow"]
for ci in c:
colors.remove(ci)
print(6 - n)
for color in colors:
if color == "purple":
print("Power")
elif color == "green":
print("Time")
elif color == "blue":
pri... |
A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ -th flag corresponds to 1 (ON) or 0 (OFF). The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1.
Given a sequence of bits with 6... | 3 | import sys
class BitFlag:
ALL_ON = 0xffffffffffffffff
ALL_OFF = 0x0000000000000000
def __init__(self):
self.FLAGS = self.ALL_OFF
self.Masks = [1 << i for i in range(64)]
def _test(self, i):
return self.FLAGS & self.Masks[i] != 0b00
def _set(self, i):
self.FLAGS |... |
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:
* the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;
* the lower half of matrix c (rows with n... | 1 | get = lambda: map(int, raw_input().split())
n, m = get()
mat = [get() for i in range(n)]
while (n % 2) == 0:
if any(mat[n-1-i][j] != mat[i][j] for i in range(n/2) for j in range(m)):
break
mat = mat[:n/2]
n /= 2
print len(mat) |
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())
k = [int(i) for i in input().split()]
ans = []
for i in range(n):
m = [int(j) for j in input().split()]
ans.append(sum(m)*5+k[i]*15)
print(min(ans))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.