problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ... | 1 | n = int(raw_input())
a = []
b = []
a = raw_input()
a = map(int, a.split(' '))
b = raw_input()
b = map(int,b.split(' '))
ans = 0
for i in xrange(n):
valA = 0
valB = 0
for j in xrange(i,n):
valA = valA|a[j]
valB = valB|b[j]
ans = max(ans,valA+valB)
print ans |
The Easter Rabbit laid n eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
* Each of the seven colors should be used to paint at least one egg.
* Any four eggs lying ... | 1 | n = int(raw_input())
colors = 'ROYGBIV'
eggs = [colors[i % 7] for i in xrange(n)]
if(eggs[-1] == 'Y'):
eggs[-1] = 'G'
eggs[-2] = 'B'
eggs[-3] = 'Y'
if(eggs[-1] == 'O'):
eggs[-2] = 'Y'
eggs[-1] = 'G'
if(eggs[-1] == 'R'):
eggs[-1] = 'G'
print ''.join(eggs)
|
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?
Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ... | 3 | def funct(arr,n):
c = 0
for i in range(len(arr) - 1):
if (arr[i] <= arr[i+1]):
return "YES"
# if (c > n * (n - 1) / 2 - 1):
# return("No")
return ('NO')
t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split(' ')))
print(funct(ar... |
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.
To make everything right, Petya is going to move at most one bracket from i... | 1 | rr = raw_input
rri = lambda: int(raw_input())
rrm = lambda: map(int, raw_input().split())
def solve(N, S):
if N%2: return False
A = [1 if c=='(' else -1 for c in S]
if sum(A) != 0: return False
bal = 0
pickup = False
for x in A:
bal += x
if bal < 0:
if pickup: return... |
Let N be a positive odd number.
There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.
Taro has tossed all the N coins. Find the probability of having more heads than tails.
Constraints
* N is an od... | 3 | N = int(input())
p = list(map(float, input().split()))
dp = [[0 for j in range(N+2)] for i in range(N+1)]
dp[0][1] = 1
for i in range(N):
for j in range(i+2):
dp[i+1][j+1] = dp[i][j+1] * (1 - p[i]) + dp[i][j] * p[i]
print(sum(dp[N][N + N//-2 + 2:]))
|
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 | s=raw_input()
h=['o','l','l','e','h']
for a in s:
if a == h[-1]:
h.pop()
if len(h) == 0:
break
if len(h) == 0:
print "YES"
else:
print "NO"
|
You are given an array a consisting of n integers.
Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.
Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c... | 3 | from collections import *
for _ in range(int(input())):
n = int(input())
l = [*map(int,input().split())]
dic = Counter(l)
flag = False
for i in dic:
if(dic[i] >= 3):
flag = True
break
if(flag):
print("YES")
else:
dic = {}
for i in range... |
Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either
* contains no nodes, or
* is composed of three disjoint sets of nodes:
- a root node.
- a binary tree called its left subtree.
- a binary tree called its right subtree.
Your task is to write a program ... | 3 | NIL = -1
n = int(input())
class Node():
def __init__(self):
self.id = NIL
self.left = NIL
self.right = NIL
self.parent = NIL
def __str__(self):
return "id : {}, left : {}, right : {}, parent : {}".format(self.id, self.left, self.right, self.parent)
tree = [Node... |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 1 | n=input()
x=0
y=0
z=0
for i in range(n):
s=raw_input()
l=s.split(" ")
x+=int(l[0])
y+=int(l[1])
z+=int(l[2])
if x==0 and y==0 and z==0:
print 'YES'
else:
print 'NO'
|
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same tim... | 3 | import sys
input = sys.stdin.readline
a, b = map(int, input().split())
c, d = map(int, input().split())
found = False
for i in range(int(1e6)):
j = (a*i + b - d)/c
if j % 1 == 0 and j >= 0:
print(a*i + b)
found = True
break
if not found:
print(-1) |
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | 3 | n = int(input())
p = int(pow(n,0.5))
div = []
prime = 0
for i in range(2,p+1):
if n % i == 0 :
div.append(i)
#print(i,n/i)
for j in range(2,int(pow(i,0.5)+1)):
if i%j==0:
break
else:
prime += 1
m = int(n/i)
#print(m,i,m!=i)
... |
This is a very easy warm-up problem.
You are given a string. Your task is to determine whether number of occurrences of some character in the string is equal to the sum of the numbers of occurrences of other characters in the string.
Input
The first line of the input contains an integer T denoting the number of test... | 1 | for tests in xrange(int(raw_input())):
s = raw_input()
count_of = {}
for i in s:
count_of[i] = count_of.get(i, 0) + 1
print ['NO', 'YES'][max(count_of.values()) == len(s) / 2 and len(s) % 2 == 0] |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n = int(input())
prev_magnet, islands = input(), 1
for _ in range(n - 1):
magnet = input()
if prev_magnet[1] == magnet[0]:
islands += 1
prev_magnet = magnet
print(islands) |
As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.
Snuke, an employee, would like to play with this sequence.
Specifically, he would like to repeat the following operation as many times as possible:
For every i satisfy... | 3 | N=int(input())
s=list(map(int,input().split()))
z=0
for i in range(N):
while s[i]%2==0:
z+=1
s[i]//=2
print(z) |
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | 3 | n=int(input())
for i in range(n):
x=int(input())
a=[int(y) for y in input().split()]
c=0
d=0
for j in range(x):
if(j%2!=a[j]%2 and j%2==0):
c=c+1
elif(j%2!=a[j]%2 and j%2==1):
d=d+1
if(c!=d):
print("-1")
else:
print(d) |
Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.
* insert $k$: Insert a node containing $k$ as key into $T$.
* find $k$: Report whether $T$ has a node containing $k$.
* print: Print the keys of the binary search tree by inorde... | 3 | class Node:
def __init__(self, key):
self.key = key
self.left = self.right = self.parent = None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
parent = None
current = self.root
while current != None:
parent = current
if key < current.key:
current = current.left
els... |
Ridbit starts with an integer n.
In one move, he can perform one of the following operations:
* divide n by one of its proper divisors, or
* subtract 1 from n if n is greater than 1.
A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 2... | 3 | def countt(n):
if(n==1):
return 0
elif(n==2):
return 1
elif(n==3):
return 2
if(n%2!=0):
return 3
elif(n%2==0):
return 2
else:
return -1
for _ in range(int(input())):
print(countt(int(input()))) |
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same tim... | 3 | # http://codeforces.com/problemset/problem/787/A
a, b = [int(x) for x in input().split()]
c, d = [int(x) for x in input().split()]
vmax = max(a,b,c,d)
for i in range(vmax+1):
temp = a*i + b
# print(temp)
if ( ((temp-d)%c == float(0)) and (temp-d >= 0) ):
print(temp)
break
else:
print(-1) |
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | 3 | def R(): return map(int, input().split())
def I(): return int(input())
def S(): return str(input())
def L(): return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
n=I()
for _ in range(n):
a,b=R()
if a!=b:
print('Happy Alex')
exit()
pr... |
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means... | 3 | from bisect import bisect
from collections import defaultdict
# l = list(map(int,input().split()))
# map(int,input().split()))
from math import gcd,sqrt,ceil,inf
from collections import Counter
import sys
sys.setrecursionlimit(10**9)
n = int(input())
l = []
hash = defaultdict(int)
count1 = 0
count2 = 0
la = []
for i i... |
There is a binary string a of length n. In one operation, you can select any prefix of a with an equal number of 0 and 1 symbols. Then all symbols in the prefix are inverted: each 0 becomes 1 and each 1 becomes 0.
For example, suppose a=0111010000.
* In the first operation, we can select the prefix of length 8 sin... | 3 | # from sys import stdin,stdout
# input=stdin.readline
import math
# t=int(input())
from collections import Counter
import bisect
for _ in range(int(input())):
n = int(input())
a = list(map(int,input()))
b = list(map(int,input()))
# print(a,b)
count = [0 for i in range(n)]
if a[0]:
count[... |
You are given a positive integer x. Check whether the number x is representable as the sum of the cubes of two positive integers.
Formally, you need to check if there are two integers a and b (1 ≤ a, b) such that a^3+b^3=x.
For example, if x = 35, then the numbers a=2 and b=3 are suitable (2^3+3^3=8+27=35). If x=4, t... | 3 | from collections import *
import math
test = int(input())
while test > 0:
test -= 1
n = int(input())
m= int(math.pow(n, 1/3))
arr = defaultdict(lambda : 0)
for t in range(1, m + 1):
arr[t ** 3] += 1
flag = 0
arr2= list(arr.keys())
for k in range(m):
val =n - arr2[k]
... |
One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, ... | 1 | n,m=map(int,raw_input().split())
l=[]
ans=1
for i in range(n):
l.append(raw_input())
for i in range(m):
d={}
for j in range(n):
if l[j][i] not in d:
d[l[j][i]]=1
else:
d[l[j][i]]+=1
ans*=len(d)
print ans%(1000000007)
|
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please hel... | 3 | n = int(input())
if n == 0:
print(1)
else:
if n%2==0:
if n%4==0:
print(6)
else:
print(4)
else:
if (n-1)%4==0:
print(8)
else:
print(2) |
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.
So the team is considered perfect if it includ... | 3 | q = int(input())
for tmp in range(q):
c,m,x = list(map(int,input().split()))
x += abs(c-m)
c,m = min(c,m),min(c,m)
if c <= x:
print(c)
else:
print(x+2*(c-x)//3)
|
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 | no=int(input())
j=3
count=0#number of levels
sum=1#number of cubes used
if no!=0:
if no==1:
count=1
else:
count=1
while(sum+j<=no):
count=count+1
sum=sum+j
j=0
for k in range(count+2):
j=j+k
print(count)
|
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must ... | 3 | for _ in range(int(input())):
n,m = map(int,input().split())
mat=[]
row=col=0
for i in range(n):
li = list(map(int,input().split()))
mat.append(li)
aa = li.count(0)
if aa==m:
row+=1
c=0
for i in range(m):
c=0
for j in range(n):
... |
AquaMoon had n strings of length m each. n is an odd number.
When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!
In her rage, she disrupted each pair of strings. For each pair, she selected some positions... | 3 | for _ in range(int(input())):
n, m = [int(_num) for _num in input().split(' ')]
counters = [[0.] * 26 for _ in range(m)]
ord_a = ord('a')
for _ in range(n):
for i, letter in enumerate(input()):
counters[i][ord(letter) - ord_a] += 1
for _ in range(n - 1):
for i, letter in ... |
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the re... | 3 | from collections import defaultdict
cantidad = int(input())
dic_o = {}
dic_nuevo = {}
class User:
def __init__(self,nombre):
self.nombre = nombre
self.padre = nombre
contador = 0
lista_nombre = []
for i in range(cantidad):
lista = [str(x) for x in input().split(" ")]
nombre = lista[0]
... |
You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b.
The i-th operation is as follows:
1. Append a_i to the end of b.
2. Reverse the order of the elements in b.
Find the sequence b obtained after these n operations.
Constraints... | 3 | n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(0, n, 2):
b.append(a[i])
b = list(reversed(b))
for i in range(1, n, 2):
b.append(a[i])
if n % 2 == 0:
b = list(reversed(b))
print(' '.join(list(map(str, b)))) |
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the... | 3 | # python 3
"""
From tutorial:
If first player can't make first move (table is too small and plate doesn't fit it, i.e. 2r > min(a, b)),
second player wins. Else first player wins. Winning strategy for first player:
place first plate to the center of table. After that he symmetrically reflects moves of second player
wit... |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ld... | 3 | n,k=[int(i) for i in input().split()]
h=[int(i) for i in input().split()]
d=[0]*n
for i in range(1,n):
d[i]=min([d[j] + abs(h[i]-h[j]) for j in range(max(i-k,0),i)])
print(d[n-1]) |
There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball. The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by... | 3 | # copy
# https://beta.atcoder.jp/contests/arc097/submissions/2509168
N = int(input())
balls = []
for _ in range(2 * N):
c, a = input().split()
balls += [(c, int(a))]
# numB[i][b]: 初期状態において、i番目の玉より右にある、1~bが書かれた黒玉の数
numB = [[0] * (N + 1) for _ in range(2 * N)]
numW = [[0] * (N + 1) for _ in range(2 * N)]
for i ... |
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 | import sys
import math
from collections import Counter
input = sys.stdin.readline
from functools import lru_cache
import bisect;
def solve():
n, a, b = map(int, input().split(' '))
base = ""
curr = [chr(c) for c in range(ord('a'), ord('z') + 1)]
for i in range(b):
base += curr[i]
for i in r... |
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.
Vasiliy plans to buy his favorite drink fo... | 3 | ln=int(input())
p=list(map(int,input().split()))
q=int(input())
p.sort()
u=q
m=[]
ml=max(p)
dp=[0]*(ml+1)
dp[0]=0
fre=[0]*(ml+1)
while q>0:
x=int(input())
m.append(x)
q=q-1
num=p[0]
count=1
for i in range(1,ln):
if p[i]==num:
count+=1
else:
fre[num]=count
count=1
num=... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | n = int(input())
a = list(map(int, input().split()))
res = []
for i in a:
add = True
for r in res:
if i not in r:
r.add(i)
add = False
break
if add:
res.append({i})
print(len(res))
|
You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and ... | 3 | def solve(n, m, As):
dp = [0] * m
for a in As:
a %= m
newdp = dp[:]
for i, d in enumerate(dp):
if d: newdp[(i + a) % m] = 1
newdp[a] = 1
dp = newdp
if dp[0]:
return True
return False
n, m = map(int, input().split())
if n > m:
print... |
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... | 3 | n = int(input())
l = list(map(int, input().split()))
l = l[::-1]
s = []
s.append(l[0])
res = 0
for i in range(1, n):
if l[i] < s[-1]:
res += l[i]
s.append(l[i])
else:
if s[-1] == 1:
break
temp = s[-1] -1
res += temp
s.append(temp)
print(res + l[0]) |
You are given four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50). Find any such rectangular matrix of size n × m that satisfies all of the following conditions:
* each row of the matrix contains exactly a ones;
* each column of the matrix contains exactly b ones;
* all other elements are zeros.... | 3 | ''' ## ## ####### # # ######
## ## ## ## ### ##
## ## ## # # # ##
######### ####### # # ## '''
import sys
import math
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(... |
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. ... | 3 | N,M = list(map(int,input().split()))
H = []
for i in range(M):
d,h = list(map(int,input().split()))
H.append((d,h))
#print(H[0])
best = (H[0][0]-1) + H[0][1]
for i in range(M - 1):
diffd = H[i + 1][0] - H[i][0]
diffh = abs(H[i + 1][1] - H[i][1])
if (diffd >= diffh):
best = max(best,max(H[i +... |
The progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit... | 3 | import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
import string
ORDA = 97 # a
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return [int(i) for i in input().split()]
def lcm(a, b): return abs(a * b) // math.gcd... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | n,m=map(int,input().split())
for i in range(n):
if (i+1)%2!=0:
print("#"*m)
elif (i+1)%2==0:
if (i+1)%4==0:
print("#"+"."*(m-1))
else:
print("."*(m-1)+"#")
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighb... | 1 | A = [map(int, raw_input().split()) for _ in xrange(input())]
print sum(len({(cmp(x,X),cmp(y,Y)) for x,y in A if x==X or y==Y}) > 4 for X,Y in A)
|
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | N=int(input())
final="I hate "
for i in range(1,N):
final+="that "
if i%2==0:
final+="I hate "
else:
final+="I love "
final+="it"
print(final)
|
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 | score=0
for _ in range(int(input())):
x,y,z = map(int,input().split())
if (x+y+z > 1):
score+=1
print(score)
|
You are given a string S of length 3 consisting of `a`, `b` and `c`. Determine if S can be obtained by permuting `abc`.
Constraints
* |S|=3
* S consists of `a`, `b` and `c`.
Input
Input is given from Standard Input in the following format:
S
Output
If S can be obtained by permuting `abc`, print `Yes`; otherwis... | 1 | print "Yes" if "".join(sorted(list(raw_input().strip()))) == "abc" else "No" |
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers.
Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, em... | 3 | n=int(input())
b=[]
a=list(map(int,input().split()))
i=0
j=n-1
p=0
q=0
s=0
while(i<=j):
if p<=q:
p+=a[i]
i+=1
b.append(p)
else:
q+=a[j]
j-=1
if p==q:
s=max(s,p)
print(s) |
"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 ... | 3 | n,m=map(int,input().split())
a,c=list(map(int,input().split())),0
for i in range(0,len(a)):
if(a[i]>0 and a[i]>=a[m-1]):
c=c+1
print(c)
|
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.
Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.
In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell ... | 3 | import sys;Z=sys.stdin.readline;o=[]
for _ in range(int(Z())):
n=int(Z());a=[list(Z().strip())for i in range(n)]
l=sum(i.count('X')for i in a)
for i in range(3):
w=0
for j in range(n):
for k in range(n):
if (j+k)%3==i and a[j][k]=='X':w+=1
if w<=l//3:break... |
Write a program which prints multiplication tables in the following format:
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Input
No input.
Output
1x1=1
1x2=2
.
.
9x8=72
9x9=81
Example
Input
Output | 3 | for i in range(9):
for k in range(9):
print(str(i+1)+"x"+str(k+1)+"="+str((i+1)*(k+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 | n = int(input())
while n >0:
a = input()
if len(a) > 10:
b = a[0]
c = a[-1]
d = len(a) -2
d = str(d)
b += d
b += c
print(b)
else:print(a)
n = n-1
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | import math
ip = map(int, raw_input().split())
print int(math.ceil(float(ip[0])/ip[2])*math.ceil(float(ip[1])/ip[2])) |
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 | import sys
def main():
n = int(input())
ar = list(map(int, input().split()))
indices = [i for i, x in enumerate(ar) if x == 1] + [n]
res = [indices[i + 1] - indices[i] for i in range(len(indices) - 1)]
print(len(res))
print(" ".join(str(x) for x in res))
if __name__ == '... |
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | a,b= map(int,input().split())
hip = min(a,b)
print(hip,(a+b-2*hip)//2) |
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i.
This year 2D decided to cultivate a new culture, but what exactly he d... | 3 | from math import sqrt
input()
l = sorted(map(int,input().split()))
total = sum(l)
minimum = total
for i in l:
for j in range(2,int(sqrt(i))+1):
if i % j ==0:
minimum = min(total-i+i//j+l[0]*j-l[0],minimum)
print(minimum) |
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of... | 1 |
import sys
a=raw_input()
a=list(a)
# a=map(jnt,a)
j=a[-1]
index=-1
flag=False
f=False
for i in range(len(a)):
if a[i]<j and (int(a[i]))%2==0:
f=True
flag=True
temp=a[i]
a[i]=j
a[-1]=temp
break
elif int(a[i])%2==0:
f=True
index=i
if f==Fals... |
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 1 | n,k=map(int,raw_input().split())
a=[]
for i in range(n):
a.append(raw_input())
y=raw_input()
a.sort()
count=best=0
for i in a:
if len(i)<len(y):
best+=1
count+=1
if count==k:
best+=5
count=0
worst=count=0
b=[]
for i in a:
if i!=y and len(i)<=len(y):
b.append(i)
for i in b:
worst+=1
count+=1
if count... |
You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | 3 | n = int(input())
s = input()
k = int(input())
t = s[k - 1]
print(''.join(t if t == i else '*' for i in s)) |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | def main():
limak, bob = list(map(int, input().split()))
output = get_years(limak,bob)
print(output)
def get_years(bearA, bearB):
smaller = True
count = 0
if bearA == bearB:
return '1'
else:
pass
while smaller == True:
bearA *= 3
bearB *= 2
count ... |
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... | 1 | a = raw_input()
print "YES" if '1' * 7 in a or '0' * 7 in a else "NO" |
Bizon the Champion isn't just charming, he also is very smart.
While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i·j (the rows and ... | 3 | def main():
from math import sqrt
m, n, k = map(int, input().split())
if n < m:
n, m = m, n
lo, hi = 1, k + 1
while lo + 1 < hi:
mid = (lo + hi) // 2
t = mid - 1
v = min(int(sqrt(t)), m)
tn, tm = (t - 1) // m, t // n
vv = [t // i for i in range(tm + 1,... |
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 | from sys import stdin as si
from sys import stdout as so
def func():
[n,x] = [int(x) for x in si.readline().split()]
arr = [int(x) for x in si.readline().split()]
arr.sort()
arr.reverse()
#print(arr)
c = 0
for i in range(n):
c += arr[i]
if c/(i+1) < x :
so.write... |
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | 3 | n = int(input())
teams, score = ['', ''], [0, 0]
for i in range(n):
s = input()
if (teams[0] == ''):
teams[0] = s
score[0] = 1
elif (teams[0] == s):
score[0] += 1
elif (teams[1] == ''):
teams[1] = s
score[1] = 1
else:
score[1] += 1
print(teams[0] if ... |
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.
Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.
Find the inversion number of B, modulo 10^9 + 7.
Here the inversion number of B is defined as the number of o... | 3 | n,k = map(int,input().split())
a = list(map(int,input().split()))
MOD = 10**9+7
ans=0
for i in range(n):
cnt1=0
cntall=0
for j in range(n):
if a[i]>a[j]:
cntall+=1
if i<j:
cnt1+=1
ans =(ans + cnt1*k + cntall*k*(k-1)//2) % MOD
print(ans)
|
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n = int(input())
l = []
for _ in range(n):
l.append(int(input()))
c = 1
for i in range(n-1):
if l[i] != l[i+1]:
c += 1
print(c) |
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l... | 1 | import sys
def Q(i):
return Reps[i]
s=sys.stdin.readline().split()[0]
k=int(sys.stdin.readline())
Reps={}
Alphabet="abcdefghijklmnopqrstuvwxyz"
for item in Alphabet:
Reps[item]=0
for item in s:
Reps[item]+=1
X=sorted(Reps,key=Q)
ans=0
for item in X:
ans+=Reps[item]
if(ans>k):
break
... |
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | 3 | from sys import stdin
from math import floor
n = int(input())
def solve(a, b, c, d):
if (d % c <= b and floor(d / c) <= a) or (a * c < d and a * c + b >= d):
return 'YES'
return 'NO'
while(n > 0):
a, b, c, d = map(int, stdin.readline().rstrip().split())
print(solve(a, b, c, d))
n = n - 1
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int, input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int, input().split()))
def foo():
n = inp()
out = 0
st = []
for i in range(n... |
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | 3 | import sys
import collections
from collections import Counter
import itertools
import math
import timeit
#input = sys.stdin.readline
#########################
# imgur.com/Pkt7iIf.png #
#########################
def sieve(n):
if n < 2: return list()
prime = [True for _ in range(n + 1)]
p = 3
while p *... |
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 3 | n, k = map(int, input().split())
passwords = []
best = 0
worst = 0
for i in range(n):
password = input()
passwords.append(password)
correctPassword = input()
lengthOfCorrectPassword = len(correctPassword)
#passwords.sort(key=len)
numberOfPasswordsShorter = 0
numberOfPasswordsLonger = 0
for password in password... |
Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities nu... | 3 | n,m,k=map(int,input().split())
t=0
if k:
q={}
p=[]
for i in range(m):
p.append(list(map(int,input().split())))
w=set(map(int,input().split()))
for i in p:
if not(i[0]in w and i[1]in w):
q[i[0]]=min(i[2],q.get(i[0],10**9))
q[i[1]]=min(i[2],q.get(i[1],10**9))
... |
An SNS has N users - User 1, User 2, \cdots, User N.
Between these N users, there are some relationships - M friendships and K blockships.
For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.
For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i... | 3 | import queue
N,M,K=map(int,input().split())
friend=[[] for i in range(N)]
block=[[] for i in range(N)]
color=[-1]*N
c=0
for i in range(M):
a,b=map(int,input().split())
friend[a-1].append(b-1)
friend[b-1].append(a-1)
for i in range(K):
a,b=map(int,input().split())
block[a-1].append(b-1)
block[b-... |
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:
1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea... | 3 | t=int(input())
while t:
t=t-1
n=int(input())
a=list(map(int,input().split()))
for i in range(n):
a[i]=abs(a[i])
#n,m=map(int,input().split())
x=n//2
l=[]
'''for i in range(n-1,x,-1):
if a[i]-a[i-1]==0:
continue
if a[i]-a[i-1]>0:
a[i]*=... |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | n = int(input())
points = list(map(int, input().split()))
max, min = points[0], points[0]
res = 0
for x in points:
if x < min:
min = x
res += 1
if x > max:
max = x
res += 1
print(res) |
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http... | 1 | t = int(raw_input())
for i in range(0,t):
a = map(int,raw_input().split())
print(a[0]^a[1]) |
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 |
t = int(input())
def ckeven(c):
if c%2==0:
return True
else:
return False
while t:
t-=1
r,g,b,w = map(int,input().split())
if r == 0 or g == 0 or b == 0:
cnt=0
cnt += not ckeven(r)
cnt += not ckeven(g)
cnt += not ckeven(b)
cnt += not ckev... |
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 | s=str(input())
d=str(int(s)+1)
e=len(set(str(d)))
if(e==4):
print(d)
else:
while(e<4):
d=str(int(d)+1)
e=len(set(d))
if(e==4):
print(d)
break
|
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input... | 3 | N, A, B = map(int, input().split())
for i in range(N//A+1):
if (N-i*A)%B==0:
ans = []
for j in range(i):
l = []
for k in range(1, A+1):
l.append(j*A+k)
ans += l[1:]+[l[0]]
for j in range((N-i... |
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters.
Hacker went home and started preparing to... | 3 | import sys
import string
def input():
return sys.stdin.readline().strip()
def dfs(i,vis,al):
vis[i] = True
for j in al[i]:
if not vis[j]:
dfs(j,vis,al)
al = [list() for _ in range(26)]
got = set()
n = int(input())
for _ in range(n):
s = input()
s = set([ord(c)-ord('a') for c i... |
"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 ... | 3 | n,s = map(int, input().split())
arr = [int(x) for x in input().strip().split()]
score = arr[s-1]
c=0
for cs in arr:
if cs > 0 and cs >= score:
c+=1
print(c) |
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Input
The only line contains odd integer n (1 ≤ n ≤ 49).
Output
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main di... | 3 | size = int(input())
square = [[0 for j in range(2 * size - 1)] for i in range(2 * size - 1)]
counter = 1
dj = 0
for i in range(size):
di = size - 1
for j in range(size):
square[i + di][j + dj] = counter
counter += 1
di -= 1
dj += 1
for j in range(size // 2):
for i in range(2 * si... |
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 | n = int(input())
print( *sorted(list(map(int, input().split()))) ) |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | t = int(input())
for _ in range(t):
n = int(input())
if (n/2)%2!=0:
print('NO')
else:
ans = []
for i in range(2,2*(n+1),4):
ans.append(i)
flag = False
n = len(ans)
for i in range(n):
if flag == False:
ans.append(ans[i]-1... |
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.
Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num... | 1 | n=input();L=[];x=0
for i in range(n):
k=input()
L.append(k)
N=list(set(L))
#print N
if(len(N)==2):
for i in range(n):
if L[i]==N[0]:
x+=1
#print k
if x==(n/2):
print "YES"
print N[0],N[1]
else:
print "NO"
else:
print "NO"
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | def main():
ls = list(input())
k = str(ls[0]).upper()
ls = list(k)+ls[1:]
print(''.join(str(i) for i in ls))
if __name__ == "__main__":
main() |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | 3 | n = input()
n = n.split()
m = int(n[1])
n = int(n[0])
c=0
for i in range(1,n+1):
if i%2!=0:
for j in range(m):
print("#",end = "")
print()
else:
c+=1
if c%2!=0:
for j in range(m-1):
print(".",end = "")
print("#")
else:
print("#",end = "")
for j in range(m-1):
print(".",end = "")
p... |
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right.
Also, you are given a positive integer k < n.
Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k.
You need to find the smallest beautiful integer y,... | 3 | n, k = list(map(int, input().split()))
number = list(input())
pre = "".join(number[:k])
unit = pre
cur = 0
while(cur < n):
if cur + k < n:
temp = "".join(number[cur:cur+k])
if temp == pre:
cur += k
continue
elif temp < pre:
break
elif temp... |
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d... | 1 | from sys import stdin, stdout
import math
k = int(stdin.readline().rstrip())
n = int(math.ceil((-1 + math.sqrt(1 + 8*k)) / 2))
sumBefore = (n * (n - 1)) >> 1
expected = k - sumBefore
print(expected) |
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people c... | 3 | import math
n=int(input())
m=int(input())
a=[]
for i in range(n):
a.append(int(input()))
x=max(a)
y=min(a)
op=((sum(a)+m)/n)
# print(op)
if(op!=int(op)):
op=op+1
print(max(x,int(op)),x+m)
|
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = input()
n = int(n)
i = 0
while (n > 0):
n -= 1
a = input()
if a.count('1') >= 2:
i += 1
print (i) |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps... | 1 | a, b = map(int, raw_input().split())
c, d = map(int, raw_input().split())
print max([abs(a-c), abs(b-d)]) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | N = int(input())
def solve(string):
if len(string) == 1:
return 0
if len(string) == 2:
if string[0] == string[1]:
return 1
else:
return 0
li_string = list(string)
stack = []
counter = 0
char = li_string.pop(0)
stack.append(char)
while(li_... |
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 | yes = 'YES'
no = 'NO'
hello = ('h', 'e', 'l', 'l', 'o')
w = raw_input()
def is_success_hello(word):
it = 0
for char in word:
if char == hello[it]:
it = it + 1
if it == 5:
return yes
return no
print is_success_hello(w)
|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | # import sys
# sys.stdin=open("input.in","r")
*k,m=(int(input()) for i in range(5))
c=0
for i in range(1,m+1):
if(1-all(i%x for x in k)):
c+=1
print(c) |
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the... | 1 | n = input()
l = map(int, raw_input().split())
l.sort()
powersof2 = [1]
MAX = 3 * 10**5 + 10
MOD = int(10**9 + 7)
for i in range(1, MAX):
powersof2.append((powersof2[-1] * 2) % MOD)
ans = 0
for i in range(n):
ans = ans % MOD + (l[i] * (powersof2[i] - 1)) % MOD - (l[i] * (powersof2[n - (i + 1)] - 1)) % MOD
an... |
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 | for i in range(int(input())):
s=input()
l=len(s)
if l<=10:
print(s)
else:
print(s[0]+str(l-2)+s[-1])
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighb... | 1 | import sys
input = sys.stdin.readline
n = int(input())
points = []
cute_x = {}
cute_y = {}
for i in range(n):
x, y = map(int, input().split())
if x in cute_x.keys():
cute_x[x].append(y)
else:
cute_x[x] = [y]
if y in cute_y.keys():
cute_y[y].append(x)
else:
cute_y[y] = [x]
points.a... |
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... | 1 | input()
c=[int(x) for x in raw_input().split()]
a=c.count
print sum([a(0)*(a(0)-1)/2]+[a(i)*a(-i) for i in range(1,11)])
|
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | 3 | n, m = map(int, input().split())
if m % n != 0:
print(-1)
else:
ans = 0
k = m // n
while k > 1:
if k % 3 == 0:
k //= 3
ans += 1
elif k % 2 == 0:
k //= 2
ans += 1
else:
break
if k == 1:
print(ans)
else:
... |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | 3 | for _ in range(int(input())):
a,b,c=map(int,input().split())
a1,b1,c1=map(int,input().split())
ans=0
if(c1<=a):
ans=min(c,b1)*2
else:
c1=c1-a
if(c>=c1):
c=c-c1
ans=min(c,b1)*2
else:
ans=-1*(c1-c)*2
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.