problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 3 | n = int(input())
q = list(map(int, input().split()))
ans = [0 for i in range(n)]
ans[0] = 1
for i in range(1, n):
ans[i] = ans[i - 1] + q[i - 1]
t = 1 - min(ans)
b = [i for i in range(1, n + 1)]
x = set(b)
ann = []
for i in ans:
ann.append(i + t)
x.discard(i + t)
if len(x):
print(-1)
else:
print(*an... |
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,... | 3 | def solve():
pass
from collections import Counter
n = int(input())
stairs = [int(x) for x in input().split(' ')]
total = 0
t = []
for s in range(n):
if stairs[s] == 1:
if total > 0:
t.append(stairs[s-1])
total += 1
if s == n-1:
t.append(stairs[s])
print(total)
print(" ".join([str(x) for x in t]))
|
We have N balls. The i-th ball has an integer A_i written on it.
For each k=1, 2, ..., N, solve the following problem and print the answer.
* Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.
Constraint... | 3 | from collections import Counter
N = int(input())
A = list(map(int,input().split()))
cnt = Counter(A)
s = 0
for v in cnt.values():
s += v*(v-1)//2
for a in A:
print(s - (cnt[a]-1))
|
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc... | 3 | import math
t=int(input())
for i in range(t):
n=int(input())
if(n%2==0):
print(n//2,n//2)
elif(n%2!=0):
flag=0
for i in range(2,int(math.sqrt(n))+1,1):
if(n%i==0):
flag=1
break
if(flag==0):
print(1,n-1)
elif(flag... |
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 __ in range(int(input())):
n,m=list(map(int,input().split()))
l=list(map(int,input().split()))
print(min(sum(l),m)) |
This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequenc... | 1 | import heapq
e=raw_input()
c=0
k=0
l=[0]*len(e)
heap=[]
for i in xrange(len(e)):
if e[i]=="(":
l[i]="("
k+=1
elif e[i]==")":
l[i]=")"
k-=1
else:
a,b=map(int,raw_input().split())
c+=b
heapq.heappush(heap,(a-b,i))
l[i]=")"
... |
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of... | 1 | n = int(raw_input())
fila = [-1] * n
frente = set([])
tras = set([])
relacoes = {}
for i in xrange(n):
aluno1, aluno3 = map(int, raw_input().split())
frente.add(aluno1)
tras.add(aluno3)
relacoes[aluno1] = aluno3
primeiro = frente.difference(tras).pop()
segundo = relacoes[0]
saida = ""
for i in xrange(n):
... |
You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l β€ x β€ r.
Input
The first l... | 3 | n = int(input())
for i in range(n):
l, r, d = map(int, input().split())
if d < l or d > r:
print(d)
else:
print(2 * d + (r - d) // d * d)
|
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | 3 | for i in range(int(input())):
nab = list(map(int, input().split()))
alpha = "abcdefghijklmnopqrstuvwxyz"
s = ""
res = ""
n = nab[0]
a = nab[1]
b = nab[2]
for i in range(a // b + 1):
s += alpha[:b]
s = s[:a]
for i in range(n // a + 1):
res += s
print(res[:n])
... |
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of cust... | 3 | N=int(input())
A=list(map(int,input().split()))
L={}
for i in range(-10,11):
L[i]=0
for i in range(N):
L[A[i]]+=1
ans=0
for i in range(1,11):
ans+=L[i]*L[-i]
ans+=(L[0])*(L[0]-1)//2
print(ans)
|
There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?
Constraints
* 1β¦Nβ¦100
Input
The input is given from Standard Inpu... | 1 | a=input()
print a*(a+1)//2 |
Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms:
* Everyone must gift as many coins as others.
* All coins given to Ivan must be different.
* Not l... | 3 | def happy_birthday(n, m, k, l):
result = (l + k) // m
if result * m < l + k:
result += 1
if result * m > n:
return -1
return result
N, M, K, L = [int(i) for i in input().split()]
print(happy_birthday(N, M, K, L))
|
Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:
\begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*}
Constraints
... | 3 | N = int(input())
fib = [1,1]
for i in range(2, N + 1):
fib.append(fib[i - 1] + fib[i - 2])
print(fib[N])
|
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | 3 | n = int(input())
arr = input().split()
arr = [ int(x) for x in arr ]
lengths = [1]
for i in range(1,n):
if arr[i] > arr[i-1]:
pass
else:
lengths.append(i+1)
lengths.append(n+1)
dis = []
for i in range(1,len(lengths)):
m = lengths[i] - lengths[i-1]
dis.append(m)
print (max(dis))
... |
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 3 | n, k = [int(_) for _ in input().split()]
shit = list(input())
if n == 1 and k == 1:
print(0)
elif n == 1 and k == 0:
print(shit[0])
else:
i = 0
while(k > 0 and i < n):
if i == 0:
if shit[i] != '1':
k -= 1
shit[i] = '1'
else:
if shit... |
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation... | 1 | M = 1000000007
a = raw_input()
b = raw_input()
k = input()
r = [i for i in xrange(0,len(a)) if a[i:] + a[:i] == b]
x,y = 1, 0
l = len(a)
for _ in xrange(k):
x, y = y*(l-1)%M, (x+y*(l-2))%M
if 0 in r: print (x + y * (len(r) - 1))%M
else: print y * len(r) % M
|
You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.
You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monste... | 3 | import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
for _ in range(int(input())):
n = int(input())
m = [list(map(int, input().split())) for i in range(n)]
ans = 0
for i in range(n):
t = m[i][0] - m[i-1][1]
if t > 0:
ans += t
m[i][0] = m[i-1][1]
MIN = min(m)[0]
sys.stdout... |
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t... | 3 | import collections
n = int(input())
s = input()
cnt = collections.Counter(s)
one_cnt = zero_cnt = 0
if 'z' in cnt:
zero_cnt = cnt['z']
if 'n' in cnt:
one_cnt = cnt['n']
print(' '.join((list('1' * one_cnt + '0' * zero_cnt))))
|
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.
The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t... | 3 | n=int(input())
a,b,cur=[],'_',1
for c in input().split():
if b==c:
cur+=1
else:
if b!='_':
a.append(cur)
b,cur=c,1
a.append(cur)
ans=0
for i in range(len(a)-1):
ans=max(ans,min(a[i],a[i+1]))
print(ans*2)
|
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | from sys import stdin, stdout
t=int(stdin.readline())
for _ in range(t):
n,s=stdin.readline().split()
s=int(s)
sum=0
movs=0
for i in range(len(n)):
sum+=int(n[i])
if sum>=s:
p=int(n[min(i+1,len(n)-1):])
if sum!=s or (p!=0 and i!=len(n)-1):
movs... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | a=list(map(int,input().split()))
s=input()
p=0
for i in range(len(s)):
p+=a[int(s[i])-1]
print(p) |
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A β€ B β€ C β€ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A β€ x β€ B β€ y β€ C β€ z β€ D holds?
Yuri is preparing problems for a new contest now, so he is v... | 1 | a,b,c,d = map(int, raw_input().split())
# import random
# l = [random.randint(1,500000) for i in range(4)]
# l.sort()
# a = l[0]; b = l[1]; c = l[2]; d = l[3]
# # a = 39530; b = 76603; c = 120561; d = 434466
u = (b - a + 1)
v = (c - b + 1)
w = (d - c + 1)
mi = min(u-1,v-1)
ma = max(u-1,v-1)
numways = 0
running_remov... |
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver... | 1 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright Β© 2015 vivek9ru <vivek9ru@Vivek9RU>
#
# Distributed under terms of the MIT license.
from math import acos,asin,atan,sqrt,pi,sin,cos,tan,ceil,floor
import re
from operator import itemgetter as ig
n=input()
lis=map(int,raw_input().split())
ac... |
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week.
Write a program which computes the amount of the debt in n weeks.
Input
An integer n (0 β€ n β€ 100) is g... | 3 | import math
N=int(input())
a=100000
for i in range(N):
b=a/1000
a=math.ceil(b*1.05)
a=a*1000
print(a)
|
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).
Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of... | 3 | from sys import stdin
def main():
input()
cc, nc, c, d = [0] * 31, [0] * 31, 1, {}
for i in range(31):
d[str(c)], cc[i], c = i, c, c * 2
for i in map(d.get, input().split()):
nc[i] += 1
ncc = tuple((n, c) for n, c in zip(nc, cc) if n)[::-1]
l, cache = stdin.read().splitlines(),... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | a = [int(x) for x in input()[::2]]
a.sort()
s = '+'.join([str(x) for x in a])
print(s)
|
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 | for iih in range(int(input())):
n = int(input())
s = input()
l = ""
for i in range(n):
l += s[2*i]
print(l) |
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 | p,q,r=map(int,input().split())
print(-p//r*(-q//r)) |
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 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 03:02:26 2020
@author: Kashem Pagla
"""
n=int(input())
a=list(map(int, input().strip().split()))[:n]
j=0
j=100*(sum(a)/(100*n))
print(round(j,12)) |
Write a program which reads two integers a and b, and calculates the following values:
* a Γ· b: d (in integer)
* remainder of a Γ· b: r (in integer)
* a Γ· b: f (in real number)
Constraints
* 1 β€ a, b β€ 109
Input
Two integers a and b are given in a line.
Output
Print d, r and f separated by a space in a line. For ... | 3 | a,b = map(int,input().split())
print(int(a//b),int(a%b),format(a/b,'.5f'))
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | n = int(input())
n += 1
while len(str(n)) != len(set(str(n))):
n += 1
print(n)
|
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n... | 3 | n=int(input())
for i in range(n):
flag=0
a=input()
b=list(map(ord,a))
b.sort()
for j in range(len(b)-1):
if b[j]+1==b[j+1]:
continue
else:
flag=1
break
if flag==0:
print('Yes')
else:
print('No') |
There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | 3 | s=input()
ans=753
for i in range(len(s)-2):
ans=min(abs(int(s[i:i+3])-753),ans)
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.... | 1 | n=input()
a=[]
out=0
for i in range(0,n):
a.append(list(map(int,raw_input().split())))
#print a
for j in a:
if j.count(1)>=2:
out=out+1
print out
|
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x.
P... | 3 | import sys
import os
import math
from io import BytesIO, IOBase
from collections import defaultdict,Counter,deque
import heapq
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
sel... |
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 | t = int(input())
for _ in range(t):
s = list(input())
count =0
mx = 0
for c in s:
if(c=='L'):
count+=1
else:
if(count>mx):
mx = count
count=0
#print(c,count,end=' ')
if(count>mx):
mx = count
pr... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | n =input()
l = list(n)
a = []
for i in range(len(l)):
if l[i] != '+':
a.append(int(l[i]))
a.sort()
for i in range(len(a)):
if len(a) > 1 and i != len(a)-1:
print("{}+".format(a[i]),end='')
elif len(a) > 1:
print(a[i])
else:
print(a[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 | R=lambda:map(int,raw_input().split(' '))
n = input()
a = R()
b = R()
s = set(a[1:] + b[1:])
if len(s) == n:
print 'I become the guy.'
else:
print 'Oh, my keyboard!' |
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order... | 3 | I=lambda:map(int,input().split())
n,a=I()
x=sorted(I())
s=abs
print(0if n==1else min(min(s(a-x[1]),s(a-x[-1]))+x[-1]-x[1],min(s(a-x[-2]),s(a-x[0]))+x[-2]-x[0]))
# Made By Mostafa_Khaled |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | from math import ceil
int(input())
text = input()
taxi = 0
ones = text.count("1")
twos = text.count("2")
threes = text.count("3")
fours = text.count("4")
taxi += fours
taxi += threes
if ones >= threes:
ones -= threes
else:
ones = 0
taxi += twos//2
twos = twos % 2
taxi += twos
if twos != 0:
if ones >=... |
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 | def main():
w = int(input())
if(isEven(w) and w != 2):
print("YES")
else:
print("NO")
def isEven(x):
return (x%2 == 0)
if __name__ == '__main__':
main()
|
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 1 | [n,k]=map(int,raw_input().split())
tem=map(int,raw_input().split())
op=[]
for item in tem:
if item >=tem[k-1]and item>0:
op.append(str(item))
print len(op) |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
You have a sequence of integers a1, a2, ..., an. In on... | 1 | n = input()
a = sorted(map(int,raw_input().split()))
print sum([abs(a[i] - (i+1)) for i in xrange(n)]) |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | n=int(input())
for i in range(n):
s=input()
if len(s)>10:
l=len(s)-2
out=s[0]+str(l)+s[len(s)-1]
print(out)
else:
print(s) |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s=input()
n=s.count('4')+s.count('7')
if n==4 or n==7:
print('YES')
else:
print('NO') |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | y,b,r=map(int,input().split())
l=1
m=2
n=3
while(l!=y and m!=b and n!=r):
l+=1
m+=1
n+=1
print("%d"%(l+m+n)) |
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!
When building the graph, he needs four conditions to... | 1 | from math import sqrt
N = input()
arr = [True] * (1011)
arr[0] = False
arr[1] = False
for i in range(2,int(sqrt(1010)+1)) :
if arr[i] :
j = i * i
while j < 1010 :
arr[j] = False
j += i
extra = 0
while not arr[N+extra] : extra += 1
edges = [(n,(n+1)%N) for n in range(N)]
notused = set(range... |
Problem statement
JOI decided to start a new social game from tomorrow.
In this social game, you can log in up to once a day, and you will get A coins each time you log in.
Also, if you log in for 7 consecutive days from Monday to Sunday, you will get an additional B coins each time.
No other coins will be given.
... | 3 | A, B, C = map(int,input().split())
x = 0
c = 0
while c < C:
x = x + 1
if x % 7 != 0:
c = c + A
elif x % 7 == 0:
c = c + A + B
print(x)
|
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | a,b = input().split()
result = int(a)
for x in range(int(b)):
result = result/10 if(result%10==0) else result-1
print(int(result)) |
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro... | 3 | import math
t= int(input())
for i in range(t):
n= int(input())
a= list(map(int,input().split()))
while(False):
break
maxel= max(a)
ans=list()
for j in range(n):
if(maxel==1):
break
maxgcd= math.gcd(maxel,a[0])
ind=0
for k in range(n):
... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 |
def foo(n):
c=0
while(n!=1):
ok=0
if(n%5==0):
n=(4*n)//5
ok=1
elif(n%3==0):
n=(2*n)//3
ok=1
elif(n%2==0):
n=n//2
ok=1
if(ok==0):
return -1
else:
c=c+1
return c
t=int(input())
for i in range(0,t):
n=int(input())
#c=0
ok=0
if(n==1):
print(0)
else:
print(foo(n)) |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | def steps(n):
steps=0
while(n>0):
if(n>=5):
steps+=1
n-=5
else:
steps+=1
n-=n
return steps
n = int(input())
print(steps(n)) |
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.
There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one... | 1 | import sys
n, m = map(int, raw_input().split())
for _ in xrange(m):
ids = set(map(int, raw_input().split())[1:])
ok = False
for x in ids:
if (-x) in ids:
ok = True
break
if not ok:
print 'YES'
sys.exit(0)
print 'NO'
|
We have a rectangular parallelepiped of size AΓBΓC, built with blocks of size 1Γ1Γ1. Snuke will paint each of the AΓBΓC blocks either red or blue, so that:
* There is at least one red block and at least one blue block.
* The union of all red blocks forms a rectangular parallelepiped.
* The union of all blue blocks for... | 3 | a,b,c=map(int,input().split())
print(min(a*b*(c-(c//2)*2),a*c*(b-(b//2)*2),c*b*(a-(a//2)*2)))
|
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.
Therefore, Sasha decided ... | 3 | n=int(input())
a=list(map(int,input().split()))
l=[0,a[0]]
for i in range(1,n):
l.append(l[-1]^a[i])
d,ans={},0
for i in range(n+1):
if l[i] not in d:
d[l[i]]=[0,0]
d[l[i]][i%2]=1
else:
ans+=d[l[i]][i%2]
d[l[i]][i%2]+=1
print(ans) |
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 β€ q β€ 1000
* -10000 β€ xpi, ypi β€ 10000
* p0 β p1 and p2 β p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth... | 3 | import math
class Vector:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,other):
return Vector(self.x+other.x,self.y+other.y)
def __sub__(self,other):
return Vector(self.x-other.x,self.y-other.y)
def __mul__(self,scalar):
return... |
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each ot... | 3 | a = list(map(int, input().split()))
d, i = 1, 0
while a[i] >= d:
a[i] -= d
i = (i + 1) % 2
d += 1
if i == 0:
print("Vladik")
else:
print("Valera")
|
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K poi... | 1 | import collections
n,s,m = map(int, raw_input().split(' '))
cc = collections.Counter()
cumul = 0
for _ in range(m):
cc[int(raw_input()) - 1] += 1
cumul += 1
for u in range(n):
q = s
q += cc[u] - cumul
if q > 0:
print 'Yes'
else:
print 'No'
|
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | 1 | l,r = map(int, raw_input().strip().split(' '))
if l == r:
print r
else:
print 2 |
You are given a collection of words, say as in a dictionary.
You can represent it in the following compressed form:
The first word will be followed by a sequence of pair of a integer (x) and a word.
The number in the pair is the position till which the previous word's characters are included in the new word
and ... | 1 | N = int(raw_input())
dictionary = []
dictionary.append([0,str(raw_input())])
for _ in range(N-1):
(num,tail) = str(raw_input()).split()
dictionary.append([int(num),tail])
reqd = dictionary[N-1][0]
tail = dictionary[N-1][1]
i = N-2
while (reqd > 0):
num = dictionary[i][0]
if reqd > num:
tail = dictionary[i][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... | 3 | a=int(input())
list1=[]
for i in range(0,a):
b=str(input())
c=len(b)
if(c<=10):
print(b)
else:
x=str(c-2)
print(b[0]+x+b[-1])
|
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel... | 1 | n=int(raw_input())
if n == 0:
print 1
elif n == 1:
print 7
else:
print 3*n*n + 3*n + 1
|
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ... | 3 | def main():
def solve():
n = int(input())
aa = list(map(int, input().split()))
min = 1000000
bad = 0
for a in reversed(aa):
if a < min:
min = a
elif a > min:
bad += 1
print(bad)
q = int(input())
for _ i... |
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.
The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that... | 3 | import math
for w in range(int(input())):
x=list(map(int,input().split()))
a=list(map(int,input().split()))
a.sort(reverse=True)
if x[0]==1:
if a[0]>=x[1]:
print("1")
else:
print("0")
else:
cont=0
soma=0
if a[0]>=x[1]:
cont+... |
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.
He can perform the following operation any number of times:
* Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.
He would like to perform this operation between 0 and 2N times (inclusive) so ... | 3 | N = int(input())
A = list(map(int, input().split()))
maxA = max(A)
minA = min(A)
argmax = -1
argmin = -1
print(2*N - 1)
for i in range(N):
if maxA == A[i]:
argmax = i
if minA == A[i]:
argmin = i
if abs(maxA) >= abs(minA):
for i in range(N):
print(argmax+1, i+1)
for i in range(N-1):
print(i+1,... |
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i β€ x holds for each i (1 β€ i β€ n).
Input
The first line of input contains one integer t (1 β€ t β€ 100) β the number of test cases. t blocks follow, each d... | 1 | def solve(n, x, arr, brr):
c = []
for i in range(n):
c.append(x - arr[i])
c.sort()
brr.sort()
for i in range(n):
if brr[i] > c[i]:
return "No"
return "Yes"
for _ in range(int(input())-1):
n,x=map(int,raw_input().split())
arr=list(map(int,raw_input().split())... |
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown be... | 3 | ##print('ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΡΠΈΡΠ»ΠΎ Π»ΠΈΠ½ΠΈΠΉ ΠΏΠΎ Π³ΠΎΡΠΈΠ·ΠΎΠ½ΡΠ°Π»ΠΈ')
n,m = map(int,input().split())
##if n<1 and n>100 and m<1 and m>100:
#### print('ΠΡΠ΅Π²ΡΡΠ΅Π½ΠΎ ΡΠΈΡΠ»ΠΎ Π»ΠΈΠ½ΠΈΠΉ')
## quit
##else:
if min(n,m)%2==0 and n*m%2==0:
print('Malvika')
else:
print('Akshat')
|
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | 1 | n, m = map(int, raw_input().split())
p = (n * (n + 1)) / 2
m %= p
for i in xrange(n):
if m - i >= 0:
m -= i
else:
break
print(m) |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n, t = input().split()
n=int(n)
t=int(t)
s=input()
Line=[]
i=0
while i<n:
Line.append(s[i])
i=i+1
j=0 #position
i=0 #time
while i<t:
j=n-1
while j>0:
if Line[j-1]=="B" and Line[j]=="G":
Line[j-1]="G"
Line[j]="B"
j=j-2
else:
j=j-1
i=i+1
pri... |
You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.
When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where... | 3 | N=int(input())
V=list(map(int,input().split()))
V.sort()
v=V[0]
for i in range(1,len(V)):
v=(v+V[i])/2
print(v) |
There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.
Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).
When a slime with a value x eats a slime with a value y, the eaten slime disappears, and ... | 3 | from sys import stdin
input = stdin.buffer.readline
n = int(input())
*a, = map(int, input().split())
x = max(a)
ans = x
a.remove(x)
if n > 1:
x = min(a)
ans -= x
a.remove(x)
for i in a:
ans += abs(i)
print(ans) |
Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.
Given is a string S. Find the minimum number of hugs needed to make S palindromic.
Constraints
* S is a string consisting of lowercase English ... | 3 | s=input()
l,r=0,len(s)-1
a=0
while l<r:
if s[l]!=s[r]: a+=1
l+=1
r-=1
print(a) |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | a=input()
b=input()
print('EHAASRYD'['1' in b::2])
|
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four... | 3 | from functools import reduce
import os
import sys
from collections import *
#from fractions import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value(): return tuple(map(int, input().split())) # multiple values
def a... |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | import math
LI = lambda: list(map(int,input().split()) )
MI = lambda: map(int,input().split())
SI = lambda: input()
II = lambda: int(input())
t = II()
for q in range(t):
n = II()
a = LI()[::-1]
i = 1
while i<n and a[i]>=a[i-1]:
i+=1
while i<n and a[i]<=a[i-1]:
i+=1
ans = i
print(n-max(ans,i)) |
Little Elephant loves magic squares very much.
A magic square is a 3 Γ 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15... | 3 | L = []
for i in range(3):
L.append(list(map(int, input().split())))
L[0][0] = (L[1][2] + L[2][1])//2
L[1][1] = (L[0][2] + L[2][0])//2
L[2][2] = (L[0][1] + L[1][0])//2
for i in range(3):
print(*L[i])
# Made By Mostafa_Khaled |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | def ber_to_bir(berlandish, birlandish):
for i in range(int(len(berlandish))):
if berlandish[i] != birlandish[-1-i]:
return False
return True
berlandish = input()
birlandish = input()
if ber_to_bir(berlandish, birlandish):
print('YES')
else:
print('NO')
|
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | a,b=[int(x) for x in input().split()]
for i in range(b):
if a%10==0:
a=int(a/10)
else:
a=a-1
print(a) |
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim... | 3 | n=list(input())
for i in range(len(n)):
if int(n[i])==9 and i!=0:
n[i]=str(0)
elif int(n[i])==9 and i==0:
n[i]=n[i]
elif int(n[i])>=5 and int(n[i])<=9:
n[i]=str(9-int(n[i]))
print(''.join(n))
|
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now sh... | 3 | def solve(a,b,c,d):
x=b
y=c
z=d
if x+y>z: return x,y,z
else: return x,y,y
def main():
t=int(input())
for i in range(t):
a,b,c,d=list(map(int,input().split()))
x,y,z=solve(a,b,c,d)
print(x,y,z)
if __name__=='__main__': main() |
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 | import math
for _ in range(int(input())):
a, b = map(int, input().split())
print(math.ceil((abs(b-a))/10))
|
There are many sunflowers in the Garden of the Sun.
Garden of the Sun is a rectangular table with n rows and m columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burn... | 3 | from sys import stdin, stdout
from collections import defaultdict
import math
def main():
t = int(stdin.readline())
for _ in range(t):
n,m = list(map(int, stdin.readline().split()))
arr = []
for _ in range(n):
arr.append([x for x in stdin.readline().strip()])
if m =... |
You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend β at position 106 (and there is no prize in any of these two positi... | 1 | n = int(raw_input())
prizes = [int(x) for x in raw_input().split(" ")]
p1 = 1
p2 = 1000000
a1 = prizes[0]
a1Index = 0
a2 = prizes[n-1]
a2Index = n-1
prizesColected = 0
sec1 = 0
sec2 = 0
while(prizesColected!=n):
a1 = prizes[a1Index]
a2 = prizes[a2Index]
if(a1-p1+sec1 <= p2-a1+sec2):
sec1+=a1-p1
... |
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a β
b = d.
Input
The first line contains t (1 β€ t β€ 10^3) β the number of test cases.
Each test case contains one integer d (0 β€ d β€ 10^3).
... | 3 | for test in range(int(input())):
d = int(input())
delta = d**2 - 4*d
if delta < 0:
print('N')
else:
x = max((-d+delta**0.5)/-2,(-d-delta**0.5)/-2)
if delta == 0:
x = max(abs(x),d/2)
print('Y','%.9f %.9f' %(x,d-x)) |
Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | 3 | for _ in range(int(input())):
r,g,b,w = map(int,input().split())
e=0
f=0
for i in [r,g,b,w]:
if i%2==0:
e+=1
if e>=3:
f=1
else:
if 0 not in [r,g,b]:
e=0
ri,gi,bi,wi=r-1,g-1,b-1,w+3
for i in [ri,gi,bi,wi]:
if ... |
This is the easy version of this problem. The only difference is the constraint on k β the number of gifts in the offer. In this version: k=2.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β today the offer "k of goods for the price of one" is held in store... | 3 | def f(x, k):
return (x // k) * k + (1 if x % k > 0 else 0)
for _ in range(int(input())):
n, p, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
s = [0] * n
s[0] = a[0]
for i in range(1, k-1):
s[i] = s[i-1] + a[i]
for i in range(k-1, n):
s[i] = ... |
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 | n = int(input())
s = [int(i) for i in input().split()]
s.sort(reverse = True)
sum_max = 0
sum_mid = sum(s)/2
for i in range(0,n):
if sum_max > sum_mid:
print(i)
break
elif sum_max <= sum_mid:
sum_max += s[i]
else:
print(len(s))
|
[Chopsticks (singular: chopstick) are short, frequently tapered sticks used in pairs of equal length, which are used as the traditional eating utensils of China, Japan, Korea and Vietnam. Originated in ancient China, they can also be found in some areas of Tibet and Nepal that are close to Han Chinese populations, as w... | 1 | n, d = map(int , raw_input().split())
a= []
for _ in xrange(n):
a.append(input())
a.sort()
p = i = 0
while i< n-1:
if a[i+1] - a[i] <= d:
p += 1
i += 2
else:
i += 1
print p |
This problem is same as the next one, but has smaller 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 the n... | 3 | input()
a,b={},{}
r=i=0
for u in input().split():
i+=1;c=a.get(u,0)
if c:
b[c]-=1
if b[c]<1:del b[c]
c+=1;a[u]=c;b[c]=b.get(c,0)+1;l=len(b)
if l<2>[*b][0]or len(a)<2:r=i
if l==2:
x,y=sorted(b)
if x<2>b[x]or y-x<2>b[y]:r=i
print(r) |
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... | 3 | import re
s = input()
x = re.search("^[a-z]*[h][a-z]*[e][a-z]*[l][a-z]*[l][a-z]*[o][a-z]*$", s)
if (x):
print("YES")
else:
print("NO")
|
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n.
In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 β€ l β€ r β€ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, β¦, a_r.
For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ... | 3 | def same(a,b):
foo = 1
for i in range(len(a)):
if a[i] != b[i]:
return 0
return 1
def perfect(a,b):
foo = 1
for i in range(len(a)):
if a[i] > b[i]:
return 0
return 1
for _ in range(int(input())):
n = int(input())
aray = list(map(int, input().spli... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
A = [int(x) for x in input().strip().split()]
evens = []
odds = []
for i in range(len(A)):
if A[i] % 2 == 0 and len(evens) < 2:
evens.append(i)
elif A[i] % 2 == 1 and len(odds) < 2:
odds.append(i)
if len(evens) > 1 and len(odds) == 1:
print(odds[0] + 1)
bre... |
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 | num = input()
if 0 == (int(num) % 2) and int(num)!= 2:
print("YES")
else:
print("NO") |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | import sys
index = 0;
for line in sys.stdin:
if(index == 0):
index += 1;
continue;
all_nums_str = line.split(" ");
all_nums = [];
for word in all_nums_str:
all_nums.append(int(word));
all_nums.sort();
for num in all_nums[0:len(all_nums)-1]:
sys.stdout.write... |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | def dastan(x, y):
x, y = int(x), int(y)
if x > y:
t = x; x = y; y = t
return min(y - x, 10 - y + x)
n = int(input())
s = input()
t = input()
ans = 0
for i in range(n):
ans += dastan(s[i], t[i])
print(ans) |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | a=input()
a=a.replace('{','').replace('}','').replace(',','').replace(' ','')
a=set(a)
print(len(a)) |
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n Γ n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 β€ i, j β€ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | def crossesCount(matrix):
count = 0
for i in range(1, len(matrix) - 1):
for j in range(1, len(matrix[0]) - 1):
if matrix[i][j] == matrix[i - 1][j - 1] and matrix[i][j] == matrix[i + 1][j - 1] and matrix[i][j] == matrix[i - 1][j + 1] and matrix[i][j] == matrix[i + 1][j + 1] and matrix[i][j] =... |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | case=int(input())
for i in range(case):
numlen=int(input())
number=input()
if numlen>=11 and "8" in number[:-10]:
print("YES")
else:
print("NO") |
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them β a black one, and for the rest the suit will be bought in the future.
On ... | 1 | import sys
import math
inarr = map(int, sys.stdin.readline().split())
suits = map(int, sys.stdin.readline().split())
n = inarr[0]
a = inarr[1]
b = inarr[2] # black
cheapest = min(a,b)
totCost = 0
for i in range(int(math.floor(n/2.0))):
l = suits[i]
r = suits[-1 - i]
if l == 0:
if r == 0:
continue
... |
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 | s = raw_input();
arr = s.split("+")
arr.sort();
c = '+'.join(arr)
print c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.