problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
There are n pillars aligned in a row and numbered from 1 to n.
Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.
You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met:
... | 3 | def solve(b):
# Is the array b, increasing and then decreasing
m = len(b)
d = False
for i in range(1, m):
if a[i] < a[i - 1]:
d = True
elif a[i] > a[i - 1] and d:
return False
return True
n = int(input())
a = [int(x) for x in input().split(' ')]
if solve(a):... |
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 | t=int(input())
while(t>0):
j=input()
if(len(j)<=10):
print(j)
else:
p=""
p+=j[0:1]
p+=str(len(j)-2)
p+=j[-1]
print(p)
t-=1 |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t=int(input())
for _ in range(t):
n=int(input())
s=list(map(int,input().split()))
e=0
o=0
for i in s:
if(i%2==0):
e+=1
else:
o+=1
if((o==n and n%2==0) or e==n):
print("NO")
else:
print("YES") |
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | 3 | # @oj: codeforces
# @id: hitwanyang
# @email: 296866643@qq.com
# @date: 2020-04-28 14:14
# @url:https://codeforces.com/problemset/problem/1338/A
import sys,os
from io import BytesIO, IOBase
import collections,itertools,bisect,heapq,math,string
# region fastio
BUFSIZE = 8192
BUFSIZE = 8192
class FastIO(IOBase):
n... |
We want to encode a given string $S$ to a binary string. Each alphabet character in $S$ should be mapped to a different variable-length code and the code must not be a prefix of others.
Huffman coding is known as one of ways to obtain a code table for such encoding.
For example, we consider that appearance frequencyc... | 3 | from typing import Dict
class Node():
left = None
right = None
parent = None
char = ''
value = 0
def __init__(self, char: str = '', value: int = 0) -> None:
self.char = char
self.value = value
def get_coded_str_len(node: Node, base_str: str) -> int:
if node.char:
... |
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t... | 3 | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
c=[0]*(10**5+1)
for i in a:
c[i]+=1
k=max(c)
x=0
for i in c:
if i==k:
x+=1
print(((n-x-1)-(k-2))//(k-1)) |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | def a(n, b):
if b.count("A") > b.count("D"):
return "Anton"
elif b.count("A") < b.count("D"):
return "Danik"
return "Friendship"
n = input()
b = input()
print(a(n, b))
|
Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.
Input
The first line contains two integers n and k (2 β€ n β€ 100000, 1 β€ k β€ 20).
Output
If it's impossible to find the representation of n as a product of k... | 3 | import math
r = 0
k = str()
n, m = list(map(int, input().split()))
for i in range(2,round(math.sqrt(n))+1):
while n % i==0 and r < m -1:
n = n//i
k += str(i) + " "
r += 1
if r >= m-1:
break
if n>1:
k += str(n)
r += 1
if r<m:
print("-1")
exit()
print(k)
|
Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but m... | 3 | from decimal import *
import sys
getcontext().prec=100
n,m=input().split()
n=eval(n)
m=eval(m)
if n*m<=2:
if n==2 and m==1:
print(0.5)
else:
print(1)
sys.exit()
n=Decimal(n)
m=Decimal(m)
a=m*n
b=n-1
b=b*b
ans=(a-1+(n-1)*(m-1))/(n*(a-1))
print(ans) |
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | 3 | p, n = map(int ,input().split())
mod = [0]*(p+2)
for i in range(1,n+1):
j = int(input())
if(mod[j%p]):
print(i)
exit(0)
mod[j%p] = 1
print(-1)
|
Vasya likes to solve equations. Today he wants to solve (x~div~k) β
(x mod k) = n, where div and mod stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solu... | 3 | n,k=[int(s) for s in input().split()]
for i in range(k-1,0,-1):
if n%i==0:
print(n//i*k+i)
exit(0)
|
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai β€ bi).
Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
Input
The first line of the input contains one integer n (2 β€ n β€ 100 000) β number of cola... | 3 | #http://codeforces.com/problemset/problem/892/A
#solved
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
max1 = max(b)
b.remove(max1)
max2 = max(b)
suma = max1 + max2
s = 0
for i in a:
s += i
if s <= suma:
print("YES")
else:
print("NO") |
The Squareland national forest is divided into equal 1 Γ 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner.
Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i... | 3 | def connect(x1, y1, x2, y2):
a = set()
if x2 > x1:
for i in range(x1, x2+1): a.add((i, y1))
if y2 > y1:
for j in range(y1, y2+1): a.add((x2, j))
else:
for j in range(y2, y1+1): a.add((x2, j))
else:
for i in range(x2, x1+1): a.add((i, y2))
if y2... |
<image>
While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, β¦, a_n to -a_1, -a_2, β¦, -a_n... | 3 | for _ in range(int(input())):
n=int(input());l=list(map(int,input().split()));print(n*3)
for i in range(0,n,2):
x=" "+str(i+1)+" "+str(i+2)
for j in range(6):print(str(2-j%2)+x) |
We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. On this grid, there is a piece, which is initially placed at square (s_r,s_c).
Takahashi and Aoki will play a game, where each player has a st... | 3 | import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
h,w,n=map(int,input().split())
i0,j0=map(int,input().split())
S=input()
T=input()
u,d,l,r=1,h,1,w
for t,s in zip(T[::-1],S[::-1]):
if(t=='U'): d=min(h,d+1)... |
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())
count = 0
for i in range(n):
su = sum([int(x) for x in input().split()])
if su >= 2:
count += 1
print(count) |
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).
What is xor?
For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\... | 3 | n = int(input())
a = [int(i) for i in input().split()]
b = 0
for i in a:
b ^=i
ans = [i ^ b for i in a]
print(*ans) |
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | # ---------------------------------------------------------------------------------------------------- #
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Copyright Β© 2017 pmxt <pmxt@Manjunathas-MacBook-Air.local>
# --------------------------------------------------------------------------------------... |
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location β is denoted by an integer in \{0, β¦, |s|\}, with the following meaning:
* If β = 0, then the cursor... | 3 | import sys
mod=10**9+7
t=int(sys.stdin.readline())
for _ in range(t):
x=int(sys.stdin.readline())
s=[i for i in sys.stdin.readline()][:-1]
length=len(s)
for i in range(1,x+1):
#print(length,'length')
#print(s,'s')
if len(s)>=x:
#print(int(s[i-1]))
add=((le... |
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.
<image>
Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight.
Now, she is going to pick three gems.
Xenia loves colorful things, ... | 3 | from bisect import bisect_left
def fun(arr, val):
pos = bisect_left(arr, val)
if(pos == 0):
return arr[0]
elif(pos == len(arr)):
return arr[-1]
else:
left = arr[pos - 1]
if((val - left) < (arr[pos] - val)):
return left
else:
return arr[po... |
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | for _ in range(int(input())):
l, b = map(int, input().split(" "))
print(max(max(l,b),2*min(l,b))**2) |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | 3 | n=int(input ())
s=[[int(z),0] for z in input().split()]
for i in range(n):
s[i][1]=i+1
s.sort()
for i in range(n//2):
print(s[i][1],s[n-i-1][1]) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
length = int(input())
pangram = input()
results = "NO"
if length >= 26:
pangram = pangram.lower()
letter = 0
while letter < len(alphabet):
if not alphabet[let... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w=int(input())
if w==1 or w==2:
print("NO")
elif w%2==0:
print("YES")
else:
print("NO") |
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())
x=1
while n:
if x:
print("I hate ",end="")
x=0
else:
print("I love ",end="")
x=1
n=n-1
if n:
print("that ",end="")
print("it")
|
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | import math
n=int(input())
r=list(map(int,input().split()))
b=list(map(int,input().split()))
u,v=0,0
for i in range(len(r)):
if r[i]==1 and b[i]==0:
u+=1
if b[i]==1 and r[i]==0:
v+=1
if u==0:
print(-1)
elif u>v:
print(1)
else:
x=(v+u)//u
print(x) |
A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:
* S is a palindrome.
* Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.
* The string consisting of the (N+3)/2-st through N-th charact... | 3 | s=input()
n=len(s)
if not s[0:(n-1)//2]==s[(n+1)//2:n]:
print('No')
elif s==s[::-1]:
print('Yes')
else:
print('No') |
You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1).
Input
The... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = [int(c) for c in input().split()]
s1 = 0
s2 = 0
for i in range(2 * n):
if a[i]%2==0:
s1+=1
else:
s2+=1
if s1==s2:
print('YES')
else:
print('NO') |
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | a = int(input())
s=0
b = list(map(int,input().split()))
b.sort()
s= b[a-1]- b[0]
s = s-a
print(s+1) |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | # cook your dish here
l=list(map(str,input().split()))
a=0
b=0
c=0
d=0
e=0
for i in range(len(l[0])):
if(l[0][i]=='h'):
a=i
break
for i in range(len(l[0])):
if(l[0][i]=='e' and i>a):
b=i
break
for i in range(len(l[0])):
if(l[0][i]=='l' and i>b):
c=i
... |
You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 β€ j < c_i.
Now you decided... | 3 |
def main():
t=int(input())
allAns=[]
for _ in range(t):
n=int(input())
c=readIntArr()
a=readIntArr()[1:]
b=readIntArr()[1:]
#dp
maxOpenLen=[0 for _ in range(n-1)]
maxOpenLen[0]=abs(a[0]-b[0])
ans=0
for i in range(1,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'... | 3 | import math
n,m,a=map(int,input().split())
k=max(n,m)
j=min(n,m)
print(math.ceil(k/a)*math.ceil(j/a)) |
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D β₯ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | 1 | import atexit
import io
import sys
buff = io.BytesIO()
sys.stdout = buff
@atexit.register
def write():
sys.__stdout__.write(buff.getvalue())
n = input()
l = map(int, raw_input().split())
l = list(set(l))
l.sort()
if len(l) > 3:
print -1
elif len(l) == 3:
if l[1]-l[0] == l[2]-l[1]:
print l[2]-l[1]
else:
... |
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | 3 | n,m=map(int,input().split())
B = 0
W = 0
G = 0
for i in range(0, n):
a = input().split()
for j in a:
if j == 'B':
B += 1
elif j == 'W':
W += 1
elif j == 'G':
G += 1
if B+W+G == n*m:
print('#Black&White')
else:
print('#Color')
... |
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t... | 3 | #CF
n,a,b,c=list(map(int,input().split()))
variandid=[[c,3*a,a+b,c+2*b],[2*a,b,3*a+c,c+b,2*c],[a,c+b,c+2*a,2*b+a,3*c]]
ju=n%4
if ju==0:
if n!=0:
print(0)
else:
t=[4*a,2*b,4*c,a+c]
print(min(t))
else:
t=variandid[ju-1]
print(min(t))
|
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 Γ n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h... | 3 | def main():
n = int(input())
a = [int(i) for i in input().split()]
cnt = 0
for i in range(n):
temp = 1
k = i
j = i - 1
while j >= 0 and a[j] <= a[k]:
temp += 1
j -= 1
k -= 1
if i == n - 1:
cnt = max(cnt, temp)
break
k = i
j = i + 1
while j <= n - 1 and a[j] <= a[k]:
temp += 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 | # 800
for _ in range(int(input())):
count = 0
h, m = list(map(int, input().split()))
z = 24 - h
count += (60*z) - m
print(count) |
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colo... | 3 | t = int(input())
str = input()
if 'MM' in str or 'YY' in str or 'CC' in str:
print("No")
elif '??' in str or str[0] == '?' or str[-1] == '?' or 'M?M' in str or 'Y?Y' in str or 'C?C' in str:
print("Yes")
else:
print("No")
|
This is an easier version of the next problem. In this version, q = 0.
A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal.
Let's define difficulty of a sequence as a minimum possible num... | 3 | import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,_=kk()
ls = ll()
cnt, maxi = {}, {}
for i,l in enumerate(ls):
if l not in cnt: cnt[l]=0
... |
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | 3 | for s in [*open(0)][1:]:
n,a,b=map(int,s.split())
print(''.join(chr(97+i%b) for i in range(n))) |
In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.
The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.
Given a string S of length N and an integer k (k \geq 3), he defines the k-DMC number of S as the number o... | 3 | import sys
input = sys.stdin.readline
from collections import defaultdict
N = int(input())
S = input().strip()
Q = int(input())
K = list(map(int,input().split()))
'''
import random
import string
S = "".join(random.choices(string.ascii_uppercase, k=10**6))
Q =75
K = [random.randint(1,10**6) for i in range(Q)]
'''
for... |
<image>
Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's s... | 3 | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
impor... |
Jzzhu has a big rectangular chocolate bar that consists of n Γ m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:
* each cut should be straight (horizontal or vertical);
* each cut should go along edges of unit squares (it is prohibited to divide any unit choc... | 1 | import sys
#sys.stdin=open('data.in','r')
R=lambda:map(int,raw_input().split())
while True:
try:
n,m,k=R()
if k>n+m-2:
print -1
continue
k1=max(0,k+1-m)
k2=min(n-1,k)
C=lambda x:(int(n/(x+1))*int(m/(k-x+1)))
print max(C(k1),C(k2))
except:
... |
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | a=int(input())
ans=[]
for i in range(0,a):
b=input()
c=[int(x) for x in b.split()]
ans.append((c[0]+c[1]+c[2])//2)
for j in range(0,a):
print(ans[j])
|
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())
MAX=int(B/A)
print(min(MAX,C)) |
Recently, Norge found a string s = s_1 s_2 β¦ s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a β¦ b] = s_{a} s_{a + 1} β¦ s_{b} (1 β€ a β€ b β€ n). For e... | 3 | n,k=map(int,input().split())
s=input()
broken=[False]*26
for i in input().split():
broken[ord(i)-ord('a')]=True
ans,curr=0,0
def fun(n):
return (n*(n+1))//2
for i in s:
if not broken[ord(i)-ord('a')]:
ans+=fun(curr)
curr=0
else:
curr+=1
ans+=fun(curr)
print(ans) |
Imp likes his plush toy a lot.
<image>
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only on... | 3 | n=input().split()
x=int(n[0])
y=int(n[1])
needx=x-(y-1)
if y==1 and x==0:
print("Yes")
elif y==1 and x>0:
print("No")
elif (x==0 and y>1) or y==0:
print('No')
elif needx<0:
print("No")
elif needx==x:
print("Yes")
elif needx==0:
print("Yes")
else:
if needx%2 != 0 :
print("No... |
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 | # cook your dish here
for _ in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))
cntx=[0]*(2*k+1)
prefx=[0]*(2*k+2)
for i in range(n//2):
cntx[a[i]+a[n-i-1]]+=1
prefx[min(a[i],a[n-i-1])+1]+=1
prefx[max(a[i],a[n-i-1])+k+1]+=-1
ans=n
... |
You are given a string s consisting of n lowercase Latin letters. n is even.
For each position i (1 β€ i β€ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi... | 3 | T = int(input())
for _ in range(T):
N = int(input())
s = input()
for i in range(N//2):
if ord(s[i])-ord(s[N-i-1]) not in {0, 2, -2}:
print('NO')
break
else:
print('YES') |
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.
Input
Input contains one integer number n (1 β€ n β€ 3000).
Output
Output the amount ... | 3 | n=int(input())
s=0
l=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 31... |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 β€ i β€ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 | import math,sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda:int(input())
li = lambda:list(map(int,input().split()))
def solve():
n=I()
n=n+1
print(n//2)
for _ in range(I()):
solve() |
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | 1 | from collections import Counter
s = Counter(raw_input().strip())
c = sum(1 for i in s.values() if i % 2)
print "First" if c % 2 or not c else "Second" |
Write a program which computes the area of a shape represented by the following three lines:
$y = x^2$
$y = 0$
$x = 600$
It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles... | 3 | # coding: utf-8
# Your code here!
def seki(x):
a=[]
for i in range(600//x):
a.append((i*x)**2*x)
print(sum(a))
while 1:
try:
n=int(input())
except EOFError:
break
seki(n)
|
You are given two integers b and w. You have a chessboard of size 10^9 Γ 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white.
Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s... | 3 | for _ in range(int(input())):
b, w = tuple(map(int, input().split()))
if 3 * min(b, w) + 1 >= max(b, w):
print("YES")
nax, nin = max(b,w), min(b,w)
if b <= w:
startx, starty = 2, 3
else:
startx, starty = 2, 2
for i in range(2*nin - 1):
... |
This problem is given in two editions, which differ exclusively in the constraints on the number n.
You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 β€ l β€ r β€ n). Thus, a block is defined by a pair of indices (l, r).
Find a... | 3 | import sys
from collections import defaultdict
DBG = not True
n = int(input())
a = list(map(int, input().split()))
acc = [0] * (n+1) # a[-1]=0
for i in range(n):
acc[i] = acc[i-1] + a[i]
h = [defaultdict(int) for i in range(n)]
h[0][a[0]] = 1
for i in range(1,n):
h[i][acc[i]] = 1 # sum 0..i
for j in ra... |
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d... | 1 | import math
n = input();
name = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"];
m = int(math.log(n/5+1, 2));
n -= 5 * (2**m - 1);
print name[n/(2**m)-1] if n % (2**m) == 0 else name[n/(2**m)]
|
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan... | 3 | from timeit import default_timer as timer
from datetime import timedelta
def solve(s):
n = len(s)
cs = ['R', 'G', 'B']
res = ""
res_dist = int(1e8)
best = ""
for c1 in cs:
for c2 in cs:
if c1 == c2:
continue
for c3 in cs:
if c1 ==... |
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 | a = input()
print(' '.join([str(i-((i+1)%2)) for i in [int(a) for a in input().split()]])) |
You have decided to give an allowance to your child depending on the outcome of the game that he will play now.
The game is played as follows:
* There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a `+` printed on it.
* The player should constru... | 3 | *x,=map(int,input().split());print(sum(x)+max(x)*9) |
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | for _ in range(int(input())):
n,m=map(int,input().split())
if n%2==1 and m%2==1:
print(n//2*m+m//2+1)
elif (n%2==1 and m%2==0 ):
print(n//2*m+m//2)
elif m%2==1 and n%2==0:
print(m//2*n+n//2)
elif n%2==0 and m%2==0:
print(n//2*m)
|
The dice are placed in the orientation shown in the figure below.
<image>
As shown in this figure, the dice used here have 1 on the upper side and 2 on the south side, and 3 on the east side. Since the sum of the facing faces of the dice is always 7, the invisible faces are 5 on the north side, 4 on the west side, a... | 1 | class Dice:
def __init__(self):
self._top = 1
self._front = 2
self._side = 3
self._sum = 1
def to_north(self):
tmp = self._top
self._top = self._front
self._front = 7 - tmp
self._sum += self._top
def to_east(self):
tmp = self._top
... |
You are given a string S consisting of letters `b`, `d`, `p` and `q`. Determine whether S is a mirror string.
Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S:
1. Reverse the order of the characters in S.
2. Replace each occurrence of `b` by `d`, `d... | 3 | # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | n = input().split('+')
n.sort()
new = ""
for i in range(len(n)-1):
new = new + n[i] + "+"
new = new + n[len(n)-1]
print(new) |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | import math
for i in range(int(input())):
n=int(input())
hg=math.ceil(n/4)
s="9"*(n-hg)
s+="8"*hg
print(s)
|
You have array of n numbers a_{1}, a_{2}, β¦, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| β€ |a_{2} - a_{3}| β€ β¦ β€ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 3 | for i in range(int(input())):
N = int(input())
a = [int(x) for x in input().split()]
a.sort()
n = len(a)
while n:
print(a.pop(n // 2), end=" ")
n -= 1 |
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...
Lee has n integers a_1, a_2, β¦, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe... | 3 | import math as mt
import sys,string
input=sys.stdin.readline
#print=sys.stdout.write
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
from collections import defaultdict
t=I()
for _ in range(t):
n,k=M()
l=L()
w=L()
w... |
Petya loves computer games. Finally a game that he's been waiting for so long came out!
The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is... | 3 | n, k = map(int,input().split())
a = list(map(int,input().split()))
a.sort(key=lambda x: -(x % 10))
for i in range(n):
if a[i] % 10 == 0:
break
add = min(k, 10 - a[i] % 10)
a[i] += add
k -= add
for i in range(n):
add = min(k, 100 - a[i])
a[i] += add
k -= add
print(sum(x // 10 for x in a)) |
Xsquare got bored playing with the arrays all the time. Therefore he has decided to buy a string S consists of N lower case alphabets. Once he purchased the string, He starts formulating his own terminologies over his string S. Xsquare calls a string str A Balanced String if and only if the characters of the string str... | 1 | for t in range(input()):
s = raw_input()
n = [0 for _ in xrange(26)]
for ss in s:
n[ord(ss)-ord('a')] += 1
ok = True
for i in xrange(26):
if n[i]&1:
ok = False
break
if ok:
print 1
else:
print -1 |
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l... | 3 | z=int(input())
for i in range(z):
x=int(input())
s=str(input())
a=s.count('>')
b=s.count('<')
if(a==0 or b==0):
print(0)
else:
m=[]
if(s[0]=='<'):
for j in range(0,len(s)):
if(s[j]=='<'):
m.append(j)
else:
... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s = input()
uc_count = lc_count = 0
for char in s:
if char >= 'A' and char <= 'Z':
uc_count += 1
else:
lc_count += 1
if uc_count > lc_count: print(s.upper())
else: print(s.lower())
|
The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.
According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situat... | 3 | N, Y = map(int, input().split())
Y //= 1000
for i in range(N+1):
for j in range(N-i+1):
if 0<=Y-10*i-5*j==N-i-j:
print(i,j,N-i-j)
exit()
print(-1, -1, -1) |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | for _ in range(int(input())) :
a,b=map(int,input().split())
if a==b :
print(0)
else :
if a>b :
diff=a-b
else :
diff=b-a
cnt=0
if diff>10 :
cnt+=diff//10
diff=diff%10
if diff!=0 :
cnt+=1
print(... |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | n = int(input())
for _ in range(n):
a,b = map(int, input().split())
if a%b == 0:
print(0)
else:
print((a//b + 1)*b - a)
|
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should no... | 3 |
import collections
# 011011
# 11000
#
# 0:[]
# 1:[1,2]
def solve(lst):
stck=[]
lst=[int(i) for i in lst]
prev=-1
mx1,mx2=1,1
mps={0:[],1:[]}
for i in range(len(lst)):
if lst[i]:
if mps[lst[i]-1]:
p=mps[lst[i]-1].pop()
mps[lst[i]].append(p)
stck.append(p)
if mx1<p:
mx1=p
else:
i... |
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 Counter
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int,input().split()))
b = Counter(a)
b = list(b)
m = len(b)
rui = [[0]*m for i in range(n+2)]
for i in range(n):
for j in range(m):
if a[i] == b[j]:
... |
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | 3 | n=int(input())
ls=[int(x) for x in input().split()]
l=[int(x) for x in input().split()]
a=ls.count(1)
b=l.count(1)
d1=dict()
d2=dict()
c=0
for i in range(n):
if ls[i]==1:
d1[i]=1
if l[i]==1:
d2[i]=1
for i in range(n):
if i in d1 and i in d2:
c+=1
res=a-c
if res==0:
print(-1)
else... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | a = list(map(int,input().split()))
a.sort()
for i in range(3):
print(a[3]-a[i],end=' ') |
Given is a number sequence A of length N.
Find the number of integers i \left(1 \leq i \leq N\right) with the following property:
* For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_... | 3 | from collections import Counter
N=int(input());dp=[1]*(10**7);C=Counter(sorted(list(map(int,input().split()))));ans = 0
for a,b in C.items():
if b != 1:dp[a] = 0
elif dp[a]:ans += 1
for j in range(a,10**6+1,a):dp[j] = 0
print(ans) |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 1 | from __future__ import division
from collections import Counter as ctr
import math
def rl():
return [int(i) for i in raw_input().split()]
def rm():
n = input()
return [raw_input() for i in range(n)]
def rlm():
n = input()
return [rl() for i in range(n)]
s = raw_input()
c = ctr(s)
if len(c) % 2 == 1:
print "IGN... |
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of... | 1 | import sys
n = int(sys.stdin.readline())
firstTechs = []
secondTechs = []
flen = 0
slen = 0
lastTech = 'none'
for x in range(n):
tech = int(sys.stdin.readline())
if tech > 0:
firstTechs.append(tech)
flen += 1
lastTech = 'first'
else:
secondTechs.append(-tech)
slen... |
You are given a string S consisting of `0` and `1`. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into `0` by repeating the following operation some number of times.
* Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfi... | 3 | from itertools import groupby, accumulate
S = list(input())
n = len(S)
s = list(accumulate([len(list(j)) for i, j in groupby(S)]))
s = [max(i, n - i) for i in s]
print(min(s))
|
In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.
One day, there was an exam where a one-year-old child must write a program that prints `Hello World`, and a two-year-old child must write a program that receives integers A, B... | 3 | n=int(input())
if n-1:
print(int(input())+int(input()))
else:
print('Hello World') |
Snuke is making sugar water in a beaker. Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.
* Operation 1: Pour 100A grams of water into the beaker.
* Operation 2: Pour 100B grams of water into the beaker.... | 3 | a,b,c,d,e,f=map(int,input().split());ans,ma=[0]*2,0
for i in range(f//100+1):
if i%b==0 or i%a==0:
w=i*100
x=min(f-w,i*e)
s=0
for j in range(x//c+1):
ss=j*c
s=max(s,ss+((x-ss)//d)*d)
if w!=0:
if ma<=(100*s)/(w+s):ans=[w,s];ma=(100*s)/(w+s)
print(ans[0]+ans[1],ans[1]) |
Find the edit distance between given two words s1 and s2.
The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations:
* insertion: Insert a character at a particular position.
* deletion: Delete a character at a particular posi... | 3 | def main():
S = input()
T = input()
N = len(S)
M = len(T)
dp = [[0 for j in range(M+1)] for i in range(N+1)]
for i in range(N+1):
dp[i][0] = i
for j in range(M+1):
dp[0][j] = j
for i in range(N):
for j in range(M):
if S[i] == T[j]:
dp[... |
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 | for _ in range(int(input())):
n = int(input())
a = [int(i) for i in input().split()]
arr = {1:0, 2:0, 4:0, 8:0, 16:0, 32:0, 64:0, 128:0, 256:0, 512:0, 1024:0, 2048:0}
flag = 0
for i in a:
if i in arr:
arr[i] = arr[i]+1
temp = 1
while temp>0:
temp -= 1
for ... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | w = input()
we = int(w)
if we<=2: print("NO")
elif we%2==0:
print("YES")
else:
print("NO")
|
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and reverse specified elements by a list of the following operation:
* reverse($b, e$): reverse the order of $a_b, a_{b+1}, ..., a_{e-1}$
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i \leq 1,000,000,000$
* $1 \leq ... | 3 | input()
listnum = list(map(int, input().split()))
for i in range(int(input())):
eachq = list(map(int, input().split()))
newlist = listnum[eachq[0]:eachq[1]]
newlist.reverse()
listnum = listnum[:eachq[0]] + newlist + listnum[eachq[1]:]
print(" ".join(map(str, listnum)))
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | palavra = input()
minuscula = 0
maiuscula = 0
for letra in palavra:
if letra.islower():
minuscula += 1
else:
maiuscula += 1
print(palavra.lower()) if minuscula >= maiuscula else print(palavra.upper()) |
There is a frog staying to the left of the string s = s_1 s_2 β¦ s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ... | 3 | def solve(level):
ll = 0
index = 0
while(index < len(level)):
if level[index] == "R":
index += 1
else:
cll = 0
while(index < len(level) and level[index] != "R"):
cll += 1
index += 1
ll = max(ll,cll)
return l... |
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 β€ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ... | 3 | from sys import stdin
def main():
n = int(stdin.readline())
ar = list(map(int, stdin.readline().split()))
if n <= 2:
print(0)
else:
ans = 10 ** 18
find = False
for i in range(-1, 2):
for j in range(-1, 2):
ok = True
curr_ans =... |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 3 | #!/usr/bin/env python
import math
def main():
# Read input
i = input().split()
a = int( i[0] )
b = int( i[1] )
x = a
e = 0 # extra
while int(a/b + e) > 0:
t = (a/b + e)
e = t - int(t)
a = int(t)
x += a
print(x)
if __name__ == '__main__':... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | n,k = input().split(" ")
n = int(n)
k = int(k)
for i in range(k):
if(n % 10 != 0):
n = n-1
else:
n = n//10;
print(n) |
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 3 | n,t=map(int,input().split())
if t==10:
if n==1:
print("-1")
else:
for i in range(n-1):
print(t-1,end="")
print('0')
else:
for i in range(n):
print(t,end='')
|
Β«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 | from sys import stdin
input = stdin.readline
def dragon(k, l, m, n, d):
sieve = [0] * (d + 1)
sieve[k:d + 1:k] = [1] * (d // k)
sieve[l:d + 1:l] = [1] * (d // l)
sieve[m:d + 1:m] = [1] * (d // m)
sieve[n:d + 1:n] = [1] * (d // n)
return sum(sieve)
print(dragon(*(int(input()) for _ in 'drago')))
|
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.
The box's lock is constructed... | 1 | from itertools import permutations as p
def equivalent(s):
alts = []
ind = [[0,1,2,3,4,5],
[0,2,3,4,1,5],
[0,3,4,1,2,5],
[0,4,1,2,3,5],
[3,0,2,5,4,1],
[2,0,1,5,3,4],
[1,0,4,5,2,3],
[4,0,3,5,1,2],
[4,1,0,3,5,2],
... |
You have a long fence which consists of n sections. Unfortunately, it is not painted, so you decided to hire q painters to paint it. i-th painter will paint all sections x such that l_i β€ x β€ r_i.
Unfortunately, you are on a tight budget, so you may hire only q - 2 painters. Obviously, only painters you hire will do t... | 3 | # from sys import stdin
# def rl():
# return [int(w) for w in stdin.readline().split()]
from collections import defaultdict
# from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# l = list(map(int,input().split()))
n,q=map(int,input().split())
a=[list(map(int,input().split())) for _ in ran... |
There is a rectangular grid of n rows of m initially-white cells each.
Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and... | 3 | r,c = map(int, input().split())
grid = [input() for x in range(r)]
rows_checked = []
black_set = []
for i,row in enumerate(grid):
index_black = [x for x,c in enumerate(row) if c == '#']
black_set.append(index_black)
done = False
for b1 in black_set:
for b2 in black_set:
if b1 == b2: continue
... |
"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 | a, b = map(int, input().split(" "))
c = list(map(int, input().split(" ")))
d = c[b-1]
e = 0
for i in c:
if i >= d and i > 0:
e += 1
print(e) |
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the... | 1 | a,b,c = map(int, raw_input().split())
if c==0:
if a==b:
z=0
else:
z=-1
else:
z = (b-a)%(c)
#print z
if z==0:
if c==0 and a==b:
print 'YES'
elif c!=0 and (b-a)/c >=0:
print 'YES'
... |
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.
In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o... | 3 | a1, a2, a3, a4 = map(int, input().split())
c = input()
b = 0
for i in range(len(c)):
if c[i] == '1':
b += a1
elif c[i] == '2':
b += a2
elif c[i] == '3':
b += a3
else:
b += a4
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.