problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
The only difference between easy and hard versions is the constraints.
Polycarp has to write a coursework. The coursework consists of m pages.
Polycarp also has n cups of coffee. The coffee in the i-th cup Polycarp has a_i caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can dri... | 3 | # -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict, namedtuple
from math import sqrt, factorial, gcd, ceil, atan, pi
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.... |
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. ... | 3 | N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
ans = 0
f = True
while f:
f = False
for i in range(N):
a,b,c = B[(i-1)%N],B[i],B[(i+1)%N]
if b > a+c and b > A[i]:
if (b-A[i])%(a+c)==0:
B[i] = A[i]
ans += (b-A[i]... |
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 | def caps_lock(s):
b=s
if s.islower() and len(s)==1:
b=s.upper()
if s.isupper():
b=s.lower()
if s[0].islower() and s[1:].isupper():
b=s[0].upper()+s[1:].lower()
return b
# --------------------------------------------------------------
if __name__ == '__main__':
print(caps_... |
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 | def read_int():
inp = map(int, input().strip().split())
return inp
def test():
n, = read_int()
s = input().strip()
count = {0: {0: 0, 1: 0}, 1: {0: 0, 1: 0}}
for i, v in enumerate(s, 1):
v = int(v)
count[i % 2][v % 2] += 1
if n % 2:
if count[1][1]:
print... |
Alice lives on a flat planet that can be modeled as a square grid of size n × n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water.
<image> An example planet with n = 5. It also appears i... | 3 | from collections import deque
from sys import stdin
input=stdin.readline
def bfs(sx,sy,vis,grid):
points=[[0,1],[0,-1],[1,0],[-1,0]]
q=deque()
q.append([sx,sy])
vis[sx][sy]=0
while q:
x,y=q.popleft()
for ptx,pty in points:
if x+ptx>=0 and y+pty>=0 and x+ptx<len(grid) and y+pty<len(grid[0]) and vis[x+ptx][y... |
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine... | 3 | p=input()
q=input()
print(p.count(q))
|
There are N cards. The i-th card has an integer A_i written on it. For any two cards, the integers on those cards are different.
Using these cards, Takahashi and Aoki will play the following game:
* Aoki chooses an integer x.
* Starting from Takahashi, the two players alternately take a card. The card should be chose... | 3 | from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursi... |
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible num... | 3 | n, m, s, t = list(map(int , input().split()))
dors = []
for i in range(n+1):
dors.append(set()) # инициализируем множество смежных вершин
for i in range(m):
a, b = list(map(int , input().split()))
dors[a].add(b)
dors[b].add(a)
dists = [-1] *(n+1) # расстояния от старта
dists[s] = 0
q = [s]
v = 0
whi... |
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?
Note, that you can't keep bags for yourself or thro... | 3 | a1, a2, a3, a4 = list(map(int, input().strip().split()))
X = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 0], [1, 0, 1, 0], [0, 0, 1, 1], [1, 0, 1, 1], [
0, 1, 0, 0], [1, 1, 0, 0], [0, 1, 0, 1], [1, 1, 0, 1], [0, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1], [1, 1, 1, 1]]
flag = 1
for B in X:
if... |
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str... | 1 | for _ in range(input()):
a,b=[int(i) for i in raw_input().split()]
if b>=2*a:
print "NO"
else:
print "YES"
|
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... | 1 | # In the name of Allah
# Force converting the chars to lower case
a=raw_input().lower()
b=raw_input().lower()
print cmp(a,b) # cmp compares to string x,y for me
|
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
* either the boy in the dancing pair must dance for the first time (so... | 3 | #190 div 2 A. Ciel and Dancing
data = input().split(" ")
boys = int(data[0])
girls = int(data[1])
total = boys + (girls-1)
print(total)
for g in range(girls):
print("1 %s" %(g+1))
for b in range(1, boys):
print("%s %s" %(b+1, girls)) |
A Hitachi string is a concatenation of one or more copies of the string `hi`.
For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not.
Given a string S, determine whether S is a Hitachi string.
Constraints
* The length of S is between 1 and 10 (inclusive).
* S is a string consisting of lowerc... | 3 | s = input()
if s.count("hi") == len(s) / 2:
print("Yes")
else:
print("No") |
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | a=input()
c=0
for i in a:
if(i =='4' or i == '7'):
c+=1
if c == 4 or c == 7:
print('YES')
else:
print('NO')
|
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | 3 | import math
t=int(input())
for _ in range(t) :
n=int(input())
x=math.pi/(4*n)
print(0.5/math.sin(x)) |
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())
imp=0
for i in range(n):
a,b,c=input().split()
if (int(a)+int(b)+int(c))>1:
imp+=1
print(imp) |
Write a program, which takes an integer N and if the number is less than 10 then display "What an obedient servant you are!" otherwise print "-1".
Input
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
Output
Output the given string or -1 depend... | 1 | #!/usr/bin/env/ python
#Servant
#https://www.codechef.com/problems/FLOW008
def servant(n):
if n<10:
return "What an obedient servant you are!"
else:
return -1
t=input()
while t!=0:
t-=1
print servant(input()) |
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | 3 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 20:38:04 2018
@author: dell001
"""
n,m=map(int,input().strip().split())
a=[0]*m
k=1
for i in range(m):
a[i]=k
k+=1
for _ in range(n):
l,r=map(int,input().strip().split())
for i in range(l,r+1):
if i in a:
a.remove(i)
... |
The number 105 is quite special - it is odd but still it has eight divisors. Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?
Constraints
* N is an integer between 1 and 200 (inclusive).
Input
Input is given from Standard Input in the following... | 3 | import bisect;print(bisect.bisect([6,36,66,90,96],int(input())-99)) |
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 | first = "I hate that "
second = "I love that "
line = ""
for i in range(int(input())):
if i % 2 == 0:
line += first
else:
line += second
print(line.strip().rstrip("that") + "it") |
You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.
Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subse... | 3 | input()
ar1 = list(map(int, input().split()))
ar2 = set(list(map(int, input().split())))
ans = []
for a in ar1:
if a in ar2:
ans += [a]
for a in ans:
print(a, end= ' ') |
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak... | 3 | n,k=map(int,input().split())
if k>n or (not(k>n) and n//k%2==0):
print('NO')
if not(k>n) and n//k%2==1:
print('YES')
|
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | # 2nd question - Captain Flint and a Long Voyage
test = int(input())
def solve():
n = int(input())
nine = (n+3)//4
for x in range(n-nine):
print(9,end='')
for x in range(nine):
print(8, end='')
print("")
for x in range(test):
solve() |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 1 | n = input()
count = 0
while n!=0:
if n>=5:
n-=5
elif n==4:
n-=4
elif n==3:
n-=3
elif n==2:
n-=2
elif n==1:
n-=1
count += 1
print count |
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces ... | 1 | import os,sys
inp = raw_input().split()
inp = [int(x) for x in inp]
n = inp[0]
a = inp[1]
b = inp[2]
c = inp[3]
changes = inp[1:]
dp_table = [0 for i in xrange(n+1)]
for ch in changes:
if ch <= n:
dp_table[ch] = 1
#if n in changes:
# print 1
#else:
for i in xrange(n+1):
for c in changes:
if c <= i and dp_tabl... |
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:
1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea... | 3 | for _ in range (int(input())):
n=int(input())
L=list(map(int,input().split()))
L1=list(map(abs,L))
for i in range (1,n,2):
L1[i]*=-1
print(*L1)
|
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the d... | 3 | a=int(input())
b=(a**(1/2))
if b == int(b):
print (int(b),int(b))
else:
if a==2:
print(1,2)
else:
y=1
z=a/2
entre=0
primero=1
while y<z:
entre=1
if a%y==0:
z=a//y
primero=y
... |
Given a string s of length n and integer k (1 ≤ k ≤ n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s:
* x non-intersecting (non-overlapping) substrings of length k,
* all characters of these x substrings are the same (i.e. each substring contains only one ... | 3 | n,k=map(int,input().split())
s=input()
l1=[0]*26
i=0
t=""
while i<len(s):
t=s[i]
c=0
while i<n and s[i]==t and c<k:
c+=1
i+=1
if c==k:
l1[ord(t)-ord('a')]+=1
print(max(l1))
|
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | x,y,z,k = map(int,input().split())
num = sorted([x,y,z,k])
print(num[-1]-num[0],num[-1]-num[1],num[-1]-num[2])
|
The very famous football club Manchester United decided to popularize football in India by organizing a football fest. The fest had many events for different sections of people.
For the awesome coders of Hacker Earth, there was an event called PASS and BACK. In this event, the coders were given N passes and players hav... | 1 | T=input()
#N_P= [int(i) for i in raw_input().split()]
st = []
for n in range(T):
N_P = raw_input().split()
N=N_P[0]
P=[]
P.append(int(N_P[1]))
for i in range(int(N)):
c = raw_input().split()
if c[0]=='B':
P.append(P[len(P)-2])
else:
P.append(int(c[1]))
st.append(P.pop())
for i in st:
print "Player",... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | #!/usr/bin/env python3
n = int(input())
a = [int(x) for x in input().split()]
b = [0] * 100
c = [0] * n
for x in range(n):
for y in range(a[x]):
b[y] += 1
for x in range(100):
for y in range(b[x]):
c[n-y-1] += 1
for x in range(n):
print(c[x], end=" ")
|
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya!
Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya.
Filya works a lot and he plans to visit ... | 3 | l1, r1, l2, r2, k = map(int, input().split())
l = max(l1, l2)
r = min(r1, r2)
if l <= k <= r:
r -= 1
print(max(0, r-l+1))
|
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | """""""""""""""""""""""""""""""""""""""""""""
| author: mr.math - Hakimov Rahimjon |
| e-mail: mr.math0777@gmail.com |
"""""""""""""""""""""""""""""""""""""""""""""
#inp = open("spaceship.in", "r"); input = inp.readline; out = open("spaceship.out", "w"); print = out.write
TN = 1
# =================... |
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 | import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
#sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def power(x, p,m):
res = 1
while p:
if p... |
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 | a=[0,0,0,0]
for i in range(3):
x,y=map(int,input().split())
a[x-1]+=1
a[y-1]+=1
b=1
for i in range(4):
if a[i]==3:
print("NO")
b=0
break
if(b):
print("YES") |
We have N camels numbered 1,2,\ldots,N. Snuke has decided to make them line up in a row.
The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.
Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.
Solve this probl... | 3 | import sys
from heapq import heappush, heappop
from operator import itemgetter
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
N = int(rl())
res = 0
camel_left, camel_right = [], []
for _ in range(N):
K, L, R = map(int, rl().split())
res += min(L, R)
if R <... |
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two equal integers from s, remove them from s and insert the number eq... | 3 |
import math
import collections
def check(a):
cnt = collections.Counter(a)
new_cnt = collections.defaultdict(int)
for k in cnt:
new_cnt[k] = cnt[k]
keys = list(new_cnt.keys())
max_key = max(keys)
for k in range(max_key+10):
new_cnt[k + 1] += new_cnt[k] // 2
if k ==... |
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 | one = input().lower()
two = input().lower()
print("0" if one == two else "1" if one > two else "-1") |
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 ≤ i, j ≤ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is ... | 1 | a=raw_input();print sum(a.count(i)**2for i in set(a)) |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | n = int(input())
li = [5, 4, 3, 2, 1]
c = 0
for i in li:
c += n//i
n %= i
print(c) |
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont... | 3 | import math
n,k=map(int,input().split())
ans=0
for i in range(1,n+1):
if (i%2==1):
print("1",end="")
else:
print("0",end="") |
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 | a = int(input())
if a == 2:
print("NO")
else:
if a%2 == 0:
print('YES')
else:
print('NO') |
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each ot... | 3 | #n = int(input())
m,n = map(int,input().split())
#s = input()
#arr = [int(x) for x in input().split()]
val = int(m**(1/2))
val += 1
temp = val*(val-1)
if n>=temp:
print("Vladik")
else:
print("Valera")
|
Mislove had an array a_1, a_2, ⋅⋅⋅, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | 3 | n,l,r=map(int, input().split())
c=0;
d=0;
for i in range(l):
c=c+pow(2,i)
min=c+n-l
for i in range(r):
d=d+pow(2,i)
f=pow(2,(r-1))
max=d+f*(n-r)
print(min,max) |
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 | a, b = map(int, input().split())
i = 0
while(True):
a *= 3
b *= 2
i += 1
if(a > b):
break
print(i) |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | for _ in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))[:n]
b=list(map(int,input().split()))[:n]
for i in range(k):
if(min(a)<=max(b)):
mina=min(a)
maxb=max(b)
c=a.index(mina)
d=b.index(maxb)
a[c],b[d... |
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel... | 3 | from sys import stdin, stdout
from gc import disable
def main() -> int:
disable()
n = int(stdin.readline())
ans = 6 * (2+(n-1))*n//2 + 1
stdout.write("%i"%ans)
return 0;
if (__name__ == "__main__"):
main() |
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.
One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.
Vasya ha... | 3 | n = int(input())
d = input()
a,b = input().split()
a,b = map(int,[a,b])
D = []
for i in d.split():
D.append(int(i))
Sum = 0
for j in range(a-1,b-1):
Sum = Sum + D[j]
print(Sum) |
N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a ... | 3 | n = int(input())
a = map(int, input().split())
s = 0
m = 0
for e in a:
if e > m:
m = e
else:
s += m - e
print(s)
|
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of... | 3 | a,b = list(map(int,input().split()))
if b ==1 :
print(0)
else :
res = a + b*a*(a+1)//2
res = (res*(b)*(b-1)//2)
print(res%(10**9 +7))
|
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change).
In a prototype progr... | 3 | t=int(input())
for _ in range(t):
a,b,n=map(int,input().split())
steps=0
if a<b:
a,b=b,a
while max(a,b)<=n:
if b<a:
b+=a
else:
a+=b
steps+=1
print(steps) |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length ... | 3 | i = n = int(input())
t = p = 1
mod = 10**9 + 7
while i :
t = t * i % mod
i -= 1
print((t - 2**n // 2) % mod) |
Notes
Template in C
Constraints
2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +... | 3 | import re
pat = re.compile(r'(\-?\d+\.?\d*)\s(\-?\d+\.?\d*)\s([\+\-\*/])(?!\d)')
def revPolish(f):
global pat
f = pat.sub(lambda m: str(eval(m.group(1) + m.group(3) + m.group(2))),f)
if f[-1] in '+-*/':
return revPolish(f)
else:
return f
print(revPolish(input()))
|
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | 3 | #https://codeforces.com/problemset/problem/27/A
n=int(input())
l=list(map(int,input().split()))
l.sort()
ans=0
for i in range(n):
if l[i]!=i+1:
ans=i+1
break
if not ans:
ans=n+1
print(ans)
|
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of n men (n is always even). The current player sp... | 3 | #Total Turns = 3
#There's always a 2n number when starting the game
print((3*int(input()))//2)
|
You are given a connected undirected simple graph, which has N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices A_i and B_i. Your task is to find a path that satisfies the following conditions:
* The path traverses two or more vertices.
* The... | 3 | from collections import deque as dq
N,M=map(int,input().split())
Graph=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
Graph[a-1].append(b-1)
Graph[b-1].append(a-1)
path=dq(["1",str(Graph[0][0]+1)])
p=[False]*N
ep1=0
ep2=Graph[0][0]
p[ep1],p[ep2]=True,True
flag=0
while len(path)<=N:
for ... |
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox.
In one minute each friend independently from other friends can change the position x by 1 to the... | 3 | n = int(input())
resultados = ""
def get_saltos(minimo,medio,maximo):
global resultados
total = 0
if minimo == medio or maximo == medio:
if maximo - medio == 1 or minimo - medio == -1:
resultados += "0 "
else:
maximo -= 1
minimo += 1
resultado... |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | 3 | n,p=map(int,input().split())
c=1
for i in range(1,10) :
if (n*i-p)%10==0 :
print(i)
c=0
break
if (i*n)%10==0 :
print(i)
c=0
break
if c==1 :
print(10)
|
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.
Today, when IA looked at the fridge, she noticed that... | 3 | s=input()
a=[]
for i in range(0,len(s)-1):
if(s[i]!=s[i+1]):
a.append(1)
else:
a.append(0)
if(s[-1]=="b"):
a.append(0)
else:
a.append(1)
for i in range(len(s)):
print(a[i],end=" ")
|
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
You have a sequence of integers a1, a2, ..., an. In on... | 3 | def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(... |
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase ... | 3 | s=input()
n=int(input())
l=list(map(int,input().split()))
m=max(l)
#s=s+chr(m+96)*n
c=0
j=1
for i in range(1,len(s)+1):
#print(l[ord(s[i-1])-96-1])
c+=(l[ord(s[i-1])-96-1])*i
j+=1
#print(c)
#print(j)
for i in range(n):
c+=j*m
j+=1
print(c) |
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first... | 1 | n, k = map(int, raw_input().split())
s = [ord(x) - ord('0') for x in raw_input()]
cur = 0
while cur < len(s) and k > 0:
if cur == 0 and len(s) > 1:
if s[cur] > 1:
s[cur] = 1
k -= 1
else:
if s[cur] > 0:
s[cur] = 0
k -= 1
cur += 1
print(''.join... |
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).
Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.
You have to answer t independent test cases.
Input
The fi... | 3 | for testcase in range(int(input())):
n = int(input())
cnt2, cnt3 = 0, 0
while n % 2 == 0:
n //= 2
cnt2 += 1
while n % 3 == 0:
n //= 3
cnt3 += 1
if n > 1 or cnt3 < cnt2:
print(-1)
continue
print(2 * cnt3 - cnt2)
|
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.
For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbit... | 3 | import math
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
n=int(input())
a,b=map(int,input().split())
for i in range(n-1):
x,y=map(int,input().split())
x=x*y
a=gcd(a,x)
b=gcd(b,x)
if(a==1 and b==1):
print(-1)
exit()
else:
i=2
while((i*i<=a) or (i*i<=b))... |
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | 3 | import math
for _ in range(int(input())):
a,b,c=map(int,input().split())
d=c/b
if a<=d and a*b<=c:
print(1,end=" ")
print(-1)
elif a*b>c and a>=c:
print(-1,b)
elif a>=d and a<c:
print(1,end=" ")
print(b)
|
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re... | 3 | import sys
import math
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
import math
t=int(input())
for q in range(t):
n, k = inputnums()
s = inputstring(... |
Unlucky year in Berland is such a year that its number n can be represented as n = xa + yb, where a and b are non-negative integer numbers.
For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 20 + 31, 17 = 23 + 32 = 24 + 30) and year 18 isn't unlucky as there is no such representation for it.
Su... | 1 | x, y, l, r = map(int, raw_input().split())
A = [1]
tmp = 1
while tmp <= 1e18:
tmp *= x
A.append(tmp)
if y == x:
B = A
else:
B = [1]
tmp = 1
while tmp <= 1e18:
tmp *= y
B.append(tmp)
unluckies = []
for a in A:
for b in B:
tmp = a + b
if tmp >= l and tmp <= r:
... |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th... | 3 | n = int(input())
for i in range(n):
x = int(input()); ans = 0
for k in range(1,x//3+1):
if (x%(3*k))%7 == 0:
ans = 1
break
for k in range(1,x//7+1):
if (x%(7*k))%3 == 0:
ans = 1
break
if ans: print("YES")
else: print("NO") |
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | 1 | from sys import stdin, stdout
input()
inp = stdin.readlines()
out = []
ptr = 0
while ptr < len(inp):
n = int(inp[ptr]); ptr += 1
a = map(int, inp[ptr].split()); ptr += 1
ans = 0
for i in xrange(1, n):
if a[i - 1] <= a[i]: continue
x = abs(a[i - 1] - a[i])
p2 = 1
k = ... |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 3 |
I0 = lambda :map(int,input().split())
I1 = lambda :int(input())
I2 = lambda :list(map(int,input().split()))
#####################################################
from math import log2,ceil
n,m = I0()
res = 0
while m>=n and n!=m:
if m%2==0:m//=2
else:m+=1
res+=1
print(res+(n-m))
|
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n,t= map(int,input().split())
s = str(input())
for i in range(t):
s=s.replace("BG","GB")
print(s)
|
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a n× m grid (rows are numbered from 1 to n, and columns are nu... | 3 | from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
#sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
#sys.stdout = BytesIO()
#register(lambda: os... |
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.
The bus stop queue has n groups of people. The i-th group from the beginning has ... | 1 | r = 1
n, m = map(int, raw_input().split())
arr = map(int, raw_input().split())
z = m
for i in arr:
if z < i:
z = m - i
r += 1
else:
z -= i
print r
|
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected ... | 3 |
List = list(map(str,input().split()))
a = List[0]
b = List[1]
n = int(input())
kill= []
replace =[]
for i in range(n):
Killer = list(map(str,input().split()))
c = Killer[0]
d= Killer[1]
#print(a,b)
kill.append(a)
replace.append(b)
if(c==a):a=d
else: b=d;
for i in range(n):
print(kil... |
Polycarp has an array a consisting of n integers.
He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its... | 3 | n=int(input())
A=list(map(int,input().split()))
E=list()
O=list()
e=0
o=0
s=0
for i in A:
if(i%2==0):
E.append(i)
e+=1
else:
O.append(i)
o+=1
E.sort()
O.sort()
E=E[::-1]
O=O[::-1]
if(e>o):
A.remove(E[0])
E.pop(0)
for i in range(0,o):
A.remove(E[i])
A.r... |
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.
Vasiliy plans to buy his favorite drink fo... | 3 | from bisect import bisect_right
input()
prices = sorted(map(int, input().split()))
print(*(bisect_right(prices, int(input())) for _ in range(int(input()))), sep='\n') |
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store... | 3 | for _ in range(int(input())):
n,p,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
r1=1*(a[0]<=p)
r2=0
t1=0
t2=1*(a[0]<=p)
p1=p-a[0]*(a[0]<=p)
p2=p
for i in range(1,n):
if a[i]<=p1:
if t1==0:
t1=1
else:
... |
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.
You're given a number. Determine if it is a magic number or not.
Input
The first line of input contains ... | 3 | def solve(num):
str1 = list(str(num))
if num == 1:
return 'YES'
elif num > 1 and num < 11:
return 'NO'
prevPrev = str1[0]
prev = str1[1]
if prevPrev != '1':
return 'NO'
if prev != '1' and prev != '4':
return 'NO'
length = len(str1)
for ... |
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.
Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all... | 3 | n = list(map(int, input().split()))
a = list(map(int, input().split()))
a.reverse()
mx = a[0]
ans = list()
ans.append(0)
for i in a[1:]:
ans.append(max(0, mx - i + 1))
mx = max(mx, i)
ans.reverse()
p = ''
for i in ans:
p += i.__str__() + ' '
print(p)
|
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again.
Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, ..., d_n (-10^6 ≤ d_i ≤ 10^6). Th... | 3 | from sys import exit
from itertools import accumulate
H, n = map(int, input().split())
L = map(int, input().split())
LA = list(accumulate(L))
for i, v in enumerate(LA, 1):
if H + v <= 0:
print(i)
exit()
if LA[-1] >= 0:
print(-1)
exit()
loop = LA[-1]
print(min([-(-(H+LA[i-1])//(-loop))*n + 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 | from sys import stdin,stdout
t = 1
t=int(input())
for i in range(t):
#solve
n=int(input())
ans=0
while n>=10:
ans+=(n//10)*10
n=n//10+n%10
print(ans+n) |
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wan... | 1 | l = lambda: map(int, raw_input().split())
m = input()
a,b = l(),l()
b = [(i,x) for i, x in enumerate(b)]
c = [0] * m
a.sort(reverse=True)
b.sort(key=lambda x:x[1])
for i, x in enumerate(b):
c[x[0]] = a[i]
print ' '.join(map(str,c)) |
You have a string s consisting of n characters. Each character is either 0 or 1.
You can perform operations on the string. Each operation consists of two steps:
1. select an integer i from 1 to the length of the string s, then delete the character s_i (the string length gets reduced by 1, the indices of characters ... | 3 | from sys import stdin,stdout
import math,bisect
from collections import Counter,deque,defaultdict
L=lambda:list(map(int, stdin.readline().strip().split()))
M=lambda:map(int, stdin.readline().strip().split())
I=lambda:int(stdin.readline().strip())
S=lambda:stdin.readline().strip()
C=lambda:stdin.readline().strip().split... |
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the displ... | 1 | #delme
raw_input()
number = map(int, list(raw_input()))
minimun = int(len(number) * '9')
for i in range(len(number)):
number = [number[-1]] + number[:-1]
sum = 10 - number[0]
number = [(n+sum)%10 for n in number]
minimun = min(minimun, int(''.join(map(str, number))))
zeros = ''
if len(str(minimun)) < len(number):... |
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ... | 3 | t = int(input())
while t != 0:
n = int(input())
a = list(map(int, input().split()))[:n]
a.sort()
net = []
for i in range(n):
aa = a[(n - 1 + i) % n]
bb = a[(n - 2 + i) % n]
cc = a[(n - 3 + i) % n]
dd = a[(n - 4 + i) % n]
ee = a[(n - 5 + i) % n]
high = ... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | num1=list(map(int,input().split()))
a=num1[0]
i=0
while i<num1[1]:
if a%10==0:
a=int(a/10)
else:
a-=1
i+=1
print(a) |
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | for _ in range(int(input())):
n,k=map(int,input().split())
s=input()
pre_one=False
i=0
j=0
ans=0
if(n==k):
if(s.count('1')==0):
print(1)
else:
print(0)
else:
while(i<n):
pre_one=False
if(s[i]=='1'):
i... |
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t).
Input
The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ... | 3 | import itertools
from functools import reduce
t = int(input())
for _ in range(t):
n = int(input())
a = [int(i) for i in input().split()]
pos = reduce(lambda acc,cur:acc+int(cur>0), a, 0)
a.sort()
if(n > 10):
a = a[:5] + a[-5:]
res = -pow(10,25)
for comb in itertools.combinations(a,... |
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | 1 | from fractions import gcd
g = map(long, raw_input().split())
t = g[0]
w = g[1]
b = g[2]
k = min(w, b)
lcm = w*b/(gcd(w, b))
if ((t/lcm) == 0):
res = min(w-1, b-1, t%lcm)
else:
res = (t/(lcm))*(min(w, b)) - 1 + min(w, b, t%lcm+1)
print str(res/gcd(res, t)) + '/' + str(t/gcd(res, t))
|
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for n days. On the i-th day:
* If Du can speak, he'll make fun of Boboniu ... | 3 | # -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def rea... |
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an... | 1 | "Template made by : https://codeforces.com/profile/c1729 , github repo : https://github.com/cheran-senthil/PyRival"
from __future__ import division, print_function
import bisect
import math
import itertools
import sys
from atexit import register
if sys.version_info[0] < 3:
from io import BytesIO as stream
else:
... |
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
* the queen's weight is 9,
* the rook's weight is 5,
* the ... | 3 | __author__ = 'eunice'
class A:
def a(self,board):
aCount = 0
bcount = 0
values = {'q': 9, 'r': 5, 'b': 3, 'n': 3, 'p': 1, 'k': 0, 'Q': 9, 'R': 5, 'B': 3, 'N': 3, 'P': 1, 'K': 0, '.': 0}
validvalues = {'q', 'r', 'b', 'n', 'p', 'k', '.'}
for i in board:
if i.lower... |
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.
The j-th key can be used to unlock the ... | 3 | n,m = [int(n) for n in input().split()]
a = [int(n) for n in input().split()]
b = [int(n) for n in input().split()]
a_even = 0
a_odd = 0
b_even = 0
b_odd = 0
for i in range(n):
if a[i]%2==0:
a_even+=1
else:
a_odd+=1
for i in range(m):
if b[i]%2==0:
... |
You are given a string S.
Takahashi can insert the character `A` at any position in this string any number of times.
Can he change S into `AKIHABARA`?
Constraints
* 1 \leq |S| \leq 50
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If it i... | 3 | #1
#入力
S=input()
#処理
import re
m=re.fullmatch(r'A?KIHA?BA?RA?',S)
if m==None:
print("NO")
else:
print("YES")
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | n = int(input())
for i in range(n):
t = input()
# print(e)
res = []
while int(t) > 0:
e = int('1' + '0'*(len(t) - 1))
t = int(t)
res.append(t - (t % e))
t %= e
t = str(t)
print(len(res))
print(' '.join(str(i) for i in 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... | 1 | from collections import Counter
n = int(raw_input())
t = map(int, raw_input().split())
c = Counter(t)
s = 0
for val in c:
if val > 0 and -val in c:
s += c[val] * c[-val]
print s + (c[0]**2 - c[0])/2
|
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | count=0
for i in range(int(input())):
n=int(input())
s=[]+list(map(int, input().split()))
for i in range(n):
if s[i]==0:
s[i]+=1
count+=1
if sum(s)==0:
s[0]+=1
count+=1
print(count)
count=0 |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | import math
n = int(input())
b = map(int, input().split())
one = 0
two = 0
three = 0
four = 0
remaining_two = 0
for i in b:
if i == 1:
one += 1
elif i == 2:
two += 1
elif i == 3:
three += 1
elif i == 4:
four += 1
ans = 0
ans += four
ans += int(math.floor(two/2))
remainin... |
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's an... | 3 | n=int(input())
a=int(input())
b=int(input())
c=int(input())
mmin = min(a, b, c)
if mmin == a or mmin == b:
print((n - 1) * mmin)
elif n!=1:
print(min(a, b) + (n-2)* mmin)
else:
print(0)
|
Navi got a task at school to collect N stones. Each day he can collect only one stone. As N can be a very large number so it could take many days to complete the task, but then he remembers that his mother gave him a magic that can double anything (i.e if he has 2 stones, the magic will make them to 4 stones). Navi ... | 1 | __author__ = 'legion'
iteration = int(raw_input())
for num in range(iteration):
count = 0
input_no = int(raw_input())
while input_no:
input_no &= input_no - 1
count += 1
print count |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.