name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1009_D. Relatively Prime Graph | Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) ∈ E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.
Construct a rela... | ```python
from math import gcd
from itertools import islice
def get_all(n):
for i in range(1, n+1):
for j in range(i+1, n+1):
if gcd(i, j) == 1: yield i, j
def solve(n, m):
x = list(islice(get_all(n), m))
if len(x) == m >= n - 1:
return x
res = solve(*map(int, input().split()))... |
1032_A. Kitchen Utensils | The king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from 1 to 100.... | ```python
import math
n, k = map(int, input().split())
a = [int(t) for t in input().split()]
d = {}
for i in a:
if d.get(i) is None:
d[i] = 0
d[i] += 1
print(math.ceil(max(d.values()) / k) * len(d.keys()) * k - n)
``` |
1145_D. Pigeon d'Or | From "ftying rats" to urban saniwation workers - can synthetic biology tronsform how we think of pigeons?
The upiquitous pigeon has long been viewed as vermin - spleading disease, scavenging through trush, and defecating in populous urban spases. Yet they are product of selextive breeding for purposes as diverse as r... | ```python
n = int(input())
a = list(map(int, input().split()))
print(2+(min(a)^a[2]))
``` |
1166_C. A Tale of Two Lands | The legend of the foundation of Vectorland talks of two integers x and y. Centuries ago, the array king placed two markers at points |x| and |y| on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at poin... | ```python
num = int(input())
data = [abs(int(i)) for i in input().split()]
data.sort()
def bins(a, b, n):
if a == b:
if data[a] <= n:
return a+1
else:
return a
else:
m = (a+b)//2
if data[m] <= n:
return bins(m+1,b,n)
else:
... |
1185_A. Ropewalkers | Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.
The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa... | ```python
a, b, c, d = map(int, input().split())
a, b, c = sorted([a, b, c])
def solve1(a, b, c):
r1 = max(0, d-(b-a))
b += r1
r2 = max(0, d-(c-b))
return r1+r2
def solve2(a, b, c):
r1 = max(0, d-(c-b))
r2 = max(0, d-(b-a))
return r1+r2
def solve3(a, b, c):
r1 = max(0, d-(c-b))
b -=... |
1203_E. Boxers | There are n boxers, the weight of the i-th boxer is a_i. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.
It is necessary to choose the largest boxing team in terms of the number o... | ```python
N = int(input())
A = sorted([int(a) for a in input().split()])
k = 0
ans = 0
for i in range(N):
if k > A[i]:
pass
elif k >= A[i] - 1:
ans += 1
k += 1
else:
ans += 1
k = A[i] - 1
print(ans)
``` |
1220_C. Substring Game in the Lesson | Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string s and a number k (0 ≤ k < |s|).
At the beginning of the game, players are given a substring of s with left border l and right border r, both equal to k ... | ```python
s = input().rstrip()
minimum = "z"
for ch in s:
if ch > minimum:
print("Ann")
else:
print("Mike")
minimum = ch
``` |
1245_E. Hyakugoku and Ladders | Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snake... | ```python
X = [[int(a) for a in input().split()] for _ in range(10)]
Y = [(i//10, 9-i%10 if (i//10)&1 else i%10) for i in range(100)]
Z = [[i * 10 + 9 - j if i & 1 else i * 10 + j for j in range(10)] for i in range(10)]
E = [0] * 100
F = [0] * 100
for i in range(1, 6):
F[i] = E[i] = (sum(E[:i]) + 6) / i
for i in ra... |
1265_C. Beautiful Regional Contest | So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n.
Help the jury distrib... | ```python
def func(a, total):
d = {}
temp = total
for no in a:
if total - 1 >= 0:
total -= 1
if no in d:
d[no] += 1
else:
d[no] = 1
else:
if no in d:
del d[no]
break
if len(d) < 3:... |
134_B. Pairs of Numbers | Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n... | ```python
import sys
def solve():
n = int(input())
if n == 1: return 0
res = 1000000
for other in range(n - 1, 0, -1):
pair = [n, other]
temp = 0
while (pair[0] > 1 or pair[1] > 1) and (pair[0] > 0 and pair[1] > 0):
pair.sort()
multiples = (pair[1] - 1) /... |
1370_B. GCD Compression | Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a:
* Remove any two elements from a and append their sum to... | ```python
t = int(input())
def swap(a,b):
if len(a)>len(b):
return b,a
else:
return a,b
def printcomb(a,b):
a, b = swap(a,b)
for i in range(0,len(a),2):
print(a[i]+1, a[i+1]+1)
for i in range(0,len(b),2):
print(b[i]+1, b[i+1]+1)
for i in range(t):
... |
1417_C. k-Amazing Numbers | You are given an array a consisting of n integers numbered from 1 to n.
Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write i... |
1434_A. Perform Easily | After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j.
Tayuya wants to play a melody of n notes. Each note can be play... | ```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.... |
1459_A. Red-Blue Shuffle | There are n cards numbered 1, …, n. The card i has a red digit r_i and a blue digit b_i written on it.
We arrange all n cards in random order from left to right, with all permutations of 1, …, n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the sa... | ```python
for _ in range(int(input())):
n=int(input())
s=input()
s1=input()
a=0
b=0
for i in range(n):
if s[i]>s1[i]:
a=a+1
elif s[i]<s1[i]:
b=b+1
if a>b:
print("RED")
elif b>a:
print("BLUE")
else:
print("EQUAL")
... |
1485_A. Add and Divide | You have two positive integers a and b.
You can perform two kinds of operations:
* a = ⌊ a/b ⌋ (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 ≤ t ≤ 10... | ```python
def incre(a,b):
flag=0
if a//b==0:
return 1
if b==1:
b+=1
flag=1
tb=b
ans=float("inf")
if a//b==0:
return 1+flag
while b<=a:
ta=a
cnt=b-tb
while ta:
ta//=b
cnt+=1
b+=1
if ans<cnt:
return ans+flag
ans=min(ans,cnt)
return ans+flag
for i in range(int(input())):
a,b=map(int,... |
1509_B. TMT Document | The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.
However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to fig... | ```python
import collections
import itertools
from functools import reduce
mod = (10 ** 9) + 7
def permutationbysum():
for _ in range(int(input())):
num, l, r, achieve = map(int, input().split())
k = r - l + 1
if (k * (k + 1)) // 2 <= achieve <= (k * (num * 2 + 1 - k)) // 2:
o... |
1535_C. Unstable String | You are given a string s consisting of the characters 0, 1, and ?.
Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).
Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can... | ```python
for s in[*open(0)][1:]:
r=p=i=j=k=0
for x in s[:-1]:
i+=1;x=ord(x)^i&1
if x<50:k=(k,j)[p!=x];p=x;j=i
r+=i-k
print(r)
``` |
182_B. Vasya's Calendar | 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... | ```python
d = int(input())
n = int(input())
months = list(map(int, input().split()))
changes = 0
for month in months[:-1]:
changes += d - month
print(changes)
``` |
205_D. Little Elephant and Cards | The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks... | ```python
def solve():
n = int(input())
cards = []
cnt = {}
for i in range(n):
card = tuple(map(int, input().split(' ')))
cards.append(card)
cnt[card[0]] = [0, 0]
cnt[card[1]] = [0, 0]
for card in cards:
if card[0] != card[1]:
cnt[card[0]][0] += ... |
22_C. System Administrator | Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of se... | ```python
if __name__ == '__main__':
n, m, v = (int(_) for _ in input().split())
if m < n - 1:
print(-1)
elif m > (n - 1) * (n - 2) / 2 + 1:
print(-1)
else:
v = v % n
print((v - 1) % n + 1, v + 1)
for i in range(1, n - 1):
print((v + i) % n + 1, (v ... |
255_B. Code Parsing | Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:
1. Find two consecutive characters in the string, such that the first of them equals "y", and the s... | ```python
from sys import stdin,stdout
import bisect as bs
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
s=input()
n=len(s)
x=s.count('x')
y=n-x
if y>=x:
for i in range(y-x):
stdout.write('y')
else:
... |
279_B. Books | When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ... | ```python
import bisect
n,t=list(map(int,input().split()))
a=list(map(int,input().rstrip().split()))
b=[0]
sol=0
for i in range(n):
b.append(b[-1]+a[i])
b.pop(0)
for i in range(n):
sol=max(sol,bisect.bisect_right(b,t)-i)
t+=a[i]
print(sol)
``` |
301_A. Yaroslav and Sequence | Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | ```python
#!/usr/bin/python3
n = int(input())
data = list(map(int, input().split()))
negative, zero, positive = 0, 0, 0
for element in data:
if element < 0:
negative += 1
elif element == 0:
zero += 1
else:
positive += 1
seen = {}
min_negative = negative
def go(negative, positive)... |
327_D. Block Tower | After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any bui... | ```python
#Connected component
import sys
from collections import deque
sys.setrecursionlimit(501 * 501)
n,m = [int(i) for i in input().split()]
a=[[0 for i in range(m)] for i in range(n)]
d=[(0,1),(0,-1),(1,0),(-1,0)]
q=deque()
def main():
global a
ans=[]
first=[]
q=deque()
for i in range(n):... |
373_A. Collecting Beats is Fun | 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... | ```python
n = int(input())
memo = {}
for _ in range(4):
s = input()
for i in s:
if i != '.':
if i not in memo:
memo[i] = 1
else:
memo[i] += 1
res = True
for k, v in memo.items():
if v > n*2:
res = False
if res:
print("YES")
els... |
394_C. Dominoes | During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes.
The teacher responded instantly at our request. He put nm dominoes on the table as an n × 2m rectangle so that each of the n rows contained m dominoes arranged horizontally. Each half... | ```python
n, m = map(int, input().split())
doubles, singles = 0, 0
for r in range(n):
for s in input().split():
if s == '11':
doubles += 1
elif s != '00':
singles += 1
lines = {
'zero': ' '.join(m * [ '00' ]),
'double': ' '.join(m * [ '11' ]),
'single_0': ' '.join... |
466_C. Number of Ways | You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>... | ```python
def NoW(xs):
if sum(xs) % 3 != 0:
return 0
else:
part = sum(xs) // 3
ci = ret = 0
acum = xs[0]
for i, x in enumerate(xs[1:]):
if acum == 2*part:
# print("2. x=",x)
ret += ci
if acum == part:
... |
48_A. Rock-paper-scissors | Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obvio... | ```python
I = lambda: int(input())
IL = lambda: list(map(int, input().split()))
L = [input()[0] for i in '123']
gt = {'r': 'rp', 'p': 'ps', 's': 'sr'}
print('F' if L[1] not in gt[L[0]] and L[2] not in gt[L[0]] else
'M' if L[0] not in gt[L[1]] and L[2] not in gt[L[1]] else
'S' if L[0] not in gt[L[2]] and L... |
567_A. Lineland Mail | All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | ```python
n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
print(min(abs(a[i]-a[(i+1)%n]), abs(a[i]-a[i-1])), max(abs(a[i]-a[0]), abs(a[i]-a[-1])))
``` |
588_C. Duff and Weight Lifting | Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi... | ```python
from collections import *
import sys
import math
from functools import reduce
def factors(n):
return set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def st():return input().rstrip('\n')
def val(... |
60_E. Mushroom Gnomes | Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighbori... | ```python
#!/usr/bin/pypy3
from sys import stdin, stdout
input, print = stdin.readline, stdout.write
p = 0
def readints():
return list(map(int, input().split()))
def writeln(x):
print(str(x) + '\n')
def mod(x):
return (x % p + p) % p
def matmul(a, b):
n = len(a)
c = [[0 for x in range(n)] for y ... |
630_J. Divisibility | IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from 2 to 10 every developer ... | ```python
n = int(input())
a = n // 2 + n // 3 + n // 5 + n // 7
b = n // 6 + n // 10 + n // 14 + n // 15 + n // 21 + n // 35
c = n // 30 + n // 42 + n // 70 + n // 105
d = n // 210
print(n - (a - b + c - d))
``` |
659_B. Qualifying Contest | Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m ... | ```python
#!/usr/bin/env python3
read_ints = lambda : list(map(int, input().split()))
if __name__ == '__main__':
n, m = read_ints()
R = [[] for _ in range(m)]
for i in range(n):
n,r,s = input().split()
r = int(r)
s = int(s)
R[r-1].append((s,n))
for r in R:
r.so... |
681_D. Gifts by the List | Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to b... | ```python
# [https://codeforces.com/contest/681/submission/37694242 <- https://codeforces.com/contest/681/status/D <- https://codeforces.com/contest/681 <- https://codeforces.com/blog/entry/45425 <- https://codeforces.com/problemset/problem/681/D <- https://algoprog.ru/material/pc681pD]
(n, m) = map(int, input().split... |
727_A. Transformation: from A to B | Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations:
* multiply the current number by 2 (that is, replace the number x by 2·x);
* append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1).
You need to help Vasil... | ```python
n, target = map(int, input().split())
def keep(target, ans):
#print(target)
while target % 2 == 0:
target = target // 2
ans = [target]+ans
if str(target).endswith("1") and target != 1:
return keep((target-1) // 10, [(target-1) // 10]+ans)
else:
return target, ... |
748_B. Santa Claus and Keyboard Check | Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
... | ```python
#k=int(input())
#n,m=map(int,input().split())
#a=list(map(int,input().split()))
#b=list(map(int,input().split()))
a=input()
b=input()
l=len(a)
d=set()
d2=set()
deg=dict()
for i in range(l):
if a[i]==b[i]:
d2.add(a[i])
deg[a[i]]=0
deg[b[i]]=0
for i in range(l):
if a[i]!=b[i]:
... |
771_A. Bear and Friendship Condition | Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that membe... | ```python
n,m = map(int,input().split())
dic = {}
edges = []
from collections import Counter
def find(node):
tmp = node
while node!=dic[node]:
node = dic[node]
while tmp!=dic[tmp]:
dic[tmp],tmp=node,dic[tmp]
return node
for _ in range(m):
p1,p2 = map(int,input().split())
dic.setd... |
796_A. Buying A House | Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
<image>
The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou... | ```python
def main():
n, m, k = map(int, input().split())
m -= 1
a = list(map(int, input().split()))
min_dist = n
for i, ai in enumerate(a):
if ai != 0 and ai <= k:
min_dist = min(min_dist, abs(i - m))
print(min_dist * 10)
if __name__ == '__main__':
# import sys
#... |
816_B. Karen and Coffee | To stay woke and attentive during classes, Karen needs some coffee!
<image>
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows n ... | ```python
ranges, maps, strs = range, map, str
fout = ""
count = 0
n, k, q = maps(int, input().split())
rangeArr = []
for i in ranges(200002):
rangeArr.append(0)
for recipe in ranges(n):
left, right = maps(int, input().split())
rangeArr[left] += 1
rangeArr[right + 1] -= 1
for recipe in ranges(1, len(rangeArr)... |
841_B. Godsend | Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts a... | ```python
input()
for t in input().split():
if int(t) % 2:
print("First")
break
else:
print("Second")
``` |
862_C. Mahmoud and Ehab and the xor | Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to f... | ```python
n, x = map(int, input().split())
if (n == 2 and x == 0):
print("NO")
quit()
a = 2**17
b = 2**18
ans = 0
print("YES")
if(n == 1):
print(x)
quit()
if (n == 2):
print(x, 0)
quit()
for i in range(n-3):
print(i+1, end = " ")
ans = (ans ^ (i+1))
if (ans == x):
print(b, a, a+b)
el... |
888_A. Local Extrema | You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | ```python
n = int(input())
arr = [int(x) for x in input().split()]
cnt = 0
for i in range(1,n-1):
if arr[i]< arr[i-1] and arr[i] < arr[i+1]:cnt += 1
else:
if arr[i]> arr[i-1] and arr[i] > arr[i+ 1]:
cnt += 1
print(cnt)
``` |
910_B. Door Frames | Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed t... | ```python
n = int(input())
a = int(input())
b = int(input())
ans = 6
cnt = 0
cur = 2
cnt += 2 * ((n - b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
ans = min(ans, cur)
if b * 2 <= n:
cur, cnt = 0, 0
cur = 1
cnt += ((n - 2 * b) // a)
while cnt < 4:
cur += 1
cnt += (n // a)
... |
959_E. Mahmoud and Ehab and the xor-MST | Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is t... | ```python
import math
n = int(input())
ans = 0
cur = 1
while cur < n:
cnt = math.ceil((n-cur)/(cur << 1))
ans += cnt*cur
cur <<= 1
print(ans)
``` |
986_C. AND Graph | You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). C... | ```python
n, m = map(int, input().split())
a = set(map(int, input().split()))
y = 2 ** n
mk = [0] * (2 * y)
cur = 0
for x in a:
if mk[x]: continue
mk[x] = 1
st = [x]
def push(v):
if not mk[v]: mk[v] = 1; st.append(v)
while st:
u = st.pop()
if u < y:
push(y + u)
... |
p02583 AtCoder Beginner Contest 175 - Making Triangle | We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.
In how many ways can we choose three of the sticks with different lengths that can form a triangle?
That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:
... | ```python
n=int(input())
s=input().split()
s=[int(i) for i in s]
s.sort()
a=0
for i in range(len(s)-2):
for j in range(i+1,len(s)-1):
for k in range(j+1,len(s)):
if s[i]!=s[j] and s[j]!=s[k] and s[i]+s[j]>s[k]:
a+=1
print(a)
``` |
p02714 AtCoder Beginner Contest 162 - RGB Triplets | We have a string S of length N consisting of `R`, `G`, and `B`.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
* S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
* j - i \neq k - j.
Constraints
* 1 \leq N \leq 4000
* S is a string of length N consisting of... | ```python
from collections import *
N=int(input())
S=input()
c=Counter(S)
ans=c['R']*c['G']*c['B']
for i in range(1,N//2+1):
for j in range(i,N-i):
if S[j-i]!=S[j] and S[j]!=S[j+i] and S[j+i]!=S[j-i]:
ans-=1
print(ans)
``` |
p02843 Sumitomo Mitsui Trust Bank Programming Contest 2019 - 100 to 105 | AtCoder Mart sells 1000000 of each of the six items below:
* Riceballs, priced at 100 yen (the currency of Japan) each
* Sandwiches, priced at 101 yen each
* Cookies, priced at 102 yen each
* Cakes, priced at 103 yen each
* Candies, priced at 104 yen each
* Computers, priced at 105 yen each
Takahashi wants to buy s... | ```python
X = int(input())
q,mod = divmod(X,100)
if 5*q<mod:
print(0)
else:
print(1)
``` |
p02980 AtCoder Grand Contest 035 - Two Histograms | We have a square grid with N rows and M columns. Takahashi will write an integer in each of the squares, as follows:
* First, write 0 in every square.
* For each i=1,2,...,N, choose an integer k_i (0\leq k_i\leq M), and add 1 to each of the leftmost k_i squares in the i-th row.
* For each j=1,2,...,M, choose an intege... | ```python
N, M = map(int, input().split())
mod = 998244353
if N > M:
N, M = M, N
fact = [0] * (M + 1)
powm = [0] * (M + 1)
pown = [0] * (M + 1)
fact[0] = 1
powm[0] = 1
pown[0] = 1
for i in range(1, M + 1):
fact[i] = fact[i - 1] * i % mod
powm[i] = powm[i - 1] * (M + 1) % mod
pown[i] = pown[i - 1] * (N + 1) % ... |
p03263 AtCoder Beginner Contest 109 - Make Them Even | There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and con... | ```python
(h,w),*a=[map(int,o.split())for o in open(0)]
B=[];l=[]
for y in range(h):
*A,=a[y];x=0
for x in range(1,w):c=A[x-1]%2;l+=[(y+1,x,y+1,x+1)]*c;A[x]+=c
B+=A[x],
if y and B[-2]%2:l+=(y,w,y+1,w),;B[y]+=1
print(len(l))
for a in l:print(*a)
``` |
p03421 AtCoder Regular Contest 091 - LISDL | Determine if there exists a sequence obtained by permuting 1,2,...,N that satisfies the following conditions:
* The length of its longest increasing subsequence is A.
* The length of its longest decreasing subsequence is B.
If it exists, construct one such sequence.
Constraints
* 1 \leq N,A,B \leq 3\times 10^5
* ... | ```python
n, a, b = [int(item) for item in input().split()]
if n < a + (b-1) or n > a + (b-1) * a:
print(-1)
exit()
for i in range(a):
print(n - a + i + 1, end=" ")
n -= a
if n == 0:
print("")
exit()
loop = n // (b-1)
option = n % (b-1)
for j in range(b-1):
if option > 0:
for i in range(... |
p03579 CODE FESTIVAL 2017 qual B - 3 Steps | Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i.
Rng will add new edges to the graph by repeating the following operation:
* Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly thr... | ```python
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.... |
p03736 AtCoder Regular Contest 073 - Many Moves | There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to squar... | ```python
import sys
read = sys.stdin.buffer.read
INF = 10**12
class Rmin():
def __init__(self, size):
#the number of nodes is 2n-1
self.n = 1 << (size.bit_length())
self.node = [INF] * (2*self.n-1)
def Access(self, x):
return self.node[x+self.n-1]
def Update(self, x, val):
x += self.n-1
self.node[x] ... |
p03898 CODE FESTIVAL 2016 Relay (Parallel) - Problem on Tree | There is a tree with N vertices, numbered 1 through N.
The i-th of the N-1 edges connects the vertices p_i and q_i.
Among the sequences of distinct vertices v_1, v_2, ..., v_M that satisfy the following condition, find the maximum value of M.
* For every 1 \leq i < M, the path connecting the vertices v_i and v_{i+1}... | ```python
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 7)
"""
・次数3以上の点は使わないとしてよい
・次数1の点は全て回収できる。次数2の点を、パスとなる形で回収する。
"""
N = int(readline())
PQ = [tuple(int(x)-1 for x in line.split()) for line in readlines()]
graph = [[] for _ in range(N)]
for p,q in PQ:
gr... |
p00004 Simultaneous Equation | 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 ... | ```python
import sys
lines = sys.stdin.readlines()
for l in lines:
nums = list(map(int, l.split()))
A = [nums[0], nums[1], nums[3], nums[4]]
B = [nums[2], nums[5]]
detA = A[0]*A[3] - A[1]*A[2]
inA = [A[3], -A[1], -A[2], A[0]]
solutions = [n/detA+0.0 for n in [inA[0]*B[0] + inA[1]*B[1], inA[2]*B... |
p00136 Frequency Distribution of Height | The height of the student was measured at the medical examination. Create a program that takes height data as input, creates a frequency distribution, and outputs it. The frequency distribution is divided into 6 classes in 5 cm increments, and the number of people is indicated by * (half-width asterisk). However, if th... | ```python
# -*- coding: utf-8 -*-
"""
"""
import sys
from sys import stdin
input = stdin.readline
def main(args):
ranks = [0] * 6
n = int(input())
for _ in range(n):
h = float(input())
if h < 160.0:
h = 160.0
if h >= 190.0:
h = 189.9
pos = int((h -... |
p00457 Chain | problem
There are the following games.
N characters are lined up in a vertical row. The color of these characters is red, blue, or yellow, and in the initial state, four or more characters of the same color are not lined up in a row. The player can select a character at a certain position and change it to another col... | ```python
# p周辺の4つは消えることが前提
def erase(array, i, N):
if array[i - 1] == array[i]:
up = i - 1
down = i
elif array[i] == array[i + 1]:
up = i
down = i + 1
else:
return N - 2
while True:
if array[up] == -1 or array[down] == -1 or not array[up] == array[down]:... |
p00647 It's our delight!! | You are a student of University of Aizu. And you work part-time at a restaurant.
Staffs of the restaurant are well trained to be delighted to provide more delicious products faster.
The speed providing products particularly depends on skill of the staff. So, the manager of the restaurant want to know how long it take... | ```python
while 1:
N = int(input())
if N == 0:
break
a = b = c = 0
a0 = b0 = c0 = 0
for i in range(N):
s0, s1 = input().split()
h, m = map(int, s0.split(":"))
tm = 100*h + m
m1 = int(s1)
if m1 < m:
m1 += 60
if 1100 <= tm < 1500:
... |
p01493 DisconnectedGame | Example
Input
3
NNN
NNN
NNN
Output
Taro | ```python
from collections import deque
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
G = [[] for i in range(N)]
for i in range(N):
*vs, = readline()
for j in range(N):
if vs[j] == "Y":
... |
p01806 Dice Stamp | Dice Stamp
Dice stamp
At a local fair, you found a game store you've never seen before. This is a game in which N 6-sided dice are dropped and rolled on the board. More precisely, N buttons are tied to N dice on a one-to-one basis, and pressing the button causes the corresponding dice to fall onto the board. It is a ... | ```python
def main():
while True:
n = int(input())
if n == 0:break
def spin(dice, direct):
l, r, f, b, d, u = dice
if direct == "R":
return [d, u, f, b, r, l]
if direct == "L":
return [u, d, f, b, l, r]
if direct == "B":
return [l, r, d, u, b, f]
if di... |
p01941 Indecision | D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the... | ```python
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
def solve():
L = 250
dp = [[-10**18]*(L+1) for i in range(C+1)]
for j in range(C+1):
dp[j][0] = 0
for a, b, c in events:
for j in range(C-c, -1, -1):
... |
p02090 Shuttle Run | C: Shuttle Run
Story
University H has a unique physical fitness test program, aiming to grow the mindset of students. Among the items in the program, shuttle run is well-known as especially eccentric one. Surprisingly, there are yokans (sweet beans jellies) on a route of the shuttle run. Greedy Homura-chan would like... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline(... |
p02222 Painting Tree | Problem statement
Modulo is very good at drawing trees.
Over the years, Modulo has drawn a picture of a tree with $ N $ vertices. The vertices of this tree are numbered from $ 1 $ to $ N $, and the vertices $ a_i $ and $ b_i $$ (1 \ leq i \ leq N-1) $ are directly connected by edges. All vertices are not yet painted.... | ```python
import sys
from collections import deque
readline = sys.stdin.readline
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
... |
p02374 Range Query on a Tree | Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to the edge which connects node $v$ and its parent
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique I... | ```python
import sys
sys.setrecursionlimit(int(1e6))
class B_I_T:
def __init__(self, n):
self.n = n
self.data = [0] * (n + 1)
def get_sum(self, i):
ret = 0
while i > 0:
ret += self.data[i]
i -= (i & -i)
return ret
def add(self, i, w):... |
1006_F. Xor-Paths | There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints:
* You can move to the right or to the bottom onl... | ```python
from collections import*
n, m, k = map(int, input().split())
b = [[int(v) for v in input().split()] for _ in range(n)]
if m < n:
a = [[b[j][i] for j in range(n)] for i in range(m)]
b = a
m, n = n, m
cntrs = [Counter() for _ in range(n)]
d = (n + m-1) // 2
for i in range(1<<d):
ones = bin(i).co... |
1051_E. Vasya and Big Integers | Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123",... | ```python
def kmp(pat,text,t):
s=pat+"?"+text;
#z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...]
z=[0 for i in range(len(s))]
L=0;R=0;n=len(s);
for i in range(1,len(s)):
if i>R:
L=R=i
while R<n and s[R-L]==s[R]:
R+=1
... |
1073_F. Choosing Two Paths | You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to t... | ```python
import sys
n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
i, j = tuple(int(k) for k in sys.stdin.readline().split())
i -= 1
j -= 1
edges[i].append(j)
edges[j].append(i)
# Prunes the graph starting from the vertices with
# only 1 edge until we reach a ... |
1095_F. Make It Connected | You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are... | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
e = []
for _ in range(m) :
u, v, w = map(int, input().split())
e.append((u-1, v-1, w))
a = sorted(zip(a, range(n)), key = lambda x : x[0])
for i in range(1, n) :
e.append((a[0][1], a[i][1], a[0][0] + a[i][0]))
fa = list(range(... |
1117_A. Best Subsegment | You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).
If there are many such subsegments find the longest one.
Input
The first line contains single integer... | ```python
n=int(input())
s=[int(x) for x in input().split()]
el=max(s)
pos1=-1
pos2=-1
c=0
ans=0
for i in range(0,len(s)):
if(s[i]==el):
c=c+1
else:
ans=max(ans,c)
c=0
ans=max(ans,c)
print(ans)
``` |
1143_C. Queen | You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the ... | ```python
"""
https://codeforces.com/problemset/problem/1143/C
"""
n = int(input())
respect = [0 for _ in range(n)]
child_respect = [0 for _ in range(n)]
root = -1
for i in range(n):
p, c = map(int,input().split())
if p == -1:
root = i
continue
respect[i] = c
if p != -1 and not c: ch... |
1163_C1. Power Transmission (Easy Edition) | This problem is same as the next one, but has smaller constraints.
It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system cons... | ```python
import sys
import collections
import math
import heapq
from operator import itemgetter
def getint():
return int(input())
def getints():
return [int(x) for x in input().split(' ')]
n = getint()
points = [tuple(getints()) for _ in range(n)]
result = 0
slopes = collections.defaultdict(set)
for i in r... |
1184_A1. Heidi Learns Hashing (Easy) | Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.
Heidi figured out that Madame Kovarian uses a... | ```python
from math import sqrt
def get_int():
from sys import stdin
return int(stdin.readline().replace('\n', ''))
def is_even(n):
return n%2 == 0
def heidi_hash(r):
k = r-1
rt = int(sqrt(k))
for x in range(1, rt+2):
if k % x == 0:
temp = k/x -x -1
if temp > ... |
1201_D. Treasure Hunting | You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i).
Initially you stand at the lower left corner of the island, at the position (1, 1). I... | ```python
from sys import stdin
from bisect import bisect_left
input=stdin.readline
n,m,k,q=map(int,input().split(' '))
x=sorted(list(map(int,input().split(' ')))for i in range(k))
y=sorted(list(map(int,input().split(' '))))
def rr(c0,c1,c2):
return abs(c2-c0)+abs(c1-c2)
def tm(c0,c1):
t=bisect_left(y,c0)
... |
1219_C. Periodic integer number | Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example:
X = 123123123 is periodic number with length L = 3 and L = 9
X = 42424242 is periodic number with... | ```python
import math as m
def main():
n = int(input())
s = input()
l = len(s)
p = int(m.ceil(l/n))
if l%n!=0 :
t = '1'
for i in range(1,n):
t+='0'
for i in range(0,p):
print(t ,end = '')
else :
z = s[0:n]
t=''
for i in range(0,p):
t+=z
if t > s:
print(t)
return
z = str(int(s[0:n]... |
1243_C. Tile Painting | Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit... | ```python
def prime_factor(n):
ass = []
for i in range(2,int(n**0.5)+1):
while n % i==0:
ass.append(i)
n = n//i
if n != 1:
ass.append(n)
return ass
n = int(input())
p = list(set(prime_factor(n)))
if len(p) == 1:
print(p[0])
else:
print(1)
``` |
1263_B. PIN Codes | A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.
Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i.
Polycarp has recently read a recommendation that it is bette... | ```python
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
# from math import gcd
# from itertools import combinations,permutations,accumulate, product # (string,3) 3回
# #from collections import deque
# from collections import deque,de... |
1328_A. Divisibility Problem | You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c... | ```python
t=int(input())
for i in range(0,t):
a,b=input().split()
a=int(a)
b=int(b)
print((b-a%b)%b)
``` |
1348_A. Phoenix and Balance | Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | ```python
t=eval(input())
for j in range(t):
n=eval(input())
if n==2 :
print(2)
else:
sum=2
for i in range(1,n//2):
sum=sum+2**(i+1)
print(sum)
``` |
1413_A. Finding Sasuke | Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e... | ```python
T = int(input())
a = []
b=[]
i = 0
j = 0
n = 0
for i in range(T):
n = int(input())
a = list(map(int, input().split()))
b.append([])
for j in range(int(n/2)):
if (a[j*2] > a[j*2 + 1]):
b[i].append(a[j*2 + 1])
b[i].append(-a[j*2])
elif(a[j*2 + 1] >= a[j*... |
1455_A. Strange Functions | Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.
Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well... | ```python
from sys import stdout,stdin,maxsize
from collections import defaultdict,deque
import math
t=int(stdin.readline())
for _ in range(t):
#n=int(stdin.readline())
#d=map(int,stdin.readline().split())
#l=list(map(int,stdin.readline().split()))
s=input()
print(len(s))
... |
1479_B2. Painting the Array II | The only difference between the two versions is that this version asks the minimal possible answer.
Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i ind... | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
A = [int(a) for a in input().split()]
S = set()
ans = 0
la = -1
for a in A:
if a == la:
continue
elif a in S:
S = {a, la}
else:
S.add(a)
la = a
ans += 1
print(ans)
``` |
1506_A. Strange Table | Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":
* cells are numbered starting from one;
* cells are numbered from left to right by columns, and inside each column from top to bottom;
... | ```python
def somefunc(n, m, x):
if n == m and n == 1:
return x
ans = 0
row = 0
if x % n == 0:
# 2
row = x / n
else:
row = x // n + 1
col = x % n
if col == 0:
col = n
ans = int(m * (col - 1))
ans += row
return int(ans)
for t in range(i... |
1529_B. Sifid and Strange Subsequences | A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequenc... | ```python
"""
Author : Ashish Sasmal
Python3 / PyPy3
"""
from sys import stdin as sin
def aint():return int(input())
def amap():return map(int,sin.readline().split())
def alist():return list(map(int,sin.readline().split()))
def astr():return input()
for _ in range(aint()):
n = aint()
l = alist()
l... |
160_B. Unlucky Ticket | Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th... | ```python
number_of_testcases = 1 #int(input())
for _ in range(number_of_testcases):
number_of_digits = int(input())
ticket_number = input()
ticket_number = list(ticket_number)
first_half = ticket_number[:number_of_digits]
second_half = ticket_number[number_of_digits:]
#print(first_half)
f... |
227_D. Naughty Stone Piles | There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.
During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of... | ```python
n = int(input())
stones = list(map(lambda t : int(t), input().split()))
q = int(input())
queries = list(map(lambda t : int(t), input().split()))
stones.sort()
added_stones = []
added_stones.append(stones[0])
for i in range(1, n, 1):
added_stones.append(stones[i] + added_stones[i - 1])
computed_queries ... |
251_B. Playing with Permutations | Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n.
A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct.
There is only one thing Petya likes more than permutations: playing with little Masha... | ```python
n,k=map(int,input().strip().split())
a=list(map(int,input().strip().split()))
b=list(map(int,input().strip().split()))
ups = [[i+1 for i in range(n)]]
downs = [[i+1 for i in range(n)]]
def apply(arr):
out = [0]*n
for i in range(n):
out[i] = arr[a[i]-1]
return out
def unapply(arr):
ou... |
276_C. Little Girl and Maximum Sum | The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to f... | ```python
n,m = map(int,input().split())
a = list(map(int,input().split()))
l = [0]*(n+2)
for i in range(m):
x,y=map(int,input().split())
l[x] += 1
l[y+1] -= 1
for i in range(2, n+2):
l[i] += l[i-1]
l.sort(reverse=True)
a.sort(reverse=True)
# print(l, a)
ans=0
for i in range(n):
ans += l[i]*a[i]
print(ans)
... |
322_C. Ciel and Robot | Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:
* 'U': go up, (x, y) → (x, y+1);
* 'D': go down, (x, y) → (x, y-1);
* 'L': go left... | ```python
target = tuple(map(int, input().split()))
s = input()
#print(target)
#print(s)
ok = False
pos = (0, 0)
for c in s:
if c == 'L': pos = (pos[0]-1, pos[1])
if c == 'R': pos = (pos[0]+1, pos[1])
if c == 'U': pos = (pos[0], pos[1]+1)
if c == 'D': pos = (pos[0], pos[1]-1)
if pos == target: ok ... |
347_A. Difference Row | You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The ... | ```python
# t=int(input())
# import math
# for _ in range(t):
# n,k=list(map(int,input().split()))
# s=input()
# a=[]
# summer=0
# for i in range(len(s)):
# if(s[i]=='1'):
# a.append(i)
# i=0
# while(i<len(a)-1):
# dist=a[i+1]-k-1-(a[i]+k+1)+1
# # print(a,... |
370_B. Berland Bingo | Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.
During the game the host takes num... | ```python
n = int(input())
cards = [None] + [[] for i in range(n)]
for i in range(1, n+1):
cards[i] = list(map(int, input().split()))[1:]
ans = [None] + [True for i in range(n)]
#print(cards, ans)
for i in range(1, n + 1):
for j in range( 1, n + 1):
if i == j :
continue;
if set(card... |
441_C. Valera and Tubes | Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).
Valera wants to place... | ```python
import sys
import math as mt
#input=sys.stdin.buffer.readline
#import bisect
mod=1000000007
#t=int(input())
#tot=0
t=1
for __ in range(t):
#n=int(input())
n,m,k=map(int,input().split())
x,y=1,0
d=0
r=1
ch=1
cnt1=1
for i in range(k-1):
print(2,end=" ")
for j... |
463_D. Gargari and Permutations | Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can... | ```python
n, k = map(int, input().split())
ra = [[0] * k for _ in range(n)]
for p in range(k):
for i, v in enumerate(map(int, input().split())):
v -= 1
ra[v][p] = i
g = [[] for _ in range(n)]
for u in range(n):
for v in range(n):
if all(x < y for x, y in zip(ra[u], ra[v])):
g... |
487_C. Prefix Product Sequence | Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>.
Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
Input
The only input line contains an integer n (1 ≤ n ≤ 105).
Output
In the first output line, print ... | ```python
n = int(input())
if n == 1:
print('YES\n1')
exit(0)
if n == 4:
print('YES\n1 3 2 4')
exit(0)
for p in range(2, int(n ** 0.5) + 1):
if n % p == 0:
print('NO')
exit(0)
print('YES')
print(1)
for j in range(2, n):
print(j * pow(j - 1, n - 2, n) % n)
print(n)
``` |
510_B. Fox And Two Dots | Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:
<image>
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain d... | ```python
'''
Zijian He
1429876
'''
# Import
from sys import setrecursionlimit
setrecursionlimit(10**6)
# Function from class
class Graph:
def __init__ (self):
self._alist = {}
def add_vertex (self, vertex):
if vertex not in self._alist:
self._alist[vertex] = set()
def add_ed... |
535_C. Tavas and Karafs | Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.
<image>
Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is ... | ```python
a,b,n=map(int,input().split())
for _ in range(n):
l,t,m=map(int,input().split())
lo=l
hi=100000000
while lo<hi:
mid=(lo+hi)//2
count=(mid-l)+1
first=a+(l-1)*b
last=a+(mid-1)*b
if last<=t and (count*(first+last))//2<=m*t:
lo=mid+1
else... |
586_A. Alena's Schedule | Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way that every day it... | ```python
n = int(input())
a = list(map(int, input().split())) + [0]
home = True
ans = 0
for i in range(n):
if a[i]:
ans += 1
home = False
elif not a[i + 1] and not home:
home = True
elif not home:
ans += 1
print(ans)
``` |
608_B. Hamming Distance Sum | Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming ... | ```python
from sys import stdin
input=stdin.readline
'''
if i+k
'''
def getcnt(a):
cnt=[[0,0] for i in range(len(a)+1)]
for i in range(len(a)):
# if i==0:
# cnt[i][a[i]]+=1
# else:
cnt[i+1][0]=cnt[i][0]
cnt[i+1][1]=cnt[i][1]
cnt[i+1][a[i]]+=1
return cnt
d... |
62_A. A Student's Dream | Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.
A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess... | ```python
g_l,g_r=input().split()
b_l,b_r=input().split()
g_l=int(g_l)
g_r=int(g_r)
b_l=int(b_l)
b_r=int(b_r)
flag=0
if g_l==b_r:
flag=1
elif g_l>b_r and g_l-1==b_r:
flag=1
elif b_r>g_l and 2*g_l+2>=b_r:
flag=1
if flag==0:
if g_r == b_l:
flag = 1
elif g_r > b_l and g_r - 1 == b_l:
f... |
724_A. Checking the Calendar | You are given names of two days of the week.
Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong t... | ```python
a = str(input())
b = str(input())
k = {'monday':1,'tuesday':2,'wednesday':3,'thursday':4,'friday':5,'saturday':6,'sunday':7}
a=k[a]-1
b=k[b]-1
res = False
res = res or ((a+2)%7+1)%7==b
res = res or ((a+1)%7+1)%7==b
res = res or ((a+6)%7+1)%7==b
if res:
print("YES")
else:
print("NO")
``` |
746_A. Compote | Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, ... | ```python
l = int(input())
a = int(input())
p = int(input())
ll = l
aa = a // 2
pp = p // 4
print(min(ll,aa,pp) * 1 + min(ll,aa,pp) * 2 + min(ll,aa,pp) * 4)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.