problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into n sub-tracks. You are given an array a where a_i represents the number of traffic cars in the i-th sub-track. You def... | 3 | import math, sys
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
MOD = int(1e9) + 7
INF = float('inf')
def solve():
n = int(input())
arr = list(map(int, input().split()))
total = sum(arr)
c1 = total // n
have = total - c1 * n
if have:
print(have * (n - hav... |
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special β it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s... | 3 | n,s=(map(int,input().split()))
x=[]
for i in range(n):
a,b=(map(int,input().split()))
x.append([a,b])
x.sort(key=lambda i:i[0],reverse=True)
c=0
p=s
for i in x:
c=max(i[1],c+p-i[0])
p=i[0]
c+=i[0]
print(c) |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | n = int(input())
coords = [int(x) for x in input().split()]
last = n - 1
print(coords[1] - coords[0], coords[last] - coords[0])
i = 1
while i < last:
print(min(abs(coords[i+1]-coords[i]), abs(coords[i]-coords[i-1]))
, max(abs(coords[i]-coords[0]), abs(coords[last]-coords[i])))
i += 1
print(coords[l... |
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha... | 3 | import operator as op
from functools import reduce
from operator import mul # or mul=lambda x,y:x*y
from fractions import Fraction
def ncr(n,k):
return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )
arr2 = str(input())
arr = arr2.split()
n = int( arr[0] )
m = int( arr[1] )
if m == 1:
... |
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | 1 | k=raw_input()
n,m=map(int,k.split(" "))
price=raw_input()
arr=[int(x) for x in price.split(" ")]
earned=0
carry=0
while carry<m:
if min(arr)<0:
earned-=min(arr)
arr[arr.index(min(arr))]=0
carry+=1
else:
break
print earned
|
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | ans = 0
now = 0
for i in range(int(input())):
a,b = map(int ,input().split())
now -=a
now += b
ans = max(ans, now)
print(ans) |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | n=int(input())
b=0
b+=n//100
n-=n//100*100
b+=n//20
n-=n//20*20
b+=n//10
n-=n//10*10
b+=n//5
n-=n//5*5
print(b+n) |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | a=input()
b=input()
c=a.lower()
d=b.lower()
if c<d :
print(-1)
if c==d :
print(0)
if c>d :
print(1) |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n β length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | 3 | t = int(input())
for i in range(t):
n = int(input())
arr = [int(j) for j in input().split()]
j = 0
tot = 0
s = 0
if sum(arr)%2 != 0:
while j < len(arr):
if arr[j] == 1:
del arr[j]
break
j+=1
while j < len(arr):
if arr[j] == 1:
if tot == 0:
tot = 1
else:
if s%2 != 0:
del arr[j... |
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.
The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.
Ther... | 3 | n = int(input())
s1 = []
s2 = []
for a in range(n):
s1.append(input())
for a in range(n):
x = input()
if x in s1:
s1.remove(x)
else:
s2.append(x)
print(len(s1))
|
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i β€ r_i) and it covers all integer points j such that l_i β€ j β€ r_i.
The integer point is called bad... | 3 | scount, badness = [int(x) for x in input().split(' ')]
segments = []
length = 200
for i in range(scount):
segments.append([int(x) - 1 for x in input().split(' ')])
segments[-1].append(True)
array = [[] for x in range(length)]
badcheck = [0 for x in range(length)]
for i in range(scount):
for k in range(segme... |
You are given an array a of n integers and an integer s. It is guaranteed that n is odd.
In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.
The median of the array with odd length is the ... | 3 | n, s = map(int, input().split())
a = sorted(list(map(int, input().split())))
res = abs(s-a[n//2])
for i in range(n//2):
if a[i]>s: res+=a[i]-s
for i in range(n//2+1, n):
if a[i]<s: res+=s - a[i]
print(res) |
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 β€ ti β€ 10). Of course, one number can be assigned to any number of cust... | 3 | import math
n = int(input())
clientlist = list(map(int, input().split()))
num_of_pairs = 0
set_of_numbers = dict()
f = math.factorial
for i in clientlist:
set_of_numbers[i] = set_of_numbers.get(i, 0) + 1
if 0 in set_of_numbers.keys():
if set_of_numbers[0] > 1:
num_of_pairs += ((set_of_numbers[0] - 1) *... |
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se... | 3 | n, pos, l, r = map(int, input().split())
if l > 1 and r < n:
print(min(abs(pos - l), abs(pos - r)) + r - l + 2)
elif l == 1 and r < n:
print(abs(pos - r) + 1)
elif l > 1 and r == n:
print(abs(pos - l) + 1)
else:
print(0) |
Dark was deeply studying in the afternoon and came across a concept called as "REVERSE OF A NUMBER"
Hearing first time he became eager to learn and searched on "INTERNET" , after his research on reverse of a number he decided to design a program which can reverse any long numbers.
At the end of afternoon, he started... | 1 | def rev(t):
df = 0
while df < t:
a = raw_input()
reverse = a[::-1]
if int(reverse)%2 == 0:
print 'EVEN'
else:
print 'ODD'
df += 1
t = int(raw_input())
rev(t) |
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party.
She invited n guests of the first type and m guests of the second type to the party. They will come to the ... | 3 | import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
"""
Facts and Data representation
Constructive? Top bottom up down
"""
def solve():
... |
During cleaning the coast, Alice found n piles of stones. The i-th pile has a_i stones.
Piles i and i + 1 are neighbouring for all 1 β€ i β€ n - 1. If pile i becomes empty, piles i - 1 and i + 1 doesn't become neighbouring.
Alice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to... | 1 | from sys import stdin, stdout
tc = input()
inp = stdin.readlines()
out = []
ptr = 0
while ptr < len(inp):
n = int(inp[ptr].strip()); ptr += 1
a = map(int, inp[ptr].strip().split()); ptr += 1
b = [x for x in a]
for i in xrange(1, n): b[i] -= b[i - 1]
if all([x >= 0 for x in b]) and b[n - 1] =... |
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | 3 | for _ in range(int(input())):
s = input()
t = input()
i = 0; j = 0; ls = len(s); lt = len(t); flag = True
if lt < ls:
print('NO')
continue
while flag and i < ls and j < lt:
if s[i] != t[j]:
flag = False
else:
if i == ls - 1:
while j < lt and s[i] == t[j]:
j += 1
if j != lt and s[i] != t[... |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | s = input()
ans = []
i = 0
while i <len(s):
if s[i] == '-':
if s[i+1] == '.':
ans.append('1')
else:
ans.append('2')
i+=2
else:
ans.append('0')
i+=1
print(''.join(ans)) |
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integ... | 3 | import math
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int,input().split()))
suffix = [0]*n
suffix[-1] = a[-1]
for i in range(n-2,-1,-1):
suffix[i] = math.gcd(a[i],suffix[i+1])
gcd1 = (a[0]*suffix[1])//suffix[0]
for i in range(1,n-1):
lcm = a[i]*suffix... |
It is September 9 in Japan now.
You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?
Constraints
* 10β€Nβ€99
Input
Input is given from Standard Input in the following format:
N
Output
If 9 is contained in the decimal notation of N, print `Yes`; if not, print `No... | 3 | N=input();N_list=list(N);print(['No','Yes']['9' in N_list])
|
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.
Let [n] denote the set {1, ..., n}. We will also write f: [x] β [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.
Now then, you are given a function f: [... | 3 | import sys
n = int(input())
s = input().split()
a = [int(i) for i in s]
a.insert(0,0)
hash = [0 for i in range(n+1)]
g = [0 for i in range(n+1)]
h = [0 for i in range(n+1)]
index = 1
for i in range(1, n+1):
if hash[a[i]] == 0:
if index>n:
print(-1)
exit()
hash[a[i]]=index
g[i] = index
h[index] = a[i]
... |
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.
Alice can erase some characters from her string s. She would like to know wh... | 3 | a=input()
b=a.count('a')
c=len(a)-b
if(b>c):
print(len(a))
else:
print(2*b-1) |
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by rem... | 3 | from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
s = input()
n = len(s)
def valid(s):
s = 'x' + s
return (
... |
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s... | 3 | N, First, Second, Third = int(input()), sorted(list(map(int, input().split()))), sorted(
list(map(int, input().split()))), sorted(list(map(int, input().split())))
Check, i = False, 0
while i < N - 1:
if First[i] != Second[i]:
Check = True
break
i += 1
print(First[i] if Check else First[-1])
... |
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights... | 3 | from sys import stdin,stdout
from itertools import combinations
from collections import defaultdict
import math
def listIn():
return list((map(int,stdin.readline().strip().split())))
def stringListIn():
return([x for x in stdin.readline().split()])
def intIn():
return (int(stdin.readline()))
def ... |
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).
<image> Examples of convex regular polygons
Your task is to say if it is poss... | 3 | t = int(input())
for i in range(t):
[n, m] = [int(x) for x in input().split()]
print("YES" if n % m == 0 else "NO")
|
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.
At any time Andrew can visit the store where tasty buns are sold (y... | 3 | import math
numbers = list(map(int, input().split()))
hh = numbers[0]
mm = numbers[1]
numbers = list(map(int, input().split()))
H = numbers[0]
D = numbers[1]
C = numbers[2]
N = numbers[3]
def func(hh, mm, H, D, C, N):
minute = hh * 60 + mm
if minute >= 1200:
return C * math.ceil(H / N) * 0.8
else:
t = 1200 -... |
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.
You are asked to calculate the number of ways he can... | 3 |
def solve(n, arr):
ans = arr.count(1)
if ans == 0:
print(0)
else:
res = 1
for i in range(n):
if arr[i] == 1:
for j in range(i+1,n):
if arr[j] == 1:
res *= (j - i)
break
print(res... |
The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)
We will close the window so as to minimize the total horizontal length of the uncovered part of the window. Fin... | 3 |
a,b=map(int,input().split())
c=max(0,a-2*b)
print(c) |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | # https://codeforces.com/contest/1399/problem/0
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
# do magic here
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
ok = "YES"
for x in range(1,n):
if arr[x]-arr[x-1]... |
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.
Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi... | 3 | n, d = map(int, input().split())
t = list(map(int, input().split()))
k = d - sum(t) - 10 * (n - 1)
print(-1 if k < 0 else 2 * (n - 1) + k // 5) |
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.
Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not... | 3 | t=int(input())
for _ in range(t):
a,b,k=map(int,input().split())
a1=list(map(int,input().split()))
b1=list(map(int,input().split()))
ans=(k*(k-1))//2
dic1={}
dic2={}
for i in range(k):
if a1[i] in dic1:
dic1[a1[i]]+=1
else:
dic1[a1[i]]=1
if b1[i] in dic2:
dic2[b1[i]]+=1
e... |
In some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users.
Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least o... | 3 | import sys
sys.setrecursionlimit(10**5)
def find(x):
if (x == parent[x]):
return x
parent[x] = find(parent[x])
return parent[x]
def union(x,y):
p_x = find(x)
p_y = find(y)
if (p_x != p_y):
if (tamanho[p_x] > tamanho[p_y]):
parent[p_y] = p_x
... |
We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.
How many squares i satisfy both of the following conditions?
* The assigned number, i, is odd.
* The written integer is odd.
Constraints
* All values in input are integers.
* ... | 3 | n = input()
a = list(map(int,input().split()))
ans = 0
for i in a[::2]:
if i % 2 == 1:
ans += 1
print(ans) |
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.
Given a string S, determine whether it is coffee-like.
Constraints
* S is a string of length 6 consisting of lowercase English l... | 3 | S = input()
if S[4]==S[5] and S[2]==S[3]:
print("Yes")
else:
print("No") |
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | 3 | import sys
temp1 = sys.stdin.readline()
temp2 = sys.stdin.readline()
list1 = temp1.split()
list2 = temp2.split()
x, y, z = map( int, tuple(list1))
a, b, c = map( int, tuple(list2))
if a >= x and a + b >= y + x and a + b + c >= x + y + z:
print("YES")
else:
print("NO")
|
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 | a = int(input())
b = []
for i in range (a):
x = input()
u = len(x)
if u <= 10:
t = x
else:
t = (x[0]+str(u-2)+(x[u-1]))
b.append(t)
for j in b:
print(j)
|
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ... | 1 | import sys
def main(a):
sol = min(
a[0] + a[1] + a[2],
a[0] + a[2] + a[2] + a[0],
a[0] + a[1] + a[1] + a[0],
a[1] + a[1] + a[2] + a[2],
)
return sol
def test_me():
assert main([10, 20, 30]) == 60
assert main([1, 1, 5]) == 4
assert main([1, 5, 1]) == 4
asser... |
There are N people standing in a queue from west to east.
Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`.
A person is happy if the person in front of him/her is facing the... | 3 | N, K = map(int,input().split())
S = input()
cnt = 1
for i in range(N-1):
if S[i] != S[i+1]:
cnt += 1
print(min(N - 1,N - (cnt - 2*K))) |
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()
upper = 0
lower = 0
for i in s:
if i.isupper():
upper+=1
elif i.islower():
lower+=1
if upper>lower:
s=s.upper()
else:
s=s.lower()
print(s) |
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value β_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | import math
t = int(input())
while t > 0:
n, m = map(int, input().split())
print(min(2, n-1)*m)
t -= 1
|
There are four towns, numbered 1,2,3 and 4. Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally. No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roa... | 3 | print('YES'*(sum(map(int,open(0).read().split()))%2)or'NO') |
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the scre... | 3 | import math
from fractions import Fraction
a,b,c,d=map(int,input().split())
x=a*c//(math.gcd(a,c))
y=b*d//(math.gcd(b,d))
ans1=abs(b*(x//a)-d*(x//c)),max(b*x//a,d*x//c)
ans2=abs(a*(y//b)-c*(y//d)),max(a*y//b,c*y//d)
f1=Fraction(ans1[0],ans1[1])
f2=Fraction(ans2[0],ans2[1])
if f1>f2:
print(f1.numerator,end="")
p... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
line = [int(i) for i in input().split()]
linenew = []
for i in range(n):
if line[i]%2 == 0:
linenew.append(0)
else:
linenew.append(1)
if linenew.count(0) == n-1:
print(linenew.index(1)+1)
else:
print(linenew.index(0)+1) |
The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:
... | 3 | n = int(input())
print(n, *range(1, n))
|
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`.
Constraints
* 2 β€ N β€ 200000
* 1 β€ A_i β€ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
If the elements... | 3 | n=int(input())
a=len(set(map(int,input().split())))
print('YES' if n==a else 'NO') |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 1 | n = int(raw_input())
s = map(int, raw_input().split())[:n]
res = 0
mins, maxs = s[0], s[0]
for i in range(1, n):
if mins > s[i]:
res += 1
mins = s[i]
if maxs < s[i]:
res += 1
maxs = s[i]
print res |
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that:
* If we consider any color, all elements of this color must be divisible by the minimal element of this color.
* The number of used colors must be minimized.
For example, it's fine to paint elements [40, 1... | 3 | n=int(input())
l=[]
l=list(map(int,input().split()))
l=list(set(l))
l = sorted(l)
#print(l)
check=[]
what=[]
#print(l)
for i in range(len(l)):
if l[i] not in check:
check.append(l[i])
temp=[]
temp.append(l[i])
for j in range(i+1,len(l)):
if l[j] not in check:
... |
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 | k,n,w = map(int, input().split(" "))
cost = 0
for i in range(1,w+1):
cost += i*k
print(max( cost - n , 0) ) |
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] m... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
b=[j%2 for j in range(n)]
c=[a[j]%2 for j in range(n)]
d,e=[],[]
for j in range(n):
if c[j]!=b[j] and c[j]==0:
d.append(j)
elif c[j]!=b[j] and c[j]==1:
e.append(j)
if len(d)==len(e):
print(len(d))
else:
print(-1) |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
m = 0
result = 0
for i in range(n):
k = list(map(int, input().split()))
for j in range(3):
m += k[j]
if m > 1:
result += 1
m = 0
print(result) |
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game...
In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f... | 3 | t=int(input())
for q in range(0,t):
n=int(input())
a=input()
if n==1:
if int(a)%2==0:
print(2)
else:
print(1)
elif len(a)%2==0:
# if even number of digits
ans=1
for i in range(1,n,2):
if int(a[i])%2==0:
ans=2
... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n=int(input())
lst=list(map(int,input().split()))
lst=sorted(lst)
count=0
add=0
total=sum(lst)
for coins in reversed(lst):
add+=coins
count+=1
total-=coins
if add>total:
break
print(count)
|
"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().split(" "))
p = list(map(int,input().split(" ")))
counter = 0
for i in range(n):
if(p[i]>=p[k-1] and p[i]>0):
counter += 1
print(counter) |
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | 3 | n=int(input())
a=[int(n) for n in input().split(" ")]
n=n-1
if a[n]==15:
print("DOWN")
elif a[n]==0:
print("UP")
elif n==0:
print("-1")
elif n>0:
if a[n-1]>a[n]:
print("DOWN")
else:
print("UP")
|
You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0.
Write the program which finds the number of points in the intersection of two given sets.
Input
The first line of the input contains three integer numb... | 3 | def res():
a,b,c=map(int,input().split(" "))
d,e,f=map(int,input().split(" "))
if((a==0 and b==0 and c!=0) or (d==0 and e==0 and f!=0)):
print(0)
return
if(b==0 and e==0):
k=-100
while(k<=100):
if(a*k==d and b*k==e and c*k==f):
print(-1)
return
k=k+1
print(0)
return
if(b==0):
if(a==... |
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 =m*n
ans =0
if c > 1 :
if c%2 ==0:
ans = c/2
else:
c=c-1
ans = c/2
print(int(ans)) |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | t=int(input())
for j in range(t):
n=int(input())
a=[int (i) for i in input().split()]
b=[a[0]]
ans=0
for i in range(1,n):
if a[i]>0 and a[i-1]>0:
b.append(a[i])
elif a[i]<0 and a[i-1]<0:
b.append(a[i])
else:
ans+=max(b)
b=[a[i]]
ans+=max(b)
print(ans) |
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob... | 3 | def fact(n):
return fact(n-1)*n if n>1 else 1
def c(k, n):
return fact(n)//fact(k)//fact(n-k)
n = int(input())
print(c(5,n)**2*120)
|
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | k,n=map(int,input().strip().split())
count=0
for i in range(100):
if k>n:
break
else:
k=k*3
n=n*2
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... | 3 | L = list(map(int, input().split('+')))
L = sorted(L)
L = list(map(str,L))
print('+'.join(L)) |
There is a train going from Station A to Station B that costs X yen (the currency of Japan).
Also, there is a bus going from Station B to Station C that costs Y yen.
Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then trav... | 3 | s=input().split()
print(int(s[0])+int(s[1])//2) |
Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i.
Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j.
Games in the shop are ordered from left to right, Maxim tries to buy every game i... | 3 | n,m=map(int,input().split())
c=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
count=0
for i in range(0,n):
#print(i)
if(a[0]>=c[i]):
#print(a[0],c[i])
del(a[0])
count+=1
if(len(a)==0):
break
print(count) |
You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.
Here, a self-loop is an edge where a_i = b_i (1β€iβ€M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1β€i<jβ€M).
How many different paths start from vertex 1 and vi... | 3 | import itertools
N, M = map(int, input().split())
edges = {tuple(sorted(map(int, input().split()))) for _ in range(M)}
answer = 0
for i in itertools.permutations(range(2, N+1), N-1):
l = [1] + list(i)
answer += sum(1 for edge in zip(l, l[1:]) if tuple(sorted(edge)) in edges) == N-1
print(answer) |
Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:
* A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.
* Bob won some programming competition and got a 2x MB memory ... | 3 | import math
n = int(input())
Size = 2002
dp = [0] * (Size)
for i in range(0, Size, 1) :
dp[i] = -1
dp[0] = 0
for i in range (1 , n+1 , 1):
s = input()
In = s.split()
x = int(In[1])
x = x + 1
if In[0] == "win" :
dp[x] = max(0, dp[0])
if In[0] == "sell" :
if dp[x] != -1 :
... |
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it o... | 3 | n,m = map(int, input().split())
rooms = [int(i) for i in input().split()]
lets = [int(i) for i in input().split()]
ind = 0
prev = 0
for let in lets:
while prev + rooms[ind] < let:
prev += rooms[ind]
ind += 1
print(ind+1, let-prev) |
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | 1 | _ = raw_input()
letters = map(int, raw_input().split())
steps = 0
inside = False
for i in range(len(letters)):
if letters[i] == 1:
steps += 1
inside = True
elif inside:
steps += 1
inside = False
if letters[-1] != 1:
steps -= 1
steps = max(0, steps)
print steps
|
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 | import math
m=0
n,t=[int(i) for i in input().split()]
value=0
while n>=1:
value+=n
m=m+n%t
n=math.floor(n/t)
if m>=t:
value+=math.floor(m/t)
m=1+m%t
#print(n,m)
print(value)
|
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 | n = input()
if ('0000000' in n) or ('1111111' in n):
print("YES")
else:
print("NO")
|
Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?
Constraints
* 1 \leq N \leq 50
* 1 \leq A \leq 50
* 1 \leq x_... | 3 | N,A = map(int,input().split())
X = list(map(int,input().split()))
dp = [[[0 for k in range(2501)] for j in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
x = X[i-1]
dp[i][1][x] += 1
for j in range(1,i+1):
for k in range(1,2501):
if k-x > 0:
dp[i][j][k] += dp[i-... |
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 β€ k β€ n) such that the ratings of all team members are distinct.
If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri... | 3 | from collections import OrderedDict
stud_1, team_num = input().split()
stud_1, team_num = int(stud_1), int(team_num)
rating_list = input().split()
rating_list1 = map(lambda x: int(x), rating_list)
rating_list1 = list(rating_list1)
non_d = []
non_d_in = []
for pos,ele in enumerate(rating_list1):
if ele not in non_... |
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10.
You... | 1 | # your code goes here
for i in range(input()):
n,m=map(int,raw_input().split())
a=[0 for j in range(10)]
a[1]=45
a[2]=40
a[3]=45
a[4]=40
a[5]=25
a[6]=40
a[7]=45
a[8]=40
a[9]=45
ans=((n/m)-((n/m)%10))/10
ans*=a[m%10]
for j in range(1,(n/m)%10+1):
ans+=((m*... |
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... | 3 | n = int(input())
p = [int(i) for i in input().split()]
print(100*(sum(p) / 100) / n)
|
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.
To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t... | 1 | R = lambda:map(int,raw_input().split())
n,k = R()
a = R()
b = R()
b.sort()
k=0
for i in xrange(len(a)):
if a[i]==0:
a[i]=b[k]
k += 1
#print a
s = True
for i in xrange(len(a)):
prev,nxt = True,True
if i>0: prev = a[i-1]<a[i]
if i<len(a)-1: nxt = a[i+1]>a[i]
s = prev and nxt
if not s:
brea... |
An agent called Cypher is decrypting a message, that contains a [composite number](https://en.wikipedia.org/wiki/Composite_number) n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle.
In one move Cypher can choose two adjacent numbers in ... | 3 |
import math
def iinput():
return int(input())
def finput():
return float(input())
def linput():
return [int(_) for _ in input().split()]
def gcd(x, y):
if y == 0:
return x
return gcd(y, x%y)
T = iinput()
for _ in range(T):
n = iinput()
s = int(math.sqrt(n))
divs = []
c... |
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010...
Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal... | 3 | for _ in range(int(input())):
n,X=[int(x) for x in input().split()]
arr=input()
asum=[0]
for i in range(n):
asum.append(asum[-1] + (1 if arr[i]=='0' else -1))
if asum[-1]==0:
if X in asum:
print(-1)
else:
print(0)
continue
else:
tot... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | a = ["hate", "love"]
n = int(input())
for i in range(n):
print("I " + a[i % 2] + (" it" if i == n - 1 else " that "), end="") |
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 | my_inp=input()
list=my_inp.split("+")
ordered=[]
done=[]
for char in list:
ordered.append(int(char))
ordered.sort()
for char in ordered:
done.append(str(char))
print("+".join(done)) |
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it:
* At first, choose index i (1 β€ i β€ n) β starting position in the array. Put the chip at the index i (on the value a_i).
* While i β€ n, add a_i to your score and move the chip a_i positions to the right (i.e. r... | 1 |
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
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase)... |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | 3 | treasure = int(input())
s = input()
if treasure <= 2:
print(0)
else:
pos1 = "0"
access = treasure - 1
i = 0
j = 0
pos33 = 0
while pos33 != -1:
pos1 = s.find(" ")
number1 = s[0:pos1]
number11 = int(number1)
s = s.replace(number1, "", 1)
s = s.replace(" ... |
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 | T = int(input())
for test in range(T):
n = int(input())
s = input()
ans = 0
ok, rev = 0, 0
for el in s:
if el == '(':
ok += 1
else:
rev += 1
if rev > ok:
ans += 1
rev -= 1
print(ans) |
The professor is conducting a course on Discrete Mathematics to a class of N students. He is angry at the lack of their discipline, and he decides to cancel the class if there are fewer than K students present after the class starts.
Given the arrival time of each student, your task is to find out if the class gets ca... | 1 | t = int(raw_input())
while(t):
cnt = 0
n,k=map(int,raw_input().split())
lis = list(map(int,raw_input().split()))
for i in lis:
if(i<=0):
cnt+=1
if(cnt>=k):
print ("NO")
else:
print("YES")
t-=1 |
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha... | 1 | T=input()
d={}
score=[25, 18, 15, 12, 10, 8, 6, 4, 2, 1]
for race in xrange(T):
n=input()
for i in xrange(n):
s=raw_input()
if not s in d:
d[s]=[0]*51 + [s]
#print d
if i<10:
d[s][0] += score[i]
d[s][i+1] += 1
print max(d.itervalues())[51]
for ... |
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | x=int(input())
for i in range(x):
ch=input()
l=ch.split(" ")
sume=0
for i in l:
sume=sume+int(i)
print(sume // 2)
|
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which
* two planks of length at least k+1 β the base of the ladder;
* k planks of length at least 1 β the steps of the ladder;
Note that neither the base planks, nor the steps planks are required to be equal.
For example... | 3 | t=int(input())
for _ in range(t):
n=int(input())
A=[int(x) for x in input().split()]
A.sort(reverse=True)
k=A[1]-1
print(min(k,n-2))
|
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 | c = input()
d = 0
x = input().split()
for i in range(5):
if(x[i][0] == c[0] or x[i][1] == c[1]):
print("YES")
d = 1
break
if (not d):
print("NO") |
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
<image>
You should count, how many there are pai... | 3 | n,m = map(int,input().split())
if n>m:
largest = n
else:
largest = m
pair = 0
for a in range (0,largest+1):
for b in range (0, largest+1):
if ((a**2)+b==n) and (a+(b**2)==m):
pair+=1
print(pair)
|
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | 3 | t=int(input())
for i in range(t):
n=int(input())
if n%2==0:
z='1'*(n//2)
print(z)
else:
z='7' + '1'*((n-3)//2)
print(z) |
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?
Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.
Constraints
* 1 \leq N \leq 100
* N is an integer.
Input
Input is given from S... | 3 | from collections import Counter as c
from itertools import permutations as p
def fact(n):
d=[]
for i in range(2,int(n**0.5)+2):
while n%i==0:
n//=i
d.append(i)
if n!=1:d.append(n)
return c(d)
n=int(input())
d=c()
for i in range(1,n+1):
d+=fact(i)
v=sum(1 for i,j,k ... |
You are given a special jigsaw puzzle consisting of nβ
m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 3 | t = int(input())
for i in range(t):
n, m = map(int, input().split())
if(n == 1):
print("YES")
elif(m == 1):
print("YES")
elif(n<=2 and m<=2):
print("YES")
else:
print("NO")
|
We have N ID cards, and there are M gates.
We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.
How many of the ID cards allow us to pass all the gates alone?
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* ... | 3 | n,m=map(int,input().split())
al,bl=[],[]
for i in range(m):
a,b=map(int,input().split())
al.append(a)
bl.append(b)
print(max(min(bl)-max(al)+1,0)) |
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())
from math import ceil
for i in range(a):
b,c=map(int,input().split())
if b==1 or b==2:
print(1)
else:
print(ceil((b-2)/c)+1) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 3 | s=input()
t=input()
r=''
for i in range(len(s)):
if s[i]==t[i]:
r+='0'
else:
r+='1'
print(r) |
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 | n,bit=map(int,input().split())
arr=list(map(int,input().split()))
odd=0
even=0
coin=0
part=0
d=[]
for r in range(len(arr)-1):
if arr[r]%2==0:
even+=1
else:
odd+=1
if odd==even:
d.append(abs(arr[r+1]-arr[r]))
d=sorted(d)
for r in range(len(d)):
coin+=d[r]
if coin... |
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim... | 3 | from sys import stdin, stdout, stderr, setrecursionlimit
setrecursionlimit(100000)
def debug (*e):
if not __debug__:
print(*e, file=stderr)
def dd(*vals):
import inspect, re
frame = inspect.getframeinfo(inspect.stack()[1][0])
vs = re.search("dd\((.+)\)", frame.code_context[0]).group(1).split("... |
There are n students standing in a row. Two coaches are forming two teams β the first coach chooses the first team and the second coach chooses the second team.
The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive.
Firstly, the first coach will choose ... | 3 | n, k = map(int, input().split())
A = list(map(int, input().split()))
A = [(a, i) for i, a in enumerate(A)]
A.sort(key=lambda x: x[0])
A.reverse()
left = [-1] * n
for i in range(1, n):
left[i] = i - 1
right = [-1] * n
for i in range(n - 1):
right[i] = i + 1
vis = [0] * n
join = [0] * n
jo = 1
for i in range(n):
if... |
Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`.
When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.
Then, he rewrote the code to correctly solve each of th... | 3 | a,b = map(int,input().split())
print((b*1900+(a-b)*100)*(2**b)) |
Find the minimum area of a square land on which you can place two identical rectangular a Γ b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 β€ a, b β€ 100) β positive integers (you are given ... | 3 | import math
t=int(input())
while t:
t-=1
a,b=map(int,input().split())
c=2*min(a,b)
d=max(c,max(a,b))
print(d**2) |
There are N slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i.
Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime:
* Choose two adjacent slimes, and combine them into a new slime. The new sli... | 3 | N = int(input())
a = list(map(int, input().split()))
DP = [[[0] * 2 for _ in range(N)] for _ in range(N + 1)]
for i in range(N):
DP[1][i] = [a[i], 0]
for i in range(2, N + 1):
for j in range(N - i + 1):
DP[i][j][0] = DP[1][j][0] + DP[i - 1][j + 1][0]
DP[i][j][1] = DP[i][j][0] + DP[i][j][1] + DP[i - 1][j +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.