name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p01831 Line Gimmick | Example
Input
7
>>
Output
7 | ```python
import re
n = int(input())
s = input()
res = 10**10
res = min(res, len(re.search(r'^<*', s).group()))
res = min(res, len(re.search(r'>*$', s).group()))
print(n-res)
``` |
p02113 Palindrome | Problem
Taro has N character strings, each of which is L in length. Taro loves palindromes, so I want to make palindromes as long as possible by selecting some of the N character strings and arranging them in any order.
Find the longest palindrome that Taro can make. If there are more than one, output the smallest on... | ```python
from functools import cmp_to_key
n, l = map(int, input().split())
ss = {}
for i in range(n):
s = input()
ss[s] = ss.get(s, 0) + 1
ans = ""
ma = ""
for s in sorted(ss):
if s[::-1] == s:
ans += s * (ss[s]//2)
ss[s] -= 2*(ss[s]//2)
if ss[s] > 0 and len(ma) < len(s):
... |
p02253 Activity Selection Problem | There are $ n $ acitivities with start times $ \\ {s_i \\} $ and finish times $ \\ {t_i \\} $. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person.
Constraints
* $ 1 \ le n \ le 10 ^ 5 $
* $ 1 \ le s_i \ lt t_i \ le 10 ^ 9... | ```python
n = int(input())
A = [[int(i) for i in input().split()] for _ in range(n)]
A.sort(key = lambda x:x[1])
t = 0
ans = 0
for i in A:
if t < i[0]:
ans += 1
t = i[1]
print(ans)
``` |
p02401 Simple Calculator | Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.
The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.
Constraints
* 0 ≤ a, b ≤ 20000
* No divisions by zero are given.
Input
The input c... | ```python
while(1):
a,op,b = input().split()
a ,b = int(a), int(b)
if(op == '+'): print(a+b)
if(op == '-'): print(a-b)
if(op == '*'): print(a*b)
if(op == '/'): print(int(a/b))
if(op == '?'): break
``` |
1028_E. Restore Array | While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers a_1, a_2, …, a_n. Since the talk was long and not promising, Kostya created a new cyclic array b_1, b_2, …, b_{n} so that b_i = (a_i mod a_{i + 1}), where we take a_{n+1} = a_1. Here mod is the [modulo operati... | ```python
####################################### Define
maxN = int(2e5 + 10)
n = 0
b = [0] * maxN
ans = [0] * maxN
####################################### Functions
####################################### Main
n = int(input())
inp = input().split()
flag = False
for i in range(1, n + 1) :
b[i] = int(inp[i - 1])
... |
1047_A. Little C Loves 3 I | Little C loves number «3» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 ≤ n ≤ 10^9) — the integ... | ```python
def main():
n = int(input())
if (n % 3 == 0) or (n % 3 == 1):
print(1, 1, n - 2)
else:
print(1, 2, n - 3)
if __name__ == '__main__':
main()
``` |
1092_E. Minimal Diameter Forest | You are given a forest — an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) ... | ```python
from collections import deque
##make the tree
n,m=[int(x) for x in input().split()]
tree={}
for i in range(m):
a,b=[int(x) for x in input().split()]
if a not in tree:
tree[a]=[b]
else:
tree[a].append(b)
if b not in tree:
tree[b]=[a]
else:
tree[b].append(a)
f... |
1111_D. Destroy the Colony | There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.
Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole.
Iron Man can destroy a colony only if the colon... | ```python
from sys import stdin
MOD = 1000000007
s = stdin.readline().strip()
n = len(s)
buc = [0] * 101
fac = [0] * (n + 1)
inv = [0] * (n + 1)
dp = [0] * (n + 1)
# temp_dp = [0] * (n+1)
ans = [[0] * 55 for _ in range(55)]
def find(c: 'str') -> 'int':
if 'A' <= c <= 'Z':
return ord(c) - ord('A') + 26
... |
1141_B. Maximal Continuous Rest | Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go ... | ```python
n=int(input())
ans=0
curr=0
l=list(map(int,input().split()))
for i in range(2*n):
if(l[i%n]==1):
curr+=1
else:
curr=0
ans=max(ans,curr)
print(ans)
``` |
115_A. Party | A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manag... | ```python
import sys;readline = sys.stdin.buffer.readline
def i1(): return int(readline())
def nl(): return [int(s) for s in readline().split()]
def nn(n): return [int(readline()) for i in range(n)]
def nlp(x): return [int(s)+x for s in readline().split()]
def nll(n): return [[int(s) for s in readline().split()] for i ... |
1182_A. Filling Shapes | You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles.
Input
The only line cont... | ```python
import sys
from random import choice,randint
inp=sys.stdin.readline
out=sys.stdout.write
flsh=sys.stdout.flush
sys.setrecursionlimit(10**9)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def MI(): return map(int,... |
11_A. Increasing Sequence | A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.
You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasin... | ```python
n,d=map(int,input().split())
l=[int(i) for i in input().split()]
s=0
import math
for i in range(1,n):
if l[i]>l[i-1]:
continue
diff=l[i-1]-l[i]+1
s+=math.ceil(diff/d)
l[i]+=d*math.ceil(diff/d)
print(s)
``` |
1217_D. Coloring Edges | You are given a directed graph with n vertices and m directed edges without self-loops or multiple edges.
Let's denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color.
Find a good k-coloring of given d... | ```python
import sys
input = sys.stdin.readline
def dfs(cur_node, childs, vis, cur_dfs):
if cur_node in cur_dfs:
return True
if vis[cur_node]:
return False
vis[cur_node] = True
cur_dfs.add(cur_node)
for ele in childs[cur_node]:
if dfs(ele, childs, vis, cur_dfs):
... |
1240_A. Save the Nature | You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of t... | ```python
t = int(input())
for case_num in range(t):
n = int(input())
p = list(map(int, input().split(' ')))
x, a = map(int, input().split(' '))
y, b = map(int, input().split(' '))
k = int(input())
p.sort()
p.reverse()
sum = [0]
for i in range(n):
sum.append(sum[-1] + p[i])
... |
1260_B. Obtain Two Zeroes | You are given two integers a and b. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.
Is it possible to mak... | ```python
t = int(input())
for i in range(t):
a, b = map(int, input().split())
if a > b:
[a, b] = [b, a]
if (a * 2 >= b and (a + b) % 3 == 0):
print("YES")
else:
print("NO")
``` |
1282_B2. K for the Price of One (Hard Version) | This is the hard version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: 2 ≤ k ≤ n.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in... | ```python
T=int(input())
for _ in range(T):
n,amt,k=map(int,input().split())
l=list(map(int,input().split()))
l=sorted(l);dp=[0]*(n+1);ans=0;
for i in range(n):
if i-k>=-1:dp[i]=dp[i-k]+l[i]
else:dp[i]=l[i]+dp[i-1]
#print(dp)
for i in range(n):
if dp[i]<=amt:ans=i+1;
print(ans)
``` |
1326_C. Permutation Partitions | You are given a permutation p_1, p_2, …, p_n of integers from 1 to n and an integer k, such that 1 ≤ k ≤ n. A permutation means that every number from 1 to n is contained in p exactly once.
Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_... | ```python
import sys
input = sys.stdin.readline
if __name__ == "__main__":
n, k = map(int, input().split())
p = list(map(int, input().split()))
max_val = sum(range(n, n - k, -1))
num_perm = 1
last_idx = -1
for i in range(n):
if p[i] > n - k:
if last_idx != -1:
... |
1345_B. Card Constructions | A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
... | ```python
import os
import bisect
def get_sizes():
s = [0]
i = 1
while s[-1] <= int(1e9):
s.append(s[-1] + (i - 1) * 3 + 2)
i += 1
return s
SIZES = get_sizes()[1:]
def g(n, p = 0):
if n < 2:
return p
b = SIZES[bisect.bisect_right(SIZES, n) - 1]
return g(n - b,... |
1367_A. Short Substrings | Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | ```python
t=int(input())
for i in range (t):
a=input()
print(a[0::2]+a[-1])
``` |
1388_A. Captain Flint and Crew Recruitment | 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... | ```python
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
t = 1
t = int(input())
while t:
t -= 1
n = int(input())
# s = input()
if n > 30:
if (n-30) in [6, 10, 14]:
if n > 31:
print('YES')
print(6,10,15,n-31... |
142_B. Help General | Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot h... | ```python
n, m = sorted(map(int, input().split()))
k = 4 * (m >> 2)
print(m if n == 1 else k + 2 * min(2, m - k) if n == 2 else (m * n + 1 >> 1))
``` |
1476_D. Journey | There are n + 1 cities, numbered from 0 to n. n roads connect these cities, the i-th road connects cities i - 1 and i (i ∈ [1, n]).
Each road has a direction. The directions are given by a string of n characters such that each character is either L or R. If the i-th character is L, it means that the i-th road initiall... | ```python
from sys import stdin, exit
from bisect import bisect_left as bl, bisect_right as br
from itertools import accumulate
input = lambda: stdin.readline()[:-1]
intput = lambda: int(input())
sinput = lambda: input().split()
intsput = lambda: map(int, sinput())
def dprint(*args, **kwargs):
if debugging:
... |
1503_A. Balance the Bits | A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.
You are given a binary string s of length n. Construct two balanced bracket sequences ... | ```python
T = int(input())
for ts in range(T):
N = int(input())
s = input()
if s[0] == '0' or s[-1] == '0':
print("NO")
continue
a = ['(']
b = ['(']
# y_n = 0
# y = jie(1, 1, 1)
# if y == 1:
# print("YES")
# print(''.join(a))
# print(''.join(b))
... |
1526_E. Oolimry and Suffix Array | Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array.
More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array.
Let s be a string of length n. Then the i-th suffix of s is the subst... | ```python
MOD = 998244353
n, k = map(int, input().split())
arr = list(map(int, input().split()))
pos = [-1] * (n+1)
for i, a in enumerate(arr):
pos[a] = i
pos[-1] = -1
for i in range(n-1):
if pos[arr[i]+1] < pos[arr[i+1]+1]:
k += 1
if k < n:
print(0)
else:
fact = [1]
for i in range(1, k+1)... |
158_C. Cd and pwd commands | Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure... | ```python
#!/usr/bin/env python3
def pwd(cur):
if len(cur) == 0:
print('/')
else:
print('/' + '/'.join(cur) + '/')
def process(cmd, cur):
cmd = cmd[3:]
ds = cmd.split('/')
if cmd[0] == '/':
cur = []
for d in ds:
if d == '..':
cur.pop()
el... |
224_E. Partial Sums | You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:
1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that ... | ```python
def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
p=10**9+7
n,k=map(int,input().split())
b=list(map(int,input().split(... |
297_A. Parity Game | You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a... | ```python
print('YES' if input().count('1')+1>>1<<1 >= input().count('1') else 'NO')
``` |
31_D. Chocolate | Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parall... | ```python
w,h,n=list(map(int,input().split()))
a=[[0 for i in range(2*w-1)] for j in range(2*h-1)]
for i in range(1,2*h-1,2):
for j in range(1,2*w-1,2):
a[i][j]=' '
for i in range(n):
x1,y1,x2,y2=list(map(int,input().split()))
if x1==x2:
if x1!=0 and x1!=w:
for j in range(min(y1,... |
344_D. Alternating Current | Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u... | ```python
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(se... |
368_A. Sereja and Coat Rack | 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... | ```python
racks, fine = map(int, input().split())
cost = list(map(int, input().split()))
cost.sort()
guests = int(input())
if guests > racks:
print (sum(cost) - ((guests - racks) * fine))
else:
print (sum(cost[:guests]))
``` |
390_B. Inna, Dima and Song | Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.
A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at vo... | ```python
num = int(input())
arr_a = list(map(int,(input()).split()))
arr_b = list(map(int,(input()).split()))
joy = 0
for i in range(num):
if arr_b[i] == 1:
joy -= 1
continue
if arr_a[i] * 2 >= arr_b[i]:
temp = arr_b[i] // 2
joy = joy + temp * (arr_b[i] - temp)
else:
... |
412_A. Poster | The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a lar... | ```python
n, k = map(int, input().split())
s = input()
def goRight():
i = k - 1
while i < n - 1:
print("RIGHT")
i += 1
i = n - 1
while i >= 0:
print("PRINT", s[i])
if i:
print("LEFT")
i -= 1
def goLeft():
i = k - 1
while i > 0:
print("LEFT")
i -= 1
i = 0
while i < n:
... |
439_C. Devu and Partitioning of the Array | Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?
Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty part... | ```python
def solve():
n,k,p=map(int,input().split())
a=list(map(int,input().split()))
even=list(filter(lambda x: x%2==0, a))
odd=list(filter(lambda x:x%2==1, a))
if (len(odd)-(k-p))%2!=0:
print("NO");
return
ans=[[] for _ in range(k)]
for i in range(k-p):
if odd:
... |
484_D. Kindergarten | In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maxim... | ```python
#import sys
#input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
dp = [0] * n
pos, neg = -10 ** 18, -10 ** 18
for i, x in enumerate(a):
prv = 0 if i == 0 else dp[i - 1]
dp[i] = max(neg + x, pos - x, prv)
pos = max(pos, prv + x)
neg = max(neg, prv - x)
print(dp[-... |
508_D. Tanya and Password | While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password ... | ```python
from collections import Counter, defaultdict
def main():
ht = defaultdict(list)
cnt = Counter()
n = int(input())
for _ in range(n):
s = input()
h, t = s[:2], s[1:]
ht[h].append(t)
cnt[h] += 1
cnt[t] -= 1
st = nd = flag = True
for t, i in cnt.it... |
583_C. GCD Table | The GCD table G of size n × n for an array of positive integers a of length n is defined by formula
<image>
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6,... | ```python
import collections as cc
import math as mt
I=lambda:list(map(int,input().split()))
n,=I()
l=I()
f=cc.Counter(l)
ans=[]
for i in range(n):
now=max(f)
f[now]-=1
for j in ans:
f[mt.gcd(now,j)]-=2
ans.append(now)
f+=cc.Counter()
print(*ans)
``` |
605_C. Freelancer's Dreams | Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions to wo... | ```python
def get_bounds(points):
if len(points) == 1:
return points[:]
points.sort()
bounds = [points[0], points[1]]
for xi, yi in points[2:]:
while len(bounds) > 1 and not is_convex(bounds, xi, yi):
del bounds[-1]
bounds.append((xi, yi))
return bounds
... |
627_D. Preorder Test | For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.
Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to ... | ```python
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [[] for _ in range(n)]
for i in range(n - 1):
u, v = map(int, input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
stack = [0]
done = [False] * n
par = [0] * n
order = []
while len(stack) > 0... |
651_D. Image Preview | Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec... | ```python
import bisect
def preview(n, a, b, t, S):
t -= b+1 if S[0] else 1
S[0] = False
if t < 0:
return 0
R = []
s = 0
for i in range(1, n):
s += a + (b+1 if S[i] else 1)
if s > t:
break
R.append(s)
else:
return n
L = []
s = 0... |
677_B. Vanya and Food Processor | Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya h... | ```python
n, h, k = map(int, input().split())
pots = map(int, input().split())
comb = [0]
for pot in pots:
if (comb[-1] % k + pot <= h):
comb[-1] += pot
else:
comb.append(pot)
sec = lambda x : x // k + int(x % k > 0)
ans = sum(map(sec, comb))
print(ans)
``` |
6_B. President's Office | President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all ... | ```python
n, m, c = input().split()
n, m = int(n), int(m)
lst = []
for i in range(n):
lst.append(input())
N = set()
for i in range(n):
for j in range(m):
if lst[i][j] == c:
if j != 0 and lst[i][j-1] != c and lst[i][j-1] != ".":
N.add(lst[i][j-1])
if i != 0 and lst[i-1][j] != c and lst[i-1][j] != ".":
... |
721_D. Maxim and Array | Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of ... | ```python
import heapq as hq
from math import ceil
n, k, x = [int(i) for i in input().strip().split(' ')]
arr = [int(i) for i in input().strip().split(' ')]
is_neg = False
for i in arr:
if i < 0:
is_neg = True if is_neg == False else False
narr = [[abs(i), pos, i < 0] for pos, i in enumerate(arr)]
hq.heapi... |
743_B. Chloe and the sequence | Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq... | ```python
n, k = list(map(int, input().split()))
finish = False
length = 1
for i in range(n-1):
length = length * 2 + 1
while n!=1:
gran = length // 2 + 1
if k == gran:
print(n)
finish = True
break
if k < gran:
length = length // 2
n -= 1
if k > gran:
... |
766_D. Mahmoud and a Dictionary | Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have ... | ```python
class Union:
def __init__(self, n):
self.p = {i:i for i in range(n)}
self.rank = {i:1 for i in range(n)}
def find(self, x):
if x < 0: return x
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(s... |
78_C. Beaver Game | Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Eac... | ```python
from sys import stdin, stdout
def check(m, k):
for i in range(2, int(m ** 0.5) + 1):
if not m % i and (i >= k or m // i >= k):
return 1
else:
return 0
n, m, k = map(int, stdin.readline().split())
if m < 2 * k or (k != 1 and not check(m, k)):
stdout.wr... |
837_B. Flag of Berland | The flag of Berland is such rectangular field n × m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
... | ```python
n, m = map(int, input().split())
f = [0 for _ in range(n)]
for i in range(n):
f[i] = input()
hor = True
if n % 3 != 0:
hor = False
else:
c = "RGB"
used = {"R":False, "G":False, "B":False}
used[f[0][0]] = True
cnt = 0
if [f[0][0] * m for i in range(n // 3)] == \
f[:n //... |
926_F. Mobile Communications | A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. Th... | ```python
n,p,m=map(int,input().split())
flag,t_neg,t_in,d,tot=0,0,0,1,0
for i in range (n):
ini_d=d
if flag==1:
tot+=(t-p)
if tot<0:
t_neg+=1
d,t=map(int,input().split())
if flag==0:
t_neg=(d-ini_d)
tot=t_neg*-p
flag=1
else:
tot+=(((d-1)-... |
p02555 AtCoder Beginner Contest 178 - Redistribution | Given is an integer S. Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S. The answer can be very large, so output it modulo 10^9 + 7.
Constraints
* 1 \leq S \leq 2000
* All values in input are integers.
Input
Input is given from Standard Input in ... | ```python
n=int(input())
p=10**9+7
l=[1]*(2001)
l[1],l[2]=0,0
s=1
for i in range(6,2001):
l[i]+=s
l[i]%=p
s+=l[i-2]
print(l[n])
``` |
p02686 AtCoder Beginner Contest 167 - Bracket Sequencing | A bracket sequence is a string that is one of the following:
1. An empty string;
2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ;
3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B /
Given are N strings S_i. Can a bracket sequence be forme... | ```python
import sys
input = sys.stdin.readline
N = int(input())
S = [input()[:-1] for _ in range(N)]
rl1, rl2 = [], []
for Si in S:
l, r = 0, 0
for i in range(len(Si)):
if Si[i]=='(':
l += 1
else:
if l==0:
r += 1
else:
l... |
p02815 AtCoder Beginner Contest 150 - Change a Little Bit | For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows:
* Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations.
* Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \time... | ```python
n = int(input())
a = list(map(int,input().split()))
a.sort(reverse=True)
mod = 10 ** 9 + 7
ans = 1
for _ in range(2*n-2):
ans *= 2
ans %= mod
cef = [i+2 for i in range(n)]
for i in range(n):
a[i] *= cef[i]
ans *= sum(a)
ans %= mod
print(ans)
``` |
p02951 AtCoder Beginner Contest 136 - Transfer | We have two bottles for holding water.
Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.
Bottle 2 contains C milliliters of water.
We will transfer water from Bottle 2 to Bottle 1 as much as possible.
How much amount of water will remain in Bottle 2?
Constraints
* All val... | ```python
A, B, C = list(map(int,input().split()))
print(max((B+C-A),0))
``` |
p03087 AtCoder Beginner Contest 122 - GeT AC | You are given a string S of length N consisting of `A`, `C`, `G` and `T`. Answer the following Q queries:
* Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many t... | ```python
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
s=input();a=[0]*2
for i in range(2,n+1):
a+=[a[i-1]+s[i-2:i].count("AC")]
for _ in range(q):
l,r=map(int,input().split())
print(a[r]-a[l])
``` |
p03232 AtCoder Grand Contest 028 - Removing Blocks | There are N blocks arranged in a row, numbered 1 to N from left to right. Each block has a weight, and the weight of Block i is A_i. Snuke will perform the following operation on these blocks N times:
* Choose one block that is still not removed, and remove it. The cost of this operation is the sum of the weights of t... | ```python
MOD = 10**9+7
def main():
N = int(input())
A = list(map(int, input().split()))
prodasc = [1] * (N+1)
prodesc = [1] * (N+1)
for i in range(N):
prodasc[i+1] = (prodasc[i] * (i+1)) % MOD
prodesc[i+1] = (prodesc[i] * (N-i)) % MOD
inv = [1] * (N+1)
for i in range(1, N+... |
p03383 AtCoder Regular Contest 095 - Symmetric Grid | There is an H \times W grid (H vertical, W horizontal), where each square contains a lowercase English letter. Specifically, the letter in the square at the i-th row and j-th column is equal to the j-th character in the string S_i.
Snuke can apply the following operation to this grid any number of times:
* Choose two... | ```python
from collections import Counter
n,m = map(int,input().split())
grid = [list(input()) for i in range(n)]
def jc(a,b):
l = len(a)
used = [0]*l
for i in range(l):
if used[i]:
continue
for j in range(i+1,l):
if used[j]:
continue
if a[i] == b[j] and b[i] == a[j]:
use... |
p03547 AtCoder Beginner Contest 078 - HEX | In programming, hexadecimal notation is often used.
In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters `A`, `B`, `C`, `D`, `E` and `F` are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.
In this problem, you are given two letters X and Y. Each X and Y is `A`, `B`, `C`,... | ```python
x,y = map(str, input().split())
print(">" if x > y else "<" if x < y else "=")
``` |
p03703 AtCoder Regular Contest 075 - Meaningful Mean | You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K.
a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K?
Constraints
* All input values are integers.
* 1 ≤ N ≤ 2 ... | ```python
def examC():
N = I()
S = [I() for _ in range(N)]
S1 = []
for s in S:
if s%10==0:
continue
S1.append(s)
if S1==[]:
print(0)
return
S1.sort()
ans = sum(S)
if ans%10==0:
ans -= S1[0]
print(ans)
return
def examD():
N,... |
p03858 AtCoder Regular Contest 065 - Manhattan Compass | There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i).
We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|).
You have a peculiar pair of compasses, called Manhattan Compass. This instrument always points at two of the pinholes. The two legs ... | ```python
import sys
input = sys.stdin.readline
from collections import defaultdict
import bisect
INF = 10 ** 12
N,a,b = map(int,input().split())
X_to_Y = defaultdict(lambda: [-INF,INF])
Y_to_X = defaultdict(lambda: [-INF,INF])
for i in range(1,N+1):
x,y = map(int,input().split())
x,y = x+y,x-y
X_to_Y[x].... |
p04023 AtCoder Grand Contest 003 - Sequential operations on Sequence | Snuke got an integer sequence from his mother, as a birthday present. The sequence has N elements, and the i-th of them is i. Snuke performs the following Q operations on this sequence. The i-th operation, described by a parameter q_i, is as follows:
* Take the first q_i elements from the sequence obtained by concaten... | ```python
import bisect,sys
input=sys.stdin.readline
N,Q=map(int,input().split())
que=[(N,0)]
for i in range(Q):
q=int(input())
que.append((q,i+1))
que.sort(reverse=True)
ext=[]
while que:
q,id=que.pop()
if not ext:
ext.append((q,id))
else:
if ext[-1][1]<id:
if ext[-1... |
p00107 Carry a Cheese | Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A × B × C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you he... | ```python
while True:
d, w, h = sorted(map(int, input().split()))
if d == w == h == 0:
break
dw = (d**2 + w**2)
n = int(input())
for i in range(n):
y = int(input())
if (2*y)**2 > dw:
print("OK")
else:
print("NA")
``` |
p00241 Quaternion Multiplication | An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $... | ```python
while True :
n = int(input())
if n == 0 :
break
for i in range(n) :
x1, y1, z1, w1, x2, y2, z2, w2 = map(int, input().split())
print((x1*x2 - y1*y2 - z1*z2 - w1*w2), (x1*y2 + x2*y1 + z1*w2 - z2*w1), (x1*z2 - y1*w2 + x2*z1 + y2*w1), (x1*w2 + y1*z2 - y2*z1 + x2*w1))
``... |
p00617 Simple GUI Application | Advanced Creative Mobile (ACM) has decided to develop a GUI application to be installed in a new portable computer.
As shown in the figure below, the GUI has a nested structure in which it has one main panel, several panels are arranged on it, and some panels are arranged on top of those panels. .. All panels are rect... | ```python
class Panel:
def __init__(self, name, points, children):
self.name = name
self.x1 = points[0]
self.x2 = points[2]
self.y1 = points[1]
self.y2 = points[3]
self.children = children
self.child_cnt = len(children)
def search(self, x, y):
if ... |
p00761 Recurring Decimals | A decimal representation of an integer can be transformed to another integer by rearranging the order of digits. Let us make a sequence using this fact.
A non-negative integer a0 and the number of digits L are given first. Applying the following rules, we obtain ai+1 from ai.
1. Express the integer ai in decimal nota... | ```python
while True:
list_a = []
a, L = input().split(" ")
if a=='0' and L=='0': break
L = int(L)
list_a.append(int(a))
while True:
if len(a) < L: a += '0'*(L-len(a))
an = int(''.join(sorted(a, reverse=True))) - int(''.join(sorted(a)))
if an in list_a:
idx =... |
p00893 Matrix Calculator | Dr. Jimbo, an applied mathematician, needs to calculate matrices all day for solving his own problems. In his laboratory, he uses an excellent application program for manipulating matrix expressions, however, he cannot use it outside his laboratory because the software consumes much of resources. He wants to manipulate... | ```python
from string import digits
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def parse(S, mp):
M = 32768
cur = 0
def transpose(m):
p, q, v = m
res = [[0]*p for i in range(q)]
for i in range(q):
for j in range(p):
res[i][j] = v[j]... |
p01296 Futon | The sales department of Japanese Ancient Giant Corp. is visiting a hot spring resort for their recreational trip. For deepening their friendships, they are staying in one large room of a Japanese-style hotel called a ryokan.
In the ryokan, people sleep in Japanese-style beds called futons. They all have put their futo... | ```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(... |
p01911 Rainy Bus Stops | problem
AOR Ika is at the $ S $ th bus stop at time $ 0 $ and wants to go from there to the $ G $ th bus stop. The number of bus stops $ N $ and $ M $ routes (*) connecting different bus stops are given. The bus stops are numbered $ 1, \ dots, and N $, respectively. Each route consists of $ 4 $ values: origin $ u $, d... | ```python
from heapq import heappush, heappop
def main():
n, m, s, g = map(int, input().split())
s -= 1
g -= 1
edges = [[] for _ in range(n)]
for _ in range(m):
u, v, t, c = map(int, input().split())
u -= 1
v -= 1
edges[u].append((t, t + c, v))
score = {}
score[(0, 0)] = 0
que = []
... |
p02346 Range Sum Query (RSQ) | Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(i, x): add x to ai.
* getSum(s, t): print the sum of as, as+1,...,at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* If comi is 0, then 1 ≤ xi... | ```python
from array import array
import bisect
import collections
import heapq
import itertools
import operator
import sys
class BIT:
def __init__(self, n):
self.n = n
self.arr = array("l", [0] * (n + 1))
def __str__(self):
return str(self.arr.tolist())
def add(self, i, x):
... |
1023_E. Down or Right | This is an interactive problem.
Bob lives in a square grid of size n × n, with rows numbered 1 through n from top to bottom, and columns numbered 1 through n from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer n.
Bob can move... | ```python
from sys import stdout
n=int(input())
x=1
y=1
s='! '
s2=''
for i in range (n-1):
print('? '+str(x+1)+' '+str(y)+' '+str(n)+' '+str(n))
stdout.flush()
b=input()
if b=='YES':
s=s+'D'
x+=1
else:
s=s+'R'
y+=1
x1=x
y1=y
x=n
y=n
for i in range (n-1):
if y!=y1:... |
108_C. Dorm Water Supply | The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, the... | ```python
n, m = map(int, input().split())
t, p = [], [[0, 0, 0] for i in range(n + 1)]
for i in range(m):
a, b, d = map(int, input().split())
p[b][1], p[a][0], p[a][2] = a, b, d
for a in range(1, n + 1):
if p[a][1] == 0:
b, c, d = a, p[a][0], p[a][2]
if not c: continue
whil... |
1109_B. Sasha and One More Name | Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t... | ```python
s = input()
n = len(s)
def check(name):
return name == name[::-1] and name != s
for i in range(1, n):
new_name = s[i:] + s[:i]
if check(new_name):
print(1)
exit()
for i in range(1, n // 2 + 1):
new_name = s[-i:] + s[i:-i] + s[:i]
if check(new_name):
print(2)
... |
1156_G. Optimizer | Let's analyze a program written on some strange programming language. The variables in this language have names consisting of 1 to 4 characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.
There are four types ... | ```python
from random import seed, randint
import sys
sys.setrecursionlimit(10000)
opr = ['#', '^', '&', '$']
namespace = { "res" : (False, "res") }
rules = dict()
lookup = dict()
cnt = -1
def get_tag(var):
if var in namespace:
return namespace[var][1]
else:
return var
N = int(input())
for _ ... |
1179_A. Valeriy and Deque | Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A >... | ```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... |
1197_C. Array Splitting | You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i ≥ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | ```python
n, k = map(int, input().split())
l = list(map(int, input().split()))
ll = []
for i in range(n-1):
ll.append(l[i+1]-l[i])
ll.sort()
print(sum(ll[:n-k]))
``` |
1214_D. Treasure Island | All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.
Treasure Island may be represented as a rectangular table n × m which is surrounded by the ocean. Let us number rows of the field with consecutive integers from 1 to n from top to bottom and columns with consecutive integers from... | ```python
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" n... |
1255_E2. Send Boxes to Alice (Hard Version) | This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend... | ```python
import sys
# inf = open('input.txt', 'r')
# input = inf.readline
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
def primeDivisors(num):
sqrtNum = int(num ** 0.5) + 1
primes = []
if not num & 1:
primes.append(2)
while not num & 1:
num ... |
1279_E. New Year Permutations | Yeah, we failed to make up a New Year legend for this problem.
A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once.
An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on.
The decomposition of a permut... | ```python
# 1279E - New Year Permutations
# Idea:
# dp(i) --> # of good permutations of [i,n]
# cycles(m) --> # of blocks of len m ( == (m-2)! as first element is fixed)
# It is easy to test for impossibility ie. k > dp(1)
# Another subproblem: how to compute jth smallest cycle
# getGoodPerm(n,k) uses both getCycle(b... |
129_C. Statues | In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains... | ```python
from sys import stdin
from collections import *
from copy import deepcopy
def valid(i, j):
n, m = [8] * 2
return i > -1 and i < n and j > -1 and j < m
def str_inp(n):
return list(reversed(list((list(stdin.readline()[:-1]) for x in range(n)))))
def check(x, y, step):
if step + 1 < 8 and a... |
1341_E. Nastya and Unexpected Guest | If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.
On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place s... | ```python
import sys
input = sys.stdin.readline
from collections import deque
from typing import List
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
... |
1363_E. Tree Shuffling | Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.
To achieve this, he can perform the following operation any number of times:
* Select any... | ```python
import sys
data = [list(map(int, line.rstrip().split())) for line in sys.stdin.readlines()]
n = data[0][0]
dic = [[] for _ in range(n+1)]
dic[1].append(0)
for u,v in data[n+1:]:
dic[u].append(v)
dic[v].append(u)
cost = [0]*(n+1)
cost[1] = 1000000001
father = [0]*(n+1)
now = [1]
leaf = []
gress = [0]*... |
1384_A. Common Prefixes | The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≤ k ≤ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k.
Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}.
For each i (1 ≤ i ≤ n) she calculated a_i — the length of ... | ```python
T = int(input())
def solve():
N = int(input())
A = list(map(int,input().split()))
def next_char(c):
if c == 'a':
return 'b'
return 'a'
ans = []
ans.append('a'*101)
for a in A:
lst = ans[-1]
lst = lst[:a] + next_char(lst[a]) + lst[a+1:]
... |
1405_B. Array Cancellation | You're given an array a of n integers, such that a_1 + a_2 + ⋅⋅⋅ + a_n = 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin.
How many coins do you have to spend in order to make a... | ```python
def main():
t = int(input())
for _ in range(t):
n = int(input())
alst = list(map(int, input().split()))
ans = 0
total = 0
for a in alst:
total -= a
ans = max(ans, total)
print(ans)
main()
``` |
1426_D. Non-zero Segments | Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros.
Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array.
Y... | ```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
pass
# 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 o... |
144_C. Anagram Search | A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.
The string t is called a substring of the string s if it can be read starting from some posi... | ```python
s = input()
p = input()
fit = 0
cnts = {}
cntp = {}
for c in s:
cnts[c] = cntp[c] = 0
for c in p:
cnts[c] = cntp[c] = 0
for c in p:
cntp[c] += 1
def extend(c):
if c == '?':
return
global fit
if cnts[c] == cntp[c]:
fit += 1
cnts[c] += 1
def remove(c):
if c ==... |
1473_C. No More Inversions | You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k ≤ n < 2k).
Let's call as inversion in a a pair of indices i < j such that a[i] > a[j].
Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]].
Your goal... | ```python
from collections import Counter
import string
import math
import sys
# sys.setrecursionlimit(10**6)
from fractions import Fraction
def array_int():
return [int(i) for i in sys.stdin.readline().split()]
def vary(arrber_of_variables):
if arrber_of_variables==1:
return int(sys.stdin.readline())
... |
1499_E. Chaotic Merge | You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then re... | ```python
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
fr... |
1521_C. Nastia and a Hidden Permutation | This is an interactive problem!
Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 ≤ t ≤ 2), two different indices i and j (1 ≤ i, j ≤ n, i ≠ j), and an integer x (1 ≤ x ≤ n - 1).
Dep... | ```python
import math,sys
## from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
# sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def... |
1550_C. Manhattan Subarrays | Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|.
Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r).
Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose... | ```python
A=[]
t=int(input())
def isg(l,r):
for i in range(l,r+1):
for j in range(i+1,r+1):
for k in range(j+1,r+1):
if(A[i]>=A[j] and A[j]>=A[k]):
return False
if(A[i]<=A[j] and A[j]<=A[k]):
return False
return True
for... |
177_A1. Good Matrix Elements | The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exac... | ```python
n = int(input())
gh = [0 for _ in range(n)]
arr = [gh[:] for _ in range(n) ]
visited = [gh[:] for _ in range(n)]
for i in range(n):
a = input()
a1 = a.split()
for j in range(n):
arr[i][j] = int(a1[j])
if n == 1:
print( a)
else:
middleR = (n - 1) // 2
middleC = (n - 1 ) /... |
197_C. Lexicographically Maximum Subsequence | You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y... | ```python
from collections import Counter
s = input()
c = Counter(s)
cur_char = 'z'
for ch in s:
while c[cur_char] == 0:
cur_char = chr(ord(cur_char) - 1)
if ch == cur_char:
print(cur_char, end='')
c[ch] -= 1
``` |
26_C. Parquet | Once Bob decided to lay a parquet floor in his living room. The living room is of size n × m metres. Bob had planks of three types: a planks 1 × 2 meters, b planks 2 × 1 meters, and c planks 2 × 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, f... | ```python
n, m, a, b, c = map(int, input().split())
mat = [0]*n
for i in range(n):
mat[i] = [0] * m
n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)]
p = ['c', 'a', 'b']
z = ['d', 'e', 'f', 'g']
z1 = ['m', 'n', 'u', 'o']
z2 = ['p', 'q', 'r', 'w']
#print(n1)
def fill(h, w):
if h <= 0 or w <= 0:
r... |
292_E. Copying Data | We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.
More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of... | ```python
import sys
'''
SEGMENT TREE
Assign
'''
class SegmTree():
'''
- modify elements on interval
- get single element
'''
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2*N)
def modify_range(self, l, r, value... |
316_G1. Good Substrings | Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (... | ```python
def count(p, s):
start = 0
c = 0
while True:
try:
pos = s.index(p, start)
c += 1
start = pos + 1
except ValueError:
return c
s = input()
n = int(input())
pravs = []
for i in range(n):
p, l, r = input().split()
l = int(l); r... |
340_C. Tourist Problem | Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t... | ```python
import math
n = int(input())
l = [int(x) for x in input().split()]
a1 = sum(l)
a2 = n
a3 = 0
temp = 0
l.sort()
for i in range(n):
temp += l[n-i-1]
a3-=(a1-temp)
a3+=(n-i-1)*(l[n-i-1])
a1 = a1+a3+a3
a4 = math.gcd(a1, a2)
print(a1//a4, a2//a4)
``` |
387_D. George and Interesting Graph | George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, ... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def matching(n,m,path):
# Hopkrocft Karp O(EV^0.5)
match1 = [-1]*n
match2 = [-1]*m
for node in range(n):
for nei in path[node]:
if match2[nei] == -1:
... |
408_B. Garland | Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.
The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece s... | ```python
#!/usr/bin/python
import re
import inspect
from sys import argv, exit
def rstr():
return input()
def rstrs(splitchar=' '):
return [i for i in input().split(splitchar)]
def rint():
return int(input())
def rints(splitchar=' '):
return [int(i) for i in rstrs(splitchar)]
def varnames(obj, nam... |
435_C. Cardiogram | In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contai... | ```python
n = int(input())
a_list = list(map(int, list(str(input()).split(" "))))
out = [' '*(sum(a_list))]*2000
cur,pref_size = 1000, 0
cur_max, cur_min = 1000,1000
for k in range(n):
for i in range(a_list[k]):
ind = pref_size + i
if k % 2 == 0:
out[cur] = out[cur][:ind] + '/' + out[cu... |
47_C. Crossword | Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity ... | ```python
from itertools import permutations
v = []
for p in permutations(input() for i in range(6)):
if len(p[1]) != len(p[0]) + len(p[2]) - 1 or len(p[4]) != len(p[3]) + len(p[5]) - 1:
continue
elif p[0][0] != p[3][0] or p[0][-1] != p[4][0]:
continue
elif p[1][0] != p[3][-1] or p[1][len(p[... |
528_A. Glass Carving | Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice t... | ```python
# import itertools
# import bisect
# import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = la... |
553_D. Nudist Beach | Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.
There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every ci... | ```python
import heapq
def read_data():
'''
n: number of cities
m: number of roads
k: initial numuber of fortresses of Life Fibers
Es: list of edges
fs: fs[i] = True -> city i is under control of Life Fibers
gs: gs[i] number of edges connected to city i
hs: hs[i] number of adjacent citi... |
57_C. Array | Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful... | ```python
#love python :)
#medo journy to icpc
n = int(input())
m = int(1e9 + 7)
p = 1
for i in range(1, n + 1):
p *= 2 * n - i
p *= pow(i, m - 2, m)
p %= m
print((2 * p - n) % m)
``` |
601_B. Lipshitz Sequence | A function <image> is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all <image>. We'll deal with a more... discrete version of this term.
For an array <image>, we define it's Lipschitz constant <image> as follows:
* if n < 2, <image>
* if n ... | ```python
f = lambda: map(int, input().split())
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
j = n - i
x, y = i - 1, j + 1
a, b = p[i], p[j]
while a > p[x]: x = L[x]
while b >= p[y]: y = R[y]
L[i], R[j] = x, y
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.