problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 β€ t β€ 1000) β the ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 18:19:03 2020
@author: Admin
"""
t=int(input())
for i in range(t):
a,b=input().split()
a=int(a)
b=int(b)
ans=b
y=(b-1)//(a-1)
print(ans+y) |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 1 | def maths():
n = input()
if n % 2 == 0:
print 8, n-8
else:
print 9,n-9
maths() |
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)
We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.
Whe... | 3 | import math
a,b,x=map(int,input().split())
if 2*x<=a*a*b:
print(math.degrees(math.atan2(b,2*x/(a*b))))
else:
print(math.degrees(math.atan2(2*b-(2*x/(a*a)),a))) |
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.
Everybody knows that the Wo... | 1 | def main():
n = int(raw_input())
events = []
for i in range(n):
a, b = map(int, raw_input().split())
events.append((a, b))
events.sort()
max_right = events[0][1]
count = 0
for a, b in events[1:]:
if b < max_right:
count += 1
elif b > max_right:
... |
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.
It was decided ... | 3 | n = int(input())
arr = input().split()
for i in range(n):
arr[i] = int(arr[i])
sum = 0
for i in range(n):
sum += 4 * arr[i] * i
print(sum)
|
The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares.
There are the following methods to create a magic square wit... | 1 | ans = []
while True:
n = input()
if n == 0:
break
c = 1
N = n*n
circle = [0]*N
p = (N+1)/2-1
while c <= N:
if p == N:
p = 1
elif p % n == 0:
p += 1
elif p+n > N:
p -= (N-n-1)
else:
p += n+1
... |
Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | 3 | def func(x):
if x%2==0:
return x-1
return x
n = int(input())
array = [int(x) for x in input().split()]
array = [func(x) for x in array]
print(*array) |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | a = int(input())
b = input()
b = [int(s) for s in b.split(' ')]
b = list(set(b))
n = len(b)
c = 0
for i in range(0,n):
b[i] = int(b[i])
if b[i] == 0:
c = 1
#
print(n-c)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | s = input()
if s[0].islower() and s[1:].isupper() and len(s)>1:
s = s.lower()
s = s[0].upper() + s[1:]
elif s.isupper():
s = s.lower()
elif len(s)== 1 and s.islower():
s = s.upper()
print(s)
|
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 1 | # Codeforces 133A: HQ9+
program = raw_input()
def solve(program):
output = ['H', 'Q', '9']
for i in xrange(len(program)):
if program[i] in output:
return True
return False
if (solve(program)):
print 'YES'
else:
print 'NO' |
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this si... | 3 | d = {"S": 0, "M": 1, "L":2,"XL":3,"XXL":4,"XXXL":5}
cnt = [int(t) for t in input().split()]
n = int(input())
ind = [i for i in range(n)]
p = []
for i in range(n):
p.append(input().split(','))
ind.sort(key=lambda x:[d[p[x][0]], len(p[x])])
ans = {}
for i in ind:
cur = p[i]
if cnt[d[cur[0]]] != 0:
an... |
You are given an n Γ m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
... | 3 | def kkr():
n, m= [int(i) for i in input().split()]
a= []
for i in range(n):
a.append([i for i in input()])
ans= 0
for i in range(m):
for j in range(n-1):
if a[j][:i+1]> a[j+1][:i+1]:
for k in range(n):
a[k][i]= "z"
... |
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum numb... | 3 | N=int(input())
H=list(map(int,input().split()))
s=0
t=0
for i in range(N-1):
if H[i]>=H[i+1]:
s+=1
else:
t=max(s,t)
s=0
t=max(s,t)
print(t)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | word = input()
if (word[0].islower() and word[1:].isupper()):
print(word.capitalize())
elif len(word) == 1 and word.islower():
print(word.capitalize())
elif len(word) == 1 and word.isupper():
print(word.lower())
elif word.isupper():
print(word.lower())
else:
print(word) |
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t... | 3 | #!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import Counter
t = int(input())
for _ in range(t):
n = int(input())
a = [int(item) for item in input().split()]
cnt = Counter(a)
items = []
for k, v in cnt.items():
items.append((k, v))
items.sort()
total ... |
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c... | 1 | line = raw_input()
cnt_one = line.count('1')
cnt_zero = line.count('0')
cnt_ques = line.count('?')
if cnt_one < cnt_zero + cnt_ques:
print '00'
length = len(line)
ex_one = ex_zero = length//2
if length&1:
ex_one += 1
ex_one = ex_one - cnt_one
ex_zero = ex_zero - cnt_zero
if ex_one>=0 and ex_zero>=0:
if line... |
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 | num = int(input())
Polyhedrons = {
'Tetrahedron': 4,
'Cube': 6,
'Octahedron': 8,
'Dodecahedron': 12,
'Icosahedron': 20
}
acu = 0
for i in range(num):
poly = str(input())
if(poly in Polyhedrons):
acu += Polyhedrons[poly]
print(acu) |
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first.
On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first... | 1 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq
# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7
def solve(f):
n = f.read_int()
a = f.read_int_list()
s = sum(a)
c = 0
for i, ai in enume... |
Takahashi likes the sound when he buys a drink from a vending machine.
That sound can be heard by spending A yen (the currency of Japan) each time.
Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.
How many times will he h... | 3 | A,B,C=map(int,input().split())
print(B//A if C>B//A else C) |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 β€ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI():... |
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... | 3 | s = input()
print("Yes"if ''.join(sorted(s))=="abc" else "No") |
You are given N positive integers a_1, a_2, ..., a_N.
For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).
Here, X\ mod\ Y denotes the remainder of the division of X by Y.
Find the maximum value of f.
Constraints
* All values in input are integers.
* 2 \leq N \leq 3000
* 2 ... | 3 | a = input();print(sum(list(map(lambda x:int(x)-1,input().split())))) |
N people are waiting in a single line in front of the Takahashi Store. The cash on hand of the i-th person from the front of the line is a positive integer A_i.
Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer P indicating its price, and shows this product... | 3 | n = int(input())
alst = [int(input()) for _ in range(n)]
ans = alst[0] - 1
price = 2
max_p = 2
for a in alst[1:]:
if a > price:
ans += (a - 1) // price
elif max_p == a:
max_p += 1
price += 1
print(ans) |
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 | for i in range(int(input())):
n=int(input())
a=list(map(int,input().split(' ')))
for i in range(n):
if i%2==0:
if a[i]<0:
a[i]=-a[i]
else:
if a[i]>0:
a[i]=-a[i]
for i in range(n):
print(a[i],end=' ')
print('') |
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n Γ n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th... | 1 | import sys
def check_arr(arr):
for x in range(num):
for y in range(num):
ctr = 0
if x+1 < num:
if arr[y][x+1] == 'o':
ctr += 1
if x-1 >= 0:
if arr[y][x-1] == 'o':
ctr += 1
if y+1 < num:
... |
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does th... | 3 | N, M = map(int, input().split())
a = [[] for i in range(N+1)]
for i in range(M):
u, v = map(int, input().split())
a[u].append(v)
#print(a)
S, T = map(int, input().split())
def main():
c = [S]
m = [[False, False, False] for i in range(N+1)]
for count in range(1, 3*N+1):
c2 = []
for u in c:
m[u][... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | from sys import stdin
def main():
num_stops = int(stdin.readline().strip()) # 2-1000, inclusive
min_capacity = 0
curr_passengers = 0
for i in range(num_stops):
num_enter_str, num_exit_str = stdin.readline().strip().split(' ')
num_exit, num_enter = int(num_enter_str), int(num_exit_str)... |
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi.
How many ways are there to choose K consecutive integers?
Constraints
* All values in input are integers.
* 1 \leq K \leq N \leq 50
Input
Input is given from Standard Input in the following format:
N K
Output
Print the a... | 3 | N, K = map(int, input().split())
S = N - K + 1
print(S) |
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manag... | 1 | n = input()
p = []
for i in range(n):
p.append(input() - 1)
res = 0
for i in range(n):
t = 0
while i != -2:
t += 1
i = p[i]
res = max(res, t)
print res
|
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that:
* If we consider any color, all elements of this color must be divisible by the minimal element of this color.
* The number of used colors must be minimized.
For example, it's fine to paint elements [40, 1... | 3 | n=int(input())
l=list(map(int,input().split()))
l.sort()
vis=[0]*n
ans=0
for i in range(n):
if(vis[i]==0):
ans+=1
x=l[i]
for j in range(n):
if l[j]%x==0:
vis[j]=1
print(ans) |
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into wΓ h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one β 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | 3 | w,h,k=map(int,input().split())
a=[]
while k>0:
b=[]
b.append(w)
b.append(h)
a.append(b)
w=w-4
h=h-4
k=k-1
c=0
for i in a:
m=i[0]
n=i[1]
c=c+2*(m+n-2)
print(c) |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | t = int(input())
for i in range(t):
n = int(input())
r = 0
s = input().split()
k = 0
mk = 1000000001
for i in range(n):
s[i] = int(s[i])
if s[i] < mk:
mk = s[i]
k = i
z = input().split()
q = 0
aq = 1000000001
for i in range(n):
z[i] = int(z[i])
if z[i] < aq:
aq = z[... |
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | def program():
num = int(input())
total=0
for dig in range(1,10):
for siz in range(1,5):
total+=siz
n = int(str(dig)*siz)
if n==num:
return total
for i in range(int(input())):
print(program()) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 1 | a=map(int,raw_input().split())
b=map(int,raw_input().split())
for i in b:
if (i>a[1]):
a[0]+=1
print a[0]
|
Your friend has n cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a car... | 1 | o = "aeiou"
o1 = "13579"
s = raw_input()
sol = 0
for l in s:
if (l in o) or(l in o1):
sol += 1
print sol
|
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of... | 3 | # Contest: Educational Codeforces Round 68 (Rated for Div. 2) (https://codeforces.com/contest/1194)
# Problem: C: From S To T (https://codeforces.com/contest/1194/problem/C)
def rint():
return int(input())
def rints():
return list(map(int, input().split()))
q = rint()
for _ in range(q):
s = input()
... |
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 | n = ["Tetrahedron","Cube","Octahedron","Dodecahedron","Icosahedron"]
s = [4,6,8,12,20]
f = 0
for i in range(int(input())):
q = input()
f += s[n.index(q)]
print(f)
|
Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | 1 | n = input()
m = 2*n-1
nums = map(int,raw_input().split())
if n % 2 == 1:
for i in range(len(nums)):
if nums[i] < 0:
nums[i] = -nums[i]
print sum(nums)
else:
t = 0
nums.sort()
for i in range(len(nums)):
if nums[i] < 0:
t += 1
nums[i] = -nums[i]
else:
break
nums.sort()
if t % 2 == 1:
print sum(... |
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.
Anton can perform the following sequence of operations any number of ti... | 3 | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mn = 0
pl = 0
no = 0
if a[0] != b[0]:
print("NO")
continue
for i in range(N - 1):
if a[i] > 0: pl = 1
elif a[i] < 0: mn = 1
... |
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 β€ hh < 24 and 0 β€ mm < 60. We use 24-hour time format!
Your task is to find the number of minutes before the New Year. You know that New Year comes when the... | 3 | t = int(input())
for j in range(t):
res = 0
n,k = list(map(int,input().split()))
res += n*60
res += k
print(1440-res)
|
Β«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 | k = int(input())
l = int(input())
m = int(input())
n = int(input())
d = int(input())
lista = [0 for x in range(d+1)]
for i in range(k, d+1, k):
lista[i]+=1
for i in range(l, d+1, l):
lista[i]+=1
for i in range(m, d+1, m):
lista[i]+=1
for i in range(n, d+1, n):
lista[i]+=1
#print(lista)
p = 0
for i in list... |
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak... | 3 | l = list(map(int, input().split()))
def sticks(n,k):
if n==k:
return "YES"
else:
if (n//k)%2==0:
return "NO"
elif (n//k)%2==1:
return "YES"
print(sticks(l[0],l[1])) |
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... | 1 | matrix = [];
for i in range(3):
matrix.append(raw_input().split(" "));
sumXYZ = (int(matrix[0][1])+int(matrix[0][2])+int(matrix[1][0])+int(matrix[1][2])+int(matrix[2][0])+int(matrix[2][1]))/2;
matrix[0][0] = str(sumXYZ-int(matrix[0][1])-int(matrix[0][2]));
matrix[1][1] = str(sumXYZ-int(matrix[1][0])-int(matrix[1][2... |
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as ... | 3 | import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
from functools import lru_cache #use @lru_cache(None)
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')
#
def input(): return sys.stdin.readline()
def mapi(arg=0): ret... |
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times β at i-th step (0-indexed) you can:
* either choose position pos (1 β€ pos β€ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | #!/usr/bin/env python3
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
def conv(num, n):
ret = []
while num > 0:
ret.append(num%n)
... |
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of cons... | 1 | s=raw_input()
t,r=0,0
for i in range(5,len(s)+1):
t+=(s[i-5:i]=='heavy')
r+=t*(s[i-5:i]=='metal')
print r
|
There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i. You are choosing K among these N pieces to eat. Your "satisfaction" here will be calculated as follows:
* The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".
* The base total de... | 3 | a = list(map(lambda x: int(x), input().split()))
N = a[0]
K = a[1]
sushis = []
for i in range(0, N):
sushis.append(list(map(lambda x: int(x), input().split())))
sushis.sort(key=lambda x:x[1], reverse=True)
netas = set()
duplicates = []
choices = sushis[:K]
for choice in choices:
if choice[0] in netas:
dupli... |
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.
Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ... | 3 | # cook your dish here
#code
import math
import collections
from sys import stdin,stdout,setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2**20)
T = 1
#T = int(stdin.readline())
for _ in range(T):
#n = int(stdin.readline())
... |
You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:
res = 0
for init = 0 to inf
cur = init
ok = true
for i = 1 to |s|
res = res + 1
... | 3 | for _ in range(int(input())):
s = input()
n = len(s)
plus = 0
ans = 0
for i in range(n):
if s[i]=="-":
plus = max(plus, 0)
if plus == 0:
ans += i+2
else:
ans += 1
plus -= 1
else:
ans += 1
... |
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 β
n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import sys
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')
from math import cos, pi
t = int(input())
for tc in range(t):
n = int(input())
a = cos(pi / (4*n))
b = cos(((n-1) * pi) / (2*n))
print(a/b) |
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Va... | 3 | n,m=map(int,input().split())
b=list(range(1,m+1))
for i in range(n):
a=[int(n) for n in input().split()]
for j in range(1,len(a)):
p=a[j]
if a[j] in b:
b.remove(a[j])
if b==[]:
print('YES')
else:
print('NO')
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (... | 1 | l=map(int,raw_input().split())
print 'Yes' if (l[0]+l[1])%2==l[2]%2 and abs(l[2])>=abs(l[0])+abs(l[1]) else 'No' |
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.
For some indices i (1 β€ i β€ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the ... | 3 | n = int(input())
a = list(map(int,input().split()))
t = input()
mx = [0 for i in range(n+1)]
mn = [float("inf") for i in range(n+2)]
total = 0
for i in range(1,n+1):
mx[i] = max(mx[i-1],a[i-1])
for i in range(n,0,-1):
mn[i] = min(mn[i+1],a[i-1])
for i in range(n-1):
if t[i] == '1':
continue
... |
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | s=input()
for i in s:
if i in ["H","Q","9"]:
print("YES")
break
else:
print("NO") |
Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold?
Constraints
* 1 \leq a, b, c \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
a \ b \ c
Output
If \sqrt{a} + \sqrt{b} < \sqrt{c}, print `Yes`; otherwise, print `No`.
Examples
Input
2 3 9
Output
No
I... | 3 | a, b, c = map(int, input().split())
if 4*a*b < (c-a-b)**2 and 0 < c-a-b:
print("Yes")
else:
print("No")
|
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | for i in range(int(input())):
a,b,c,n=map(int,input().split())
d=max(a,b,c)
a=d-a
b=d-b
c=d-c
need=a+b+c
n-=need
#print(a,b,c,d,need)
if n<0:
print("NO")
elif n%3==0:
print("YES")
else:
print("NO")
|
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.
Given a string S, determine whether it is coffee-like.
Constraints
* S is a string of length 6 consisting of lowercase English l... | 3 | s = input()
X = s[2]==s[3] and s[4]==s[5]
if X : print("Yes")
else : print("No") |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | 3 | n = int(input())
db = {}
for _ in range(n):
name = input()
c = db.setdefault(name, 0)
if not c:
print("OK")
else:
print(name + str(c))
db[name] += 1
|
Vivek has encountered a problem. He has a maze that can be represented as an n Γ m grid. Each of the grid cells may represent the following:
* Empty β '.'
* Wall β '#'
* Good person β 'G'
* Bad person β 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a... | 3 | import sys
input = sys.stdin.readline
def inInt():
return int(input())
def inStr():
return input().strip("\n")
def inIList():
return(list(map(int, input().split())))
def inSList():
return(input().split())
def bsearch(nums, target):
N = len(nums or [])
l = 0
r = N - 1
while l <... |
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only lin... | 3 | pre_cal_sum_dec = {}
def sum_dec (n):
'''Sum of 10**n + 10**(n-1) + ... 10**1
Parameter: n: number
Return: result of the sum'''
global pre_cal_sum_dec
try:
return pre_cal_sum_dec[n]
except:
sumer = 0
for i in range (1,n):
sumer += 10**i
pre_cal_sum_dec... |
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 |
_ = input()
stones = list(input())
new_alignment = []
new_alignment.append(stones[0])
count = 0
for idx, stone in enumerate(stones[1:], start=1):
if stone == new_alignment[-1]:
count += 1
else:
new_alignment.append(stone)
print(count)
|
Heading ##There are two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format
First line of the input contains T, the number of testcases to follow.
Each testcase in a newline contains A and B separated by a single space.
Constrai... | 1 | N = int(raw_input())
for i in range(N):
x = map(int,raw_input().split())
f=x[0]
for j in x:
s=f&j
print f |
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.
Given a string S, determine whether it is coffee-like.
Constraints
* S is a string of length 6 consisting of lowercase English l... | 3 | a = input()
print('Yes') if (a[2] == a[3] and a[4] == a[5]) else print('No') |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | import sys
t = int(sys.stdin.readline())
while t:
x,y,z = map(int,sys.stdin.readline().strip().split())
if [x,y,z].count(max(x,y,z))<2:
print("NO")
else:
print("YES")
print(max(x,y,z),min(x,y,z),min(x,y,z))
t-=1 |
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.
There is a set S containing very important number... | 3 | from collections import defaultdict
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
visited = [0]*(1025)
ans = -1
maxi = max(l)
mini = min(l)
for i in range(n):
visited[l[i]] = True
for i in range(1,1024):
flag = 0
for j in l:
p = j^i
if p<=mini and p>=maxi:
... |
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... | 3 | # Problem: A. Array Rearrangment
# Contest: Codeforces - Codeforces Round #680 (Div. 2, based on Moscow Team Olympiad)
# URL: https://codeforces.com/contest/1445/problem/A
# Memory Limit: 512 MB
# Time Limit: 1000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
r... |
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 β€ i < n there is an edge between the vertices of i and i+1.
Denote the function f(l, r), which takes two in... | 1 | '''input
10
1 5 2 5 5 3 10 6 5 1
'''
RI = lambda : [int(x) for x in raw_input().split()]
rw = lambda : raw_input().strip()
mod = 10**9+7
n = input()
A = RI()
ans = 0
for i in range(n):
if i == 0:
ans += A[i] * (n - A[i] + 1)
else:
mi = 1
mx = n
if A[i] > A[i-1]:
mi = A[i-1]+1
ans += (A[i... |
Alicia has an array, a_1, a_2, β¦, a_n, of non-negative integers. For each 1 β€ i β€ n, she has found a non-negative integer x_i = max(0, a_1, β¦, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, β¦, b_n: ... | 3 | '''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineerin College
Date:19/03/2020
'''
from math import ceil,sqrt,log
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
def main():
n=ii()
a=li()
x=0
for i ... |
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two equal integers from s, remove them from s and insert the number eq... | 3 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
n = int(input())
for i in range(n):
m = int(input())
sum=0
S = [int(x) for x in input().split()]
for j in range(m):
if S[j] <= 2048:
sum+=S[j]
if sum>=2048:
print("YES")
else:
pri... |
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a ... | 3 |
s = input()
try:
a = s.find('[')
b = s.find(':',a)
c = s.rfind(']')
d = s.rfind(':',b,c)
except:
print(-1)
exit(0)
if a < c and b < d and d < c:
temp = s[b+1:d]
print(temp.count('|') + 4)
else:
print(-1) |
You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times:
* Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one ... | 3 | from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import *
from bisect import *
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
INF = 1 << 60
N, K, Q = reads()
A = reads()
A.append(-INF)
def getlub(y):
... |
Given is a string S representing the day of the week today.
S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.
After how many days is the next Sunday (tomorrow or later)?
Constraints
* S is `SUN`, `MON`, `TUE`, `WED`, `THU`,... | 3 | a={"SUN":7,"MON":6,"TUE":5,"WED":4,"THU":3,"FRI":2,"SAT":1}
print(a[input()]) |
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 | n,m,a = map(int, input().split())
na = n//a
if(n % a != 0):
na += 1
ma = m//a
if(m % a != 0):
ma += 1
print(ma * na)
|
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected ... | 3 | a, b = input().split()
N = int(input())
print(a, b)
for n in range(N):
c, d = input().split()
if c == a:
a = d
elif c == b:
b = d
elif d == a:
a = c
elif d == b:
b = c
print(a, b) |
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.
The boy is now looking at the ratings of consecutive participan... | 3 | for _ in range(int(input())):
n = int(input())
ans = 0
for i in range(60):
if n & (1<<i): ans += (1 << (i+1)) - 1
print(ans) |
Let us consider the following operations on a string consisting of `A` and `B`:
1. Select a character in a string. If it is `A`, replace it with `BB`. If it is `B`, replace with `AA`.
2. Select a substring that is equal to either `AAA` or `BBB`, and delete it from the string.
For example, if the first operation is ... | 3 | s=input()
t=input()
ss=[0]
for i in range(len(s)):
ss.append(ss[i] + (1 if s[i] == 'A' else 2))
tt=[0]
for i in range(len(t)):
tt.append(tt[i] + (1 if t[i] == 'A' else 2))
q=int(input())
for _ in range(q):
a,b,c,d=map(int,input().split())
x = (ss[b]-ss[a-1]) % 3
y = (tt[d]-tt[c-1]) % 3
print('YE... |
The police department of your city has just started its journey. Initially, they donβt have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | 3 | if __name__ == '__main__':
events = int(input())
crimes = 0
available = 0
city = list(map(int,input().split()))
if city[0] == -1:
crimes = crimes + 1
else:
available = available + city[0]
for i in range(1,len(city)):
if city[i] == -1:
if available > 0:
... |
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 | #for _ in range(int(input())):
n = int(input())
array = list(map(int, input().split()))
sum_array = sum(array)
array = sorted(array, reverse=True)
#print(array)
sum_array = sum_array // 2
ans = 0
count = 0
for i in range(n):
ans += array[i]
count += 1
if ans > sum_array:
break
print(count) |
Petya has a rectangular Board of size n Γ m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the oper... | 3 | n, m, _ = list(map(int, input().split()))
print(2 * (n - 1) + (n + 1) * (m - 1))
print("U" * (n - 1) + "L" * (m - 1), end="")
for i in range(n):
if i != 0:
print("D", end="")
if i % 2 == 0:
print("R" * (m - 1), end="")
else:
print("L" * (m - 1), end="") |
You are given a permutation p of the set {1, 2, ..., N}. Please construct two sequences of positive integers a_1, a_2, ..., a_N and b_1, b_2, ..., b_N satisfying the following conditions:
* 1 \leq a_i, b_i \leq 10^9 for all i
* a_1 < a_2 < ... < a_N
* b_1 > b_2 > ... > b_N
* a_{p_1}+b_{p_1} < a_{p_2}+b_{p_2} < ... < a... | 3 | N = int(input())
P = [int(x) for x in input().split()]
a = [i*N + 1 for i in range(N)]
b = [i*N + 1 for i in reversed(range(N))]
for i in range(N) :
a[P[i]-1] += i
print(*a)
print(*b)
|
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | 3 | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
v=[0]*n
for i in range(len(l)):
l[i]%=n
for i in range(len(l)):
x=(i+l[i])%n
if not v[x]:
v[x]=1
else:
print('NO')
break
else:
print('YES')
... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | for _ in range(int(input())):
n,r=map(int,input().split())
if r<n:
print(r*(r+1)//2)
else:
print(1+(n-1)*n//2) |
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 β€ j β€ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the... | 3 | # cook your dish here
# code
# ___________________________________
# | |
# | |
# | _, _ _ ,_ |
# | .-'` / \'-'/ \ `'-. |
# | / | | | | \ |
# | ; \_ _/ \_ _/ ; ... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 1 | #Codeforces Problem 122A William Park May 2015
import math
n = int(raw_input())
'''
k = 1
luckynumbers = []
while k <= n:
k = str(k)
is_lucky = True
for i in xrange(len(k)):
if not (k[i] == "4" or k[i] == "7"):
is_lucky = False
if is_lucky:
luckynumbers.append(int(k))
i... |
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned... | 1 | n=int(raw_input())
x=[]
y=[]
for i in range(0,n):
a=raw_input()
x1=int(a.split()[0])
y1=int(a.split()[1])
if x1 not in x:
x.append(x1)
if y1 not in y:
y.append(y1)
if len(x)==2 and len(y)==2:
print abs((x[0]-x[1])*(y[0]-y[1]))
else:
print -1
|
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string ... | 3 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.wri... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input().strip())
result = 0
for i in range(n):
if sum(list(map(int, input().strip().split()))) >= 2:
result += 1
print(result) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Let p be any permutation of length ... | 3 | a=int(input())
for i in range(a):
b=int(input())
c=list(map(int,input().split()))
c.reverse()
print(*c) |
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem... | 1 | n = int(raw_input())
m = n/3 * 2
k = n % 3
dd = [1, 1, 2]
print m+(k>0) |
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μλ
, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of n strings s_1, s_2, s_3, β¦, s_{n} and m strings t_1, t_2, t_3, β¦, t_{m}. ... | 3 | import sys
n, m = map(int, sys.stdin.readline().split())
n_strings = sys.stdin.readline().rstrip().split()
m_strings = sys.stdin.readline().rstrip().split()
q = int(sys.stdin.readline())
for year in map(int, sys.stdin):
year -= 1
n_index = year % n
m_index = year % m
name = n_strings[n_index] + m_str... |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | for _ in range(int(input())):
n=int(input())
if n<=30:
print("NO")
else:
print("YES")
if n-30==6 or n-30==10 or n-30==14:
print("{} {} {} {}".format(6,10,15,n-30-1))
else:
print("{} {} {} {}".format(6,10,14,n-(6+10+14))) |
Tic-Tac-Toe are three cousins. They planned to play cricket this afternoon but got stuck in their homework. Mrs. Jaime assigned them a task to arrange all the letters in a scrambled word in the order of their appearance in english alphabets. All the letters are in upper-case. Help Tic-Tac-Toe to solve their homework so... | 1 | t=input()
while t:
t-=1
s=raw_input()
print ''.join(sorted(s)) |
Given are a positive integer N and a string S of length N consisting of lowercase English letters.
Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T.
Constraints
* 1 \leq N \leq 100
* S consists of lowercase English letter... | 3 | N=int(input());S=input();print('YNeos'[S[:N//2]!=S[-N//2:]::2]) |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | def inp():
return list(map(int, input().split()))
def solve():
(black, white) = ('*', '.')
[n, m, priceOf1, priceOf2] = inp()
theaterPaves = []
for _ in range(n):
theaterPaves.append(list(input()))
cost = 0
for i in range(n):
for j in range(m):
if theaterPaves[i]... |
You are given two arrays a and b, both of length n.
Let's define a function f(l, r) = β_{l β€ i β€ r} a_i β
b_i.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b to minimize the value of β_{1 β€ l β€ r β€ n} f(l, r). Since the answer can be very large, you have to print it modulo... | 1 | from sys import stdin
add = lambda a, b: (a % mod + b % mod) % mod
mult = lambda a, b: ((a % mod) * (b % mod)) % mod
rints = lambda: [int(x) for x in stdin.readline().split()]
arr_enu = lambda: [[i, int(x)] for i, x in enumerate(stdin.readline().split())]
mod = 998244353
def sum_segments(a):
tem = []
for i i... |
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | 3 | N=int(input())
if N%2==1:
print(0)
else:
a=0
for i in range(1,26):
a+=(N)//(2*5**i)
print(a) |
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | 3 | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,m = map(int,input().split())
for i in range(1,n//2+1):
a,b,c,d = i,1,n-i+1,m
for _ in range(m):
print(a,b)
print(c,d)
b += 1
d... |
There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H). You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the p... | 3 | w, h, x, y = [int(x) for x in input().split()]
print(w*h/2, int(2 * x == w and 2 * y == h)) |
"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 | def solve(arr, k):
kth = arr[k-1]
for index, marks in enumerate(arr):
if marks < kth or marks < 1: return max(0, index)
return len(arr)
# if __name__ == "__main__":
# num_test_cases = int(input())
# for _ in range(num_test_cases):
# test_case = input()
# print(solve(test_case))
if __name__ == "__main__":... |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | #!/usr/bin/env pypy
n = str(input())
n = n.lower()
vowel = "aeiouy"
consonants = "bcdfghjklmnpqrstvwxz"
l = []
for i in n:
if(i in consonants):
l.append("."+i)
l = "".join(l)
print(l)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.