problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
You are given two integers x and y. You can perform two types of operations:
1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation:
* x = 0, y = 6;
* x = 0, y = 8;
* x = -1, y = 7;
* x = 1, y = ... | 3 | '''
INPUT SHORTCUTS
N, K = map(int,input().split())
N ,A,B = map(int,input().split())
string = str(input())
arr = list(map(int,input().split()))
N = int(input())
'''
def main():
n = int(input())
while n:
x,y = map(int,input().split())
a,b = map(int,input().split())
# if x!=y:
btimes = b*min(x,y)
atimes = a... |
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | 3 | a,b = map(int, input().split())
if b == a:
print(1)
elif a == b-1:
print(b%10)
else:
i = a+1
ans = 1
while i <= b:
ans *= i
ans %= 10
i += 1
if ans == 0:
break
print(ans) |
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.
In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh... | 3 | for _ in range(int(input())):
n,a,b,c,d = map(int,input().split())
v = (a+b)*n
q = (a-b)*n
e = c+d
j = c-d
if q>e or v<j:
print("No")
else:
print("Yes") |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | for i in range(int(input())):
a=list(map(int,input().split()))
x=a[0]
y=a[1]
n=a[2]
b=n%x
if(b>y):
print(n-(b-y))
elif(b<y):
print(n-(x+b-y))
elif(b==y):
print(n)
else:
print(0)
|
Alica and Bob are playing a game.
Initially they have a binary string s consisting of only characters 0 and 1.
Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char... | 3 | def solve():
arr=list(input())
zeros,ones = 0,0
for e in arr:
if e == '1':
ones += 1
else:
zeros += 1
ones = min(ones, zeros)
if ones & 1:
return 'da'
return 'net'
if __name__=='__main__':
for _ in range(int(input())):
print(solve()) |
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 | n = int(input())
a = "I love"
b = "I hate"
for i in range(1,n+1) :
if(i % 2 == 1) :
print(b, end = " ")
else :
print(a, end = " ")
if(i != n) :
print("that", end =" ")
print("it") |
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.
Let us define a function f(r, c) as follows:
* f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati... | 3 | def main():
M=10**9+7
r1,c1,r2,c2=map(int,input().split())
n=r2+c2+2
fac=[0]*(n+1)
fac[0]=val=1
for i in range(1,n+1):fac[i]=val=val*i%M
f=lambda r,c:fac[r+c+2]*pow(fac[c+1],M-2,M)*pow(fac[r+1],M-2,M)-c-r-2
print((f(r2,c2)-f(r2,c1-1)-f(r1-1,c2)+f(r1-1,c1-1))%M)
main() |
There are N people numbered 1 to N. Each person wears a red hat or a blue hat.
You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.
Determine if there are more people wearing a red hat than people wearing a blue hat.
Constraints
* 1 \l... | 3 | N=int(input())
s=input()
if s.count("R")>s.count("B"):
print("Yes")
else:
print("No") |
This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di... | 3 |
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newl... |
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 | a = sorted([int(n) for n in input().split()])
print(' '.join([str(a[-1]-e) for e in a][:3])) |
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi... | 3 | def warshall_floyd(dp, v):
for k in range(v):
for i in range(v):
for j in range(v):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
def check(dp, v):
for k in range(v):
for i in range(v):
for j in range(v):
if dp[i][j] > dp[i][k] + dp[k][j]... |
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n.
Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m.
... | 3 | for _ in range(int(input())):
n=int(input());a=list(map(int,input().split()));m=int(input());b=list(map(int,input().split()))
x=sum([1 if i%2==0 else 0 for i in a]);y=n-x
p=sum([1 if i%2==0 else 0 for i in b]);q=m-p
print(x*p+y*q) |
problem
During this time of winter in Japan, hot days continue in Australia in the Southern Hemisphere. IOI, who lives in Australia, decided to plan what clothes to wear based on the weather forecast for a certain D day. The maximum temperature on day i (1 ≤ i ≤ D) is predicted to be Ti degrees.
IOI has N kinds of cl... | 3 | INF = 10 ** 20
def main():
d, n = map(int,input().split())
temp = [int(input()) for i in range(d)]
temp.insert(0,0)
alst = []
blst = []
clst = []
for i in range(n):
a,b,c = map(int,input().split())
alst.append(a)
blst.append(b)
clst.append(c)
dp = [[0] * n for i in range(d + 1)]
... |
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a... | 3 | a = input()
b = input()
ans1 = str(int(a)+int(b))
ans2=int(a.replace('0',''))+int(b.replace('0',''))
if ans1.replace('0','')==str(ans2):
print('YES')
else:
print('NO') |
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 1 | def primes(n):
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def solve(n):
for m in range(1,1001):
if n * m + 1 not in p:
return(m)
p = s... |
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these n people has answered that th... | 3 | s=int(input())
m=input().split()
c=m.count("1")
if c>=1:
print("HARD")
else:
print("EASY") |
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.
For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly... | 3 | t = int(input())
for case in range(0, t):
a = list(input())
b = list(input())
c = list(input())
for i, item in enumerate(zip(a, b, c)):
if c[i] == a[i] and c[i] != b[i]:
c[i], b[i] = b[i], c[i]
elif c[i] != a[i] and c[i] == b[i]:
c[i], a[i] = a[i], c[i]
... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n = int(input())
capacity = 0
tram = 0
for i in range(n) :
a, b = [int(tmp) for tmp in input().split()]
tram -= a
tram += b
if tram > capacity :
capacity = tram
print(capacity)
|
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.
It turned out that among Pasha's friends there are exactly n boys and exactly n... | 1 | __author__ = '11x256'
n , w = map(int , raw_input().split())
cups = map(int ,raw_input().split())
cups =sorted(cups)
g = cups[0]
b = cups[len(cups) / 2]
ans = 0
if g * 2 <= b :
ans = g*n + 2*g*n
else:
ans = b *n + (b / 2.0) * n
if ans > w :
ans = w
print ans
|
Example
Input
6 3
1 0 0 1 0 1
1 3 2
Output
1 | 3 | N, M = map(int, input().split())
*B, = map(int, input().split())
*P, = map(int, input().split())
def solve(v):
C = B[:]
D = []
for i in range(M):
D += [(i & 1) ^ v]*P[i]
res = 0
for i in range(N):
if C[i] != D[i]:
for j in range(i, N):
if D[i] == C[j]:
... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | def solve():
k = int(input())
l = int(input())
m = int(input())
n = int(input())
d = int(input())
c = 0
j = 0
for i in range(1, d + 1):
j += 1
if j % k == 0 or j % l == 0 or j % m == 0 or j % n == 0:
c += 1
print(c)
if __name__ == '__main__':
solve()
|
Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.
Find the N-th smallest intege... | 3 | D, N = map(int, input().split())
print((N if N < 100 else 101)*(100**D)) |
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.
<image>
He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k mess... | 1 | s = raw_input()
k = int(raw_input())
ss = []
if len(s)%k or not len(s):
print 'NO'
exit()
for x in xrange(k):
ss.append(s[x*len(s)/k:x*len(s)/k+len(s)/k])
yes = True
for x in ss:
if x != x[::-1]:
yes = False
print 'YES' if yes else 'NO' |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 1 | n=raw_input()
k=sorted(map(int,raw_input().split()))
k.reverse()
s=0
c=0
for i in range(len(k)):
s+=k[i]
c+=1
if s>sum(k)/2:
print c
break
i+=1
|
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 | #https://codeforces.com/problemset/problem/977/A
n, k = map(int, input().split())
for i in range(k):
if n % 10 == 0:
n //= 10
else:
n -= 1
print(n)
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 |
import math
n,m,a = list(map(int,input().split()))
print(math.ceil(n/a)*math.ceil(m/a)) |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 1 | p = raw_input()
l = p.split('WUB')
k=''
for d in l:
if d!='':
k+=d
k+=' '
print k
|
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program... | 3 | n,k=list(map(int,input().split()))
#print(" ".join(map(str,a)))
a=n
c2=0
c5=0
while n%5==0:
n=n//5
c5+=1
while n%2==0:
n=n//2
c2+=1
c2=k-c2
c5=k-c5
c2=c2 if c2>0 else 0
c5=c5 if c5>0 else 0
print(a*(5**c5)*(2**c2))
|
Constraints
* H is an integer between 2 and 50 (inclusive).
* W is an integer between 2 and 50 (inclusive).
* s_{i, j} is `.` or `#` (1 \leq i \leq H, 1 \leq j \leq W).
* s_{1, 1} and s_{H, W} are `.`.
Input
Input is given from Standard Input in the following format:
H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2,... | 3 | from collections import deque
H, W = map(int,input().split())
S = [input() for _ in range(H)]
Q = deque([[0,0]])
dist = [[-1] * W for _ in range(H)]
dist[0][0] = 0
while Q:
h, w = Q.popleft()
for nh, nw in [[h+1,w],[h-1,w],[h,w-1],[h,w+1]]:
if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == "." and dist... |
There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO".
Input
Input consists of several datasets. In the fir... | 3 | # Aizu Problem 0021: Parallelism
#
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
N = int(input())
for n in range(N):
x1, y1, x2, y2, x3, y3, x4, y4 = [float(_) for _ in input().split()]
det = (x2 - x1) * (y4 - y3) - (y2 - y... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | q=input()
s=set()
for x in q:
s.add(x)
a=len(s)
if a/2==a//2:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!") |
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or... | 3 | n = int(input())
a = [-1] + list(map(int, input().split()))
indeg, outdeg = [0]*(n+1), [0]*(n+1)
for i in range(1, n+1):
if a[i]:
outdeg[i] = 1
indeg[a[i]] = 1
vs = [[] for _ in range(3)]
for i in range(1, n+1):
if indeg[i] and not outdeg[i]:
vs[0].append(i)
elif not indeg[i] and ou... |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | import sys, itertools
def eratos(n):
check = [True] * (n + 1)
prime = []
check[0] = check[1] = False
for i in range(2, int(n ** 0.5) + 1):
if check[i]:
j = 2 * i
while j <= n:
check[j] = False
j += i
for i in range(2, n + 1):
i... |
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 | for _ in range(int(input())):
n, x, m = map(int, input().split())
a, b = x, x
for i in range(m):
l, r = map(int, input().split())
if l <= a <= r: a = l
if l <= b <= r: b = r
print(b - a + 1)
|
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.
You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n)... | 3 | # Anuneet Anand
import sys
input = sys.stdin.readline
s = input()
n = len(s)
X = [0 for i in range(n)]
for i in range(len(s)-1):
if s[i]==s[i+1]:
X[i]=1
DP = [0]
t = 0
for i in X:
t=t+i
DP.append(t)
m = int(input())
for i in range(m):
L,R = map(int,input().split())
x = DP[R-1]-DP[L-1]
print(x) |
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
Constraints
* 1 \leq K \leq N \leq 1000
* 1 \leq... | 1 | mod = int(1e9+7)
def add(a, b):
c = a + b
if c >= mod:
c -= mod
return c
def main():
#A, B = [int(x) for x in raw_input().split()]
n, k = [int(x) for x in raw_input().split()]
arr = [int(x) for x in raw_input().split()]
arr.sort()
ans = sum(arr[0:k])
prin... |
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | import math
t = int(input())
for e in range(t):
k=2
m = int(input())
while(1):
if(m%(math.pow(2,k)-1)==0):
ans = m//(math.pow(2,k)-1)
break
k+=1
print(int(ans))
|
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re... | 3 | # coding: utf-8
for case in range(int(input())):
n = int(input())
tasks = input()
notSuspicious = 'YES'
for i in range(1, n):
if tasks[i] in tasks[:i] and tasks[i] != tasks[i - 1]:
notSuspicious = 'NO'
break
print(notSuspicious) |
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | 3 | """
ID: brandtnet1
LANG: PYTHON3
TASK: test
"""
d1 = input()
d2 = input()
zipped = zip(d1,d2)
counter = 0
incorrect = []
if len(d1) != len(d2):
print('NO')
counter = 0
else:
for a,b in zipped:
if a != b:
counter += 1
incorrect.append((a,b))
if counter > 2:
... |
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
1. Go 1 unit towards the positive direction, denoted as '+'
2. Go 1 unit towards the negative direction, ... | 3 | li = [1]*11
for i in range(1,11):
li[i] = li[i-1]*i
str1 = input()
str2 = input()
cnt, cnt1, cnt2 = 0,0,0
for i in str1:
if i=='+':
cnt2 +=1
else:
cnt2 -=1
for i in str2:
if i=='?':
cnt +=1
elif i=='+': cnt1+=1
else:
cnt1 -=1
for i in range(cnt+1):
if cnt1 + cnt -2*i == cnt2:
ans = li[cnt]//(li[i]*... |
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 |
def Main():
c = 0
n = int(input())
while n >= 1 :
x = input().split()
if (int(x[1]) - int(x[0])) > 1:
c += 1
n -= 1
print(c)
Main() |
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his... | 3 | k=int(input())
l=[0]*10
for i in range(4):
for j in input():
if (j != '.'):
l[int(j)] += 1
for i in range(10):
if l[i] > k*2:
print("NO")
exit()
print("YES") |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons... | 3 | # -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
"""
created by shhuan at 2017/11/24 19:56
"""
n, m, z = map(int, input().split())
a = [0] * (z+1)
x = n
while x <= z:
a[x] = 1
x += n
y = m
while y <= z:
a[y] += 1
... |
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an... | 3 | """https://codeforces.com/contest/1041/problem/B"""
a,b,x,y = tuple(map(int, input().split()))
if x<y: a,b,x,y = b,a,y,x
def GCD(a,b):
if b==0: return a
else: return GCD( b, a%b )
gcd = GCD(x,y)
x = x//gcd
y = y//gcd
print( min( a//x, b//y ) ) |
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.
The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr... | 3 | s = input()
mp = {1: 0}
cnt = {1: 0}
for i in range(0, 26):
for j in range(0, 26):
mp[chr(i + ord('a')) + chr(j + ord('a'))] = 0
for i in range(0, 26):
cnt[chr(i + ord('a'))] = 0
ans = 0
for i in s:
for j in range(0, 26):
c = chr(j + ord('a'))
mp[i + c] += cnt[c]
if mp[i + c] > ans:
ans = mp[i + c]
cnt[i... |
Fukushima Prefecture is also famous for producing fruits, and among them, peaches and apples boast one of the highest production volumes in Japan. By the way, when I made a print manuscript of an English pamphlet for sale, I mistakenly wrote the description about apples and the description about peaches in reverse.
Yo... | 3 | S = input()
S = S.replace("apple","!")
S = S.replace("peach","apple")
S = S.replace("!","peach")
print(S)
|
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!
On the show a dog needs to eat as many bowls of dog food as poss... | 3 | n, T = map(int, input().split())
ts = list(map(int, input().split()))
intervals = []
for i in range(n):
start = max(0, ts[i] - i - 1)
end = T - i - 2
if start > end:
continue
intervals.append((start, -1))
intervals.append((end, 1))
intervals.sort()
ans = 0
current = 0
for _, ... |
Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where
* <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive.
* <hostname> — is a sequence of word separat... | 1 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Idleness limit exceeded on test ??
from string import letters, digits
def readint(): return int(raw_input())
def readfloat(): return float(raw_input())
def readarray(N, foo):
res = []
for _ in xrange(N):
res.append(foo())
return re... |
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.
There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one... | 3 | N, M = map( int, input().split() )
for _1 in range( M ):
A = list( map( int, input().split() ) )[ 1 : ]
bag, found = set(), False
for v in A:
if - v in bag:
found = True
bag.add( v )
if not found:
exit( print( "YES" ) )
print( "NO" )
|
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0.
The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied:
* The length of s is 1, and it consists of the character c (i.e. s_1=c);
* The lengt... | 3 | def make_good(instr,ind1,ind2,inchar):
if ind1==ind2:
if instr[ind1]==inchar:
return 0
else:
return 1
mid=(ind1+ind2)//2
nextchar=chr(ord(inchar)+1)
c1=make_good(instr,ind1,mid,nextchar) + make_all_char_same(instr,mid+1,ind2,inchar)
c2=make_all_char_same(instr,ind1,mid,inchar) + make_good(instr,mid+1,i... |
Given the time in numerals we may convert it into words, as shown below:
5:00→ five o' clock
5:01→ one minute past five
5:10→ ten minutes past five
5:30→ half past five
5:40→ twenty minutes to six
5:45→ quarter to six
5:47→ thirteen minutes to six
5:28→ twenty eight minutes past five
Write a program which prin... | 1 | minutes=[]
minutes2=[]
minutes=["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen" ,"fifteen","sixteen","seventeen","eighteen","nineteen","twenty"]
h=input()
m=input()
if(m==0):
print minutes[h],"o' clock"
elif(m<=30):
if(m==15):
print"quarter past",minu... |
A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.
Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordina... | 1 | def MIN(t):
if t[0] < t[1]:
return t[0]
else:
return t[1]
def MAX(t):
if t[0] > t[1]:
return t[0]
else:
return t[1]
n = input()
name = []
while n:
n -= 1
a,b = raw_input().split()
name.append([a,b])
p = map(int,raw_input().split())
flag = True
tmp = MIN(nam... |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | #872
for _ in range(int(input())):
n=int(input())
a=input()
ans=0
ss=0
i=0
while(i<n):
x=0
while(i<n and a[i]=='('):
i+=1
x+=1
while(i<n and a[i]==')'):
i+=1
x-=1
if(x>0):
ss+=x
elif(x<0):
... |
This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to the n... | 3 | import sys
from pprint import pprint
n = int(input())
a = list(map(int, input().split()))
f = [0 for i in range(100005)]
cnt = [0 for i in range(100005)]
mx = 0
ans = 0
for i in range(n):
x = a[i]
cnt[f[x]] = max(0, cnt[f[x]] - 1)
f[x] += 1
cnt[f[x]] += 1
mx = max(mx, f[x])
if mx == 1 or cnt... |
You are given 4n sticks, the length of the i-th stick is a_i.
You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only... | 3 | def solve(arr):
n=len(arr)
arr.sort()
area = arr[0] * arr[-1]
flag=True
for i in range(0,n,2):
if(arr[i] != arr[i+1]):
flag=False
return "NO"
i=0
j=n-1
while(i<j):
curarea = arr[i] * arr[j]
if(area != curarea):
return "NO"
... |
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 | q = int(input())
for q in range(q):
n = int(input())
ch = False
nech = False
arr = list(map(int, input().split(' ')))
for x in arr:
if x % 2 == 0:
ch = True
else:
nech = True
if ch and nech:
print("NO")
else:
print("YES")
|
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | 3 | import sys
s=input()
t=0
f=len(s)-2
i=0
while(i<f):
if s[i]=="A" and s[i+1]=="B" and s[i+2]=="A":
s=s[:i]+s[i+3:]
t+=1
elif s[i]=="B" and s[i+1]=="A" and s[i+2]=="B":
s=s[:i]+s[i+3:]
t+=1
f=len(s)-2
i+=1
if t>=2:
print("YES")
sys.exit()
t2=0
t1=0
for i in range(le... |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a=int(input())
b=int(input())
c=int(input())
s1=a+b+c
s2=a*b*c
s3=(a+b)*c
s4=a*(b+c)
print(max(s1,s2,s3,s4))
|
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 | t = int(input())
for _ in range(t):
n = int(input())
if(n==1):
print("0")
else:
c1=0
c2=0
while(n%2==0):
n/=2
c1+=1
while(n%3==0):
n/=3
c2+=1
if(n!=1):
print("-1")
elif(c1>c2):
pri... |
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 = int(input())
my_list = list(map(int, input().split()))
print(max(my_list) * n - sum(my_list)) |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | t=int(input())
for _ in range(0,t):
a,b,c,d=[int(z) for z in input().split()]
x,y,z=b,c,c
print(x,y,z) |
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the Ox axis from west to east, and th... | 3 |
n = int(input())
print(f'{(n-4)/2:.0f}')
|
You are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?
Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime... | 3 | for _ in range(int(input())):
a,b=map(int,input().split())
if a-b!=1:
print('Yes')
else:
print('No')
|
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 solution():
word = input()
st = False
for i in range(len(word)):
if i == 0 and word[i].islower():
st = True
if i != 0 and word[i].islower():
break
else:
word = word.lower()
if st:
word = word.capitalize()
print(word)
if __name... |
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit p... | 3 | from collections import Counter
for _ in range(int(input())):
x,N,m=map(int,input().split())
while(N>0 or m>0):
if(x//2+10<x and N>0):
x=x//2+10
N-=1
elif(m>0):
x-=10
m-=1
else:
break
if(x<=0):
print('YES')
else:
print('NO') |
The Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6.
The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i.
The compan... | 3 | from sys import stdin, stdout
def is_valid(a):
m = []
for i in range(len(a)):
if (a[i] > 0):
if (a[i] in m):
return False
else:
m.append(a[i])
else:
if (abs(a[i]) not in m):
return False
return True
n = int(stdin.readline().rstrip())
a = [int(x) for x in stdin.readline().rstrip().split()]
... |
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 | '''
Name : Jaymeet Mehta
codeforces id :mj_13
Problem :
'''
from sys import stdin,stdout
test=int(stdin.readline())
for _ in range(test):
N=int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
b=sorted(a)
if a==b:
print(0)
continue
temp=[int(a[i]==b[i]) for i in rang... |
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 | #!/usr/bin/python3
from sys import stdin, stdout
import re
n = int(input())
besede = stdin.readlines()
for beseda in besede:
beseda = re.sub('\s+', '', beseda)
if len(beseda) > 10:
print(''.join(beseda[0] + str(len(beseda[1:-1])) + beseda[-1]))
else:
print(beseda)
|
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
<image>
The event coordinator has a list of k participants who should be picked up at the airport.... | 3 |
a=int(input())
if a==0:
print('''+------------------------+
|#.#.#.#.#.#.#.#.#.#.#.|D|)
|#.#.#.#.#.#.#.#.#.#.#.|.|
|#.......................|
|#.#.#.#.#.#.#.#.#.#.#.|.|)
+------------------------+''')
if a==1:
print('''+------------------------+
|O.#.#.#.#.#.#.#.#.#.#.|D|)
|#.#.#.#.#.#.#.#.#.#.#.|.|
|#........... |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k,n,w=map(int,input().split())
s=0
for i in range(1,w+1):
s+=i*k
if n>=s:
print(0)
else:
print(s-n) |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | a, b, n = map(int, input().split(" "))
while True:
x, y = a, n
while y:
x, y = y, x%y
if x > n:
print("1")
break
n -= x
x, y = b, n
while y:
x, y = y, x%y
if x > n:
print("0")
break
n -= x |
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).
A... | 3 | import sys
import math
from collections import Counter as cc,defaultdict
input = sys.stdin.readline
LI=lambda:list(map(int,input().split()))
MAP=lambda:map(int,input().split())
IN=lambda:int(input())
S=lambda:input()
def case():
n,=LI()
a=LI()
di=cc(a)
c=0
d=0
for i in di:
te=di[i]
... |
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0.
The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied:
* The length of s is 1, and it consists of the character c (i.e. s_1=c);
* The lengt... | 3 | def good(s, letter):
if len(s) == 1:
return 0 if s == letter else 1
half = len(s) // 2
first, second = s[:half], s[half:]
return min(half - first.count(letter) + good(second, chr(ord(letter) + 1)),
half - second.count(letter) + good(first, chr(ord(letter) + 1)))
def good_greed... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 |
n = int(input())
result = 0
for _ in range(n):
stmt = input()
if stmt[1] == '+':
result += 1
else:
result -= 1
print(result)
|
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) ≤ 3 ⋅ 10^5 and (r - l) is always odd.
You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o... | 3 | l,r = map(int,input().split())
if (r-l)%2==0:
print("NO")
exit()
print("YES")
for i in range(l,r+1,2):
print(i,i+1,sep=' ')
|
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... | 1 | n=int(raw_input())
counts=map(int,raw_input().split())
taxi=0
nums1=[]
nums2=[]
nums3=[]
nums4=[]
for i in counts:
if i==1:
nums1.append(i)
elif i==2:
nums2.append(i)
elif i==3:
nums3.append(i)
elif i==4:
nums4.append(i)
taxi=len(nums4)
a=len(nums3)-len(nums1)
if a>0:
... |
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times.
When he came to the fruit stall of Ash... | 3 | n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
a = []
for i in range(m):
fruit = input()
a.append(fruit)
b = list(set(a))
c = []
for i in range(len(b)):
c.append(a.count(b[i]))
c.sort(reverse=True)
minimum, maximum = 0, 0
for j in range(len(c)):
try:
minimum += c[j]... |
Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.
Initially, on day 1, there is one bacterium with mass 1.
Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass m splits, it becomes two bacteria of mass m/2 each. For example, a ba... | 3 | for _ in range(int(input())):
n=int(input())
ar=[]
i=1
while(i<=n):
ar.append(i)
n-=i
i*=2
if(n!=0):ar.append(n)
ar.sort()
print(len(ar)-1)
for i in range(1,len(ar)):print(ar[i]-ar[i-1],end=" ")
print()
|
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n × m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | for ii in range(int(input())):
n , m = map(int , input().split())
a = [['B' for iii in range(m)] for jjj in range(n)]
a[n-1][m-1]='W'
for i in range(n):
for j in range(m):
print(a[i][j],end="")
print()
|
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())
counter = 0
for i in range(n):
if sum([int(s) for s in input().split()]) >= 2:
counter += 1
print(counter) |
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac... | 3 | H, L = map(int, input().split())
print((H**2+L**2)/(2*H) - H)
|
Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.
The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he h... | 3 | from collections import deque
from sys import stdin
n,m,k=map(int,input().split())
s=list(map(int,input().split()))
node=[[]for i in range(n+1)]
for i in range(m):
a,b=map(int,stdin.readline().split())
node[a].append(b)
node[b].append(a)
q=deque()
depth,depth2=[-1]*(n+1),[-1]*(n+1)
q.append(1)
depth[1],dept... |
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct.
Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send... | 3 | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
result = 0
index = 0
numProcessed = 0
toSent = set(b)
processed = set()
for val in b:
if val in processed:
numProcessed... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | from math import ceil
l,b,a=input().split()
l,b,a=int(l),int(b),int(a)
l=ceil(l/a)
b=ceil(b/a)
print(l*b) |
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 | # Lang: pypy3.6-v7.1.0-win32\pypy3.exe
# Problem Name: Hulk
# Problem Serial No: 705
# Problem Type: A
# Problem Url: https://codeforces.com/problemset/problem/705/A
# Solution Generated at: 2019-05-09 00:51:53.611322 UTC
from itertools import cycle
n=int(input())
x="I hate it";x1="I hate that";x2="I love it";x3="I ... |
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 1 | s = map(int, raw_input().split())
print str(int(s[0] * s[1] / 2)) |
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | 3 | a,b=map(int,input().split())
if(b%a!=0):
print(int(b/a)+1)
else:
print(int(b/a)) |
Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.
Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to... | 3 | n, d = map(int, input().split())
arr = sorted(list(map(int, input().split())))
m = int(input())
s = sum(arr[0:m])
penalty = max(0, (m - n)) * d
print(s - penalty) |
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.
The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that... | 3 | """
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk
"""
def solution():
# This is the main code
n,m=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
s=sum(l)
i=0
while(s/n<m):
s-=l[i]
i+=1
n-=1
if n==0:
b... |
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c... | 3 | tiles = {
'm': [],
'p': [],
's': []
}
for tile in input().split():
tiles[tile[1]].append(int(tile[0]))
max_ava = 0
for suit in tiles:
# max for seq
for x in range(1, 10):
seq = 0
if x in tiles[suit]:
seq += 1
if x+1 in tiles[suit]:
seq += 1
if x+2 in tiles[suit]:
seq += 1
max_ava = max(max_ava,... |
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro... | 3 | import sys,os,io
from math import gcd
input = sys.stdin.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
ans = [0]*T
for t in range(T):
N = int(input())
ans[t] = [0]*N
A = list(map(int, input().split()))
old_g = max(A)
ans[t][0] = old_g
A.remove(old_g)
for i in range(... |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high... | 3 | import math
t = int(input())
for T in range(t):
n = int(input())
a =[int(x) for x in input().split()]
diff = 0
l = set()
for i in range(n - 1):
x = a[i]
y = a[i + 1]
if x != -1 and y != -1:
diff = max([diff, abs(x - y)])
elif x == -1 and y == -1:
... |
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string.
Your task is to find a sequence of operations after which one of the strings ... | 3 | from sys import exit
def blokovi(x):
ret = [0]
for i in range(len(x) - 1):
if x[i] != x[i + 1]:
ret.append(i + 1)
return ret + [len(x)]
s = input()
t = input()
ss = blokovi(s)
tt = blokovi(t)
if s[-1] == 'a':
s += 'b'
else:
s += 'a'
if t[-1] == 'a':
t += 'b'
else:
t ... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 1 | from __future__ import division
n = input()
s = raw_input()
good = 0
cur = 'n'
for i in s:
if cur != i:
good += 1
cur = i
print(n - good)
|
The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.
Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.
Constraints
... | 3 | N = int(input())
for i in range(N):
if i == 0:
P = list(map(int, input().split()))
continue
P.append(int(input().split()[1]))
# dpテーブルの用意 minを取るときはinf埋めしておくと処理が楽になるしバグが見つかりやすい
INF = 2**32-1
dp = [[INF]*N for _ in range(N)]
# dpテーブルの初期化
# 対角成分0
for ij in range(N):
dp[ij][ij] = 0
for l ... |
Write a program to simulate rolling a dice, which can be constructed by the following net.
<image>
<image>
As shown in the figures, each face is identified by a different label from 1 to 6.
Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the d... | 3 | def roll(die, d):
if d == "E":
return [die[3], die[1], die[0], die[5], die[4], die[2]]
if d == "N":
return [die[1], die[5], die[2], die[3], die[0], die[4]]
if d == "S":
return [die[4], die[0], die[2], die[3], die[5], die[1]]
if d == "W":
return [die[2], die[1], die[5], di... |
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ... | 3 | n = int(input())
arr = [int(i) for i in input().split()]
l = [0]*(n+1)
k = n
for i in range(n):
l[arr[i]] = 1
while l[k] == 1:
print(k, end=" ")
k -= 1
else:
print("") |
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera count... | 3 | n,k=map(int,input().split())
a=zip( list(map(int,input().split())),range(0,n) )
a=sorted(a)
i=0;start=[0]*n;count=[0]*n
for j in range(1,n):
while i<j and (count[i]==k or a[i][0]+1!=a[j][0]):
i+=1
if i==j or a[0][0]!=0:
print(-1)
exit(0)
start[j]=i
count[j]+=1
count[i]+=1
pri... |
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar... | 3 | t=int(input())
for w in range(t):
nk=list(map(int,input().strip().split()))
n=nk[0]
k=nk[1]
if n%2!=0:
if k%2==0:
print("NO")
else:
if n<k:
print("NO")
else:
q=n//k
p=q-(q%2==0)
arr=[ p fo... |
Andryusha is an orderly boy and likes to keep things in their place.
Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the sock... | 1 | n = int(raw_input())
x = map(lambda xi : int(xi), raw_input().split())
table = set()
m = 0
for i in range(0, n*2):
if x[i] in table:
table.remove(x[i])
else:
table.add(x[i])
m = max(m, len(table))
print m
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.