problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | s = list(input())
s[0] = s[0].upper()
for k in range(0,len(s)):
print(s[k],end='') |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | for _ in range(int(input())):
n = input()
if len(n)>10:
l =len(n)-2
n=n[0]+str(l)+n[-1:]
print(n) |
The Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6.
The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i.
The compan... | 3 | import sys
def schedule(a, n):
if n % 2:
return []
office = set()
used = set()
ans = []
dayStart = -1
dayEnd = -1
for i, e in enumerate(a):
if e < 0:
e = -e
if e not in office:
return []
else:
office.remove... |
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in l... | 1 | from string import ascii_lowercase
class Graph:
def __init__(self, vertex):
self.v = vertex
self.adj = {}
self.parents = {}
self.visited = {}
for i in ascii_lowercase:
self.adj[i] = []
self.parents[i] = 0
self.visited[i] = False
def a... |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. W... | 3 | N, T = map(int, input().split())
S = input()
a = 0
b = 0
r = 0
l = 0
mx = 0
while (r < N):
if S[r] == 'a':
mx = max(mx, r - l + 1)
else:
b += 1
if b <= T:
mx = max(mx, r - l + 1)
while (b > T):
if S[l] == 'b':
b -= 1
l += 1
r += 1
a = 0
b = 0
r = 0... |
Eshag has an array a consisting of n integers.
Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.
For example, if a = [1 , 4 , 3 , 2 , 4] and ... | 1 | from sys import stdin
def gcd(a,b):
if a==0:
return b
if b==0:
return a
while a%b:
t=a%b
a=b
b=t
return b
t = int(stdin.readline())
#t = 1
for _ in xrange(t):
n= int(stdin.readline())
#n,m = map(int,stdin.readline().split())
a = map(int,stdin.readline(... |
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | a= int(input())
b= list(map(int,input().split()))
dict={}
point1= 0
point2= b[0]
for k in b:
if k not in dict:
dict[k] = 1
else:
dict[k] += 1
if dict[k] > point1:
point1= dict[k]
point2= k
first= k
print(point1)
|
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | 3 | t = int(input())
for i in range(t):
n = int(input())
a, b = 0 , 0
for i in range(1, n // 2):
a += 2 ** i
for i in range(n // 2, n ):
b += 2 ** i
a += 2 ** n
print(a - b)
|
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they ma... | 3 | m, l = map(int, input().split())
a = list(map(int, input().split()))
print(max(i * sum(ai // i for ai in a) for i in range(l, 101))) |
Mike lost in a coding contest just because he was not aware with the concept of palindrome properly.
So finally he learnt about it and decided to mess up with the Winners name of the contest as he will now meddle with letters of their names.
He will change all the names into palindrome and will follow these rules:
-We... | 1 | t = int(raw_input())
for cases in range(t):
s = list(raw_input())
units = 0
l = len(s)
for i in range(int(l - l/2)):
units += abs(ord(s[i]) - ord(s[l- i - 1]))
print units |
You are given array a of length n. You can choose one segment [l, r] (1 ≤ l ≤ r ≤ n) and integer value k (positive, negative or even zero) and change a_l, a_{l + 1}, ..., a_r by k each (i.e. a_i := a_i + k for each l ≤ i ≤ r).
What is the maximum possible number of elements with value c that can be obtained after one ... | 3 | # Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
def main():
n,c=map(int,input().split())
a=list(map(int,input().split()))
ma,dp=max(a)+1,[0]*(n+1)
b=[[] for _ in range(ma+1)]
for i,v in enumerate(a):
b[v].append(i)
d... |
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t... | 1 | #encoding:utf-8
class Rookie(object):
def _input(self):
l1 = raw_input()
l2 = raw_input()
n = int(l1.strip())
a = l2.strip().split(' ')
a = [int(_) for _ in a]
return n,a
def _output(self):
print self.r
def solve(self):
n, a = self._input()... |
Description
THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month.
This game is a game in which members of the unit (formation) t... | 1 | while 1:
try:
N,M = map(int,raw_input().split())
dp = [[0]*(M+1) for i in range(3)]
for _ in range(N):
name = raw_input()
C,V,D,L = map(int,raw_input().split())
VDL = [V,D,L]
for i in range(3):
try: dp[i][C] = max(dp[i][C],VDL[i])
except: pass
for j in range(M):
if dp[i][j]:
tr... |
There are N blocks arranged in a row, numbered 1 to N from left to right. Each block has a weight, and the weight of Block i is A_i. Snuke will perform the following operation on these blocks N times:
* Choose one block that is still not removed, and remove it. The cost of this operation is the sum of the weights of t... | 3 | N=int(input())
A=[int(i) for i in input().split()]
P=10**9+7
def egcd(a, b):
(x, lastx) = (0, 1)
(y, lasty) = (1, 0)
while b != 0:
q = a // b
(a, b) = (b, a % b)
(x, lastx) = (lastx - q * x, x)
(y, lasty) = (lasty - q * y, y)
return (lastx, lasty, a)
def inv(x):
retur... |
Takahashi wants to be a member of some web service.
He tried to register himself with the ID S, which turned out to be already used by another user.
Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.
He is now trying to register with the ID T. Determine whether... | 3 | s=input()
k=input()
if(k[0:-1]==s):
print("Yes")
else:
print("No")
|
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 | a,b=map(int,input("").split())
print(a+(a-1)//(b-1)) |
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on).
There are lanterns on the... | 3 | if __name__ == "__main__":
T = int(input())
for t in range(T):
L, v, l, r = map(int, input().split())
print(L//v-r//v+(l-1)//v)
|
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 | n=int(input())
a=list(map(int,input().split()))
for i in range(n):
if a[i]%2==0:
a[i]=a[i]-1
for i in range(n):
print(a[i],end=' ') |
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=lambda:map(int,raw_input().split())
a,b,s=l()
def judge():
if a==0 and b==0:
if s%2==0:
print 'Yes'
else:
print 'No'
return
if s>=abs(a)+abs(b) and (s-abs(a)-abs(b))%2==0:
print 'Yes'
else:
print 'No'
judge() |
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls.
In one operation, you can select a ball i to charge it. Once charged, all ba... | 3 | for _ in range(int(input())):
n, r = [int(i) for i in input().split()]
balls = []
z = False
for _ in range(n):
balls.append([int(i) for i in input().split()])
for i in balls:
if max([abs(i[0] - j[0]) + abs(i[1] - j[1]) for j in balls]) <= r:
print(1)
z = True
... |
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch... | 1 | from __future__ import division, print_function
# import threading
# threading.stack_size(2**27)
import sys
sys.setrecursionlimit(10**4)
# sys.stdin = open('inpy.txt', 'r')
# sys.stdout = open('outpy.txt', 'w')
from sys import stdin, stdout
import bisect #c++ upperbound
import math
import heapq
i_m=922337203... |
Ringo is giving a present to Snuke.
Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things.
You are given a string S representing the Japanese name of ... | 3 | a = input()
if a[:4] == 'YAKI':
print('Yes')
else:
print('No') |
Snuke has one biscuit and zero Japanese yen (the currency) in his pocket. He will perform the following operations exactly K times in total, in the order he likes:
* Hit his pocket, which magically increases the number of biscuits by one.
* Exchange A biscuits to 1 yen.
* Exchange 1 yen to B biscuits.
Find the maxi... | 3 | K,A,B = map(int,input().split())
if A + 2 < B:
K2 = K - A + 1
print( K2 // 2 * ( B - A ) + K2 % 2 + A)
else:
print( 1 + K )
|
There is a beautiful garden of stones in Innopolis.
Its most beautiful place is the n piles with stones numbered from 1 to n.
EJOI participants have visited this place twice.
When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ... | 3 | n=int(input())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
a=0
b=0
i=0
while i<n:
a+=x[i]
b+=y[i]
i+=1
if a>=b:
print ('Yes')
else:
print ('No') |
Given a set of integers (it can contain equal elements).
You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).
Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:
* m... | 3 | def algo(n, arr):
arr.sort()
temp = [0 for _ in range(arr[-1]+1)]
for i in range(n):
temp[arr[i]] += 1
t1 = 0
for i in range(len(temp)):
if temp[i] == 0:
t1 = i
break
else:
t1 = len(temp)
t2 = 0
for i in range(len(temp)):
if temp[... |
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that:
1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'.
2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s... | 3 | MODULO = 1000000007
s = input()
t = ''
bEncouter = False
aCounter = 0
bCounter = 0
for c in s:
if c == 'a':
t += 'a'
bEncouter = False
aCounter += 1
elif c == 'b':
if not bEncouter:
t += 'b'
bEncouter = True
bCounter += 1
if aCounter > 0 an... |
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | 3 | R = lambda :list(map(int,input().split()))
m = int(input())
n = m*2
l = R()
s = 0
i = 0
test = 0
while(i<n):
for j in range(i+1,n) :
if l[j] == l[i] :
if (j-i-1) >0 :
s += (j-i-1)
l = l[0:i+1] + [l[i]] + l[i+1:j] + l[j+1:]
i += 2
test = 1
else :
i += 2
test = 1
break
if test == 0 :... |
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in... | 3 | n,v=[int(x) for x in input().split()]
if v>=(n-1):
print(n-1)
else:
print(int((((n-v)*(n-v+1))/2)-1+v))
|
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'... | 3 | n,m = map(int, input().split())
mat = [[0] * m for i in range(n)]
for i in range(n):
temp = input()
for j in range(m):
mat[i][j] = temp[j]
flag = False
for i in range(1, n, 1):
if mat[i][0] == mat[i - 1][0]:
flag = True
for i in range(n):
for j in range(1, m, 1):
if mat[i][j] != ... |
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an... | 3 |
n = int(input())
squares = [int(x) for x in input().split(" ")]
ladoA = 0
ladoB = sum(squares)
c = 0
for i in range(n-1):
ladoA += squares[i]
ladoB -= squares[i]
if ladoA == ladoB:
c +=1
print(c) |
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input
The single line contains two space separated i... | 3 | n,m=map(int, input().split())
kol= (n+1) // 2
for i in range(kol,n+1):
if i%m==0:
print(i)
break
else:
print(-1)
|
Our Chef is catering for a big corporate office party and is busy preparing different mouth watering dishes. The host has insisted that he serves his delicious cupcakes for dessert.
On the day of the party, the Chef was over-seeing all the food arrangements as well, ensuring that every item was in its designated posi... | 1 | import math
def isprime(n):
i = 2;
while(i * i <= n):
if(n % i == 0): return 0;
i += 1;
return 1;
t = input();
while(t > 0):
n = input();
if(isprime(n) == 1): print n - 1;
else:
i = int(math.sqrt(n));
if(n % i != 0):
i -= 1;
while(n % i != 0): i -= 1;
print (n / i) - i;
t -= 1; |
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow... | 3 | account_balance = input()
def solve():
if account_balance[0] != '-':
return account_balance
if int(account_balance[-1]) > int(account_balance[-2]):
good_bal = account_balance[0:-1]
else:
good_bal = account_balance[0:-2]+account_balance[-1]
return 0 if good_bal == '-0' else go... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | num = int(input())
who_to_whom = []
from_whom = []
str = input()
who_to_whom = str.split()
for i in range(num):
from_whom.append(0)
for j in range(num):
index = int(who_to_whom[j])
from_whom[index-1] = int(j+1)
for i in from_whom:
print(i,end=' ')
'''
4
2 3 4 1
4 1 2 3
3
1 3 2
1 3 2
2
1 2
1 2
... |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | q= int(input())
w=list(map(int,input().split()))[1::]
e=list(map(int,input().split()))[1::]
r=list(set(w+e))
if len(r)==q:
print('I become the guy.')
else:
print( "Oh, my keyboard!") |
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 | x=int(input())
if x<3 or x>100 :
print("no")
elif x%2==0:
print("yes")
else:
print("no") |
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an ... | 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... |
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end.
To achieve this, you will:
* Choose m such that 1 ≤ m ≤ 1000
* Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ... | 3 | for tetscase in range(int(input())):
n=int(input())
print(n)
for i in range(1,n+1):
print(i,end=" ")
print() |
«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,l,m,n,d,c = int(input()),int(input()),int(input()),int(input()),int(input()),0
for i in range(1,d+1):
if i%k==0: c+=1
elif i%l==0: c+=1
elif i%m==0: c+=1
elif i%n==0: c+=1
print(c)
|
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their... | 3 | k=int(input())
a,b=[int(f)for f in input()],[int(f)for f in input()]
b=list(sorted(b))
f,u=[],[]
t=list(b)
g=0
for x in a:
for y in t:
if y>=x:
t.remove(y)
break
i=list(b)
for x in a:
o=True
for y in i:
if y>x:
o=False
i.remove(y)
g... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 1 | s = raw_input()
tokens = s.split()
n = int(tokens[0])
m = int(tokens[1])
a = int(tokens[2])
ans1 = n//a
if n%a != 0:
ans1 += 1
ans2 = m//a
if m%a != 0:
ans2 += 1
print ans1*ans2
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | '''
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go t... |
A sequence a = [a_1, a_2, …, a_l] of length l has an ascent if there exists a pair of indices (i, j) such that 1 ≤ i < j ≤ l and a_i < a_j. For example, the sequence [0, 2, 0, 2, 0] has an ascent because of the pair (1, 4), but the sequence [4, 3, 3, 3, 1] doesn't have an ascent.
Let's call a concatenation of sequence... | 3 | from bisect import *
n = int(input())
low = []
high = []
ans = 0
e = 0
c = 0
for _ in range(n):
t = list(map(int, input().split()))
s = t[0]
a = t[1:]
if a == sorted(a, reverse=True):
low.append(a[s - 1])
high.append(a[0])
e += 1
else:
ans += 2*n - 1 - 2*c
c +... |
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.
LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
O... | 3 | from math import gcd
def lcm(a,b):
return a*b // gcd(a,b)
n = int(input())
inf = 9999999999999
a,b = inf,inf
if n==1:
print(1,1)
exit()
for i in range(1,int(n**0.5)+1):
if n%i==0 and max(a,b) > max(i,n//i) and lcm(i,n//i)==n:
a = n//i
b = i
print(a,b)
|
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the... | 3 | n = int(input())
a = input().split()
m = 0
for i in range (n):
m+=abs(int(a[i]))
print(m)
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 12:20:55 2020
@author: shr
"""
n,k = list(map(int,input().split()))
ans=0
ar = list(map(int,input().split()))
for i in range(n):
if 5-ar[i]>= k :
ans +=1
if(ans<3):
print(0)
else:
print(int(ans/3))
|
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$
Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes.
Your task is calculate a_{K} for given a_{1} and K.
Input
The ... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 6 10:54:15 2020
@author: Harshal
"""
test=int(input())
dic={}
for _ in range(test):
n,k=map(int,input().split())
for i in range(min(k-1,1000)):
a=int(max(str(n)))
b=int(min(str(n)))
n+=(a*b)
print(n)
|
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction ... | 3 | import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
n = int(input())
while n:
n += -1
p, q, b = map(int, inp... |
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his messa... | 3 | n, k, m = map(int, input().strip().split())
a = input().strip().split()
p = list(map(int, input().strip().split()))
priceTable = {}
for i in range(n):
priceTable[a[i]] = p[i]
for i in range(k):
line = list(map(int, input().split()))
x = line[0]
indices = line[1:]
if (x > 1):
minPrice = min... |
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract 1 from it.
In particular, we can apply this operation to the same number several times.
We want to make the product of all these numbers equal to 1, in other wo... | 3 | n=int(input())
a=sorted(list(map(int,input().split())))
product=1
cost=0
for i in range(n-1):
if a[i]<=-1:
cost+=-1-a[i]
product*=-1
elif a[i]>=1:
cost+=a[i]-1
product*=1
else:
cost+=1
product=1
if a[n-1]<=-1:
if product==-1:
cost+=-1-a[n-1]
el... |
This is an easier version of the problem. In this version n ≤ 1000
The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ... | 3 | import collections
n = int(input())
m = [int(num) for num in input().split()]
rightlessque = collections.deque([])
indrightless = [n]*n
for i in range(n):
while rightlessque and m[i]<m[rightlessque[0]]:
indrightless[rightlessque.popleft()] = i
rightlessque.appendleft(i)
leftlessque = collections.deque([])
indleftl... |
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible... | 3 | n=int(input())
a=list(map(int,input().split()))
b=max(a)
c=min(a)
a.remove(b)
a.remove(c)
if len(a)==0:
print(0)
elif(max(a)-c<b-min(a)):
print(max(a)-c)
else:
print(b-min(a))
|
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | 3 | '''
* Author : Ayushman Chahar #
* About : II Year, IT Undergrad #
* Insti : VIT, Vellore #
'''
import os
import sys
from collections import Counter
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.b... |
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 | l = ['a', 'o', 'y', 'e', 'u', 'i']
s = input().lower()
print('.' + '.'.join([i for i in s if i not in l])) |
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.
The classroom contains n rows of seats ... | 3 | import sys
input = sys.stdin.readline
n, m, k = map(int, input().rstrip().split())
M = [input() for _ in range(n)]
ans = 0
for row in M:
run = 0
for ch in row:
if ch == '.':
run += 1
else:
ans += max(0, run - k+1)
run = 0
ans += max(0, run-k+1)
if k != 1... |
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?
Constraints
* 2 \leq N \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
3
Output
3
Input
100
... | 3 | N=int(input())
c=0
for i in range(1,N+1):
d=(N-1)//i
c+=d
print(c) |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | t = int(input())
for i in range(t):
a, b, c, d, k = map(int, input().split())
i = int(a // c)
j = int(b // d)
if a % c != 0:
i += 1
if b % d != 0:
j += 1
if i + j <= k:
print(i, j)
else:
print('-1') |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 1 | def isPrime(n):
if n==2:
return True
for i in range(2,n):
if n%i==0:
return False
if i*i>n:
break
return True
n,m=map(int,raw_input().split())
if not isPrime(m):
print('NO')
else:
exist=False
for i in range(n+1,m):
if isPrime(i):
... |
An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, …, a_r for some l, r.
Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example:
* ... | 1 | n,m,k=map(int,raw_input().split())
a=map(int,raw_input().split())
p=list(enumerate(a,1))
p=sorted(p,key = lambda x:-x[1])
z=m*k
p=p[:z]
s=0
p=sorted(p)
#print p
ans=[]
for i in range(len(p)):
if i%m==m-1:
ans.append(p[i][0])
s+=p[i][1]
print s
#print ans
for i in ans[:len(ans)-1]:
print i, |
You are given an array of n integers a_1,a_2,...,a_n.
You have to create an array of n integers b_1,b_2,...,b_n such that:
* The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_... | 3 | t = int(input())
while t:
t-= 1
n = int(input())
arr= [int(x) for x in input().split()]
summ = sum(arr)
if summ == 0:
print("NO")
elif summ > 0:
print("YES")
arr.sort(reverse =True)
print(*arr)
else:
print("YES")
arr.sort()
print(*ar... |
One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.
The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targ... | 1 | import math
d = lambda t1, t2: math.hypot(t1[0] - t2[0], t1[1] - t2[1])
n = int(raw_input())
targets = []
for i in range(n):
targets.append(map(float, raw_input().split()))
targets.sort(key=lambda t: t[2])
exp = [t[3] for t in targets]
for i in range(1, n):
for j in range(i):
if d(targets[i], targets[j]) > tar... |
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means... | 3 | n = int(input())
a = []
for _ in range(n):
a.append(int(input()))
r = 0
for i in range(len(a)):
if a[i] % 2 == 0:
a[i] = a[i]/2
else:
if r == 0:
a[i] = a[i] / 2 - 0.5
r = 1
else:
a[i] = a[i] / 2 + 0.5
r = 0
print(int(a[i]))
|
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | class CodeforcesTask454ASolution:
def __init__(self):
self.result = ''
self.n = 0
def read_input(self):
self.n = int(input())
def process_task(self):
g = self.n // 2
p = -1
x = 0
result = []
while x < self.n:
result.append("*" * g... |
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())
# print(num+10)
count=0
while num>0:
str = input()
if "Tetrahedron" in str:
count+=4
elif "Cube" in str:
count+=6
elif "Octahedron" in str:
count+=8
elif "Dodecahedron" in str:
count+=12
elif "Icosahedron" in str:
count+=20
num=num-... |
Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.
A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebr... | 3 | n = int(input())
if n != 1 :
array = [1 for k in range(n+1)]
array[1] = 1
array[2] = 2
sumi = 3
for k in range(3,n+1) :
array[k] = array[k-1] + array[k-2] %int(1e9 +7)
sumi += array[k] %int(1e9 +7)
print(sumi %int(1e9 +7))
else :
print(1) |
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.
There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti... | 3 | import math
def main():
n,b=map(int,input().split())
arr=[int(x) for x in input().split()]
costs=[]
count=0
o=e=0
for i in range(len(arr)):
if o==e and (o!=0 and e!=0):
cost=abs(arr[i]-arr[i-1])
costs.append(cost)
if arr[i]%2==1:
o+=1
else:
e+=1
costs.sort()
for i in costs:
if b-i>=0:
b-=... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | a=0
for i in range(int(input())):
b=input()
if b=='++x' or b=='x++' or b == '++X' or b == 'X++' :
a+=1
else:
a-=1
print(a) |
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | n,k=map(int,input().split())
y=[int(i) for i in input().split()]
s=5-k
t=0
for i in y:
if i<=s:
t+=1
print(t//3)
|
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with... | 3 | n = int(input())
mas=[]
for i in range(n):
mas.append(list(map(int,input().split(" "))))
res=[]
for i in range(n):
if mas[i][2]>=0:
res.append(str(i+1))
d=0
col=0
for j in range(i+1,n):
if mas[j][2]>=0:
mas[j][2]-=(d+ max(0,mas[i][0]-col))
... |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | def get_seq(n,s):
L = []
for i in range(n):
if s[i]=='(':
L.append(1)
else:
L.append(-1)
i = 0
a = 0
b = 0
count = 0
while i<n:
if L[i]==1:
a+=1
elif L[i]==-1:
b+=1
if b>a:
L.pop(i)
L.append(-1)
b = b - 1
count+=1
else:
i = i + 1
return count
t = int(input())
for _ in ran... |
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S:
* its elements were distinct integers from 1 to limit;
* the value of <ima... | 1 | #coding: utf-8
soma,limite = map(int,raw_input().split())
lista = []
auxiliar = []
for i in range(1,limite + 1):
lista.append((i&-i,i))
lista.sort()
while lista:
m,n = lista.pop()
if soma >= m:
soma -= m
auxiliar += [str(n)]
if soma:
print -1
else:
print len(auxiliar)
string = " ".join(auxiliar)
p... |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | n = int(input())
if n == 2:
print(4)
elif n == 1:
print(3)
elif n % 2:
print(1)
else:
for i in range(3, 37, 2):
k = n % i
if not k:
pass
else:
for j in range(1, i + 1):
if not (n * j + 1) % i:
print(j)
... |
Every great chef knows that lucky numbers are positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Our chef has recently returned from the Lucky country. He observed that every restaurant in the Lucky country had a luc... | 1 | t = int(raw_input())
for j in xrange(t):
n = int(raw_input())
flag = False
i = n/7
while not i < 0:
if ((n-(7*i))%4) == 0:
print 7*i
flag = True
break
else:
i = i - 1
if not flag:
print -1 |
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | 3 | def bubble_sort(l):
for i in range(len(l) - 1):
for j in range(len(l) - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
return l
def main_function():
n = int(input())
output_str = ""
output_list = []
for i in range(1, 500):
for j in str(i... |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 3 | from sys import stdin,stdout
import bisect
import math
from collections import deque,Counter
mod=10**9 +7
def st():
return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def li():
return list(map(int,stdin.readline().split()))
def mp():
return map(int,stdin.readline().s... |
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u... | 1 | from itertools import *
input()
k = raw_input().split()
size = 500000
for i in xrange( len(k) ):
if abs(int(k[i])-int(k[i-1])) < size:
size = abs(int(k[i])-int(k[i-1]))
c1 = i
c2 = i+1
if c1 == 0:
c1 = len(k)
print c1, c2
|
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on).
There are lanterns on the... | 3 | import math
res=[]
t=int(input())
for x in range(t):
L,v,l,r=map(int,input().split())
res.append((L//v)-(r//v)+((l-1)//v))
for x in res:
print(x)
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | n=int(input())
flag=True
while(flag==True):
n=n+1
check=list(str(n))
check=list(set(check))
if len(check)==4:
flag=False
print(n) |
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A1440... | 3 | a=input()
a = a[1:7]
if int(a) % 2 == 0:
print(0)
else:
print(1)
|
There are N apple trees in a row. People say that one of them will bear golden apples.
We want to deploy some number of inspectors so that each of these trees will be inspected.
Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector ... | 3 | N, D = [int(i) for i in input().split()]
print(-(-N // (2 * D + 1))) |
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
... | 3 | import sys
n = int(sys.stdin.readline())
mxX = 0
mxY = 0
for i in range(n):
inp = str(sys.stdin.readline()).split()
s = inp[0]
x = int(inp[1])
y = int(inp[2])
if s=='+':
if x<y:
x,y = y,x
if x>mxX:
mxX = x
if y>mxY:
mxY = y ... |
You are given two n × m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly... | 1 | n, m = map(int, raw_input().split())
A = [map(int, raw_input().split()) for _ in xrange(n)]
B = [map(int, raw_input().split()) for _ in xrange(n)]
for i in xrange(n):
for j in xrange(m):
A[i][j], B[i][j] = max(A[i][j], B[i][j]), min(A[i][j], B[i][j])
def check(A):
for i in xrange(n):
for j in xrange(1, m):
i... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | import math
t = int(input())
for _ in range(t):
a,b = map(int,input().split())
x = abs(a-b)
r = math.ceil(x/10)
print(r) |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 1 | n,a=int(input()),sorted(map(float,raw_input().split()))
print sum(a)/(n)
|
Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.
First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.
Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of que... | 3 | def main():
n, q = input().split()
n = int(n)
q = int(q)
nums = [i for i in range(n)]
rank = [0 for i in range(n)]
def find_top(x):
if (nums[x] != x):
nums[x] = find_top(nums[x])
return nums[x]
def unite(x, y):
x = find_top(x)
y = find_top(y)
... |
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.
Help Pasha count the maximum number he can get if he has the time to make at most k sw... | 1 | s, k = raw_input().split()
S = [s[i] for i in range(len(s))]
k = int(k)
z = 0
res = ''
while z < len(S) and k > 0:
i = z
r = S[z]
x = z
while i < len(S) and i - z <= k:
if ord(S[i]) > ord(r):
r = S[i]
x = i
i += 1
k -= x - z
for i in range(x - 1, z - 1, -1... |
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.
It is allowed to leave a as it is.
Input
The first line contains integer a (1 ≤ a ≤ 1018). The second line contains i... | 3 | def main():
a = list(input(""))
b = input("")
a.sort()
a.reverse()
maxNumber = ""
if len(a) < len(str(b)):
for num in a:
maxNumber += num
else:
maxNumber = fillInDigit(a,b,[],"")
print(maxNumber)
def fillInDigit(num1, num2, usedDigits, currentMaxNumber):
... |
You have a bag of size n. Also you have m boxes. The size of i-th box is a_i, where each a_i is an integer non-negative power of two.
You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.
For example, if n = 10 and a = [1, 1, 32] then you have to divide the box of size 32 into tw... | 3 | for _ in range(int(input())):
n, m = map(int, input().split())
boxes = list(map(int, input().split()))
if sum(boxes) < n:
print(-1)
continue
needed = [0] * 60
got = [0] * 60
for b in boxes:
got[b.bit_length() - 1] += 1
divisions = 0
for bit in range(60):... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | 3 | t=int(input())
while (t>0):
t=t-1
s=input()
l=0
a=[]
i=0
while (i<len(s)):
if (s[i]=='1'):
k=0
while (s[i]=='1' and i<len(s)-1):
i+=1
k+=1
a.append(k)
if (i>=len(s)):
break
... |
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the secon... | 3 | x=int(input())
y = list(map(int, input().split(' ')))
y.sort()
c = y[0]
add = 0
for i in range(1, x):
if y[i] > c:
c = y[i]
else:
c = c + 1
add += c - y[i]
print(add) |
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 | def intergise(list,y):
for num in list:
y.append(int(num))
y = y.sort()
return y
y = []
ans = []
x = input().split('+')
intergise(x,y)
for number in y:
ans.append(number)
ans.append('+')
ans.pop()
print("".join(map(str,ans))) |
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 | import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def watermelon():
weight = inp()
a = 'NO'
for i in range(we... |
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | 3 | def main():
n = int(input())
print('123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128... |
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of... | 1 | r = lambda: map(int, raw_input().split())
n, m, a, b = r()
if b < a * m:
print n / m * b + min(n % m * a, b)
else:
print a * n |
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | 1 | n=input("")
for i in range(n):
k=input()
a=0
b=0
p=list(map(int,raw_input().split()))
for j in range(k):
if j%2==0 and p[j]%2==1:
a+=1
if j%2==1 and p[j]%2==0:
b+=1
if a==b:
print a
else:
print -1
|
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | def sum1(n): # 求一个数各位数的和
l = len(n)
sum = 0
for i in range(l):
if (n[i] != 'b'): # 兼容二进制
sum += int(n[i])
return sum
n = int(input())
for i in range(n):
num = int(input())
bnum = bin(num)
count3 = 0
while 1:
if num % 3 == 0:
num /= 3
... |
Polycarp has an array a consisting of n integers.
He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its... | 3 | def delete(array, f):
for j in range(len(array)):
if f == 0: #even
for k in range(len(array)):
if array[k]%2 != 0:
array.remove(array[k])
f = 1
break
else: #odd
for k in range(len(array)):
... |
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_... | 3 | s=input()
a=[]
for i in range(len(s)):
a.append(s[i])
x=list(reversed(a))
if x==a:
b=[]
b=list(a)
b.pop()
x=list(reversed(b))
if x==b:
print(0)
else:
print(len(b))
else:
print(len(a)) |
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty... | 3 | I = lambda: map(int, input().split())
t, k = I()
w = [1] + [0 for i in range(100001)]
for i in range(1, 100002):
w[i] = (w[i-1] + (w[i-k] if i>k else 0))%1000000007
l = [0]
for i in w:
l.append((l[-1]+i)%1000000007)
tc = [I() for i in range(t)]
for a, b in tc:
print((l[b+2]-l[a+1])%1000000007)
|
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 | number_of_games = int(input())
results = input()
anton_record = 0
danik_record = 0
for letter in results:
if letter == 'A':
anton_record = anton_record + 1
elif letter == 'D':
danik_record = danik_record + 1
if anton_record > danik_record:
print('Anton')
elif anton_record < danik_record:
print('Danik')
else:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.