problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given a string s consisting of `A`, `B` and `C`.
Snuke wants to perform the following operation on s as many times as possible:
* Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`.
Find the maximum possible number of operations.
Constraints
* 1 \leq |s| \leq 200000
* Each char... | 3 | import re
s = input()
subs = re.sub('BC', 'X', s)
answer = 0
A = 0
for i in range(len(subs)):
if subs[i] == 'A' :
A += 1
elif subs[i] == 'X':
answer += A
else:
A = 0
print(answer) |
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.
In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ... | 3 | s=input()
snew=''
for i in s:
if (len(snew)>=2 and snew[-1]==snew[-2]==i) or \
(len(snew)>=3 and snew[-3]==snew[-2] and snew[-1]==i):
continue
snew+=i
print(snew)
|
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive.
Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on.
Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone... | 3 | def testcase():
x = int(input())
d = x % 10
l = len(str(x))
ans = (d - 1) * 10 + l * (l + 1) // 2
print(ans)
return
t = int(input())
for _ in range(t):
testcase() |
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | n = int(input())
a = list(map(int, input().split(" ")))
b = list(map(int, input().split(" ")))
x = 0
for i in range(1,n+1):
if((i in a[1:] or i in b[1:])):
x += 1
if(x==n):
print("I become the guy.")
else:
print("Oh, my keyboard!") |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | n = input()
count = 0
a = 1
while int(n)!=0 and a<=len(n):
count+=1
a+=2
if int(n) == pow(10, a-3): print(count-1)
else : print(count) |
The Titanic ship is sinking. The nearest ship has answered the SOS call, and come to rescue the people. Everyone is anxious to get to safety. Unfortunately, the new ship may not have enough room to take everyone to safe land. This adds to the anxiety of people.
To avoid stampede, there has to be some rescue plan. You... | 1 | t = int(raw_input())
for _ in range(t):
n, men, women, children = map(int, raw_input().split())
max_women = min(women, 2*men)
max_children = min(children, 4*(men+max_women))
rC = min(n*4/5,max_children)
rW = min(max_women, (n-rC)*2/3)
rM = min(men,n-rW-rC)
print rM,rW,rC |
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t... | 3 | from sys import stdin
def findpass(s):
arr = suff_array(s)
n = len(s)
maxidx = arr[n - 1]
valid = False
for i in range(n - 1):
if arr[i] == maxidx:
valid = True
break
if not valid:
maxidx = arr[maxidx - 1]
if maxidx == 0:
return "Just a le... |
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
* In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z... | 3 | n = int(input())
a = list(map(int, input().split()))
s = set(a)
s.discard(0)
print(len(s))
|
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should... | 3 | def to_list(s):
return list(map(lambda x: int(x), s.split(' ')))
def get_dicts(a):
sorted_a = sorted(a)
prefix_dict = {0:0}
sorted_prefix_dict = {0:0}
sum_ = 0
sorted_sum = 0
for i, item in enumerate(a):
sum_ += item
prefix_dict[i+1] = sum_
for j, item in enumerate(sorte... |
You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.
At least how many operations are necessary to satisfy the following conditions?
* For every i (1≤i≤n), the sum of the terms from the 1-st through i-... | 3 | import copy
n = int(input())
*A, = map(int, input().split())
def solve(p):
r = 0
t = 0
for a in A:
t += a
if t * p <= 0:
r += abs(p - t)
t = p
p *= -1
return r
print(min(solve(1), solve(-1)))
|
You will be given an integer a and a string s consisting of lowercase English letters as input.
Write a program that prints s if a is not less than 3200 and prints `red` if a is less than 3200.
Constraints
* 2800 \leq a < 5000
* s is a string of length between 1 and 10 (inclusive).
* Each character of s is a lowerca... | 3 | a=int(input())
s=input()
if a<3200:
print("red")
else:
print(s)
|
You are given positive integers A and B.
Find the K-th largest positive integer that divides both A and B.
The input guarantees that there exists such a number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 100
* The K-th largest positive integer that divides both A and B exists.
* K \geq 1
In... | 1 | a, b, k = map(int,raw_input().split())
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
ab = list(set(make_divisors(a)) & set(ma... |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | n=int(input())
print(n+sum((n-i)*i for i in range(n))) |
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 | def shorten(word):
if len(word) <= 10: outputs.append(word)
else: outputs.append(word[0] + str(len(word[1:-1])) + word[-1])
n = int(input())
outputs = []
for c in range(n):
shorten(input())
for c in range(n):
print(outputs[c])
|
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ... | 3 | n,k=map(int,input().split())
ans=[]
a=list(map(int,input().split()))
for i in range(1,n-1):
if a[i]-a[i-1]>=2*k:
ans.append(a[i]-k)
else:
pass
if a[i+1]-a[i]>=2*k:
ans.append(a[i]+k)
else:
pass
if len(a)>1:
if a[0]+2*k<=a[1]:
ans.append(a[0]+k)
else:
pass
i... |
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | 1 | import fractions
import sys
a, b = map(int, raw_input().split())
result = ''
while True:
if fractions.gcd(a, b) != 1:
print 'Impossible'
sys.exit(0)
if (a, b) == (1, 1):
break
if a == 1:
result += str(b - a) + 'B'
break
elif b == 1:
result += str(a - b) + 'A'
break
c, d = a, b
if a > b:
r = a/b... |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 3 | n=int(input())
arr=[int(i) for i in input().split()]
ma=0
maxp=0
minp=0
mi=10**10
for i in range(n):
if arr[i]>ma:
ma=arr[i]
maxp=i
temp=arr[maxp]
del arr[maxp]
arr.insert(0,temp)
for i in range(n-1,-1,-1):
if arr[i]<mi:
mi=arr[i]
minp=i
print(maxp+(n-minp)-1)
|
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:
(1n + 2n + 3n + 4n) mod 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
Input
The si... | 3 | import sys
import math
import array
#sys.stdin = open("num.in", "r")
#sys.stdout = open("num.out", "w")
n = sys.stdin.readline()
n = int(n)
th = pow(3, n, 5)
tw = pow(2, n, 5)
fo = pow(4, n, 5)
sm = 1 + tw + th + fo
sm %= 5
print(sm) |
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 | ent = input()
sol = []
for one in range(ent.count("1")):
sol.append("1")
for two in range(ent.count("2")):
sol.append("2")
for three in range(ent.count("3")):
sol.append("3")
print("+".join(sol)) |
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 | l=[100,20,10,5,1]
n=int(input())
cst=0;i=0
if n>100:
rem=n%100
n=n//100
cst=n
n=rem
while(n):
while(i<5 and n>=l[i]):
n-=l[i]
cst+=1
i+=1
print(cst) |
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 | dist = int(input ())
step = 0
while dist>5:
dist = dist -5
step = step + 1
steps = step+1
print( steps )
|
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.
On ... | 3 | def sol():
N, A, B = [int(x) for x in input().split(" ")]
lst = [int(x) for x in input().split(" ")]
cost = 0
for i in range(N//2):
if lst[i] == 2: # left dancer needs a suit
if lst[-1*(i+1)] == 0:
cost += A
elif lst[-1*(i+1)] == 1:
cos... |
Let's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n.
For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1].
The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1].
The weight of a split is t... | 3 | #----Kuzlyaev-Nikita-Codeforces-----
#------------03.04.2020-------------
alph="abcdefghijklmnopqrstuvwxyz"
#-----------------------------------
n=int(input())
print(n//2+1) |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 1 | __author__ = 'RASULBEK'
n,m=map(int,raw_input().split())
a=[];b=[];
i=0;
while i<m:
s1,s2=map(str,raw_input().split())
a.append(s1)
if(len(s2)<len(s1)):
b.append(s2)
else:
b.append(s1)
i+=1
fin=map(str,raw_input().split())
i=0;res=""
while i<n:
res=res+b[a.index(fin[i])]+" "
... |
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 | dis_remaining = int(input())
num_of_steps = int(0)
for i in range(5, 0, -1):
num_of_steps += dis_remaining // i
dis_remaining = dis_remaining % i
print(num_of_steps) |
Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.
Mishka can put a box i into another box j if the following conditions are met:
* i-th box is not put into another box;
* j-th box doesn't contain any other boxes;
* box i is smaller than box j (ai < aj).
Mishka ... | 3 | n = int(input())
a = input().split()
repeats = []
for i in range(n):
repeats.append(a.count(a[i]))
print(max(repeats)) |
Write a program which solve a simultaneous equation:
ax + by = c
dx + ey = f
The program should print x and y for given a, b, c, d, e and f (-1,000 ≤ a, b, c, d, e, f ≤ 1,000). You can suppose that given equation has a unique solution.
Input
The input consists of several data sets, 1 line for each data set. In a ... | 1 | from __future__ import (division, absolute_import, print_function,
unicode_literals)
import sys
for line in sys.stdin:
a, b, c, d, e, f = (float(n) for n in line.split())
x = round((e * c - b * f) / (a * e - b * d), 4)
y = round((a * f - c * d) / (a * e - b * d), 4)
if x == -0.0... |
When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ... | 3 | def trans(log):
'''
1. Заменяет букву O на цифру 0
2. l -> 1
3. 1 -> I
4. Преобразование к верх. регистру
'''
log = list(log)
for i in range(len(log)):
if log[i] == '0':
log[i] = 'O'
if log[i] in ('l', 'L'):
log[i] = '1'
... |
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.
Given an input array, what i... | 3 | import unittest
import os
import sys
import math
class Tests(unittest.TestCase):
def test1(self):
f1 = open("tests/1.txt", "r")
f2 = open("tests/1a.txt", "r")
sys.stdin = f1
self.assertEqual(main(), f2.read().strip(), "test №1")
f1.close()
f2.close()
def test... |
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xeni... | 1 | from sys import stdin,stdout
def maa():
r=lambda:map(int, stdin.readline().split())
n,m=r()
N=1<<n
a=[0]*N*2
for i,x in enumerate(r()):
a[i+N] = x
i=N-1
for h in xrange(1, n):
for _ in xrange(1 << (n-h)):
if h&1:
a[i] = a[i+i] | a[i+i+1]
... |
You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours.
More formally, find an array b, such that:
* b is a permutation of a.
* For every i from 1 to 2n, b_i ≠ \frac{b_{i-1}+b_{i+1}}... | 3 | def solve():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
b = []
for x, y in zip(a[:n], a[n:]):
b.extend([x, y])
return ' '.join(str(x) for x in b)
if __name__=='__main__':
for _ in range(int(input())):
print(solve()) |
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) ove... | 3 | #151_E
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
mod = 10 ** 9 + 7
f = [1 for _ in range(n)]
f_inv = [1 for _ in range(n)]
for i in range(2, n):
f[i] = (f[i-1] * i) % mod
f_inv[i] = pow(f[i], mod-2, mod)
def comb(n,k):
return f[n]*f_inv[k]*f_inv[n-k]%mod
ans = 0
for i ... |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 1 | n = input()
print (-1)**n*(n+1)/2 |
Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 ≤ i ≤ n}{max} (a_i ⊕ X) is minimum possible, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
As always, Badawy is too ... | 3 | t=int(input())
lst=[int(ele) for ele in input().split()]
maxn=max(lst)
n=len(bin(maxn)[2:])
newlst=["0"*(n-len(bin(ele)[2:]))+bin(ele)[2:] for ele in lst]
def catchEvil(lstrino,loc):
count0,count1=[],[]
for ele in lstrino:
if ele[n-1-loc]=='1':
count1.append(ele)
else:
... |
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows:
* if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma... | 3 | T = int(input())
for t in range(T):
s = input()
n = len(s)
x = int(input())
w = [1] * n
for i in range(n):
if s[i] == '0':
if i + x < n:
w[i+x] = 0
if i - x >= 0:
w[i-x] = 0
for i in range(n):
expected = 0
if i - x >... |
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 | def solve(x,y):
if x >= y:
a,b = y,x
else:
a,b = x,y
return max(2*a,b) ** 2
t = int(input())
for _ in range(t):
inp = input().split()
a,b = int(inp[0]), int(inp[1])
print(solve(a,b)) |
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da... | 3 | n = int(input())
ans = 1
for i in range(1, n + 1):
ans *= i
ans //= (n * n // 2)
print(ans) |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | import sys
import math
import bisect
from sys import stdin,stdout
from math import gcd,floor,sqrt,log
from collections import defaultdict as dd
from bisect import bisect_left as bl,bisect_right as br
sys.setrecursionlimit(100000000)
ii =lambda: int(input())
si =lambda: input()
jn =lambda x,l: x.join(map(s... |
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 1 | import collections
import sys
_inp = sys.stdin.read().split(b'\n')[::-1]
input = lambda : _inp.pop().decode('ascii')
def f(ais):
ans = 0
cur = 0
for ai in ais:
cur += 1
if cur == ai:
cur = 0
ans += 1
return ans
t = int(input())
for u in range(t):
n = int(input())
ais = [int(i) for i in input().split(" ... |
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... | 1 | a = raw_input()
a = str(a)
b = raw_input()
b = str(b)
t = a.count(b);
t = int(t)
print t
|
Sometimes mysteries happen. Chef found a directed graph with N vertices and M edges in his kitchen!
The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to... | 1 | from sys import stdin
from heapq import heappush, heappop
def v_con(M, graph, N):
while M > 0:
a, b = map(int, stdin.readline().split())
graph[a][b] = 0
if not graph[b].has_key(a):
if a == 1 and b == N:
graph[b][a] = 1
elif a != 1:
graph[b][a] = 1
M = M - 1
return graph
def relax(G, u, v, D):
... |
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 | import io
import os
from collections import Counter, defaultdict, deque
def solve(N,):
pow3 = 0
while N % 3 == 0:
pow3 += 1
N //= 3
pow2 = 0
while N % 2 == 0:
pow2 += 1
N //= 2
if N != 1 or pow3 < pow2:
return -1
return (pow3 - pow2) + pow3
if __nam... |
The King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well.
So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n.... | 3 | from collections import defaultdict
for _ in range(int(input())):
n = int(input())
d = defaultdict(int)
flag1 = 0
index = set([i for i in range(1,n+1)])
s = set()
for j in range(n):
k = list(map(int,input().split()))
flag = 0
for i in k[1:]:
if d[i]==0:
... |
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth... | 3 | # from queue import Queue
s = list(map(int, input().split()))
n, m, k = s[0], s[1], s[2]
g = []
x, y = 0, 0
dots = 0
for i in range(n):
line = []
s = input()
for j in range(m):
if s[j] == '.':
dots += 1
y = j
x = i
line.append(s[j])
g.append(line)
d... |
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | 1 | import math
n = int(raw_input())
m = int(raw_input())
flash = []
for j in range(0, n):
flash.append(int(raw_input()))
i = 0;
s = 0;
flash.sort(reverse=True)
for j in range(0, n):
s+=flash[j]
i+=1
if s >= m:
print i
break
|
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b.
The second line contains n integers — ... | 3 | import bisect
x = input()
a=[int (j) for j in input().split()]
b=[int (j) for j in input().split()]
a=sorted(a)
for l in b:
print(bisect.bisect_right(a,l),"",end="")
|
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you ha... | 3 | t=int(input())
while t!=0:
n=int(input())
if n==1 or n==2:
print(2)
elif (n & 1):
print(1)
else:
print(0)
t=t-1 |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n=int(input())
a,b,c=0,0,0
for i in range(n):
x,y,z=map(int,input().split())
x=x+a
a=x
y=y+b
b=y
z=z+c
c=z
if x==0 and y==0 and z==0:
print('YES')
else:
print('NO')
|
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | 3 | n=input()
b=list(map(int,input().split()))
mx=max(b)
s=0
for i in b:
s+=mx-i
print(s)
|
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t... | 3 | a,b=input().split()
a=int(a)
b=int(b)
l=0
x,y=a,b
while(1):
if(x==y):
print (l+1)
break
else:
if(x<y):
x,y=y,x
l+=(x//y)
if(x%y!=0):
x=x-(x//y)*y
else:
print(l)
break
|
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.
Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing... | 1 | n, con, greens, blues = map(int, raw_input().split())
result = ''
lower = min(greens, blues)
higher = max(greens, blues)
curG = 0
curB = 0
tempsize = n
if con*(lower+1) < higher:
print 'NO'
else:
while n > 0:
if greens > blues:
if curG < con and greens > 0:
curG += 1
... |
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 | import sys
def gets(): return sys.stdin.readline().strip()
def get(): return int(sys.stdin.readline().strip())
def geti(): return map(int, sys.stdin.readline().strip().split())
def getli(): return list(map(int, sys.stdin.readline().strip().split()))
a, b = geti()
c = 1
while a <= b:
a *= 3
b *= 2
c += 1... |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoy... | 3 | Str = input()
num = 0
for i in range(len(Str)-2):
if (Str[i] != "Q"):
continue
for j in range(i+1, len(Str)-1):
if (Str[j] != "A"):
continue
for k in range(j+1, len(Str)):
if (Str[k] != "Q"):
continue
num += 1
print (num) |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | n = int(input())
x, y, z = [], [], []
for i in range(n):
temp = list(map(int, input().split()))
x.append(temp[0])
y.append(temp[1])
z.append(temp[2])
if sum(x) == 0 and sum(y) == 0 and sum(z) == 0:
print("YES")
else:
print("NO")
|
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a stud... | 1 | a,r=sorted(map(int,raw_input().split()) for _ in range(input())),0
for x,y in a:
r=[y,x][y<r]
print r
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 1 | mmax = 5
n, m = map(int, raw_input().strip().split())
y = map(int, raw_input().strip().split())
y = filter(lambda yi: yi <= mmax-m, y)
print len(y) / 3
|
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".
Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the ... | 3 | def main():
N = int(input())
for _ in range(N):
L =int(input())
S = [str(input()) for _ in range(L)]
# 00, 11, 01, 10
a, b, c, d = 0, 0, 0, 0
C, D = {}, {}
for k in range(L):
e = S[k]
if e[0] == "0" and e[-1] == "0":
a += 1... |
There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.
... | 1 | n,k=map(int,raw_input().split())
ar=map(int,raw_input().split())
l=[]
for i in xrange(n):
l.append([])
c1=0
flg=True
while(ar!=[0]*n):
if flg:
mi=10**9
for i in xrange(n):
if ar[i]!=0:
mi=min(ar[i],mi)
c1+=1
for i in xrange(n):
if mi+1<=ar[... |
There are N mountains ranging from east to west, and an ocean to the west.
At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.
The height of the i-th mountain from the west is H_i.
You can certainly see the ocean from the inn at the top of the westmost mountain.
F... | 3 | n,*h=map(int,open(0).read().split());print(sum(h[i]>=max(h[:i+1])for i in range(n))) |
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand... | 3 |
n, k = map(int, input().split())
A = [int(x) for x in input().split()]
b = 0
c = 0
for i in range(n):
b += A[i]
c += min([b, 8])
b = max([0, b - 8])
if c >= k:
print(i + 1)
break
else:
print(-1)
|
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.
There are n trees growing along the river, where Argus tends Io. For this problem, the river ca... | 3 | def get_ints():
return list(map(int, input().split()))
for _ in range(int(input())):
N = int(input())
diff = {}
a = get_ints()
for i in range(N):
for j in range(i+1,N):
if abs(a[i]-a[j]) not in diff:
diff[a[j]-a[i]] = 1
print(len(diff)) |
Valera is a lazy student. He has m clean bowls and k clean plates.
Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat d... | 1 | from sys import stdin
in_lines = stdin.readlines()
def int_values(line) :
return map( int, line.split(' ') )
lines = map( int_values, map( lambda x:x.strip(), in_lines ) )
n, m, k = lines[0]
dishes = lines[1]
m -= sum(map(lambda x: x == 1, dishes))
k -= sum(map(lambda x: x == 2, dishes))
if k < 0 :
m += k... |
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co... | 3 | #in the name of god
#Mr_Rubick
n=int(input())
if n%2==0: print((n-1)//2)
else: print(n//2) |
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.
There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte... | 1 | n = int(input())
b = [int(x) for x in raw_input().split()]
a = [0 for i in range(n)]
a[0] = 0
a[-1] = b[0]
for i in range(1, n / 2):
if b[i] - a[i - 1] <= a[-i]:
a[i] = a[i - 1]
a[-i - 1] = b[i] - a[i]
else:
a[-i - 1] = a[-i]
a[i] = b[i] - a[-i]
for i in range(n): a[i] = str(a[i]... |
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information ab... | 3 | a=int(input())
b=int(input())
l=list(map(int,input().split()))
l1=[ a-l[i] for i in range(len(l[:len(l)-1])) ]
print(sum(l1)) |
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names... | 3 | def solve(n, k, a):
t = 0
ans = ["" for i in range(n)]
i = 0
while ((i < len(a)) and (a[i] == 'NO')):
ans[i] = names[0]
i += 1
if (i == len(a)):
for j in range(i, i + k - 1):
ans[j] = ans[0]
return(ans)
for j in range(i, i + k):
... |
The circle line of the Roflanpolis subway has n stations.
There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ... | 3 | # -*- coding: utf-8 -*-
# Date : 2019-05-29 19:19:17
# Author : MiohitoKiri5474 ( lltzpp@gmail.com )
# Link : https://miohitokiri5474.github.io
n, a, x, b, y = [int(_) for _ in input().strip().split()]
while a != x and b != y:
if a == b:
break
if a != n:
a += 1
else:
a = 1
if b != 1:
b -= 1
else:... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | cnt=0
for _ in range(int(input())):
p,q=[int(i) for i in input().split()]
if q-p>=2:
cnt+=1
print(cnt)
|
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now.... | 3 | from math import ceil
from collections import defaultdict
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
n=int(input())
d=defaultdict(list)
a=list(map(int,input().split()))
b=list(map(int,input().split()))
for i in range(n):
d[a[i]].append(b[i])
for i in d:
... |
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever... | 1 | n,k = list(int(foo) for foo in raw_input().split())
nums = list(int(foo) for foo in raw_input().split())
neg = 0
for i in nums:
if i < 0 :
neg += 1
else:
break
if k <= neg:
ans = 0
for index,value in enumerate(nums):
if index < k:
ans -= value
else:
... |
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch... | 3 | from sys import stdin
def inp():
return stdin.readline().strip()
t = int(inp())
for _ in range(t):
n = int(inp())
a = [int(x) for x in inp().split()]
notOrd = 0
last = True
begin = 0
end = 0
for i in range(n):
if last and a[i] == i+1:
last = True
begin +... |
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | 3 | n = int(input())
arr = [int(i) for i in input().split()]
s = 0
for i in range(n):
if arr[i] > 0:
s += arr[i]
if s%2 != 0:
print(s)
else:
m = 100000
for i in range(n):
if arr[i] > 0 and arr[i]%2 != 0:
m = min(m,arr[i])
ans = s - m
for i in range(n):
if arr[i] <... |
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci... | 1 | N = int(raw_input())
print ((27 ** N) - (7 ** N)) % 1000000007 |
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The... | 3 | [n,k] = [int(w) for w in input().split()]
a = [int(w) for w in input().split()]
a.sort()
a.append(10**57)
m = n//2
for i in range(m,n):
dk = (i-m+1)*(a[i+1]-a[i])
if k < dk:
break
k -= dk
print(a[i] + k//(i-m+1))
|
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.
In the evening Noku is going to take a look at the night sky. He would like to find three d... | 1 | n=input()
a=sorted(zip([map(int,raw_input().split()) for _ in range(n)],range(1,n+1)))
[x,y],_=a[0]
[u,v],_=a[1]
u-=x
v-=y
for (p,q),i in a[2:]:
if u*(q-y)-v*(p-x):
print a[0][1],a[1][1],i
break
|
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures.
Yo... | 3 | t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
even = 0
odd = 0
for i in a:
if i % 2 == 0:
even += 1
else:
odd += 1
if even == n:
print("YES")
elif odd == n:
print("YES")
else:
print... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | int(input())
l = [int(x) for x in input().split()]
pairs = []
for i, e in enumerate(l):
pairs.append((e, i+1))
print(*(x[1] for x in sorted(pairs)))
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | a,b=map(int,input().split())
r=[]
for i in range(a+1,b+1):
def isPrime(i):
d=2
while i % d != 0:
d+=1
if d==i:
r.append("YES")
else:
r.append("NO")
isPrime(i)
if r.count("YES")>=2 or r.count("YES")<1 or r[-1]=="NO":
print("NO")
elif r.count... |
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 |
def isPrime(n) :
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n %... |
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 | for tc in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
if sum(l)==0 and 0 in l:
print(l.count(0))
elif sum(l)==0 and 0 not in l:
print(1)
elif sum(l)!=0 and 0 in l:
if sum(l)+l.count(0)==0:
print(l.count(0)+1)
else:
prin... |
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)... | 1 | n = int(raw_input())
a = raw_input().split()
num = 0
for i in range(n):
for j in range(i,n):
num = max(num,a[:i].count('1')+a[i:j+1].count('0')+a[j+1:].count('1'))
print num |
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string con... | 1 | x=raw_input()
lis=[]
for i in range(int(x)):
t=raw_input()
lis.append(t)
ans=''
for i in range(len(lis[0])):
cur='a'
fin=False
for k in range(int(x)):
if lis[k][i]!='?':
if not fin:
cur=lis[k][i]
fin=True
elif cur!=lis[k][i]:
... |
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains t... | 1 | R=lambda:map(int,raw_input().split())
n,m=R()
p,q=R()
a=R()
b=R()
print 'YES' if a[p-1]<b[-q] else 'NO'
|
I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.
I would like to create a new graph in such a way that:
* The new graph consists of the same number o... | 1 | import random
import time
n,m=map(int,raw_input().split())
e=set(frozenset(map(int,raw_input().split())) for _ in xrange(m))
t=time.time()
x=range(1,n+1)
while time.time()-t < 2.8:
random.shuffle(x)
if all(frozenset((x[i],x[i-1])) not in e for i in xrange(m)):
for i in xrange(m): print x[i], x[i-1]
break
else:
p... |
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to cho... | 3 | import sys, math
# Gives the circle ((x,y),radius) that contains all points p such that
# (p-p1)/(p-p2) = r.
def apollonian_circle(p1,p2,r):
dx = p2[0] - p1[0]
x = p1[0] + (((r/(1+r)) + (r/(r-1)))/2) * dx
dy = p2[1] - p1[1]
y = p1[1] + (((r/(1+r)) + (r/(r-1)))/2) * dy
x_ = p1[0] + (r/(1+r)) * dx
... |
Arthur and Alexander are number busters. Today they've got a competition.
Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number... | 1 | #!/usr/bin/env python
import sys
a, b, w, x, c = map(int, sys.stdin.readline().strip().split())
ans = 0
def iterate(count):
global a, b, w, x, c, ans
for i in range(count):
if c <= a:
return True
ans += 1
c -= 1
if b >= x:
b -= x
else:
... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | a = int(input())
c = 0
for i in range(a):
b = input().strip().split(" ")
p = int(b[0])
q = int(b[1])
if p+2 <= q:
c += 1
print(c) |
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins wh... | 3 | h, n = map(int, input().split())
magics = [list(map(int, input().split())) for _ in range(n)]
max_damage = max(a for a, b in magics)
dp = [0] * (h + max_damage)
for i in range(1, h + max_damage):
dp[i] = min(dp[i - a] + b for a, b in magics)
print(dp[h]) |
Let s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that
* s(a) ≥ n,
* s(b) ≥ n,
* s(a + b) ≤ m.
Input
The only line of input contain two integers n and m (1 ≤ n, m ≤ 1129).
Output
Print two lines, one for decimal... | 3 | n,m=map(int,input().split(" "))
a=150*"9"+149*"0"+"1"
b=150*"9"
print(a)
print(b)
|
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | 1 | # Author: Bishal Sarang
a = int(raw_input().strip())
if a >= -127 and a <= 127:
print "byte"
elif((a >= -32768 and a <= 32767)):
print "short"
elif((a >= -2147483648 and a <= 2147483647)):
print"int"
elif((a >= -9223372036854775808 and a <= 9223372036854775807)):
print"long"
else:
print "BigInteger"
|
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c... | 3 | for _ in range(int(input())):
s = list(input())
l = len(s)
for i in range(l):
if s[i] == "?":
arr = ['a','b','c']
if i != 0 and s[i-1] in arr:
arr.remove(s[i-1])
if l-1 != i and s[i+1] in arr:
arr.remove(s[i+1])
s[i] = a... |
You are given an array consisting of n integers a_1, a_2, ..., a_n. Initially a_x = 1, all other elements are equal to 0.
You have to perform m operations. During the i-th operation, you choose two indices c and d such that l_i ≤ c, d ≤ r_i, and swap a_c and a_d.
Calculate the number of indices k such that it is poss... | 3 | ip=lambda : list(map(int,input().split()))
for _ in range(int(input())):
n,x,m= ip()
a,b=x,x
for i in range(m):
l,r=ip()
if b>=l and a<=r:
a=min(l,a)
b=max(b,r)
print(b-a+1)
|
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.
The term is coming to an end and students start thinking about their grades. Today, a professor told his students that... | 1 | n = int(raw_input())
notas = map(float ,raw_input().split())
cont = 0
s = sum(notas)
m = s /n
while m <4.5:
notas.sort()
notas.pop(0)
notas.append(5)
m = sum(notas)/n
cont += 1
print cont
|
In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.
Write a program which reads an integer x and print it as is. Note that multiple datasets are give... | 1 | i = 0
while 1:
x = raw_input()
i += 1
if x == "0":
break
print "Case %s: %s" % (i,x) |
There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.
Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it. Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.
Q... | 3 | # AtCoderのPyPy3環境だとこれが一番速い。
class LazySegmentTree:
__slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"]
def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator):
self.me = monoid_identity
self.oe = oper... |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | 3 | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
b=sum(a)
d=set(a)
if len(d)==1:
print(a[0])
else:
v=b%n
h=b//n
if v==0:
print(h)
else:
print(h+1) |
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | 3 | def generate(string, end, total):
if string != "" and int(string) > int(end):
return
if len(string) > 0:
total.append(string)
generate(string+'4', end, total)
generate(string+'7', end, total)
total = []
i = input()
generate("", i, total)
print(len(total))
... |
The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Eac... | 3 | import math
n=int(input())
s=input()
d={}
for i in range(n):
if(s[i] not in d):
d[s[i]]=[i]
else:
d[s[i]]+=[i]
m=int(input())
for w in range(m):
t=input()
m1=0
d1={}
for i in t:
if(i not in d1):
d1[i]=0
else:
d1[i]+=1
m1=max(m1,d[i]... |
You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.
Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:
* Operation: Choose one of the strings A, B and C, and specify an integer i betwe... | 3 | N = int(input())
A = list(input())
B = list(input())
C = list(input())
ans = 0
for i in range(N):
kind = len(set((A[i], B[i], C[i])))
ans += kind - 1
print(ans)
|
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.
Polar bears Alice and Bob each have caught some fish, and they are g... | 1 | raw_input()
c=lambda: sorted(map(int, raw_input().split()),None,None,True)
a,b=c(),c()
if len(a) > len(b):
print 'YES'
exit()
for i in xrange(min(len(a),len(b))):
if a[i] > b[i]:
print 'YES'
exit()
print 'NO'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.