Dataset Viewer
src_uid
stringlengths 32
32
| prob_desc_description
stringlengths 63
2.99k
| tags
stringlengths 6
159
| source_code
stringlengths 29
58.4k
| lang_cluster
stringclasses 1
value | categories
sequencelengths 1
5
| desc_length
int64 63
3.13k
| code_length
int64 29
58.4k
| games
int64 0
1
| geometry
int64 0
1
| graphs
int64 0
1
| math
int64 0
1
| number theory
int64 0
1
| probabilities
int64 0
1
| strings
int64 0
1
| trees
int64 0
1
| labels_dict
dict | __index_level_0__
int64 0
4.98k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b37f27a98ec8f80d0bff3f7ae8f2cff | Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an n \times m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adjacent by the side. Let W be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if B = W + 1. The first coloring shown below has B=5 and W=4 (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has B=4, W=4 (only the bottom right cell doesn't have a neighbor with the opposite color). Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them. | ['constructive algorithms'] | for _ in range(int(input())):
N, M = map(int, input().split())
mat = [['B' for col in range(M)] for row in range(N)]
mat[0][0] = 'W'
for row in mat:
print(''.join(row))
| Python | [
"other"
] | 943 | 224 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,970 |
94bc4b263821713fb5b1de4de331a515 | You are given a positive integer n. Since n may be very large, you are given its binary representation.You should compute the number of triples (a,b,c) with 0 \leq a,b,c \leq n such that a \oplus b, b \oplus c, and a \oplus c are the sides of a non-degenerate triangle. Here, \oplus denotes the bitwise XOR operation.You should output the answer modulo 998\,244\,353.Three positive values x, y, and z are the sides of a non-degenerate triangle if and only if x+y>z, x+z>y, and y+z>x. | ['bitmasks', 'dp'] | MOD = 998244353
TRANS = [6, 3, 7, 4, 1, 0]
s = input().strip()
dp = [0] * 7 + [1]
for c in map(int, s):
dp1 = [0] * 8
for i in range(8):
for k in TRANS:
if c:
dp1[k & i] += dp[i]
elif (k & i) == 0:
dp1[i] += dp[i]
dp = [x % MOD for x in dp1]
n = int(s, base=2) + 1
print((n**3 + 3 * n**2 - n - 3 * sum(dp)) % MOD) | Python | [
"other"
] | 582 | 406 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,162 |
e588d7600429eb6b70a1a9b5eca194f7 | Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders).More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder.For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples.You are given a few files that Petya has managed to create. The path to each file looks as follows:diskName:\folder1\folder2\...\ foldern\fileName diskName is single capital letter from the set {C,D,E,F,G}. folder1, ..., foldern are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (n ≥ 1) fileName is a file name in the form of name.extension, where the name and the extension are nonempty sequences of lowercase Latin letters and digits from 0 to 9. It is also known that there is no file whose path looks like diskName:\fileName. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder.Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders. | ['data structures', 'implementation'] | import sys
from array import array # noqa: F401
from collections import defaultdict
def input():
return sys.stdin.buffer.readline().decode('utf-8')
cnt1 = defaultdict(set)
cnt2 = defaultdict(int)
for line in sys.stdin:
path = line.rstrip().split('\\')
key = tuple(path[:2])
for i in range(3, len(path)):
cnt1[key].add(tuple(path[2:i]))
cnt2[key] += 1
ans1 = max((len(s) for s in cnt1.values()), default=0)
ans2 = max(cnt2.values(), default=0)
print(ans1, ans2)
| Python | [
"other"
] | 1,765 | 496 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,999 |
ac02c52caac155458e998fb448b8cc0d | You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle: if you are currently in the castle i, you may leave one warrior to defend castle i; there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v. Obviously, when you order your warrior to defend some castle, he leaves your army.You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).Can you determine an optimal strategy of capturing and defending the castles? | ['dp', 'greedy', 'implementation', 'sortings', 'data structures'] | from heapq import heappush, heappop
n, m, k = map(int, input().split())
a = [0]
b = [0]
c = [0]
for i in range(n):
aa, bb, cc = map(int, input().split())
a.append(aa)
b.append(bb)
c.append(cc)
a += [0]
road = [[] for i in range(n+1)]
last = [i for i in range(0, n+1)]
for i in range(m):
u, v = map(int, input().split())
last[v] = max(last[v], u)
for i in range(1, n+1):
road[last[i]].append(i)
value = []
fin = True
for i in range(1, n+1):
while (k < a[i] and value):
k += 1
heappop(value)
if (k < a[i]):
fin = False
break
k += b[i]
for j in road[i]:
heappush(value, c[j])
k -= 1
if (fin == False):
print(-1)
else:
while (k < 0):
k += 1
heappop(value)
ans = 0
while (value):
ans += heappop(value)
print(ans)
| Python | [
"other"
] | 2,395 | 858 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 948 |
c19500d867fd0108fdeed2cbd00bc970 | A sequence of positive integers is called great for a positive integer x, if we can split it into pairs in such a way that in each pair the first number multiplied by x is equal to the second number. More formally, a sequence a of size n is great for a positive integer x, if n is even and there exists a permutation p of size n, such that for each i (1 \le i \le \frac{n}{2}) a_{p_{2i-1}} \cdot x = a_{p_{2i}}. Sam has a sequence a and a positive integer x. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence a to make it great for the number x. | ['greedy', 'sortings'] | import collections
import os, sys
from io import BytesIO, IOBase
inf = sys.maxsize
def get_ints():
return map(int, input().split())
def get_array():
return list(map(int, input().split()))
mod = 1000000007
MOD = 998244353
def main():
for _ in range(int(input())):
n,x=get_ints()
A=get_array()
d=collections.Counter(A)
A.sort()
ans=0
for ele in A:
if d[ele] and d[ele*x]:
d[ele]-=1
d[ele*x]-=1
print(sum(d.values()))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._file = 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 if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| Python | [
"other"
] | 713 | 2,382 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,196 |
9070e0d4f8071d1ee8df5189b7c17bfa | A binary string is a string consisting only of the characters 0 and 1. You are given a binary string s.For some non-empty substring^\dagger t of string s containing x characters 0 and y characters 1, define its cost as: x \cdot y, if x > 0 and y > 0; x^2, if x > 0 and y = 0; y^2, if x = 0 and y > 0. Given a binary string s of length n, find the maximum cost across all its non-empty substrings.^\dagger A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | ['brute force', 'greedy', 'implementation'] | for i in range(int(input())):
n=int(input())
s=input()
ans=max(s.count('1')*s.count('0'),1)
st=1
s=s.strip()
for j in range(1,n):
if s[j]==s[j-1]:
st+=1
else:
st=1
ans=max(ans,st*st)
print(ans) | Python | [
"other"
] | 757 | 281 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,958 |
9fd8e75cb441dc809b1b2c48c4012c76 | You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower. | ['two pointers', 'binary search', 'implementation'] | from bisect import bisect_left
n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
min_r = 0
for el in a:
i = bisect_left(b, el)
if i == 0:
min_r = max(min_r, abs(el - b[0]))
elif i == m:
min_r = max(min_r, abs(el - b[m-1]))
elif i == m - 1:
min_r = max(min_r, min(abs(el - b[m - 1]), abs(el - b[m - 2])))
else:
min_r = max(min_r, min(abs(el - b[i + 1]), abs(el - b[i - 1]), abs(el-b[i])))
print(min_r)
| Python | [
"other"
] | 749 | 512 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,282 |
0fd33e1bdfd6c91feb3bf00a2461603f | The only difference between easy and hard versions is the length of the string.You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|} (where |s| is the length of s).Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. | ['two pointers', 'binary search', 'implementation', 'greedy'] | def checker(mainstr, substr, index):
size = len(mainstr)-1
maxdrop=0
pos=[-1]
for i in substr:
temp = mainstr.find(i,index)
pos.append(temp)
index = temp+1
index=0
newmainstr = mainstr[::-1]
maxsize = len(mainstr)-1
for i in range(len(substr),0,-1):
currentpos = pos[i]
maxdrop=max(maxdrop, maxsize - currentpos)
currentpos = newmainstr.find(substr[i-1], index)
index =currentpos+1
maxsize=size - currentpos -1
maxdrop = max(maxdrop, maxsize-pos[i-1])
return maxdrop
def main():
mainstr = input()
substr = input()
ans = checker(mainstr, substr, 0)
print(ans)
if __name__ == "__main__":
main() | Python | [
"other"
] | 1,159 | 749 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,891 |
b389750613e9577b3abc9e5e5902b2db | Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check.Remainder, on how do chess pieces move: Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells. Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells. Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap". | ['implementation'] | n=input()
x,y=map(int,raw_input().split())
v=[(10**11,'?')]*8
for _ in range(n):
c,i,j=raw_input().split()
i,j=int(i),int(j)
if i==x:
d=j-y
if d>0 and d<v[0][0]:
v[0]=(d,c)
elif d<0 and -d<v[1][0]:
v[1]=(-d,c)
if j==y:
d=i-x
if d>0 and d<v[2][0]:
v[2]=(d,c)
elif d<0 and -d<v[3][0]:
v[3]=(-d,c)
if i-x==j-y:
d=i-x
if d>0 and d<v[4][0]:
v[4]=(d,c)
elif d<0 and -d<v[5][0]:
v[5]=(-d,c)
if i-x==y-j:
d=i-x
if d>0 and d<v[6][0]:
v[6]=(d,c)
elif d<0 and -d<v[7][0]:
v[7]=(-d,c)
print 'YES' if v[0][1] in 'RQ' or v[1][1] in 'RQ' or v[2][1] in 'RQ' or v[3][1] in 'RQ' or v[4][1] in 'BQ' or v[5][1] in 'BQ' or v[6][1] in 'BQ' or v[7][1] in 'BQ' else 'NO' | Python | [
"other"
] | 1,092 | 754 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,073 |
2eb101dcfcc487fe6e44c9b4c0e4024d | The only difference between easy and hard versions is constraints.Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.Each day (during the morning) Ivan earns exactly one burle.There are n types of microtransactions in the game. Each microtransaction costs 2 burles usually and 1 burle if it is on sale. Ivan has to order exactly k_i microtransactions of the i-th type (he orders microtransactions during the evening).Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for 1 burle and otherwise he can buy it for 2 burles.There are also m special offers in the game shop. The j-th offer (d_j, t_j) means that microtransactions of the t_j-th type are on sale during the d_j-th day.Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing. | ['binary search', 'implementation', 'greedy'] | import collections
def main():
from sys import stdin, stdout
def read():
return stdin.readline().rstrip('\n')
def read_array(sep=None, maxsplit=-1):
return read().split(sep, maxsplit)
def read_int():
return int(read())
def read_int_array(sep=None, maxsplit=-1):
return [int(a) for a in read_array(sep, maxsplit)]
def write(*args, **kwargs):
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
stdout.write(sep.join(str(a) for a in args) + end)
def write_array(array, **kwargs):
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '\n')
stdout.write(sep.join(str(a) for a in array) + end)
def enough(days):
bought = [] # (type, amount)
bought_total = 0
used_from = days
for d in range(days, 0, -1):
used_from = min(d, used_from)
for t in offers.get(d, []):
if K[t] > 0:
x = min(K[t], used_from)
K[t] -= x
bought.append((t, x))
bought_total += x
used_from -= x
if not used_from:
break
remaining_money = days - bought_total
ans = (total_transaction - bought_total) * 2 <= remaining_money
for t, a in bought:
K[t] += a
return ans
n, m = read_int_array()
K = read_int_array()
total_transaction = sum(K)
offers = collections.defaultdict(list)
for _ in range(m):
d, t = read_int_array()
offers[d].append(t-1)
low = total_transaction
high = low * 2
ans = high
while low <= high:
mid = (low + high) // 2
if enough(mid):
ans = mid
high = mid - 1
else:
low = mid + 1
write(ans)
main()
| Python | [
"other"
] | 1,285 | 1,868 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,323 |
5aa653e7af021505e6851c561a762578 | Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, . Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.Please help Mahmoud and Ehab. | ['data structures', 'binary search', 'sortings'] | def read(): return list(map(int, input().split(' ')))
n, m, q = read()
aa = read()
bb = read()
reqs = [read() for _ in range(q)]
asum = 0
bsum = 0
for i, (a, b) in enumerate(zip(aa, bb)):
asum += a if i % 2 == 0 else -a
bsum += b if i % 2 == 0 else -b
bpos = [bsum]
for i in range(len(aa), len(bb)):
b = bb[i]
rempos = i - len(aa)
bsum += b if i % 2 == 0 else -b
bsum -= bb[rempos] if rempos % 2 == 0 else -bb[rempos]
bpos += [bsum if rempos % 2 == 1 else -bsum]
bpos = sorted(set(bpos))
def closest(arr, value):
l = 0
r = len(arr)
while l + 1 < r:
m = (l + r) // 2
if arr[m] <= value:
l = m
else:
r = m
res = arr[l]
if l + 1 < len(arr) and abs(arr[l + 1] - value) < abs(arr[l] - value):
res = arr[l + 1]
return res
print(abs(asum - closest(bpos, asum)))
for req in reqs:
l, r, x = req
l -= 1
if (r - l) % 2 != 0:
asum += x if l % 2 == 0 else -x
print(abs(asum - closest(bpos, asum)))
| Python | [
"other"
] | 730 | 1,032 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 119 |
3c93a76f986b1ef653bf5834716ac72a | You are given a binary string s (recall that a string is binary if each character is either 0 or 1).Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.The substring s_{l}, s_{l+1}, \dots , s_{r} is good if r - l + 1 = f(s_l \dots s_r).For example string s = 1011 has 5 good substrings: s_1 \dots s_1 = 1, s_3 \dots s_3 = 1, s_4 \dots s_4 = 1, s_1 \dots s_2 = 10 and s_2 \dots s_4 = 011. Your task is to calculate the number of good substrings of string s.You have to answer t independent queries. | ['binary search', 'bitmasks', 'brute force'] | t = int(input())
for _ in range(t):
s = input()
ct = int(0)
ans = int(0)
for i in range(len(s)):
if s[i] == '0':
ct += 1
else:
num = int(0)
for j in range(i,len(s)):
num *= 2
if s[j] == '1':
num += 1
if num <= ct + j - i + 1:
ans += 1
if num > j - i + 1 + ct:
break
ct = 0
print(ans) | Python | [
"other"
] | 752 | 491 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,526 |
0a701242ca81029a1791df74dc8ca59b | Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m > 2n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus. | ['implementation'] | n,m=map(int,raw_input().split())
bus=[[0,0,0,0]for i in xrange(n)]
r=0
for i in xrange(1,m+1):
if bus[r][0]==0:
bus[r][0]=i
elif bus[r][3]==0:
bus[r][3]=i
r+=1
r%=n
elif bus[r][1]==0:
bus[r][1]=i
else:
bus[r][2]=i
r+=1
r%=n
for i in xrange(n):
for j in [1,0,2,3]:
if bus[i][j]:print bus[i][j],
| Python | [
"other"
] | 1,299 | 386 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,283 |
485d5984e34a479f2c074a305ae999ae | An integer array a_1, a_2, \ldots, a_n is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array: Choose any number x from the array a, and any letter of the English alphabet y. Replace all occurrences of number x with the letter y. For example, if we initially had an array a = [2, 3, 2, 4, 1], then we could transform it the following way: Choose the number 2 and the letter c. After that a = [c, 3, c, 4, 1]. Choose the number 3 and the letter a. After that a = [c, a, c, 4, 1]. Choose the number 4 and the letter t. After that a = [c, a, c, t, 1]. Choose the number 1 and the letter a. After that a = [c, a, c, t, a]. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array a and the string s determine if the string s could be got from the array a after the described transformation? | ['greedy', 'implementation'] | from sys import stdin, stdout
I = stdin.readline
O = stdout.write
# n = int(I())
# arr = list(map(int, I().split()))
def solve():
n = int(I())
arr = list(map(int, I().split()))
s = input()
mp = {}
ans = ""
ok = True
for i in range(n):
if arr[i] in mp:
if s[i] != mp[arr[i]]:
ok = False
break
else:
mp[arr[i]] = s[i]
if ok:
ans = "YES"
else:
ans = "NO"
print(ans)
for tc in range(int(input())):
solve() | Python | [
"other"
] | 1,058 | 586 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,107 |
c1158d23d3ad61c346c345f14e63ede4 | One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi ≤ hi + 1 holds for all i from 1 to n - 1.Squidward suggested the following process of sorting castles: Castles are split into blocks — groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence hi, hi + 1, ..., hj becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements. | ['sortings'] | input()
a=map(int,raw_input().split())
c={}
p,n,s=0,0,0
for x,y in zip(a,sorted(a)):
c[x]=c.get(x,0)+1
if 0==c[x]:
n-=1
elif 1==c[x]:
p+=1
c[y]=c.get(y,0)-1
if 0==c[y]:
p-=1
elif -1==c[y]:
n+=1
if not p and not n:
s+=1
print s | Python | [
"other"
] | 1,474 | 260 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,677 |
1f714ac601f6b5bdcb4fa32cdb56629d | You are given a sequence a of length n consisting of 0s and 1s.You can perform the following operation on this sequence: Pick an index i from 1 to n-2 (inclusive). Change all of a_{i}, a_{i+1}, a_{i+2} to a_{i} \oplus a_{i+1} \oplus a_{i+2} simultaneously, where \oplus denotes the bitwise XOR operation Find a sequence of at most n operations that changes all elements of a to 0s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of a to 0s, then there is also such a sequence of length not greater than n. | ['constructive algorithms'] | try:
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect, insort
from time import perf_counter
from fractions import Fraction
import copy
from copy import deepcopy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def A2(n,m): return [[0]*m for i in range(n)]
def A(n):return [0]*n
# sys.setrecursionlimit(int(pow(10,6)))
# from sys import stdin
# input = stdin.buffer.readline
# I = lambda : list(map(int,input().split()))
# import sys
# input=sys.stdin.readline
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
except:
pass
for _ in range(L()[0]):
n = L()[0]
A = L()
x = 0
for ele in A:
x^=ele
if x:
print("NO")
continue
if n%2:
print("YES")
ans = []
for i in range(1,n,2):
ans.append(i)
for i in range(n-4,0,-2):
ans.append(i)
print(len(ans))
print(*ans)
else:
x = 0
for i,ele in enumerate(A):
x^=ele
if i%2==0 and x==0:
print("YES")
ans = []
for j in range(1,i+1,2):
ans.append(j)
for j in range(i+1-4,0,-2):
ans.append(j)
for j in range(i+2,n,2):
ans.append(j)
for j in range(n-4,i+1,-2):
ans.append(j)
print(len(ans))
print(*ans)
break
else:
print("NO") | Python | [
"other"
] | 699 | 2,955 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,410 |
6c52df7ea24671102e4c0eee19dc6bba | Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. | ['implementation'] | n = int(input())
i = 0
l = []
c = 1
a = input()
temp = a
while(i<n-1):
a = input()
if(temp!=a):
c =c + 1
temp = a
i = i + 1
print(c) | Python | [
"other"
] | 932 | 156 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,333 |
3c066bad8ee6298b318bf0f4521c7c45 | Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack. | ['implementation'] | n, x0 = map(int, input().split())
x1, x2 = 0, 1000
for i in range(n):
a, b = map(int, input().split())
x1 = max(x1, min(a, b))
x2 = min(x2, max(a, b))
print(max(0, x1 - x0, x0 - x2) if x2 >= x1 else -1)
| Python | [
"other"
] | 784 | 215 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,371 |
c16c49baf7b2d179764871204475036e | Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. | ['dp', 'implementation'] | from sys import stdin
def main():
s = stdin.readline().strip()
if s[0] == '2' or s[-1] == '2':
print 0
return
# 0, *1, 1*, *2*, *
if s[0] == '?':
dp = [1, 0, 1, 0, 1]
elif s[0] == '0':
dp = [1, 0, 0, 0, 0]
elif s[0] == '1':
dp = [0, 0, 1, 0, 0]
elif s[0] == '*':
dp = [0, 0, 0, 0, 1]
def add(x, y):
z = x + y
return z if z < 1000000007 else z - 1000000007
for c in s[1:]:
if c == '*':
ndp = [0, 0, 0, 0, add(dp[2], add(dp[3], dp[4]))]
elif c == '0':
ndp = [add(dp[0], dp[1]), 0, 0, 0, 0]
elif c == '1':
ndp = [0, dp[4], add(dp[0], dp[1]), 0, 0]
elif c == '2':
ndp = [0, 0, 0, dp[4], 0]
else:
ndp = [add(dp[0], dp[1]), dp[4], add(dp[0], dp[1]), dp[4], add(dp[2], add(dp[3], dp[4]))]
dp = ndp
print add(dp[0], add(dp[1], dp[4]))
main()
| Python | [
"other"
] | 914 | 949 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,872 |
e48fb08f88f89154c54a3231f0d2f25c | Instructors of Some Informatics School make students go to bed.The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially, in i-th room there are ai students. All students are currently somewhere in the house, therefore a1 + a2 + ... + an = nb. Also 2 instructors live in this house.The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room n, while the second instructor starts near room n and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if n is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends.When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to b, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students.While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most d rooms, that is she can move to a room with number that differs my at most d. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously.Formally, here is what's happening: A curfew is announced, at this point in room i there are ai students. Each student can run to another room but not further than d rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. Instructors enter room 1 and room n, they count students there and lock the room (after it no one can enter or leave this room). Each student from rooms with numbers from 2 to n - 1 can run to another room but not further than d rooms away from her current room, or stay in place. Each student can optionally hide under a bed. Instructors move from room 1 to room 2 and from room n to room n - 1. This process continues until all rooms are processed. Let x1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from b, and x2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers xi. Help them find this value if they use the optimal strategy. | ['binary search', 'sortings', 'greedy', 'brute force'] | read = lambda: map(int, input().split())
n, d, b = read()
d += 1
t, a = 0, [0] * (n + 1)
for i, x in enumerate(read()):
t += x
a[i + 1] = t
print(max(i - min(a[min(n, i * d)], (a[n] - a[max(0, n - i * d)])) // b for i in range(n + 3 >> 1)))
| Python | [
"other"
] | 2,926 | 249 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,923 |
5d5dfa4f129bda46055fb636ef33515f | DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1. | ['implementation'] | p,n=map(int,raw_input().split())
a=[0]*500
for i in range(n):
x=input()
x=x%p
#print i,x
if a[x]==1:
print i+1
exit()
a[x]=1
print -1 | Python | [
"other"
] | 655 | 169 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,313 |
8c36ab13ca1a4155cf97d0803aba11a3 | Vasya has two arrays A and B of lengths n and m, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal. | ['two pointers', 'greedy'] | n = int(input())
a = list(map(int,input().split()))
m = int(input())
b = list(map(int,input().split()))
i,j,ans =0,0,0
while(i<n and j<m):
if a[i]==b[j]:
ans+=1
i+=1
j+=1
elif a[i]<b[j]:
if i+1<len(a):
a[i+1]+=a[i]
i+=1
elif b[j]<a[i]:
if j+1<len(b):
b[j+1]+=b[j]
j+=1
if i!=n or j!=m: print(-1)
else:print(ans) | Python | [
"other"
] | 989 | 403 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 182 |
dd1d166772ee06b383d4ceb94b530fd1 | You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have. | ['implementation', 'greedy'] | k,n1,n2,n3,t1,t2,t3=map(int,raw_input().split())
Z=1024
v=[-10**11]*Z+[0]*10100
v[Z]=0
for i in range(Z,Z+k):
v[i]=max(v[i],v[i-n1]+t1,v[i-n2]+t2,v[i-n3]+t3)
print v[Z+k-1]+t1+t2+t3
| Python | [
"other"
] | 772 | 185 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,350 |
b7ff1ded73a9f130312edfe0dafc626d | After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: There is at least one digit in the string, There is at least one lowercase (small) letter of the Latin alphabet in the string, There is at least one of three listed symbols in the string: '#', '*', '&'. Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. | ['dp', 'implementation', 'brute force'] | n, m = map(int, input().split())
tmp = [input() for _ in range(n)]
arr = []
for s in tmp:
t = [1e4, 1e4, 1e4]
for j in range(m):
if s[j] >= '0' and s[j] <= '9':
t[0] = min(j, t[0], m-j)
elif s[j] >= 'a' and s[j] <= 'z':
t[1] = min(j, t[1], m-j)
else:
t[2] = min(j, t[2], m-j)
arr.append(t)
res = 1e4
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or j == k or i == k:
continue
res = min(res, arr[i][0] + arr[j][1] + arr[k][2])
print(res)
| Python | [
"other"
] | 1,302 | 582 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,020 |
7f4293c5602429819e05beca45b22c05 | There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed n.You are standing at 0 and want to reach n+1 somehow. If you are standing at the position x, you can jump to any position in the range [x + 1; x + d]. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if d=1, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells 0 and n+1 belong to wooden platforms.You want to know if it is possible to reach n+1 from 0 if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if n=7, m=3, d=2 and c = [1, 2, 1], then one of the ways to reach 8 from 0 is follow: The first example: n=7. | ['greedy'] | import sys
n, m, d = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
a = []
i = 0
j = 0
while i + d < n + 1:
if j >= len(c):
print("NO")
sys.exit()
i += d + c[j] - 1
a += [0] * (d - 1)
a += [j+1] * (c[j])
j += 1
s = 0
if len(a) > n:
s += len(a) - n
elif len(a) < n:
a += [0] * (n - len(a))
for i in range(j, m):
s += c[i]
if s != 0:
for i in range(n-1, -1, -1):
if a[i] == 0:
s -= 1
if s == 0:
break
f = i
a = a[:f]
try:
j = max(a)
except:
j = 0
while j < m:
a += [j+1]*(c[j])
j += 1
print("YES")
for i in a:
print(i, end=" ") | Python | [
"other"
] | 1,575 | 711 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,303 |
b54ced81e152a28c19e0068cf6a754f6 | There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k. | ['implementation', 'greedy'] | n,m=map(int,input().split())
a=[0]*(n+1)
c=[0]*4
d=[0]*4
ans=0
for i in range(m):
x,y=sorted(map(int,input().split()))
a[x]|=1
a[y]|=2
for x in a: c[x]+=1
if c[3]==0:
for i in range(1,n):
if a[i]>1: break
d[a[i]]+=1
c[a[i]]-=1
if c[1]>0: continue
ans+=1
print(ans) | Python | [
"other"
] | 1,050 | 293 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,702 |
d6c228bc6e4c17894d9e723ff980844f | Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it: pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range; stick some of the elements together in the same order they were in the array; end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece. More formally, he partitions the sequence a_l, a_{l + 1}, ..., a_r into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length x, then no value occurs strictly more than \lceil \frac{x}{2} \rceil times in it.He didn't pick a range yet, so he's wondering: for q ranges (l, r), what is the minimum number of pieces he needs to partition the elements a_l, a_{l + 1}, ..., a_r into so that the partitioning is beautiful.A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Note that it does not have to be contiguous. | ['binary search', 'data structures', 'greedy', 'implementation', 'sortings'] |
randCnts=25
rand40=[26163, 136194, 134910, 131586, 131511, 151306, 107322, 4960, 27557, 30930, 34180, 123393, 226938, 259573, 203560, 182549, 208694, 270671, 3616, 256123, 215635, 140161, 243942, 251246, 210982, 138905, 226417, 63875, 281860, 24400, 129710, 157586, 257466, 113783, 57707, 20202, 179489, 273724, 71076, 47490]
def nPartitions(size,mode):
b=size
ep=-1 # extra partitions
while b>0:
while ep+b<size and not ((size-(ep+b)+1)//2>=mode-(ep+b)):
ep+=b
b//=2
ep+=1
return 1+ep
def main():
n,q=readIntArr()
a=readIntArr()
# n,q=(300000,300000) #
# a=[197278]*n #
idxs=[[] for _ in range(n+1)]
for i,x in enumerate(a):
idxs[x].append(i)
allans=[]
for _ in range(q):
l,r=readIntArr()
# l,r=1,_+1 #
l-=1;r-=1
gap=r-l+1
mode=0
for i in range(randCnts):
idx=l+rand40[i]%gap
x=a[idx]
arr=idxs[x]
m=len(arr)
l2=-1
b=m
while b>0:
while l2+b<m and arr[l2+b]<l:
l2+=b
b//=2
l2+=1
r2=-1
b=m
while b>0:
while r2+b<m and arr[r2+b]<=r:
r2+=b
b//=2
mode=max(mode,r2-l2+1)
allans.append(nPartitions(gap,mode))
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main() | Python | [
"other"
] | 1,188 | 2,695 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,897 |
da5f2ad6c1ef2cccab5c04f44b9e1412 | You are given an integer n and an array a_1,a_2,\ldots,a_n.In one operation, you can choose an index i (1 \le i \lt n) for which a_i \neq a_{i+1} and delete both a_i and a_{i+1} from the array. After deleting a_i and a_{i+1}, the remaining parts of the array are concatenated.For example, if a=[1,4,3,3,6,2], then after performing an operation with i=2, the resulting array will be [1,3,6,2].What is the maximum possible length of an array of equal elements obtainable from a by performing several (perhaps none) of the aforementioned operations? | ['data structures', 'dp', 'greedy'] | import sys
input = sys.stdin.readline
dp = [[1] * 5050 for _ in range(5050)]
for _ in range(int(input())):
n = int(input())
arr = [*map(int, input().split())]
for i in range(n):
for j in range(n):
dp[i][j] = 1
for j in range(n):
mx = 0
cnt = [0] * (n + 1)
for i in range(j, n):
cnt[arr[i]] += 1
mx = max(mx, cnt[arr[i]])
if ((i - j) % 2 == 0) or (2 * mx > i - j + 1):
dp[j][i] = 0
res = [0] * n
res[0] = 1
for i in range(2, n, 2):
if dp[0][i - 1]:
res[i] = 1
for i in range(1, n):
for j in range(i):
if (res[j] > 0) and (arr[j] == arr[i]) and dp[j + 1][i - 1]:
res[i] = max(res[i], res[j] + 1)
ans = res[-1]
for i in range(n - 3, -1, -2):
if dp[i + 1][n - 1]:
ans = max(ans, res[i])
print(ans) | Python | [
"other"
] | 624 | 969 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,674 |
b8016e8d1e7a3bb6d0ffdcc5ef9ced19 | Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b. | ['two pointers', 'binary search'] | import sys
range = xrange
input = raw_input
n = int(input())
A = [float(x) for x in input().split()]
m = int(input())
B = [float(x) for x in input().split()]
summa = sum(A) - sum(B)
AA = [-2*a for a in A]
BB = [-2*b for b in B]
besta = besta0 = abs(summa)
besta1i = -1
besta1j = -1
for i in range(n):
for j in range(m):
y = abs(summa + AA[i] - BB[j])
if besta > y:
besta = y
besta1i = i
besta1j = j
besta1 = besta
AA = [-2*(A[i] + A[j]) for i in range(n) for j in range(n) if i != j]
BB = [-2*(B[i] + B[j]) for i in range(m) for j in range(m) if i != j]
AA.sort()
BB.sort()
N = len(AA)
M = len(BB)
i = 0
j = 0
besta2i = -1
besta2j = -1
while i<N and j<M:
s = summa + AA[i] - BB[j]
if abs(s) < besta:
besta = abs(s)
besta2i = i
besta2j = j
if s < 0:
i += 1
else:
j += 1
besta2 = besta
print int(besta)
if besta0 == besta:
print 0
elif besta1 == besta:
print 1
print besta1i + 1, besta1j + 1
else:
print 2
aa = - AA[besta2i] // 2
bb = - BB[besta2j] // 2
for i1 in range(n):
for i2 in range(n):
if i1 != i2 and A[i1] + A[i2] == aa:
break
else:
continue
break
for j1 in range(m):
for j2 in range(m):
if j1 != j2 and B[j1] + B[j2] == bb:
break
else:
continue
break
print i1 + 1, j1 + 1
print i2 + 1, j2 + 1
| Python | [
"other"
] | 807 | 1,509 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,711 |
0f637be16ae6087208974eb2c8f3b403 | Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road si and width of lawn gi. For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer xi (0 ≤ xi ≤ gi). After it new road width of the i-th part will be equal to s'i = si + xi and new lawn width will be equal to g'i = gi - xi.On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1 ≤ i < n) the inequation |s'i + 1 - s'i| ≤ 1 should hold. Initially this condition might not be true.You need to find the the total width of lawns the Mayor will destroy according to his plan. | ['constructive algorithms', 'implementation', 'greedy'] | import sys
n = int(raw_input())
roads = [tuple(map(int, raw_input().split())) for _ in range(n)]
neck = min(enumerate(roads), key=lambda x: x[1][0] + x[1][1])
snew = [0]*n
snew[neck[0]] = neck[1][0] + neck[1][1]
i = neck[0] - 1
fail = False
while i > -1:
if fail: break
ol = snew[i+1]
mn = roads[i][0]
mx = mn + roads[i][1]
if ol + 1 < mn:
fail = True
break
snew[i] = min(mx, ol + 1)
if mx < ol - 1:
j = 1
while 1:
ol = snew[i+j-1]
mn = roads[i+j][0]
mx = min(mn + roads[i+j][1], snew[i+j])
if ol + 1 < mn:
fail = True
break
nxt = min(mx, ol + 1)
if nxt == snew[i+j]:
break
else: snew[i+j] = nxt
j += 1
i -= 1
i = neck[0] + 1
while i < n:
if fail: break
ol = snew[i-1]
mn = roads[i][0]
mx = mn + roads[i][1]
if ol + 1 < mn:
fail = True
break
snew[i] = min(mx, ol + 1)
if mx < ol - 1:
j = -1
while 1:
ol = snew[i+j+1]
mn = roads[i+j][0]
mx = min(mn + roads[i+j][1], snew[i+j])
if ol + 1 < mn:
fail = True
break
nxt = min(mx, ol + 1)
if nxt == snew[i+j]:
break
else: snew[i+j] = nxt
j -= 1
i += 1
if fail:
print(-1)
else:
s = sum(snew)
sol = sum(r for r, g in roads)
print(s - sol)
print(' '.join(map(str,snew)))
| Python | [
"other"
] | 1,294 | 1,556 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,913 |
a1951e7d11b504273765fc9fb2f18a5e | You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given): [1, 2, 3], [4, 4] is not a good pair of teams because sizes should be the same; [1, 1, 2], [3, 3, 3] is not a good pair of teams because the first team should not contain students with the same skills; [1, 2, 3], [3, 4, 4] is not a good pair of teams because the second team should contain students with the same skills; [1, 2, 3], [3, 3, 3] is a good pair of teams; [5], [6] is a good pair of teams. Your task is to find the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer t independent test cases. | ['sortings', 'binary search', 'implementation', 'greedy'] | z,zz=input,lambda:list(map(int,z().split()))
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
p=ceil(x**.5)+1
for i in range(2,p):
if (x%i==0 and x!=2) or x==0:return 0
return 1
def dfs(u,visit,graph):
visit[u]=True
for i in graph[u]:
if not visit[i]:
dfs(i,visit,graph)
###########################---Test-Case---#################################
"""
"""
###########################---START-CODING---##############################
num=int(z())
for _ in range( num ):
n=int(z())
ll=dict(cc(zzz()))
l=sorted(list(ll.values()))
ans=len(l)-1
if l[-1]>ans:
if l[-1]>=ans+2:
ans+=1
else:
ans=l[-1]
print(ans)
| Python | [
"other"
] | 1,567 | 1,308 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,990 |
4004c77b77076bf450cbe751e025a71f | Baby Ehab is known for his love for a certain operation. He has an array a of length n, and he decided to keep doing the following operation on it: he picks 2 adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by one. Now he asks you if he can make all elements of the array equal. Since babies like to make your life harder, he requires that you leave at least 2 elements remaining. | ['bitmasks', 'brute force', 'dp', 'greedy'] | t = int(input())
for i in range(t):
n = int(input())
a = ([int(i) for i in input().split()])
xor_arr = 0
for ele in a:
xor_arr = xor_arr ^ ele
if xor_arr == 0 :
print("YES")
else:
count = 0
xor = 0
for ele in a:
xor = xor ^ ele
if xor == xor_arr:
count += 1
xor = 0
if count >= 2 and xor == 0:
print("YES")
else:
print("NO") | Python | [
"other"
] | 505 | 534 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 683 |
e95fb7d4309747834b37d4bc3468afb7 | You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays. | ['binary search', 'bitmasks', 'greedy'] | from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
# main code
n,m=in_arr()
l=in_arr()
d1=Counter(in_arr())
d=Counter()
for i in l:
for j in range(30):
if (1<<j)&i:
d[j]+=1
for i in range(28,-1,-1):
d[i]+=2*d[i+1]
ans=0
for i in range(30):
ans+=min(d1[i],d[i])
d[i+1]=min(max(0,d[i]-d1[i])/2,d[i+1])
pr_num(ans)
| Python | [
"other"
] | 919 | 717 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,916 |
c1e952cb7dd158f12df6affcff07b68a | Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке.Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины wi пикселей и высоты hi пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины hi пикселей и высоты wi пикселей.Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом. | ['dp', 'greedy'] | n = int(input().rstrip())
d = []
for i in range(n):
w, h = map(int, input().rstrip().split())
d.append([w, h])
s = '.'
for i in range(len(d)):
h = d[i][0]
w = d[i][1]
f = 1
for j in range(len(d)):
if j != i:
if d[j][0] <= h and d[j][1] <= h:
w += min(d[j][0], d[j][1])
elif d[j][0] <= h and d[j][1] > h:
w += d[j][1]
elif d[j][0] > h and d[j][1] <= h:
w += d[j][0]
else:
f = 0
if not f == 0:
if s == '.' or h * w < s:
s = h * w
h = d[i][1]
w = d[i][0]
f = 1
for j in range(len(d)):
if j != i:
if d[j][0] <= h and d[j][1] <= h:
w += min(d[j][0], d[j][1])
elif d[j][0] <= h and d[j][1] > h:
w += d[j][1]
elif d[j][0] > h and d[j][1] <= h:
w += d[j][0]
else:
f = 0
if not f == 0:
if s == '.' or h * w < s:
s = h * w
print(s)
| Python | [
"other"
] | 871 | 1,086 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,157 |
08f1ba79ced688958695a7cfcfdda035 | Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: on this day the gym is closed and the contest is not carried out; on this day the gym is closed and the contest is carried out; on this day the gym is open and the contest is not carried out; on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. | ['dp'] | n = int(input())
a = [int(i) for i in input().split()]
action = 0
rest = 0
for i in range(n):
if a[i] == 0:
rest += 1
action = 0
elif a[i] == 1:
if action != 1:
action = 1
else:
rest += 1
action = 0
elif a[i] == 2:
if action != 2:
action = 2
else:
rest += 1
action = 0
else:
if action == 1:
action = 2
elif action == 2:
action = 1
else:
j = i + 1
while j < n and a[j] == 3:
j += 1
#print(j, i, ((j - i) % 2) + a[j])
if j != n:
if ((j - i) % 2) + a[j] == 2:
action = 2
else:
action = 1
print(rest)
| Python | [
"other"
] | 1,026 | 817 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 897 |
4754dd329ec5a01d4d101951656bf66a | You are given an array a of n integers a_1, a_2, a_3, \ldots, a_n.You have to answer q independent queries, each consisting of two integers l and r. Consider the subarray a[l:r] = [a_l, a_{l+1}, \ldots, a_r]. You can apply the following operation to the subarray any number of times (possibly zero)- Choose two integers L, R such that l \le L \le R \le r and R - L + 1 is odd. Replace each element in the subarray from L to R with the XOR of the elements in the subarray [L, R]. The answer to the query is the minimum number of operations required to make all elements of the subarray a[l:r] equal to 0 or -1 if it is impossible to make all of them equal to 0. You can find more details about XOR operation here. | ['binary search', 'bitmasks', 'constructive algorithms', 'data structures'] | #from math import ceil, floor #, gcd, log, factorial, comb, perm,
#log10, log2, log, sin, asin, tan, atan, radians
#from heapq import heappop,heappush,heapify #heappop(hq), heapify(list)
from collections import defaultdict as dd
#mydd=dd(list) for .append
#from collections import deque as dq #deque e.g. myqueue=dq(list)
#append/appendleft/appendright/pop/popleft
from bisect import bisect as bis #a=[1,3,4,6,7,8] #bis(a,5)-->3
#import bisect #bisect.bisect_left(a,4)-->2 #bisect.bisect(a,4)-->3
#import statistics as stat # stat.median(a), mode, mean
#from itertools import permutations(p,r)#combinations(p,r)
#combinations_with_replacement#combinations(p,r) gives r-length tuples,
#in sorted order, with repeated elements#product gives outer product combos
import sys
input = sys.stdin.readline
#print = sys.stdout.write
#sys.setrecursionlimit(100000) #default is 1000
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split()))) #.split(','), default is space
#list([0,*map(int,input().split(" "))]) # pad a zero to avoid zero indexing
def insr():
s = input()
return(list(s[:len(s) - 1]))
####################################################
t=1
#t = int(input())
for tc in range(t):
n,q=map(int, input().split())
a=inlt()
ppa=[0]
psa=[0]
for i in a:
psa.append(psa[-1]^i)
ppa.append(ppa[-1]+i)
occ1=dd(list)
occ2=dd(list)
for i in range(1,n+1):
if i%2:
occ1[psa[i]].append(i)
else:
occ2[psa[i]].append(i)
for i in range(q):
l,r=map(int,input().split())
#if i==417 and n==200000:print(str(l)+'_'+str(r)+'_'+'*'.join(map(str,a[l-1:r])));continue
if ppa[r]==ppa[l-1]:
print(0)
elif (r-l)%2: # nasty if even range, use occ1/occ2 to track odd/even indices of psa values
if psa[r]==psa[l-1]:
if l%2:
ind=bis(occ1[psa[l-1]],l-1)
if ind>=len(occ1[psa[l-1]]):
j=n+1
else:
j=occ1[psa[l-1]][ind]
else:
ind=bis(occ2[psa[l-1]],l-1)
if ind>=len(occ2[psa[l-1]]):
j=n+1
else:
j=occ2[psa[l-1]][ind]
if j<r:
if a[l-1]==0 or a[r-1]==0:
print(1)
else:
print(2)
else:
print(-1)
else:
print(-1)
elif psa[r]^psa[l-1]==0:
print(1)
else:
print(-1)
#print(*ans,sep=' ')##print("{:.3f}".format(ans)+"%")
#:b binary :% eg print("{:6.2%}".format(ans))
#print(" ".join(str(i) for i in ans))
#print(" ".join(map(str,ans))) #seems faster
#print(a[0] if a else 0)
#prefixsum a=[a1...an] #psa=[0]*(n+1)
#for i in range(n): psa[i+1]=psa[i]+a[i]
#sum[:ax]=psa[x+1] e.g. sum 1st 5 items in psa[5]
#ASCII<->number ord('f')=102 chr(102)='f'
#def binary_search(li, val, lb, ub):
# while ((ub-lb)>1):
# mid = (lb + ub) // 2
# if li[mid] >= val:
# ub = mid
# else:
# lb = mid
# return lb+1 #return index of elements <val in li
#def binary_search(li, val, lb, ub):
# ans = -1
# while (lb <= ub):
# mid = (lb + ub) // 2
# if li[mid] > val:
# ub = mid - 1
# elif val > li[mid]:
# lb = mid + 1
# else:
# ans = mid # return index
# break
# return ans
##########
#def pref(li):
# pref_sum = [0]
# for i in li:
# pref_sum.append(pref_sum[-1] + i)
# return pref_sum
##########
#def suff(li):
# suff_sum = [0]
# for i in range(len(li)-1,-1,-1):
# suff_sum.insert(0,suff_sum[0] + li[i])
# return suff_sum
#############
#def maxSubArraySumI(arr): #Kadane's algorithm with index
# max_till_now=arr[0];max_ending=0;size=len(arr)
# start=0;end=0;s=0
# for i in range(0, size):
# max_ending = max_ending + arr[i]
# if max_till_now < max_ending:
# max_till_now=max_ending
# start=s;end=i
# if max_ending<0:
# max_ending=0
# s=i+1
# return max_till_now,start,end
############# avoid max for 2 elements - slower than direct if
#def maxSubArraySum(arr): #Kadane's algorithm
# max_till_now=arr[0];max_ending=0;size=len(arr)
# for i in range(0, size):
# max_ending = max_ending + arr[i]
# if max_till_now < max_ending:max_till_now=max_ending
# if max_ending<0:max_ending=0
# return max_till_now
#############
#def findbits(x):
# tmp=[]
# while x>0:tmp.append(x%2);x//=2
# tmp.reverse()
# return tmp
##############Dijkstra algorithm example
#dg=[999999]*(n+1);dg[n]=0;todo=[(0,n)];chkd=[0]*(n+1)
#while todo:#### find x with min dg in todo
# _,x=hq.heappop(todo)
# if chkd[x]:continue
# for i in coming[x]:going[i]-=1
# for i in coming[x]:
# tmp=1+dg[x]+going[i]
# if tmp<dg[i]:dg[i]=tmp;hq.heappush(todo,(dg[i],i))
# chkd[x]=1
################
# adj swaps to match 2 binary strings: sum_{i=1}^n(abs(diff in i-th prefix sums))
###############
##s=[2, 3, 1, 4, 5, 3]
##sorted(range(len(s)), key=lambda k: s[k])
##gives sorted indices [2, 0, 1, 5, 3, 4]
##m= [[3, 4, 6], [2, 4, 8], [2, 3, 4], [1, 2, 3], [7, 6, 7], [1, 8, 2]]
##m.sort(reverse=True,key=lambda k:k[2]) #sorts m according to 3rd elements
#import bisect #li = [1, 3, 4, 4, 4, 6, 7]#sorted li, use b search, so log(n)
#bisect.bisect(li,4)-->5 #bisect.bisect_left(li,4)-->2
###############
##def chkprime(x):
## if x==2 or x==3:return True
## if x%2==0 or x<2:return False
## for i in range(3,int(x**0.5)+1,2):
## if x%i==0:return False
## return True
############### prime factoring functions
##def pfactors(n):
## f=[];d=3
## while n%2==0:f.append(2);n//=2
## while d*d<=n:
## while n%d==0:f.append(d);n//=d
## d+=2
## if n>1:f.append(n)
## return f
############################## check equivalence under rotation O(n)
##def cyclic_equiv(u,v):
## n,i,j=len(u),0,0
## if n!=len(v):return False
## while i<n and j<n:
## k=1
## while k<=n and u[(i+k)%n]==v[(j+k)%n]:k+=1
## if k>n:return True
## if u[(i+k)%n]>v[(j+k)%n]:
## i+=k
## else:
## j+=k
## return False
| Python | [
"other"
] | 839 | 6,687 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 946 |
a26a97586d4efb5855aa3b930e9effa7 | Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points. | ['two pointers', 'implementation', 'greedy'] | n, m = map(int, input().split())
l = [0 for i in range(0, n)]
c = [0 for i in range(0, n)]
sol = 0
for i in range(0, m):
a, b = map(int, input().split())
l[a-1] = 1
c[b-1] = 1
for i in range(1, n//2):
#ma ocup de liniile i si n-i, coloanele la fel
sol += 4 - (l[i] + c[i] + l[n-i-1] + c[n-i-1])
if n % 2 == 1:
if not l[n//2] or not c[n//2]: sol += 1
print(sol)
| Python | [
"other"
] | 912 | 399 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,581 |
cf912f6efc3c0e3fabdaa5f878a777c5 | A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are n students in the class, and you are given an array s in non-decreasing order, where s_i is the shoe size of the i-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation p of \{1,2,\ldots,n\} denoting a valid shuffling of shoes, where the i-th student gets the shoes of the p_i-th student (p_i \ne i). And output -1 if a valid shuffling does not exist.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). | ['constructive algorithms', 'greedy', 'implementation', 'two pointers'] | for i in range(int(input())):
n=int(input())
s=input().split()
if n==1:
print(-1)
else:
k=0
b=[]
from collections import Counter
x=Counter(s)
sorted(x.items())
for i in x:
if x[i]==1:
b=[]
print(-1)
break
else:
b.append(len(b)+x[i])
k+=1
for j in range(x[i]-1):
if j<x[i]-1:
b.append(k)
k+=1
if len(b)>0:
b=list(map(str,b))
print(' '.join(b)) | Python | [
"other"
] | 1,098 | 441 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,758 |
c914a0f00403ece367f05ba5e8d558ec | Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends.You know that Alice and Bob have already played n rounds, and you know the results of some rounds. For each x from 1 to n, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins x rounds in a row. It is possible that the last set is still not finished — in that case, you should not count it in the answer. | ['dp', 'greedy', 'two pointers', 'data structures', 'binary search'] | # Author: yumtam
# Created at: 2020-08-28 05:07
from __future__ import division, print_function
_interactive = False
def stupid(n, ar):
from itertools import product
unknowns = ar.count(-1)
print(n, end=' ')
for consec in range(2, n+1):
ans = 0
for p in product(range(1+1), repeat=unknowns):
cur = 0
it = iter(p)
arc = ar[:]
for i, e in enumerate(arc):
if e == -1:
arc[i] = next(it)
prev = -1
cnt = 0
for x in arc:
if x == prev:
cnt += 1
else:
cnt = 1
if cnt >= consec:
cur += 1
cnt = 0
prev = x
ans = max(ans, cur)
print(ans, end=' ')
def solve(n, ar):
from bisect import bisect_left
nxt = array_of(int, 2, n+1)
jmp = array_of(list, n+1)
for i in reversed(range(n)):
x = ar[i]
nxt[0][i] = nxt[0][i+1]+1
nxt[1][i] = nxt[1][i+1]+1
if x == 0:
nxt[1][i] = 0
elif x == 1:
nxt[0][i] = 0
for i in range(1, n):
for nxti in nxt:
if nxti[i-1] == 0 and nxti[i] > 0:
for j in range(1, nxti[i]+1):
jmp[j].append(i)
debug_print(nxt)
debug_print(jmp)
for k in range(1, n+1):
i = 0
ans = 0
while True:
if max(nxt[0][i], nxt[1][i]) >= k:
i += k
else:
idx = bisect_left(jmp[k], i)
if idx == len(jmp[k]):
break
else:
i = jmp[k][idx] + k
ans += 1
print(ans, end=' ')
def main():
n = int(input())
s = input()
d = {'0': 0, '1': 1, '?': -1}
ar = [d[c] for c in s]
solve(n, ar)
if LOCAL:
print()
stupid(n, ar)
# Constants
INF = float('inf')
MOD = 10**9+7
# Python3 equivalent names
import os, sys, itertools
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
# print-flush in interactive problems
if _interactive:
flush = sys.stdout.flush
def printf(*args, **kwargs):
print(*args, **kwargs)
flush()
# Debug print, only works on local machine
LOCAL = "LOCAL_" in os.environ
debug_print = (print) if LOCAL else (lambda *x, **y: None)
# Fast IO
if (not LOCAL) and (not _interactive):
from io import BytesIO
from atexit import register
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Some utility functions(Input, N-dimensional lists, ...)
def input_as_list():
return [int(x) for x in input().split()]
def input_with_offset(o):
return [int(x)+o for x in input().split()]
def input_as_matrix(n, m):
return [input_as_list() for _ in range(n)]
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
# Start of external code templates...
# End of external code templates.
main()
| Python | [
"other"
] | 711 | 3,294 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,022 |
c31fed523230af1f904218b2fe0d663d | A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house? | ['implementation', 'sortings'] | n,l = map(int, raw_input().split())
xr = xrange(n)
a = [map(float, raw_input().split()) for _ in xr]
for o in a:
st = o[0] - o[1]/2
ed = o[0] + o[1]/2
o[0] = st
o[1] = ed
b = sorted(a,key=lambda aa:aa[0])
a = None
c = []
r = 2
for i in xr:
if i < n-1:
if b[i+1][0] - b[i][1] == l:
r+=1
elif b[i+1][0] - b[i][1] > l:
r+=2
print r | Python | [
"other"
] | 819 | 388 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 550 |
56ea328f84b2930656ff5eb9b8fda8e0 | Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents — n riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver i the number a_{i} — the number of riders that would call the i-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers. | ['implementation', 'sortings'] | R=lambda:map(int,input().split())
n,m=R()
a=[[],[]]
for x,y in zip(R(),R()):a[y]+=[x]
r,d=a
s=[0]*m
i=0
for x in r:
while i<m-1and 2*x>d[i]+d[i+1]:i+=1
s[i]+=1
print(*s) | Python | [
"other"
] | 1,127 | 171 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,421 |
90be8c6cf8f2cd626d41d2b0be2dfed3 | Dreamoon likes coloring cells very much.There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.You are given an integer m and m integers l_1, l_2, \ldots, l_m (1 \le l_i \le n)Dreamoon will perform m operations.In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints. | ['constructive algorithms', 'greedy'] | n, m = [int(i) for i in input().split()]
d = [int(i) for i in input().split()]
if sum(d) < n:
print(-1)
exit()
# d = [(dd[i], i) for i in range(m)]
# d.sort()
pos = [0]*m
ind = n
for i in range(m-1, -1, -1):
ind = min(ind - 1, n - d[i])
pos[i] = ind
if pos[0] < 0:
print(-1)
exit()
lind = -1
for i in range(m):
if pos[i] <= lind+1:
break
pos[i] = lind+1
lind += d[i]
ppos = [ppp+1 for ppp in pos]
print(*ppos)
| Python | [
"other"
] | 841 | 458 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 326 |
c0068963008fdf04ba4261d32f4162a2 | Madoka has become too lazy to write a legend, so let's go straight to the formal description of the problem.An array of integers a_1, a_2, \ldots, a_n is called a hill if it is not empty and there is an index i in it, for which the following is true: a_1 < a_2 < \ldots < a_i > a_{i + 1} > a_{i + 2} > \ldots > a_n.A sequence x is a subsequence of a sequence y if x can be obtained from y by deletion of several (possibly, zero or all) elements keeping the order of the other elements. For example, for an array [69, 1000, 228, -7] the array [1000, -7] is a subsequence, while [1] and [-7, 1000] are not.Splitting an array into two subsequences is called good if each element belongs to exactly one subsequence, and also each of these subsequences is a hill.You are given an array of distinct positive integers a_1, a_2, \ldots a_n. It is required to find the number of different pairs of maxima of the first and second subsequences among all good splits. Two pairs that only differ in the order of elements are considered same. | ['dp', 'greedy'] | def solve(a):
n = len(a)
ans, dp1, dp2, dp3, dp4 = 0, [0] * N, [0] * N, [0] * N, [0] * N
val, idx = max(a), -1
for i in range(N):
if a[i] == val:
idx = i
break
dp4[N - 1] = -1e18
for i in range(N - 2, idx - 1, -1):
dp4[i] = 1e18
dp4[i] = min(dp4[i], dp4[i + 1] if a[i] > a[i + 1] else 1e18)
dp4[i] = min(dp4[i], a[i + 1] if a[i] > dp4[i + 1] else 1e18)
dp1[0] = -1e18
for i in range(1, idx):
dp1[i] = 1e18
dp1[i] = min(dp1[i], dp1[i - 1] if a[i] > a[i - 1] else 1e18)
dp1[i] = min(dp1[i], a[i - 1] if a[i] > dp1[i - 1] else 1e18)
dp2[idx], dp3[idx] = -1e18, dp4[idx]
for i in range(idx - 1, -1, -1):
dp2[i] = -1e18
dp2[i] = max(dp2[i], dp2[i + 1] if a[i] > a[i + 1] else -1e18)
dp2[i] = max(dp2[i], a[i + 1] if a[i] > dp3[i + 1] else -1e18)
dp3[i] = 1e18
dp3[i] = min(dp3[i], dp3[i + 1] if a[i] < a[i + 1] else 1e18)
dp3[i] = min(dp3[i], a[i + 1] if a[i] < dp2[i + 1] else 1e18)
if dp1[i] < dp2[i]:
ans += 1
return ans
N = int(input())
A = list(map(int, input().split()))
ans1 = solve(A)
A.reverse()
ans2 = solve(A)
print(ans1 + ans2) | Python | [
"other"
] | 1,121 | 1,118 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,187 |
ae531bc4b47e5d31fe71b6de1398b95e | We get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 \cdot t, where t — the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, \dots, r_n, where r_i — the number of requests in the i-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n]. | ['*special', 'brute force'] | def find_d(A):
n = max(A) + 1
A = [None] + A
ind = [[] for _ in range(n)]
for i in range(len(A)):
if not A[i]:
continue
if len(ind[A[i]]) == 2:
ind[A[i]][1] = i
else:
ind[A[i]].append(i)
min_ind = len(A)
d = 0
for l in ind:
if len(l) == 1:
if l[0] < min_ind:
min_ind = l[0]
else:
if d < l[0] - min_ind:
d = l[0] - min_ind
r = (d, min_ind)
elif len(l) == 2:
if d < l[1] - min_ind:
d = l[1] - min_ind
r = (d, min_ind)
if l[0] < min_ind:
min_ind = l[0]
else:
continue
return d
import sys
n = int(sys.stdin.readline())
R = [int(i) for i in sys.stdin.readline().strip().split()]
R = [i-100 for i in R]
S = []
s = 0
for i in range(n):
s = s + R[i]
S.append(s)
k = 0
d = 0
for i in range(len(S)):
if S[i] > 0:
k = i + 1
if any([x <= 0 for x in S]):
s = 1 - min(S)
S = [i+s for i in S]
d = find_d(S)
print(max(d,k)) | Python | [
"other"
] | 691 | 1,137 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,454 |
c761bb69cf1b5a3dbe38d9f5c46e9007 | As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth? | ['data structures', 'constructive algorithms', 'implementation'] | from collections import defaultdict
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(int(input()))
d = defaultdict(int)
pos, neg = 0, 0
for x in a:
d[x] += 1
if x > 0:
pos += 1
else:
neg += 1
possible = [False] * n
for i in range(1, n + 1):
t = d[i] + neg - d[-i]
if t == m:
possible[i - 1] = True
cnt = sum(possible)
for i in range(n):
if cnt == 0:
print('Lie')
continue
if a[i] > 0:
if possible[a[i] - 1]:
print('Truth' if cnt == 1 else 'Not defined')
else:
print('Lie')
else:
if not possible[-a[i] - 1]:
print('Truth')
else:
print('Lie' if cnt == 1 else 'Not defined')
| Python | [
"other"
] | 667 | 752 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,415 |
3a4b815bcc0983bca9789ec8e76e0ea0 | Your program fails again. This time it gets "Wrong answer on test 233".This is the easier version of the problem. In this version 1 \le n \le 2000. You can hack this problem only if you solve and lock both problems.The problem is about a test containing n one-choice-questions. Each of the questions contains k options, and only one of them is correct. The answer to the i-th question is h_{i}, and if your answer of the question i is h_{i}, you earn 1 point, otherwise, you earn 0 points for this question. The values h_1, h_2, \dots, h_n are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the n answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question i to the question i \bmod n + 1. So it moves the answer for the question 1 to question 2, the answer for the question 2 to the question 3, ..., the answer for the question n to the question 1.We call all the n answers together an answer suit. There are k^n possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by 1, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo 998\,244\,353.For example, if n = 5, and your answer suit is a=[1,2,3,4,5], it will submitted as a'=[5,1,2,3,4] because of a mistake. If the correct answer suit is h=[5,2,2,3,4], the answer suit a earns 1 point and the answer suite a' earns 4 points. Since 4 > 1, the answer suit a=[1,2,3,4,5] should be counted. | ['dp'] | def main():
M=998244353
n,k,*h=map(int,open(0).read().split())
m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
f=[0]*(m+1)
f[0]=b=1
for i in range(1,m+1):f[i]=b=b*i%M
inv=[0]*(m+1)
inv[m]=b=pow(f[m],M-2,M)
for i in range(m,0,-1):inv[i-1]=b=b*i%M
comb=lambda n,k:f[n]*inv[n-k]*inv[k]%M
print((pow(k,m,M)-sum(comb(m,i)*comb(m-i,i)*pow(k-2,m-i-i,M)for i in range(m//2+1)))*pow(k,n-m,M)*pow(2,M-2,M)%M)
main() | Python | [
"other"
] | 1,877 | 443 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,995 |
3fb43df3a6f763f196aa514f305473e2 | One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get? | ['data structures', 'greedy'] | import heapq
class Heap(object):
""" A neat min-heap wrapper which allows storing items by priority
and get the lowest item out first (pop()).
Also implements the iterator-methods, so can be used in a for
loop, which will loop through all items in increasing priority order.
Remember that accessing the items like this will iteratively call
pop(), and hence empties the heap! """
def __init__(self):
""" create a new min-heap. """
self._heap = []
def push(self, priority, item=None):
""" Push an item with priority into the heap.
Priority 0 is the highest, which means that such an item will
be popped first."""
if item==None: item=priority
#~ assert priority >= 0
heapq.heappush(self._heap, (priority, item))
def pop(self):
""" Returns the item with lowest priority. """
item = heapq.heappop(self._heap)[1] # (prio, item)[1] == item
return item
def top(self):
return self._heap[0][1]
def __len__(self):
return len(self._heap)
def __iter__(self):
""" Get all elements ordered by asc. priority. """
return self
def __getitem__(self, k):
return self._heap[k]
def next(self):
""" Get all elements ordered by their priority (lowest first). """
try:
return self.pop()
except IndexError:
raise StopIteration
def readval(typ=int):
return typ( raw_input() )
def readvals(typ=int):
return map( typ, raw_input().split() )
def testcase():
n = readval()
t0, w0 = readvals()
better, worse = Heap(), []
for i in xrange(n-1):
t,w = readvals()
if t>t0: better.push(priority=(w-t+1), item=(t,w))
else: worse.append((t,w))
worse.sort(key=lambda (t,w): -t)
cur_place = len(better)+1
best_place = cur_place
#~ print '---'*3, cur_place, t0
#~ print better._heap
#~ print worse._heap
idx_worse = 0
while len(better)>0 :
t,w = better.pop()
ballons_togive = w-t+1
t0 -= ballons_togive
if t0<0: break
cur_place -= 1
while idx_worse<len(worse) and worse[idx_worse][0]>t0: #len(worse)>0 and worse.top()[0]>t0:
t,w = worse[idx_worse]
better.push(priority=(w-t+1), item=(t,w))
cur_place += 1
idx_worse += 1
best_place = min(cur_place, best_place)
#~ print '---'*3, cur_place, t0
#~ print better._heap
#~ print worse._heap
print best_place
#~ def give(k): # highest rank if limak gives k ballons
#~ t_limak = limak[0]-k
#~ _teams = filter(lambda (t,w): t > t_limak, teams)
#~ _teams.sort(key=lambda (t,w): w-t+1)
#~ rank = len(_teams)+1
#~ for (ti,wi) in _teams:
#~ deltai = wi-ti+1
#~ if deltai>k: break
#~ k -= deltai
#~ rank -= 1
#~ return rank
#~ # linear search:
#~ print min( [give(k) for k in xrange(limak[0])] )
if __name__=='__main__':
testcase()
| Python | [
"other"
] | 1,294 | 3,216 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,216 |
f995d575f86eee139c710cb0fe955682 | You are given 2 arrays a and b, both of size n. You can swap two elements in b at most once (or leave it as it is), and you are required to minimize the value \sum_{i}|a_{i}-b_{i}|.Find the minimum possible value of this sum. | ['brute force', 'constructive algorithms', 'data structures', 'sortings'] | import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main(t):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
base = sum( [abs(a[i]-b[i]) for i in range(n)] )
ans = base
# print(base,"*")
greater = []
smaller = []
for i in range(n):
if a[i]<b[i]:
greater.append((a[i],b[i]))
else:
smaller.append((b[i],a[i]))
greater.sort()
smaller.sort()
# print(greater,smaller,base)
currmax = -float('inf')
maxsub = 0
index = 0
for [s,l] in smaller:
while index < len(greater) and greater[index][0] <= s:
currmax = max(currmax, greater[index][1] )
# maxsub = max(maxsub, 2*min(currmax,l) - 2*s)
index += 1
maxsub = max(maxsub, 2*min(currmax,l) - 2*s)
# print(currmax,s,l)
# print(maxsub)
currmax = -float('inf')
index = 0
for [s,l] in greater:
while index < len(smaller) and smaller[index][0] <= s:
currmax = max(currmax, smaller[index][1] )
index += 1
maxsub = max(maxsub, 2*min(currmax,l) - 2*s)
# print(maxsub)
ans = base - maxsub
print(ans)
T = 1 #int(input())
t = 1
while t<=T:
main(t)
t += 1
| Python | [
"other"
] | 261 | 1,356 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,613 |
27b73a87fc30c77abb55784e2e1fde38 | A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer n. Your goal is to construct and print exactly n different regular bracket sequences of length 2n. | ['constructive algorithms'] | n = int(input())
for i in range(n):
e = int(input())
for j in range(e):
print("()" * j + "(" * (e - j) + ")" * (e - j)) | Python | [
"other"
] | 558 | 139 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 436 |
040171969b25ad9be015d95586890cf0 | Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph x (1 ≤ x ≤ c - 1) is replaced with hieroglyph (x + 1), and hieroglyph c is replaced with hieroglyph 1.Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically. | ['data structures', 'sortings', 'greedy', 'brute force'] | #!/usr/bin/env python
# coding: utf-8
if __name__ == '__main__':
import sys
f = sys.stdin
if False:
import StringIO
f = StringIO.StringIO("""4 3
2 3 2
1 1
3 2 3 1
4 2 3 1 2""")
f = StringIO.StringIO("""2 5
2 4 2
2 4 2""")
f = StringIO.StringIO("""4 4
1 2
1 3
1 4
1 2""")
f = StringIO.StringIO("""2 10
14 9 6 7 1 6 9 3 1 9 4 6 8 8 1
3 3 7 6""")
f = StringIO.StringIO("""4 4
1 3
1 4
1 1
1 2""")
if False:
with open("/home/ilya/opt/programming/tasks/731D_gen.txt", "w") as f:
n, alp_cnt = 500000, 10**6
f.write("%(n)s %(alp_cnt)s\n" % locals())
import random
ln = 10**6 / n
for i in xrange(n):
lst = [ln]
for j in xrange(ln):
lst.append(random.randint(1, alp_cnt))
f.write("%s\n" % " ".join(str(k) for k in lst))
sys.exit(0)
def getline():
return next(f).rstrip('\n\r')
def read_int_line():
return map(int, next(f).split())
n, alp_cnt = read_int_line()
assert n > 1
def read_word():
return read_int_line()[1:]
set_lst = [0] * (alp_cnt + 1)
def add_range(x, y):
set_lst[x] += 1
set_lst[y] -= 1
prev_word = read_word()
bad_prefix = False
for i in xrange(1, n):
word = read_word()
is_prefix = True
ln = len(prev_word)
ln2 = len(word)
for i in xrange(min(ln, ln2)):
c, c2 = prev_word[i]-1, word[i]-1
diff = c - c2
if diff == 0:
pass
else:
# дополнения
if diff < 0:
# [alp_cnt - c2, alp_cnt - c)
add_range(alp_cnt - c2, alp_cnt - c)
else:
# дополнения: [alp_cnt - c2, alp_cnt), [0, alp_cnt - c)
add_range(alp_cnt - c2, alp_cnt)
add_range(0, alp_cnt - c)
is_prefix = False
break
if is_prefix and ln > ln2:
bad_prefix = True
break
prev_word = word
res = -1
if not bad_prefix:
state = 0
#for i in xrange(alp_cnt):
for i, v in enumerate(set_lst):
state += set_lst[i]
if state == 0:
break
if i < alp_cnt:
res = i
print res
| Python | [
"other"
] | 1,061 | 2,447 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,601 |
78d013b01497053b8e321fe7b6ce3760 | Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1 + c2·(x - 1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. | ['*special', 'ternary search', 'brute force'] | values = map(int, raw_input().split())
n = values[0]
c1 = values[1]
c2 = values[2]
str = raw_input()
batyas = 0
wegols = 0
for i in str:
if (i == '0'): wegols+=1
else: batyas+=1
ans = 0
for groups in range(1, batyas+1):
cost = groups * c1
d1 = (batyas + wegols) / groups
c = (batyas + wegols) % groups
cost += c2 * c * d1 * d1
cost += c2 * (groups - c) * (d1 - 1) * (d1 - 1)
if (groups == 1): ans = cost
ans = min(ans, cost)
print(ans)
| Python | [
"other"
] | 806 | 479 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,895 |
0048623eeb27c6f7c6900d8b6e620f19 | There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are k teams (a_1, b_1), (a_2, b_2), \dots, (a_k, b_k), where a_i is the weight of the first participant of the i-th team and b_i is the weight of the second participant of the i-th team, then the condition a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s, where s is the total weight of each team, should be satisfied.Your task is to choose such s that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer t independent test cases. | ['two pointers', 'greedy', 'brute force'] | t=int(input())
for j in range(t):
n=int(input())
arr=list(map(int,input().split()))
ans=0
for i in range(2,2*n+1):
c=[0]*101
cur=0
for x in arr:
if i>x and c[i-x]!=0:
c[i-x]-=1
cur+=1
else:
c[x]+=1
ans=max(ans,cur)
print(ans) | Python | [
"other"
] | 896 | 349 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,470 |
894f407ca706788b13571878da8570f5 | In some country live wizards. They love to ride trolleybuses.A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine. | ['implementation'] | n,a,d=map(int,input().split())
p=[0]*n
for i in range(n):
t,v=map(int,input().split())
x=v/a
y=(2*d/a) ** 0.5
p[i]=t+y if y<x else t+d/v+x/2
p[i]=max(p[i-1],p[i])
print('\n'.join(map(str,p))) | Python | [
"other"
] | 1,597 | 211 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,121 |
31e58e00ae708df90251d7b751272771 | Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship. | ['binary search', 'sortings', 'greedy'] | class Racer:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return '%s %d' % (self.name, self.points)
n = int(input())
best = n * [ None ]
worst = n * [ None ]
for i in range(n):
name, points = input().split()
points = int(points)
best[i] = Racer(name, points)
worst[i] = Racer(name, points)
m = int(input())
place_bonus = list(reversed(sorted(map(int, input().split()))))
your_name = input().strip()
debugging = False
def debug_print(s):
if debugging:
print(s)
def find(racers, name):
for i in range(n):
if racers[i].name == name:
return i
def sort_racers(racers):
racers.sort(key=lambda racer: (-racer.points, racer.name))
# Highest possible ranking.
you = best[find(best, your_name)]
# You get the biggest bonus.
if m != 0:
you.points += place_bonus[0]
sort_racers(best)
# People ahead of you get the next biggest bonuses.
bonus_pos = 1
for i in range(find(best, your_name) - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
# People at the end get the remaining bonuses.
for i in range(n - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
sort_racers(best)
debug_print(list(map(str, best)))
best_ranking = find(best, your_name) + 1
debug_print('best ranking: %d' % best_ranking)
# Lowest possible ranking.
you = worst[find(worst, your_name)]
# If you must get a bonus, it's the smallest one.
if m == n:
you.points += place_bonus.pop()
m -= 1
sort_racers(worst)
# Award the smallest possible bonus to the person who can pass you most easily.
bonus_pos = m - 1
worst_pos = find(worst, your_name) + 1
while bonus_pos >= 0 and worst_pos < n:
debug_print('bonus_pos = %d, worst_pos = %d' % (bonus_pos, worst_pos))
candidate = worst[worst_pos]
need = you.points - candidate.points
if candidate.name > you.name:
need += 1
if place_bonus[bonus_pos] >= need:
candidate.points += place_bonus[bonus_pos]
worst_pos += 1
bonus_pos -= 1
sort_racers(worst)
debug_print(list(map(str, worst)))
worst_ranking = find(worst, your_name) + 1
debug_print('worst ranking: %d' % worst_ranking)
print('%d %d' % (best_ranking, worst_ranking))
| Python | [
"other"
] | 991 | 2,354 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,740 |
44619ba06ec0dc410ef598ea45a76271 | Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has n sweets with sizes a_1, a_2, \ldots, a_n. All his sweets have different sizes. That is, there is no such pair (i, j) (1 \leq i, j \leq n) such that i \ne j and a_i = a_j.Since Mike has taught for many years, he knows that if he gives two sweets with sizes a_i and a_j to one child and a_k and a_p to another, where (a_i + a_j) \neq (a_k + a_p), then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset. | ['implementation', 'brute force'] | from itertools import combinations
n = int(input())
sizes = list(map(int,input().split(" ")))
targets = list(combinations(sizes,2))
freq = {}
for c in targets:
if sum(c) in freq:
freq[sum(c)].append(c)
else:
freq[sum(c)] = [c]
res = 1
for key,value in freq.items():
res = max(len(value),res)
print(res)
| Python | [
"other"
] | 1,225 | 334 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 790 |
fcd88c7b64da4b839cda4273d928429d | 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, \dots, 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 one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day. | ['implementation'] | # n = input()
# l = ''.join(input().split())
# l += l
# l = l.split('0')
# print(max(len(i) for i in l))
n = int(input())
a = ''.join(input().split())
a += a
a = a.split('0')
print(max(len(i) for i in a))
| Python | [
"other"
] | 593 | 205 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 992 |
63b20ab2993fddf2cc469c4c4e8027df | The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line? | ['implementation', 'greedy'] | #!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil, factorial, log,tan,pi,cos,sin,radians
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
from fractions import Fraction
from functools import reduce
import string
import sys
import os
import re
inf = float('inf')
mod_ = int(1e9) + 7
mod = 998244353
def factors(n):
from functools import reduce
return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def sieve(m):
n=1
primes = {}
arr=set([])
for i in range(2, int(m ** 0.5) + 1):
a = n // i
b = m // i
for k in range(max(2, a), b + 1):
c = i * k
primes[c] = 1
for i in range(max(n, 2), m + 1):
if i not in primes:
arr.add(i)
return arr
class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def isprime(t):
for i in range(2,int(t**0.5)+1):
if t%i==0:
return False
return True
def semiprime(x):
for i in range(2,int(x**0.5)+1):
if x%i==0:
if isprime(i) and isprime(x//i) and i!=x//i:
return True
return False
def main():
n=int(input())
arr=list(map(int,input().split()))
cnt_25=cnt_50=0
for i in arr:
# print(cnt_25,cnt_50)
if i==25:
cnt_25+=1
elif i==50:
cnt_25-=1
cnt_50+=1
else:
if cnt_50>=1:
cnt_50-=1
cnt_25-=1
else:
cnt_25-=3
if cnt_25<0:
print("NO")
break
else:
print("YES")
# region fastio
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def gcd(x, y):
while y:
x, y = y, x % y
return x
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| Python | [
"other"
] | 377 | 4,535 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,872 |
bb521123f9863345d75cfe10677ab344 | We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you.For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, \dots, p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: [2, 5, 6] [4, 6] [1, 3, 4] [1, 3] [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).You have to answer t independent test cases. | ['greedy', 'constructive algorithms', 'implementation', 'data structures', 'brute force'] | import sys
import collections
import threading
import copy
def check(itr, sets):
d={}
def dmap(x):
return d[x]
for i in range(len(itr)):
d[itr[i]] = i
for perm in sets:
tmp = sorted(list( map(dmap, perm) ))
if len(tmp) != tmp[-1] - tmp[0] + 1:
return False
return True
def main():
n = int( input() )
sets = []
start = set()
for _ in range(n-1):
l, *tmp = map( int, input().split() )
sets.append( set(tmp) )
if l == 2:
start.add(tmp[0])
start.add(tmp[1])
ans = collections.deque()
for i in start:
permuts = copy.deepcopy(sets)
next = i
while len(ans) > 0: ans.pop()
ans.append(next)
while len(ans) < n:
q = []
for permut in permuts:
if next in permut:
permut.remove(next)
if len(permut) == 1:
q.append(permut)
if len(q) != 1:
break ########## exit
next = list(q[0])[0]
ans.append(next)
if len(ans)==n and check(ans, sets):
print(*ans)
return
print("error")
return
input = sys.stdin.readline
#sys.setrecursionlimit(2097152)
tnum = int(input())
for _ in range(tnum):
main()
# threading.stack_size(134217728)
# main_thread = threading.Thread(target=main)
# main_thread.start()
# main_thread.join() | Python | [
"other"
] | 1,134 | 1,504 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,399 |
02932480c858536191eb24f4ea923029 | This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai.Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected. | ['data structures'] | def main():
_, k, m = [int(x) for x in input().split()]
a = []
last = ("-1", 0)
a.append(last)
for ai in input().split():
if last[0] == ai:
last = (ai, last[1]+1)
a[-1] = last
else:
last = (ai, 1)
a.append(last)
if last[1] == k:
a.pop()
last = a[-1]
a.pop(0)
s1 = 0
while len(a) > 0 and a[0][0] == a[-1][0]:
if len(a) == 1:
s = a[0][1] * m
r1 = s % k
if r1 == 0:
print(s1 % k)
else:
print(r1 + s1)
return
join = a[0][1] + a[-1][1]
if join < k:
break
elif join % k == 0:
s1 += join
a.pop()
a.pop(0)
else:
s1 += (join // k) * k
a[0] = (a[0][0], join % k)
a.pop()
break
s = 0
for ai in a:
s += ai[1]
print(s*m + s1)
if __name__ == "__main__":
main() | Python | [
"other"
] | 977 | 1,033 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,126 |
cfccf06c4d0de89bf0978dc6512265c4 | You are given an array s consisting of n integers.You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find such element in s, then you cannot cut out one more copy of t. The both arrays can contain duplicate elements.For example, if s = [1, 2, 3, 2, 4, 3, 1] and k = 3 then one of the possible answers is t = [1, 2, 3]. This array t can be cut out 2 times. To cut out the first copy of t you can use the elements [1, \underline{\textbf{2}}, 3, 2, 4, \underline{\textbf{3}}, \underline{\textbf{1}}] (use the highlighted elements). After cutting out the first copy of t the array s can look like [1, 3, 2, 4]. To cut out the second copy of t you can use the elements [\underline{\textbf{1}}, \underline{\textbf{3}}, \underline{\textbf{2}}, 4]. After cutting out the second copy of t the array s will be [4]. Your task is to find such array t that you can cut out the copy of t from s maximum number of times. If there are multiple answers, you may choose any of them. | ['binary search', 'sortings'] | n,k=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
d={}
for i in a:
if i in d.keys():
d[i]+=1
else:
d[i]=1
s=[]
for i,j in d.items():
s.append([j,i])
s.sort(reverse=True)
b=[]
for i in range(len(s)):
j=1
while s[i][0]//j!=0:
b.append([s[i][0]//j,s[i][1]])
j+=1
b.sort(reverse=True)
for i in range(k):
print(b[i][1],end=' ')
| Python | [
"other"
] | 1,374 | 397 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 180 |
facd9cd4fc1e53f50a1e6f947d78e942 | n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit. | ['implementation'] | import math
n=int(input())
l=list(map(int,input().split()))
d=0
diff=abs(l[n-1]-l[0])
o1,o2=n,1
for i in range(n-1):
d=abs(l[i+1]-l[i])
#print(d,diff)
if d<diff:
diff=d
o1=i+1
o2=i+2
print(o1,o2) | Python | [
"other"
] | 324 | 231 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,584 |
5802f9c010efd1cdcee2fbbb4039a4cb | So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!Initially, each test in that problem is just an array. The maximum size of an array is k. For simplicity, the contents of arrays don't matter. You have n tests — the i-th test is an array of size m_i (1 \le m_i \le k).Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than c_1 arrays of size greater than or equal to 1 (\ge 1), no more than c_2 arrays of size greater than or equal to 2, \dots, no more than c_k arrays of size greater than or equal to k. Also, c_1 \ge c_2 \ge \dots \ge c_k.So now your goal is to create the new testcases in such a way that: each of the initial arrays appears in exactly one testcase; for each testcase the given conditions hold; the number of testcases is minimum possible. Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase. | ['greedy', 'constructive algorithms', 'two pointers', 'sortings', 'data structures', 'binary search'] | n, k = map(int, input().split())
mmm = list(map(int, input().split()))
ccc = [0] + list(map(int, input().split()))
mmm.sort(reverse=True)
ans = [[]]
for m in mmm:
ai = 0
c = ccc[m]
if c <= len(ans[-1]):
ans.append([m])
continue
l = -1
r = len(ans) - 1
while l + 1 < r:
k = (l + r) // 2
if c > len(ans[k]):
r = k
else:
l = k
ans[r].append(m)
print(len(ans))
for ls in ans:
print(len(ls), end=' ')
print(' '.join(map(str, ls)))
| Python | [
"other"
] | 1,268 | 529 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,676 |
4ee194d8dc1d25eb8b186603ee71125e | You are given a line of n colored squares in a row, numbered from 1 to n from left to right. The i-th square initially has the color c_i.Let's say, that two squares i and j belong to the same connected component if c_i = c_j, and c_i = c_k for all k satisfying i < k < j. In other words, all squares on the segment from i to j should have the same color.For example, the line [3, 3, 3] has 1 connected component, while the line [5, 2, 4, 4] has 3 connected components.The game "flood fill" is played on the given line as follows: At the start of the game you pick any starting square (this is not counted as a turn). Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color. | ['dp'] | n = int(raw_input())
cs = map(int, raw_input().split(' '))
# remove consecutive dupes
ds = []
for c in cs:
if len(ds)==0:
ds.append(c)
elif ds[-1] != c:
ds.append(c)
cs = ds
n = len(cs)
def memoize(f):
table = {}
def g(*args):
if args in table:
return table[args]
else:
value = table[args] = f(*args)
return value
return g
def expand_interval(a,b):
'''[a,b] is a subinterval of [0,n).
returns an interval containing [a,b] and all points to the left of a with the same color as a and all points to the right of b with the same color as b.'''
if a < 0:
a = 0
if b >= n:
b = n-1
while a > 0 and cs[a-1] == cs[a]:
a -= 1
while b < n-1 and cs[b+1] == cs[b]:
b += 1
return (a,b)
cache = [[-1 for b in range(n)] for a in range(n)]
#@memoize
def dp(a,b):
''' returns least number of flood fills remaining, assuming the interval [a,b] has already been colored with the same color. '''
a,b = expand_interval(a,b)
if cache[a][b] != -1:
return cache[a][b]
left = expand_interval(a-1,b)
right = expand_interval(a,b+1)
both = expand_interval(a-1,b+1)
if a == 0 and b == n-1:
cache[a][b] = 0
elif a == 0:
cache[a][b] = 1 + dp(*right)
elif b == n-1:
cache[a][b] = 1 + dp(*left)
else:
if cs[a-1] == cs[b+1]:
cache[a][b] = 1 + dp(*both)
else:
cache[a][b] = 1 + min( dp(*left), dp(*right) ) # <- double recursion!
return cache[a][b]
# calculate the longest intervals first so we can avoid the double recursion in dp()
for length in range(n,0,-1):
for a in range(n-length):
dp(*expand_interval(a,a+length))
print min([dp(a,a) for a in range(n)]) | Python | [
"other"
] | 942 | 1,601 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,973 |
71e6ceb75852f4cd437bbf0478e37dc4 | There is a classroom with two rows of computers. There are n computers in each row and each computer has its own grade. Computers in the first row has grades a_1, a_2, \dots, a_n and in the second row — b_1, b_2, \dots, b_n.Initially, all pairs of neighboring computers in each row are connected by wire (pairs (i, i + 1) for all 1 \le i < n), so two rows form two independent computer networks.Your task is to combine them in one common network by connecting one or more pairs of computers from different rows. Connecting the i-th computer from the first row and the j-th computer from the second row costs |a_i - b_j|.You can connect one computer to several other computers, but you need to provide at least a basic fault tolerance: you need to connect computers in such a way that the network stays connected, despite one of its computer failing. In other words, if one computer is broken (no matter which one), the network won't split in two or more parts.That is the minimum total cost to make a fault-tolerant network? | ['brute force', 'data structures', 'implementation'] | def find(A,N,k,c):
num = float('inf')
for i in range(c,N-c):
num = min(num,abs(A[i]-k))
return num
for p in range(int(input())):
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
# if p==393:
# print("|".join([str(x) for x in A])+"|"+"|".join([str(x) for x in B]))
ans = min(find(A,N,B[0],1)+find(A,N,B[-1],1)+find(B,N,A[0],1)+find(B,N,A[-1],1),abs(A[0]-B[-1])+abs(A[-1]-B[0]),abs(A[0]-B[0])+abs(A[-1]-B[-1]))
l = []
for x in [A[0],A[-1]]:
l.append(abs(x-B[0])+abs(x-B[-1]))
for x in [B[0],B[-1]]:
l.append(abs(x-A[0])+abs(x-A[-1]))
l[0] += find(B,N,A[-1],0)
l[1] += find(B,N,A[0],0)
l[2] += find(A,N,B[-1],0)
l[3] += find(A,N,B[0],0)
l.append(abs(A[0]-B[0]))
l.append(abs(A[-1]-B[-1]))
l.append(abs(A[0]-B[-1]))
l.append(abs(A[-1]-B[0]))
l[4] += find(B,N,A[-1],1)+find(A,N,B[-1],1)
l[5] += find(B,N,A[0],1)+find(A,N,B[0],1)
l[6] += find(B,N,A[-1],1)+find(A,N,B[0],1)
l[7] += find(B,N,A[0],1)+find(A,N,B[-1],1)
print(min(ans,min(l)))
| Python | [
"other"
] | 1,075 | 1,008 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 957 |
b1f78130d102aa5f425e95f4b5b3a9fb | Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. | ['implementation'] | h = input()
a = input()
n = int(input())
d = dict()
for i in range(n):
arr = input().split()
mark = (h if arr[1] == 'h' else a) + ' ' + arr[2]
if mark not in d:
d[mark] = 0
if d[mark] < 2:
d[mark] += 1 if arr[3] == 'y' else 2
if d[mark] >= 2:
print(mark, arr[0]) | Python | [
"other"
] | 565 | 314 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,134 |
13fbcd245965ff6d1bf08915c4d2a2d3 | There are n segments [l_i, r_i] for 1 \le i \le n. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.To optimize testing process you will be given multitest. | ['sortings'] | def get():
return list(map(int, input().split(' ')))
def d():
n = int(input())
t = [];
for i in range(n):
t.append(get() + [i])
t.sort();
i = 0
r = t[0][1]
ans = ["2"]*n
while(i < n and t[i][0] <= r):
ans[t[i][2]] = "1"
r = max(r, t[i][1])
i+=1
if "2" in ans:
print(" ".join(ans))
else:
print(-1)
for i in range(int(input())):
d() | Python | [
"other"
] | 374 | 380 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,137 |
c8e71b942fac5c99c041ce032fbb9e4c | You are given a permutation, p_1, p_2, \ldots, p_n.Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A.For each i from 1 to n: Add p_i to A. If the i-th position contains a bomb, remove the largest element in A.After the process is completed, A will be non-empty. The cost of the configuration of bombs equals the largest element in A.You are given another permutation, q_1, q_2, \ldots, q_n.For each 1 \leq i \leq n, find the cost of a configuration of bombs such that there exists a bomb in positions q_1, q_2, \ldots, q_{i-1}. For example, for i=1, you need to find the cost of a configuration without bombs, and for i=n, you need to find the cost of a configuration with bombs in positions q_1, q_2, \ldots, q_{n-1}. | ['data structures', 'two pointers'] | import sys
input = sys.stdin.readline
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
seg_el=1<<(N.bit_length()) # Segment treeの台の要素数
SEG=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
LAZY=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
def indexes(L,R): # 遅延伝搬すべきノードのリストを下から上の順に返す. (つまり, updateやgetvaluesで見るノードより上にあるノードたち)
INDLIST=[]
R-=1
L>>=1
R>>=1
while L!=R:
if L>R:
INDLIST.append(L)
L>>=1
else:
INDLIST.append(R)
R>>=1
while L!=0:
INDLIST.append(L)
L>>=1
return INDLIST
def adds(l,r,x): # 区間[l,r)を +x 更新
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]: # 遅延伝搬. 上から更新していく. (ただし, 今回はうまくやるとこの部分を省ける. addはクエリの順番によらないので. addではなく, updateの場合必要)
if LAZY[ind]!=0:
plus_lazy=LAZY[ind]
SEG[ind<<1]+=plus_lazy
SEG[1+(ind<<1)]+=plus_lazy
LAZY[ind<<1]+=plus_lazy
LAZY[1+(ind<<1)]+=plus_lazy
LAZY[ind]=0
while L!=R:
if L > R:
SEG[L]+=x
LAZY[L]+=x
L+=1
L//=(L & (-L))
else:
R-=1
SEG[R]+=x
LAZY[R]+=x
R//=(R & (-R))
for ind in UPIND:
SEG[ind]=min(SEG[ind<<1],SEG[1+(ind<<1)]) # 最初の遅延伝搬を省いた場合, ここを変える
def getvalues(l,r): # 区間[l,r)に関するminを調べる
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]: # 遅延伝搬
if LAZY[ind]!=0:
plus_lazy=LAZY[ind]
SEG[ind<<1]+=plus_lazy
SEG[1+(ind<<1)]+=plus_lazy
LAZY[ind<<1]+=plus_lazy
LAZY[1+(ind<<1)]+=plus_lazy
LAZY[ind]=0
ANS=1<<31
while L!=R:
if L > R:
ANS=min(ANS , SEG[L])
L+=1
L//=(L & (-L))
else:
R-=1
ANS=min(ANS , SEG[R])
R//=(R & (-R))
return ANS
from operator import itemgetter
NOW=0
P_INV=sorted([(p,i) for i,p in enumerate(P)],key=itemgetter(0),reverse=True)
adds(P_INV[NOW][1],N,1)
ANS=[NOW]
for q in Q[:-1]:
adds(q-1,N,-1)
while True:
if getvalues(0,seg_el-1)<getvalues(N-1,N):
ANS.append(NOW)
break
else:
NOW+=1
adds(P_INV[NOW][1],N,1)
#print([getvalues(i,i+1) for i in range(N)],q,NOW)
print(*[N-a for a in ANS])
| Python | [
"other"
] | 1,000 | 2,681 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,224 |
874e22d4fd8e35f7e0eade2b469ee5dc | You are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: The first character '*' in the original string should be replaced with 'x'; The last character '*' in the original string should be replaced with 'x'; The distance between two neighboring replaced characters 'x' must not exceed k (more formally, if you replaced characters at positions i and j (i < j) and at positions [i+1, j-1] there is no "x" symbol, then j-i must be no more than k). For example, if n=7, s=.**.*** and k=3, then the following strings will satisfy the conditions above: .xx.*xx; .x*.x*x; .xx.xxx. But, for example, the following strings will not meet the conditions: .**.*xx (the first character '*' should be replaced with 'x'); .x*.xx* (the last character '*' should be replaced with 'x'); .x*.*xx (the distance between characters at positions 2 and 6 is greater than k=3). Given n, k, and s, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions. | ['greedy', 'implementation'] | import sys
lines = list(map(str.strip, sys.stdin.readlines()))
def replacefirstlast(s):
result = 0
for i in range(len(s)):
if s[i] == '*':
s[i] = 'x'
result+=1
break
for i in range(len(s)-1,-1,-1):
if s[i] =='*':
s[i] = 'x'
result +=1
break
return (s, result)
for i in range(1, len(lines), 2 ):
n, k = map(int, lines[i].split(" "))
s = list(lines[i+1])
s, result = replacefirstlast(s)
# print(s)
for j in range(len(s)):
if s[j] == 'x' and 'x' not in s[j+1:j+k+1]:
for l in range(min(j + k, len(s)-1), j, -1):
if s[l] == '*':
s[l] = 'x'
result += 1
break
# print(s)
print(result)
# print("\n\n")
| Python | [
"other"
] | 1,260 | 861 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,283 |
2deed55e860bd69ff0ba3973a1d73cac | You are given n integers a_1, a_2, \ldots, a_n. Find the maximum value of max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r) over all pairs (l, r) of integers for which 1 \le l < r \le n. | ['greedy'] | n=int(input())
for i in range(n):
j=int(input())
res=0
a=list(map(int,input().split()))
for i in range(j-1):
if((a[i]*a[i+1])>res):
res=a[i]*a[i+1]
else:
pass
print(res)
| Python | [
"other"
] | 241 | 233 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,824 |
097e35b5e9c96259c54887158ebff544 | One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold: x occurs in sequence a. Consider all positions of numbers x in the sequence a (such i, that ai = x). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all x that meet the problem conditions. | ['implementation', 'sortings'] | import sys
n = int(sys.stdin.readline())
a=list(map(int,sys.stdin.readline().split()))
from collections import defaultdict
d=defaultdict(list)
for i in range(len(a)):
d[a[i]]+=[i]
for v in d.values():
v.sort()
ans=[]
c=0
for k,v in d.items():
if len(v)>1:
c=v[1]-v[0]
flag=0
for j in range(1,len(v)-1):
if(v[j+1]-v[j]!=c):
flag=1
break
if flag==0:
ans.append([k,c])
else:
ans.append([k,0])
print(len(ans))
ans.sort()
for i,j in ans:
print(i,end=" ")
print(j) | Python | [
"other"
] | 446 | 553 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,874 |
3270260030fc56dda3e375af4dad9330 | Lunar New Year is approaching, and you bought a matrix with lots of "crosses".This matrix M of size n \times n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 \leq i, j \leq n. We define a cross appearing in the i-th row and the j-th column (1 < i, j < n) if and only if M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = 'X'.The following figure illustrates a cross appearing at position (2, 2) in a 3 \times 3 matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix M. Two crosses are different if and only if they appear in different rows or columns. | ['implementation'] | n = int(input())
matrix_array = []
for i in range(0, n):
next = input()
matrix_array.append(next)
matrix_array1 = [[0]*n for _ in range(n)]
for i in range(0, n):
for j in range(0, n):
matrix_array1[i][j] = matrix_array[i][j]
count = 0
for i in range(1, n-1):
for j in range(1, n-1):
if (matrix_array1[i][j] == 'X' and matrix_array1[i-1][j-1] == 'X' and matrix_array1[i+1][j-1] == 'X' and matrix_array1[i-1][j+1] == 'X' and matrix_array1[i+1][j+1] == 'X'):
count = count + 1
print(count)
| Python | [
"other"
] | 786 | 534 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,414 |
165467dd842b47bc2d932b04e85ae8d7 | By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. | ['data structures', 'brute force'] |
n, m = map(int, input().split())
a = list(map(int, input().split()))
for i in range(m):
t, l, r = map(int, input().split())
if t == 1:
a[l-1] = r
else:
s = 0
fiba = fibb = 1
for i in range(l-1, r):
s += fiba * a[i]
fiba, fibb = fibb, fiba + fibb
print(s % 1000000000)
| Python | [
"other"
] | 635 | 347 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,051 |
b4a4448af5b61fe5a8467a8d0e12fba8 | This is the hard version of the problem. The only difference is that in this version n \leq 200000. You can make hacks only if both versions of the problem are solved.There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i can be negative, meaning that potion will decrease will health.You start with 0 health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink? | ['data structures', 'greedy'] | from heapq import *
n = int(input())
a = [int(x) for x in input().split()]
h = 0
hq = []
ans = 0
for x in a:
if x >= 0:
h += x
ans += 1
elif h + x >= 0:
h += x
heappush(hq, x)
ans += 1
elif hq and hq[0] < x:
h += -heapreplace(hq, x) + x
#print(h, ans, hq)
print(ans)
| Python | [
"other"
] | 687 | 332 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,405 |
19d9a438bf6353638b08252b030c407b | Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - pi). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem. | ['data structures', 'implementation'] | from itertools import starmap
def main():
n, q = map(int, input().split())
a = list(range(n + 1))
flipped = False
start = 0
end = n
for _ in range(q):
cmd, *args = map(int, input().split())
if cmd == 1:
p = args[0]
if p > end-start-p:
flipped = not flipped
p = end-start-p
if flipped:
a[end-p:end-2*p:-1] = starmap(
lambda a, b: a+n-b,
zip(a[end-p:end-2*p:-1], a[end-p:end])
)
end -= p
else:
start += p
a[start:start+p] = starmap(
lambda a, b: a-b,
zip(a[start:start+p], a[start:start-p:-1])
)
else:
l, r = args
if flipped:
l, r = end-start-r, end-start-l
print(a[start + r] - a[start + l])
if __name__ == '__main__':
main()
| Python | [
"other"
] | 861 | 993 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,652 |
551e66a4b3da71682652d84313adb8ab | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | ['data structures', 'binary search', 'greedy'] | import sys
d = {}
n= int( sys.stdin.readline().strip('\n\r ') )
nn=0
spare=''
first=True
turnon=False
stoks=['']
while nn<n:
if len(stoks)==1:
stoks = (stoks[0] + sys.stdin.read(2048)).strip('\n\r').split(' ')
s = stoks.pop(0)
if len(s)==0: continue
j = int(s)
if j in d: d[j] += 1
else: d[j] = 1
nn += 1
nd = len(d)
if nd < 3:
print( 0 )
exit(0)
all = [[0,0]]*(nd+1)
i=0
nmulti=0
for k in d:
all[i] = [d[k],k]
if all[i][0]>1: nmulti+=1
i+=1
all.sort()
nout = 0
snomen = [ [0,0,0] ]*((n+10)/3)
lenall=len(all)
while all[-3][0]>0:
if all[-3][0]>all[-4][0]:
nToAdd = all[-3][0] - all[-4][0]
i1, i2, i3, i4 = range(1,5)
else:
i3 = 4
i4 = lenall
plateau = all[-i3][0]
while i4>(i3+1):
mid = (i4+i3)/2
if all[-mid][0]==plateau: i3 = mid
else : i4 = mid
if all[-2][0]==all[-i3][0]: i2 = i3-1
else : i2 = 2
if all[-1][0]==all[-i2][0]: i1 = i2-1
else : i1 = 1
nToAdd = 1
snoman = [ all[-i1][1], all[-i2][1], all[-i3][1] ]
snoman.sort()
snomen[nout:nout+nToAdd] = [ snoman ]*nToAdd
for i in (i1,i2,i3): all[-i][0] -= nToAdd
nout += nToAdd
print( nout )
for i in range(nout):
print( '%d %d %d' % (snomen[i][2], snomen[i][1], snomen[i][0],) )
########################################################################
| Python | [
"other"
] | 580 | 1,392 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,576 |
c37604d5d833a567ff284d7ce5eda059 | Polycarp doesn't like integers that are divisible by 3 or end with the digit 3 in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than 0) integers which he likes: 1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots. Output the k-th element of this sequence (the elements are numbered from 1). | ['implementation'] | t=int(input())
for i in range(t):
k=int(input())
counter =0
a=0
while(counter <k):
a+=1
if(a%3!=0) and(a%10!=3):
counter+=1
print(a)
| Python | [
"other"
] | 414 | 196 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,177 |
fc29e8c1a9117c1dd307131d852b6088 | It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are: 12 = 1 + 2 + 4 + 5,17 = 1 + 2 + 4 + 8 + 2,7 = 1 + 2 + 4,1 = 1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options! | ['binary search', 'greedy'] | from collections import Counter
from math import log2, ceil
MAX = ceil(log2(10 ** 12))
def can():
seqs_cp = Counter(seqs)
for num in set(nums):
cnt = nums[num]
while cnt != 0 and num < 2 ** 63:
dif = min(cnt, seqs_cp[num])
cnt -= dif
seqs_cp[num] -= dif
num *= 2
if cnt > 0:
return False
return True
n = int(input())
seq = list(map(int, input().split()))
cnt = Counter(seq)
nums = Counter(seq)
seqs = Counter()
cur_cnt = cnt[1]
cur_pow = 1
while cur_cnt != 0:
nums[cur_pow] -= cur_cnt
cur_pow *= 2
if cur_cnt > cnt[cur_pow]:
seqs[cur_pow // 2] = cur_cnt - cnt[cur_pow]
cur_cnt = cnt[cur_pow]
for num in set(nums):
addition = nums[num]
nums[num] = 0
nums[2 ** int(log2(num))] += addition
# remove elements with zero count
nums -= Counter()
seqs -= Counter()
cur_len = sum(seqs[num] for num in set(seqs))
res = []
cur_pow = 1
while can():
res.append(cur_len)
while seqs[cur_pow] == 0 and cur_pow <= 2 ** 63:
cur_pow *= 2
if cur_pow > 2 ** 63:
break
other_pow = 1
while other_pow <= cur_pow:
nums[other_pow] += 1
other_pow *= 2
seqs[cur_pow] -= 1
cur_len -= 1
print(-1 if len(res) == 0 else ' '.join(map(str, reversed(res))))
| Python | [
"other"
] | 677 | 1,331 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 692 |
c9155ff3aca437eec3c4e9cf95a2d62c | All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor! | ['data structures', 'binary search', 'sortings', 'greedy'] | from heapq import heappop, heappush
n, k = [int(x) for x in input().split()]
cs = []
for i in range(n):
l, r = [int(x) for x in input().split()]
cs.append((l, r, i+1))
cs.sort()
h = []
for i in range(k-1):
heappush(h, [cs[i][1], cs[i][2]])
lcs = h[:]
l = -1
push_i = k-1
for i in range(k-1, n):
heappush(h, [cs[i][1], cs[i][2]])
d = h[0][0] - cs[i][0]
if d > l:
l = d
if push_i != k-1:
heappop(lcs)
for j in range(push_i, i):
heappush(lcs, [cs[j][1], cs[j][2]])
heappop(lcs)
heappush(lcs, [cs[i][1], cs[i][2]])
push_i = i+1
heappop(h)
print(l+1)
if l == -1:
for i in range(1, k+1):
print(i, end=' ')
else:
for r, i in lcs:
print(i, end=' ')
| Python | [
"other"
] | 700 | 774 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 547 |
39f5e934bf293053246bd3faa8061c3b | Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: the length of the password must be equal to n, the password should consist only of lowercase Latin letters, the number of distinct symbols in the password must be equal to k, any two consecutive symbols in the password must be distinct. Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions. | ['implementation', '*special'] | n,k=map(int,input().split())
a=[]
b='a'
for i in range(k):
a.append(chr(ord(b)+i))
j=0
for i in range(n):
print(a[j],end='')
j=j+1
if j==len(a):
j=0
| Python | [
"other"
] | 581 | 182 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,745 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 40