problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | t = int(input())
for _ in range(t):
n, r = [int(i) for i in input().split()]
if n > r:
print(int((r * (r + 1)) >> 1))
else:
print(int(((n - 1) * ((n - 1) + 1)) >> 1) + 1)
|
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.
The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t... | 3 | numsushi = int(input())
sushi = list(map(int, input().split(' ')))
count = 1
sequence = []
ans = 0
for i in range(numsushi - 1):
if sushi[i] == sushi[i + 1]:
count += 1
else:
sequence.append(count)
count = 1
sequence.append(count)
for i in range(len(sequence) - 1):
ans = max(ans, m... |
Ashishgup and FastestFinger play a game.
They start with a number n and play in turns. In each turn, a player can make any one of the following moves:
* Divide n by any of its odd divisors greater than 1.
* Subtract 1 from n if n is greater than 1.
Divisors of a number include the number itself.
The player... | 3 | t = int(input())
while t:
n = int(input())
if n == 1:
print("FastestFinger")
elif n == 2 or n & 1:
print("Ashishgup")
else:
i = 3
flag = 0
while i * i <= n:
if n % i == 0 and (i % 2 == 1 or ((n / i) % 2 == 1)):
flag = 1
... |
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve... | 3 | a= int(input())
dict={}
for k in range(a):
b= input()
if b not in dict:
dict[b]= 1
else:
dict[b] += 1
dict= sorted(dict.items(), key = lambda kv:(kv[1], kv[0]),reverse=True)
print(dict[0][0])
|
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | 3 | N=int(input())
S=input()
A=[]
for i in S:
A.append(chr((ord(i)-ord('A')+N)%26+ord('A')))
print("".join(A)) |
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.
Amr asked for your help ... | 1 | n,m = map(int,raw_input().split())
class node:
v=0
seq=0
picked=0
a = [node() for i in range(105)]
b = map(int,raw_input().split())
for i in range(len(b)):
a[i].v=b[i]
a[i].seq=i
a[:n]=sorted(a[:n],key=lambda i:i.v)
num=0
for i in range(n):
if(m-a[i].v>=0):
m-=a[i].v
a[i].picked=1
num+=1
a[:n]=sorted(a[:n],... |
We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.
How many grams of sand will the upper bulb contains after t seconds?
Constraints
* 1≤X≤10^9
* 1≤t≤10^9
* X and t are integers.
Input
The input ... | 3 | X, t = map(int, input().split())
res = max(0, X-t)
print(res) |
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ... | 3 | import math as ma
n,m=map(int,input().split())
if n<ma.ceil(m/2)-1 or n>m+1:
print(-1)
else:
ans=''
while(m!=n and n!=m+1 and n>0 and m>0):
ans=ans+'110'
m-=2
n-=1
while(m>0 and n>0):
ans=ans+'10'
m-=1
n-=1
if m>0:
for i in range(m):
... |
You are given an array a consisting of n integers.
Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.
For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 ... | 3 | from sys import stdin
input=stdin.readline
from math import gcd
from math import sqrt
def countDivisors(n) :
cnt = 0
for i in range(1, (int(sqrt(n)) + 1)) :
if (n % i == 0) :
# If divisors are equal,
# count only one
if (n / i == i) :
... |
You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.
2. Skip exactly x minutes of the movi... | 3 | class Player:
def __init__(self, x):
self.skip_val = x
self.cur_pos = 1
self.watched = 0
def play_minute(self):
self.cur_pos += 1
self.watched += 1
def skip(self):
self.cur_pos += self.skip_val
def main():
n, x = map(int, input().sp... |
Two players play a game.
Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t... | 3 | n = int(input())
numbers = [int(i) for i in input().split(" ")]
i=0
while len(numbers)!=1:
numbers.remove(max(numbers))
if len(numbers)==1:
print(numbers[0])
exit()
numbers.remove(min(numbers))
print(numbers[0]) |
Input
The input contains a single integer a (0 ≤ a ≤ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 1 | print [0,4,22,27,58,85,94,121,166,202,265,274,319,346,355,378,382,391,438,454,483,517,526,535,562,576,588,627,634,636,645][input()] |
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he wi... | 3 | n = int(input().strip())
can_durability = [int(x) for x in input().strip().split(' ')]
can_durability2 = [(cd, i) for (i, cd) in enumerate(can_durability)]
can_durability2.sort( key = lambda t:t[0], reverse=True)
shoots = 0
# print(can_durability2)
for i in range(n):
# print('Shoot {0} takes {1} trials'.format(i +... |
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ... | 3 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import sys
#from blist import sortedset
from heapq import heappush, heappop
# In[ ]:
# In[8]:
n, e=map(int,input().split())
# In[17]:
dic={}
# In[18]:
for i in range(e):
start, end=map(int,input().split())
if start in dic:
... |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | x,y,z = input().split()
moneyRequired = ((int(z))*(int(z)+1)*int(x))/2
print(abs(int(int(y)-moneyRequired)) if moneyRequired>int(y) else 0)
|
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha... | 3 | from functools import reduce
from operator import *
from math import *
from sys import *
from string import *
setrecursionlimit(10**7)
dX= [ 0, 0, 1,-1, 1,-1, 1,-1]
dY= [ 1,-1, 0, 0, 1,-1,-1, 1]
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().split()
###############################################... |
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | 3 | n = int(input())
h = n
for i in range(2, int(n**0.5)+1):
if n%i==0:
while n>1:
if n%i==0:
n = n//i
else:
h = 1
break
if n==1:
h=i
break
print(h) |
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 | def dic():
dict={'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,
'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,
's':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
return dict
game=int(input())
for i in range(game):
n=int(input())
str=''
for i in range(n)... |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | for i in range(int(input())):
c=input()[-1]
if c=='o':
print("FILIPINO")
elif c=='u':
print("JAPANESE")
else:
print("KOREAN") |
Santa Claus has n candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.
Input
The only line contains positive integ... | 3 | n = int(input())
a = [set()] * (n + 1)
for i in range(1, n + 1):
b = {i}
for j in range(1, i):
aj = a[i - j]
if j not in aj:
new_len = len(aj) + 1
if new_len > len(b):
b = aj.copy()
b.add(j)
a[i] = b
print(len(a[n]))
print(' '.join(m... |
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.
For example,... | 3 | a,b=map(int,input().split())
def bn(x):
m=0
while x>0:
m+=x%2
x//=2
return m
mn=100000000
idx=0
if b==0:
print(bn(a))
exit(0)
else:
for n in range(1,100):
j=n*b
if a<=j:
break
... |
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | import sys
data = []
for line in sys.stdin:
content = []
for x in line.split():
content.append(int(x))
data.append(content)
for i in range(data[0][0]):
case = data[2*i + 2]
case.sort()
min = case[1] - case[0]
for j in range(len(case) - 1):
if case[j + 1] - case[j] < min:
... |
Create a program that outputs the surface area S of a square cone with a height of h, with a square with one side x as the base. However, assume that the line segment connecting the apex and the center of the base is orthogonal to the base. Also, x and h are positive integers less than or equal to 100.
Input
Given mu... | 3 | import math
while True:
x = int(input())
h = int(input())
if x == 0 and h == 0: break
h2 = math.sqrt((x/2)*(x/2) + h*h)
print(float(x*x + 2*x*h2))
|
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.
The three friends are very smart so they passed all the challenges very quickly and finally reached the destination... | 3 | def beautify(a,n):
l=len(a)
if n>l:
return l
d={}
max=0
for x in a:
if x in d:
d[x]+=1
else:
d[x]=1
if d[x]>max:
max=d[x]
maxl=x
if n==1 and l==max:
return l-1
if n+max>=l:
return l
else:
... |
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 | import os
if __name__ == '__main__':
line = list(map(int, input().rstrip().split('+')))
line.sort()
s = ''
for i in line:
s += str(i)+'+'
print(s[:-1])
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | x=int(input())
a=input()
b=input()
s=0
for i in range(x):
c=abs(int(a[i])-int(b[i]))
s+=min(c,10-c)
print(s) |
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 | s=input()
s=s.replace('+','')
l=list(s)
l.sort()
s=''
for i in range(len(l)-1):
s=s+str(l[i])+'+'
s=s+str(l[len(l)-1])
print(s) |
The circle line of the Roflanpolis subway has n stations.
There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ... | 3 | n,a,x,b,y=map(int,input().split())
counter=0
while 1:
if a==b:
counter=1
break
if a==x or b==y:
break
a+=1
if a==n+1:
a=1
b-=1
if b==0:
b=n
if counter:
print("Yes")
else:
print("NO")
|
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 | j=0
for _ in range(int(input())):
a=input()
if a == "0 1 1":
j+=1
elif a == "1 0 1":
j+=1
elif a == "1 1 0":
j+=1
elif a == "1 1 1":
j+=1
print(j)
|
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... | 1 | n=input()
if n>3 and n%2==0:
print 'YES'
else:
print 'NO'
|
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red.
"Oh, I just spent x_i hours solving problems", said the i-th of them.
Bob wants to train his math skills... | 3 |
for _ in range(int(input())):
n = input()
z=n.count('0')
s = 0
f = 0
for c in n:
if(ord(c)%2==0 and c!='0'):
f=1
s += ord(c)-ord('0')
if(z and s%3==0 and (f or z>1)):
print("red")
else:
print("cyan")
|
You are given an array a_1, a_2, …, a_n.
In one operation you can choose two elements a_i and a_j (i ≠ j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the size of the array.... | 3 | n = int(input())
a = sorted(map(int, input().split()))
if sum(a) % 2 or sum(a[:-1]) < a[-1]:
print('NO')
exit()
print('YES') |
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.
You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca... | 3 | import sys
t=int(sys.stdin.readline())
for _ in range(t):
m=int(sys.stdin.readline())
l=[]
for i in range(m):
s=sys.stdin.readline()[:-1]
l.append(s)
count0,count1=0,0
arr=[]
for i in range(m):
n=len(l[i])
arr.append(n)
for j in range(n):
if l[... |
We will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move... | 3 | n, m, *x = map(int, open(0).read().split())
x.sort()
d = [i-j for i, j in zip(x[1:], x)]
d.sort()
print(sum(d[:m-n]) if n < m else 0) |
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon... | 1 | print max(map(int, ([raw_input(), raw_input()][1].split())))
|
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 | n= input()
cnt=0
l=len(n)
while(l>=0):
for i in range(0,l):
if(n[i]!=n[(l-1-i)]):
cnt+=1
if(cnt>=1):
print(l)
l=-1
else:
l=l-1
if (l==0):
print(0)
|
The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...
Given is a string S representing the weather in the town today. Predict the weather tomorrow.
Constraints
* S is `Sunny`, `Cloudy`, or `Rainy`.
Input
Input is given from Standard Input in the... | 3 | s = input()
l = ['Sunny', 'Cloudy', 'Rainy']
print(l[l.index(s) - 2]) |
You are given nonnegative integers a and b (a ≤ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x?
Constraints
* 0 ≤ a ≤ b ≤ 10^{18}
* 1 ≤ x ≤ 10^{18}
Input
The input is given from Standard Input in the following format:
a b x
Output
Print the number of th... | 1 | from math import *
a, b, x = map(int, raw_input().split())
print (b / x + 1) - ((a - 1) / x + 1) |
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.
Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in... | 3 | from sys import stdin,stdout
n,m = map(int,stdin.readline().split())
M = [list(map(int,stdin.readline().split())) for i in range(n)]
depth = [[1]*m for i in range(n)]
for col in range(m):
for row in range(1,n):
if M[row][col]>=M[row-1][col]:
depth[row][col] = depth[row-1][col]+1
max_depth = [ma... |
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m... | 3 | b = int(input())
bl = list(map(int, input().split()))
g = int(input())
gl = list(map(int, input().split()))
ans = 0
bl.sort()
gl.sort()
for i in range(b):
for j in range(g):
if(abs(bl[i]-gl[j])<=1):
gl[j]=1000
ans+=1
break
print(ans) |
For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.
An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.
Constraints
* 1 ≤ n ≤ 100000
* 0 ≤ ai ≤ 109
Input
n
a0
a1
:
... | 3 | import sys
from bisect import bisect_left
def solve():
A = map(int, sys.stdin)
n = next(A)
L = [next(A)]
for a_i in A:
if a_i > L[-1]:
L.append(a_i)
else:
j = bisect_left(L, a_i)
L[j] = a_i
print(len(L))
solve()
|
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 | m='hello'
def chat_room():
s=input()
x=0
for i in range(len(s)):
if s[i]==m[x]:
x+=1
if x==5:
return "YES"
return "NO"
print(chat_room()) |
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())
s = a
r = 0
while a >= b:
r = r + a%b
s = s + a//b
a = a//b
if r >= b:
a = a + b
r = r - b
# print(s,r,a)
print(s+(r+a)//b)
|
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 | for _ in range(int(input())):
n = int(input())
A = list(map(int, input().split()))
P = [[] for _ in range(27)]
S = set(A)
for i, a in enumerate(A):
P[a].append(i)
ans = 0
for a in S:
for i in range(0, (len(P[a])//2)):
minp = P[a][i]
maxp = P[a][-(1+i)... |
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from... | 3 | n=int(input())
a=list(map(int,input().split()))
cs=abs(a[0])
a.append(0)
for i in range(n):
cs+=abs(a[i]-a[i+1])
print(cs-abs(a[0])-abs(a[0]-a[1])+abs(a[1]))
for i in range(1,n):
print(cs-abs(a[i-1]-a[i])-abs(a[i]-a[i+1])+abs(a[i-1]-a[i+1])) |
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament.
Alice's party has number 1. In order to become the prime minister, she needs to b... | 3 | n = int(input())
a = [int(i) for i in input().split()]
total_seats = sum(a)
sum_seats = a[0]
party = ['1']
i = 0
def check_double(i):
if a[0] >= 2*a[i]:
return True
else:
return False
while sum_seats <= total_seats/2 and i <= n-2:
i += 1
if check_double(i):
sum_seats += a[i... |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 | t = int(input())
while t:
a = int(input())
total = a
while a>=10:
total += a//10
a = a//10 + a%10
t-=1
print(total) |
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ... | 3 | # cook your dish here
n = int(input())
for i in range(n):
s = list(map(int,input().split(" ")))
d = (s[0]+1)//2
c = d//s[1]
if d%s[1] ==0:
print(max(s[0],c*(s[1]+s[2]) - s[2] ))
else:
print(max(s[0],c*(s[1]+s[2]) + d%s[1] )) |
There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares.
The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`.
You will perform the following operation exactly N times: choo... | 3 | mod = 10**9 + 7
n = int(input())
s = input()
crr = 0
lst= []
for i in range(2*n):
if s[i] == 'B':
if crr%2 == 1:
lst.append(-1)
crr -= 1
else:
lst.append(1)
crr += 1
else:
if crr%2 == 1:
lst.append(1)
crr += 1
... |
Let's consider all integers in the range from 1 to n (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≤ a < b ≤ n.
The greatest common divisor, gcd(a, b), of two positive integ... | 3 | import math
from collections import defaultdict, Counter, deque
INF = float('inf')
def gcd(a, b):
while b:
a, b = b, a%b
return a
def isPrime(n):
if (n <= 1):
return False
for i in range(2, n):
if (n % i == 0):
return False
return True
def primeFactor(n):
if n % 2 == 0:
return 2
i = 3
while ... |
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.
Constraints
* 10000 \leq A \leq B \leq 99999
* All input values are integers.
Inp... | 3 | A,B = map(int,input().split())
print([str(x) == str(x)[::-1] for x in range(A,B+1)].count(True)) |
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S.
You have to answer q independent test cases.
Input
The... | 3 | q = int(input())
for _ in range(q):
a, b, n, s = input().split()
a = int(a)
b = int(b)
n = int(n)
s = int(s)
ans = s//n
if ans >= a:
s -= a * n
else:
s -= ans * n
if s <= b:
print("YES")
else:
print("NO") |
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 | lis = [int(x) for x in input().split()]
lis1 = []
for i in lis:
if i not in lis1:
lis1.append(i)
print((4 - len(lis1))) |
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 | #code
def isdist(s):
s = str(s)
for i in range(len(s)):
if s[i] in list(s[i+1:]):
return 0
return 1
n = int(input())
n+=1
while(1):
if isdist(n):
print(n)
break
n+=1 |
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 | m, n = map(int, input().split())
c = 0
if(m%2 != 0):
n_r = m-1
else:
n_r = m
for i in range(0,n_r,2):
c += 1
c = c*n
n_C = m-n_r
c2 = 0
if(n%2 != 0):
n_c = n - 1
else:
n_c = n
for i in range(0,n_c,2):
c2+=1
#print(n_C)
c = c + (c2*n_C)
print(c)
|
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 != 2):
if (w%2 > 0 ):
print ("NO")
else:
print("YES")
else:
print("NO") |
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length.
Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest comm... | 3 | n=int(input())
l=list(input())
for i in range(1,n):
a=input()
for j in range(len(l)):
if l[j]!=a[j]:
del l[j:]
break
print(len(l)) |
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.
For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.
For given n find out to which integer will Vasy... | 3 | n = int(input())
down = (n//10)*10
up = ((n//10)+1)*10
if abs(n-up)>abs(n-down):
print(down)
else:
print(up) |
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()
a=0
b=0
for x in range(len(s)):
if 65<=ord(s[x])<=90:
a+=1
else:b+=1
if a>b:
print(s.upper())
else:
print(s.lower()) |
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].
You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want... | 3 | n = int(input())
a = []
b = []
for i in range(n):
tempA, tempB = map(int, input().split())
a.append(tempA)
b.append(tempB)
minx = a[0]
maxx = b[0]
for i in range(n):
minx = min(minx, a[i])
maxx = max(maxx, b[i])
for i in range(n):
if a[i] == minx and b[i] == maxx:
print(i+1)
e... |
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times:
* mul x: multiplies n by x (where x is an arbitrary positive integer).
* sqrt: replaces n with √... | 1 | from __future__ import division
from collections import deque, defaultdict, Counter
from math import *
def count_prime(n):
i = 2
while i * i < n:
if not prim[i]:
for j in range(i, n, i):
prim[j] = i
i += 1
for i in range(1, n):
if not prim[i]:
... |
problem
Create a program that counts the number of consecutive JOI or IOI characters in a given character string. The character string consists only of uppercase letters of the alphabet. For example, the character string "JOIOIOI" in the figure below contains JOI in one place and IOI in two places.
<image>
input
... | 3 | while 1:
try:
s=input()
joi=0
ioi=0
for i in range(len(s)-2):
oi=s[i]+s[i+1]+s[i+2]
if oi=="JOI":joi+=1
elif oi =="IOI":ioi+=1
print(joi)
print(ioi)
except:break
|
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | 3 | test = int(input())
for t in range(test):
n, k = map(int, input().split())
if k>=n:
print(k-n)
elif (n+k)%2==0:
print(0)
else:
print(1) |
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k d... | 3 | # coding: utf-8
n, k = [int(i) for i in input().split()]
ans = ['1']
for i in range(k):
if i%2==0:
ans.append(str(int(ans[-1])+(k-i)))
else:
ans.append(str(int(ans[-1])-(k-i)))
ans += [str(i) for i in range(k+2,n+1)]
print(' '.join(ans))
|
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... | 3 | s = input()
Q = map(str, input().split())
flag = 0
for S in Q:
if s[0] == S[0] or s[1] == S[1]:
flag = 1
break
if flag:
print("YES")
else:
print("NO") |
N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.
M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges, and increase the score of each chosen problem by 1.
After all M judges cast their vo... | 3 | N,M,V,P=map(int,input().split())
B = sorted(list(map(int, input().split())))[::-1]
count=P
dif=0
for i in range(P,N):
dif+=B[i-1]
if V<=(P-1)+(N-i) and B[P-1]<=B[i]+M:
count+=1
elif dif-B[i]*(i-P+1)<=M*(N-V) and B[P-1]<=B[i]+M:
count+=1
print(count) |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 1 | __author__ = 'user'
a=raw_input()
nlist = map(int,a.split('+'))
nnlist = []
def funcnnlist(num):
for i in nlist:
if i == num:
nnlist.append(i)
funcnnlist(1)
funcnnlist(2)
funcnnlist(3)
print "+".join(map(str,nnlist)) |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | a=int(input())
for i in range(0,a):
b,c=map(int,input().split())
ans=1
if b==1:
print('1')
else:
if (b-2)%c==0:
ans+=(b-2)//c
else:
ans+=((b-2)//c)+1
print(ans) |
Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left. Each square is painted black or white.
The grid is said to be good if and only if the following condition is satisfied:
* From (1, 1), we can reach (H, W) by moving one sq... | 3 | h, w = map(int, input().split())
mat = [[] for _ in range(h)]
for i in range(h):
mat[i] = input()
dp = [[float("inf")] * w for _ in range(h)]
if mat[0][0] == "#":
dp[0][0] = 1
else:
dp[0][0] = 0
for i in range(h):
for j in range(w):
if mat[i][j - 1] != mat[i][j]:
left = d... |
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 |
data = int(input())
if data == 2:
print("NO")
elif data % 2 == 0:
print("YES")
else:
print("NO")
|
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | 3 | n = int(input())
def Factor(n):
Ans = set()
d = 2
while d * d <= n:
if n % d == 0:
Ans.add(d)
n //= d
else:
d += 1
if n > 1:
Ans.add(n)
return Ans
if n < 4:
print(n)
exit()
divs = Factor(n)
if len(divs) == 1:
print(divs.pop())
elif not di... |
Today the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a ≠ b) will indulge if:
1. gcd(a, b) = 1 or,
2. a divides b or b d... | 3 | t = int(input())
for j in range(t):
n = int(input())
q = 4 * n
for i in range(n):
print(q, end = ' ')
q -= 2
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 | for i in range(int(input())):
a = input().split()
a, b = int(a[0]), int(a[1])
print((b - a % b) % b)
|
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a × b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents... | 1 | n = input()
a = raw_input()
aa = a.split('W')
aa = [item for item in aa if item]
print len(aa)
for i in aa:
print len(i),
|
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can pe... | 3 | n = int(input())
c = [int(x) for x in input().split(' ')]
c.sort()
i = 0
a = 0
for j in range(n):
if c[i] < c[j]:
a += 1
i += 1
print(a) |
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is h... | 1 | n = int(raw_input())
x = 1
for i in range(1, n):
x += i
x = x % n if x > n else x
print x, |
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,... | 3 | # import sys
# sys.stdin=open("input.in","r")
# sys.stdout=open("output.out","w")
x=int(input())
l=list(map(int,input().split()))
n=l.count(1)
print(n)
for i in range(1,x):
if(l[i]==1):
print(l[i-1],end=" ")
print(l[x-1])
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | #0 is ally
#1 is enemy
situation = input()
players = len(str(situation))
counter = 1
counter_max = 1
for i in range(0,len(str(situation))-1):
if str(situation)[i] == str(situation)[i+1]:
counter = counter + 1
else:
counter = 1
#checking the maximum counting
if counter > counter_max:
... |
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | 3 | import math
import string
s = input()
pr = set()
ans = 0
for x in s:
if ord('A') <= ord(x) <= ord('J'):
pr.add(x)
pr = len(pr)
r = s.count('?')
if s[0] == '?':
ans = (9 * math.factorial(10) // math.factorial(10 - pr))
print(str(ans) + '0' * (r - 1))
elif s[0] in string.ascii_uppercase:
ans = (9... |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 3 | for i in range(int(input())):
a = input()
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
min_a = min(a)
min_b = min(b)
count = 0
for ai, bi in zip(a, b):
count += max(ai - min_a, bi - min_b)
print(count) |
Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end!
The tournament consisted of n (n ≥ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After th... | 1 | from sys import stdin,stdout
from collections import defaultdict
n=input()
l=[]
d=defaultdict(int)
d1=defaultdict(list)
for i in range(n-2):
la=list(map(int,stdin.readline().split()))
d[la[0]]+=1
d[la[1]]+=1
d[la[2]]+=1
d1[la[0]].append(set(la))
d1[la[1]].append(set(la))
d1[la[2]].append(set... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ... | 3 | n, k = map(int, input().strip().split())
contestants = list(map(int, input().strip().split()))
j = 0
for i in contestants:
if i > 0 and i >= contestants[k - 1]:
j += 1
print(j)
|
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 | n=int(input())
if n>0:
print(n)
else:
x=list(str(-1*n))
if x[-1]>x[-2]:
x.pop(-1)
else:
x.pop(-2)
s=''
for i in x:
s+=i
print(int(s)*-1)
|
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
... | 3 | def sum_of_digits(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
n = int(input())
while sum_of_digits(n) % 4 != 0 :
n += 1
print(n)
|
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
* `0 l r b c`: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.
* `1 l r`: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.
Constraints
* 1 \leq N, Q \leq 500000
* 0 \leq a_i, c < 998244353
* 1 \le... | 3 | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
### 遅延評価セグメント木
class LazySegmentTree:
def __init__(self, n, a=None):
"""初期化
num : n以上の最小の2のべき乗
"""
num = 1
while num<=n:
... |
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of s:
* s > 0,
* s consists of n digits,
* no digit in s equals 0,
* s is not divisible by any of it's digits.
Input
The input consists of mult... | 3 | t = int(input())
for x in range(t):
n = int(input())
if n == 1:
print(-1)
else:
print("3"*(n-2)+"23")
|
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ... | 3 | n=int(input())
s="codeforces"
i=10
s1=""
while(i>=1):
num=n**(1/i)
# print("num --> ",num," n--> ",n)
if(int(num)==round(num,10)):
if(int(num)**i==n):
num=int(num)
else:
num=int(num)+1
else:
num=int(num)+1
# print("num --> ",num)
n=n/num
s1+=s[10-i]*num
i-=1
print(s1) |
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can:
* either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
... |
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 | import sys
t = int(sys.stdin.readline())
for query in range(t):
n = int(sys.stdin.readline())
half = n//2
if (half)%2 == 0:
print('YES')#,half)
two = 2
for i in range(half):
print(two,end=' ')
two += 2
two = 1
for i in ran... |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | def to_list(s):
return list(map(lambda x: int(x), s.split(' ')))
def solve(a,b,c,d):
print(' '.join([str(a),str(c),str(c)]))
t = int(input())
for i in range(t):
a,b,c,d = to_list(input())
solve(a,b,c,d) |
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | s = input()
if s.isupper():
print(s.lower())
else :
L = list(s)
L.pop(0)
temp_s = ''.join(L)
i = 0
while i < len(temp_s) :
if temp_s[i] > 'Z':
break;
i += 1
if i == len(temp_s):
print(s.title())
else:
print(s)
|
Given an array a of length n, find another array, b, of length n such that:
* for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i.
The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
Input
The first line contains an ... | 3 |
n = int(input())
a = list(map(int,input().split()))
b = [None] * n
ind = 0
mex = 0
import sys
for i in range(n):
if mex != a[i]:
for j in range(mex+1,a[i]):
while ind < i and b[ind] != None:
ind += 1
if ind >= i:
print (-1)
sys.e... |
Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing.
Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and th... | 3 | d={}
n=int(input())
s1=[]
s2=[]
l=list(map(int,input().split()))
for i in l:
d[i]=d.get(i,0)+1
lol=0
for i in d:
if(d[i]==1):
s1.append(i)
elif(d[i]==2):
s1.append(i)
s2.append(i)
else:
lol=1
break
if(lol==1):
print("No")
else:
print("Yes")
print(len(s... |
Cat Snuke is learning to write characters. Today, he practiced writing digits `1` and `9`, but he did it the other way around.
You are given a three-digit integer n written by Snuke. Print the integer obtained by replacing each digit `1` with `9` and each digit `9` with `1` in n.
Constraints
* 111 \leq n \leq 999
* ... | 3 | x=int(input())
print(1110-x) |
Gildong's town has a train system that has 100 trains that travel from the bottom end to the top end and 100 trains that travel from the left end to the right end. The trains starting from each side are numbered from 1 to 100, respectively, and all trains have the same speed. Let's take a look at the picture below.
<i... | 1 |
from __future__ import division
import sys
input = sys.stdin.readline
import math
from math import sqrt, floor, ceil
from collections import Counter
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input... |
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pa... | 3 | m, s = map(int, input().split())
if s == 0 and m > 1 or s > m * 9:
print(-1, -1)
else:
big = ['0' for _ in range(m)]
small = ['0' for _ in range(m)]
s1 = s2 = s
for i in range(m):
if s1 > 9:
big[i] = '9'
s1 -= 9
else:
big[i] = str(s1)
b... |
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=[int(x) for x in input().split()]
if (b-a)%10:
ans=abs(b-a)//10+1
print(ans)
else:
print(abs(b-a)//10) |
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.
In each move you can insert any positive integral number you want not greater than 109 in any place in the array.
An array is co-prime if any two adjacent numbers of it are co-prime.
In the number theory, two integer... | 1 | n = input()
l = map(int, raw_input().split())
res = []
def gcd(a, b):
if a%b == 0:
return b
return gcd(b, a%b)
for i in range(1,n):
res.append(l[i-1])
if gcd(l[i-1], l[i]) != 1:
res.append(1)
a = l[i]
res.append(l[-1])
print len(res) - len(l)
print ' '.join(map(str, res)) |
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, ... | 3 | n=int(input())
arr=list(map(int,input().split()))
s=sum(arr)
count=0
ans=[]
for x in range(n):
if arr[x]==(s-arr[x])/(n-1):
count=count+1
ans.append(x+1)
print(count)
for x in ans:
print(x,end=" ")
print()
|
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 | n=int(input())
x=0
for i in range(n):
s=str(input())
if "++" in s:
x=x+1
elif "--" in s:
x=x-1
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.