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
listlengths 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55f0ecc597e6e40256a14debcad1b878
|
The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array a_1, a_2, \dots, a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, \dots, a_n is described by an array b_1, b_2, \dots, b_n that b_i indicates the color of a_i (0 for white and 1 for black).According to a painting assignment b_1, b_2, \dots, b_n, the array a is split into two new arrays a^{(0)} and a^{(1)}, where a^{(0)} is the sub-sequence of all white elements in a and a^{(1)} is the sub-sequence of all black elements in a. For example, if a = [1,2,3,4,5,6] and b = [0,1,0,1,0,0], then a^{(0)} = [1,3,5,6] and a^{(1)} = [2,4].The number of segments in an array c_1, c_2, \dots, c_k, denoted \mathit{seg}(c), is the number of elements if we merge all adjacent elements with the same value in c. For example, the number of segments in [1,1,2,2,3,3,3,2] is 4, because the array will become [1,2,3,2] after merging adjacent elements with the same value. Especially, the number of segments in an empty array is 0.Homer wants to find a painting assignment b, according to which the number of segments in both a^{(0)} and a^{(1)}, i.e. \mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)}), is as large as possible. Find this number.
|
['constructive algorithms', 'data structures', 'dp', 'greedy', 'implementation']
|
import sys
input = lambda: sys.stdin.readline().rstrip("\n\r")
def solve():
n = int(input())
a = [0] + list(map(int, input().split()))
pos = [n + 1] * (n + 1)
nxt = [None] * (n + 1)
for i in range(n, -1, -1):
nxt[i] = pos[a[i]]
pos[a[i]] = i
ans = 0
black = [0]
white = [0]
for i in range(1, n + 1):
if a[i] != a[black[-1]] and a[i] == a[white[-1]]:
ans += 1
black.append(i)
elif a[i] != a[white[-1]] and a[i] == a[black[-1]]:
ans += 1
white.append(i)
elif a[i] != a[white[-1]] and a[i] != a[black[-1]]:
ans += 1
if nxt[white[-1]] < nxt[black[-1]]:
white.append(i)
else:
black.append(i)
else:
black.append(i)
print(ans)
for _ in range(1):
solve()
|
Python
|
[
"other"
] | 1,490
| 918
| 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,779
|
f92757d0369327f63185aca802616ad7
|
You have an n × m rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: each cell must be painted some color (the colors are marked by uppercase Latin letters); we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square. Given n and m, find lexicographically minimum coloring of the table that meets the described properties.
|
['constructive algorithms', 'greedy']
|
n, m = map(int, raw_input().split())
a = [['' for j in xrange(m)] for i in xrange(n)]
b = [[0 for j in xrange(m+1)] for i in xrange(n+1)]
alpha = 'ABCDEFGH'
for i in xrange(n):
for j in xrange(m):
if a[i][j]:
continue
c, d = 0, 1
while 1:
if b[i][j] & d:
c = c + 1
d = d + d
else:
break
e = d - 1
f = d + d - 1
k = j + 1
while k < m:
if (b[i][k] & f) != e or a[i][k]:
break
k = k + 1
l = min(n - i, k - j)
for y in xrange(i, i+l):
for x in xrange(j, j+l):
a[y][x] = alpha[c]
for y in xrange(i, i+l):
b[y][j+l] |= d
if j > 0:
for y in xrange(i, i+l):
b[y][j-1] |= d
for x in xrange(j, j+l):
b[i+l][x] |= d
if i > 0:
for x in xrange(j, j+l):
b[i-1][x] |= d
for i in xrange(n):
print ''.join(a[i])
|
Python
|
[
"other"
] | 556
| 1,039
| 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
}
| 176
|
5c63f91eb955cb6c3172cb7c8f78976c
|
Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
|
['implementation', 'sortings', 'greedy']
|
n =input()
arr = map(int,raw_input().split())
b=[0]*10000
for i in arr:
b[i]+=1
m = max(arr)
ans=[]
for i in range(10000):
if i<m and b[i]!=0:
ans.append(i)
b[i]-=1
ans.append(m)
for i in range(10000,-1,-1):
if i<m and b[i]!=0:
ans.append(i)
b[i]-=1
print len(ans)
for i in ans:
print i,
|
Python
|
[
"other"
] | 551
| 336
| 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,240
|
3fe51d644621962fe41c32a2d90c7f94
|
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.Both the given array and required subset may contain equal values.
|
['dp', 'implementation', 'greedy', 'brute force']
|
#!/bin/python3
t = int(input())
while t > 0:
n = int(input())
array = list(map(int, input().split()))
if n == 1:
# 1 is 00000001 in binary , and 2 is 00000010
# for future reference 1 bitwise AND 2 is false
# that's a fancy way to say array[0] == 1
if array[0] & 1:
print(-1)
else:
print("1\n1")
else:
# nb: every fucking odd number has 1 in the
# very right digit in binary i.e. 3 is 00000011
# 5 is 00000101 and so on....
if (array[0] & 1) and (array[1] & 1):
print("2\n1 2\n")
else:
print(1)
if array[0] & 1:
print(2)
else:
print(1)
t -= 1
|
Python
|
[
"other"
] | 276
| 746
| 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,290
|
d3c8c1e32dcf4286bef19e9f2b79c8bd
|
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≤ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?
|
['sortings']
|
n, a, b = [int(s) for s in input().split(' ')]
h = [int(x) for x in input().split(' ')]
h.sort()
print(h[b] - h[b - 1])
|
Python
|
[
"other"
] | 657
| 119
| 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,108
|
a30b5ff6855dcbad142f6bcc282601a0
|
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.
|
['two pointers', 'implementation', 'sortings', 'data structures', 'binary search', 'brute force']
|
R=lambda:(input(),sorted(map(int,raw_input().split())))
n,a=R()
m,b=R()
x,y=n*3,m*3
t=(x-y,x,y)
i,j=0,0
for v in sorted(a+b)+[1<<50]:
while i<n and v>a[i]:i+=1;x-=1
while j<m and v>b[j]:j+=1;y-=1
t=max(t,(x-y,x,y))
print '%d:%d'%t[1:]
|
Python
|
[
"other"
] | 589
| 248
| 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,878
|
b87a90f2b4822e59d66b06886a5facad
|
This is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.You are given an array [a_1, a_2, \ldots a_n] consisting of integers -1 and 1. You have to build a partition of this array into the set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] with the following property: Denote the alternating sum of all elements of the i-th segment as s_i: s_i = a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}. For example, the alternating sum of elements of segment [2, 4] in array [1, 0, -1, 1, 1] equals to 0 - (-1) + 1 = 2. The sum of s_i over all segments of partition should be equal to zero. Note that each s_i does not have to be equal to zero, this property is about sum of s_i over all segments of partition.The set of segments [l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k] is called a partition of the array a of length n if 1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n and r_i + 1 = l_{i+1} for all i = 1, 2, \ldots k-1. In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.
|
['constructive algorithms', 'dp', 'greedy']
|
def alternating_sum(n, a):
alter_sum = 0
for i in range(n):
if i % 2 != 0:
alter_sum -= a[i]
else:
alter_sum += a[i]
return alter_sum
def zero_partition(n, a):
if n % 2 != 0:
return -1
if alternating_sum(n, a) == 0:
return [[1, n]]
segments = []
for i in range(0, n, 2):
if a[i] == a[i+1]:
segments.append([i+1, i+2])
else:
segments.append([i+1, i+1])
segments.append([i+2, i+2])
return segments
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().strip().split()))
partition = zero_partition(n, a)
if type(partition) == int:
print(partition)
else:
print(len(partition))
for segment in partition:
l, r = segment
print(l, r)
|
Python
|
[
"other"
] | 1,480
| 924
| 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,663
|
bee33afb70e4c3e062ec7980b44cc0dd
|
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n.Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times.Alice wins if she beats Bob in at least \lceil \frac{n}{2} \rceil (\frac{n}{2} rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors: rock beats scissors; paper beats rock; scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers a, b, c, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.
|
['dp', 'constructive algorithms', 'greedy']
|
def ans(n):
if(n%2==0):
return int(n/2)
else:
if(int(n//2)%2==0):
return int(n//2)+1
else:
return int(n//2)+1
t=int(input())
for i in range(t):
n=int(input())
abc=list(map(int,input().split()))
op=input()
r=0
p=0
s=0
for j in range(n):
if(op[j]=='R'):
r+=1
elif(op[j]=='P'):
p+=1
else:
s+=1
ll=list()
for j in range(n):
ll.append('Q')
wins=0
wins=min(abc[1],r)+min(abc[2],p)+min(abc[0],s)
if(wins>=ans(n)):
print("YES")
for j in range(n):
if(op[j]=='R'):
if(abc[1]>0):
ll[j]='P'
abc[1]-=1
if(op[j]=='P'):
if(abc[2]>0):
ll[j]='S'
abc[2]-=1
if(op[j]=='S'):
if(abc[0]>0):
ll[j]='R'
abc[0]-=1
for j in range(n):
if(ll[j]=='Q'):
if(abc[0]>0):
ll[j]='R'
abc[0]-=1
elif(abc[1]>0):
ll[j]='P'
abc[1]-=1
elif(abc[2]>0):
ll[j]='S'
abc[2]-=1
for j in range(n):
print(ll[j],end="")
print()
else:
print("NO")
|
Python
|
[
"other"
] | 827
| 1,453
| 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
}
| 908
|
082eec813f870357dbe3c5abec6a2b52
|
This is the harder version of the problem. In this version, 1 \le n, m \le 2\cdot10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers a=[a_1,a_2,\dots,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]: [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list); [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences. Suppose that an additional non-negative integer k (1 \le k \le n) is given, then the subsequence is called optimal if: it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k; and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal. Recall that the sequence b=[b_1, b_2, \dots, b_k] is lexicographically smaller than the sequence c=[c_1, c_2, \dots, c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 \le t \le k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example: [10, 20, 20] lexicographically less than [10, 21, 1], [7, 99, 99] is lexicographically less than [10, 21, 1], [10, 21, 0] is lexicographically less than [10, 21, 1]. You are given a sequence of a=[a_1,a_2,\dots,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 \le k \le n, 1 \le pos_j \le k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
|
['greedy', 'constructive algorithms', 'sortings', 'data structures', 'binary search']
|
# Binary Indexed Tree (Fenwick Tree)
class BIT():
"""一点加算、区間取得クエリをそれぞれO(logN)で答える
add: i番目にvalを加える
get_sum: 区間[l, r)の和を求める
i, l, rは0-indexed
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def _sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def add(self, i, val):
"""i番目にvalを加える"""
i = i + 1
while i <= self.n:
self.bit[i] += val
i += i & -i
def get_sum(self, l, r):
"""区間[l, r)の和を求める"""
return self._sum(r) - self._sum(l)
def bisect_left(self, val):
"""[0, r)の和がval以下になるときの最小のrを求める"""
sum_ = 0
pos = 0
bit_length = (n+1).bit_length()
for i in range(bit_length, -1, -1):
k = pos + (1 << i)
if k < self.n + 1 and sum_ + self.bit[k] < val:
sum_ += self.bit[k]
pos += 1 << i
return pos + 1
from operator import itemgetter
n = int(input())
a = list(map(int, input().split()))
m = int(input())
info = [list(map(int, input().split())) + [i] for i in range(m)]
b = list(zip(a, range(len(a))))
b = sorted(b, key = itemgetter(0), reverse = True)
info = sorted(info, key = itemgetter(0))
bit = BIT(n)
ans = [0]*m
cnt = 0
for i in range(m):
k, pos, ind = info[i]
while cnt < k:
bit.add(b[cnt][1], 1)
cnt += 1
ans[ind] = a[bit.bisect_left(pos)-1]
for i in ans:
print(i)
|
Python
|
[
"other"
] | 2,426
| 1,511
| 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,737
|
88d54818fd8bab2f5d0bd8d95ec860db
|
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.
|
['data structures', 'sortings', 'greedy']
|
n, k1, k2 = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
k = k1+k2
C = [abs(x - y) for x, y in zip(A, B)]
E = sum([x**2 for x in C])
if k == 0:
print(E)
else:
while E > 0 and k>0:
C.sort(reverse=True)
C[0] -= 1
k -= 1
E = sum([x**2 for x in C])
if k%2 == 0:
print(E)
else:
print(E+1)
|
Python
|
[
"other"
] | 411
| 363
| 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,977
|
d174982b64cc9e8d8a0f4b8646f1157c
|
You are given a binary matrix A of size n \times n. Rows are numbered from top to bottom from 1 to n, columns are numbered from left to right from 1 to n. The element located at the intersection of row i and column j is called A_{ij}. Consider a set of 4 operations: Cyclically shift all rows up. The row with index i will be written in place of the row i-1 (2 \le i \le n), the row with index 1 will be written in place of the row n. Cyclically shift all rows down. The row with index i will be written in place of the row i+1 (1 \le i \le n - 1), the row with index n will be written in place of the row 1. Cyclically shift all columns to the left. The column with index j will be written in place of the column j-1 (2 \le j \le n), the column with index 1 will be written in place of the column n. Cyclically shift all columns to the right. The column with index j will be written in place of the column j+1 (1 \le j \le n - 1), the column with index n will be written in place of the column 1. The 3 \times 3 matrix is shown on the left before the 3-rd operation is applied to it, on the right — after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations: Select any element A_{ij} and assign it with new value A_{ij} \oplus 1. In other words, the value of (A_{ij} + 1) \bmod 2 will have to be written into element A_{ij}. Each application of this xor-operation costs one burl. Note that the 4 shift operations — are free. These 4 operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the A matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, A_{ij} = 1 if i = j and A_{ij} = 0 otherwise).
|
['brute force', 'constructive algorithms', 'greedy', 'implementation']
|
#from sys import stdin
#input = stdin.readline
#// - remember to add .strip() when input is a string
t = int(input())
for _ in range(t):
input()
n = int(input())
one_count = 0
grid = []
dp = []
for i in range(n):
row = list(input().strip())
row = list(map(int,row))
one_count += sum(row)
grid.append(row)
temp = []
for p in range(n):
temp.append(0)
dp.append(temp)
max_dp = 0
for i in range(n):
for j in range(n):
if i == 0:
dp[i][j] = grid[i][j]
elif j == 0:
dp[i][j] = dp[i-1][-1] + grid[i][j]
else:
dp[i][j] = dp[i-1][j-1] + grid[i][j]
max_dp = max(max_dp, dp[i][j])
max_dp = min(n, max_dp)
print((n - max_dp) + (one_count - max_dp))
|
Python
|
[
"other"
] | 2,168
| 875
| 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,612
|
19564d66e0de78780f4a61c69f2c8e27
|
Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).
|
['dp']
|
#!/usr/bin/env python3
from __future__ import division, print_function
def counter(a, m, d):
modulo = 1000000007
res = [0, ] * (2*m)
res[0] = 1
shift = 1
for pos in range(len(a), 0, -1):
ptype = pos % 2
cur = int(a[pos-1])
tres = [0, ] * (2*m)
for i in range(10):
if ptype==1 and i == d:
continue
if ptype==0 and i != d:
continue
k = (i * shift) % m
for j in range(m):
if i < cur:
tres[k*2+0] += res[j*2+0]
if tres[k*2+0] >= modulo:
tres[k*2+0] -= modulo
tres[k*2+0] += res[j*2+1]
if tres[k*2+0] >= modulo:
tres[k*2+0] -= modulo
elif i == cur:
tres[k*2+0] += res[j*2+0]
if tres[k*2+0] >= modulo:
tres[k*2+0] -= modulo
tres[k*2+1] += res[j*2+1]
if tres[k*2+1] >= modulo:
tres[k*2+1] -= modulo
else:
tres[k*2+1] += res[j*2+0]
if tres[k*2+1] >= modulo:
tres[k*2+1] -= modulo
tres[k*2+1] += res[j*2+1]
if tres[k*2+1] >= modulo:
tres[k*2+1] -= modulo
k = k+1 if k+1<m else 0
res = tres
shift = (shift * 10) % m
return res[0]
def solver(ifs):
m, d = list(map(int, ifs.readline().split()))
a = ifs.readline().strip()
b = ifs.readline().strip()
res = counter(b, m, d)
if a != '0':
a = str(int(a) - 1)
if len(a) < len(b):
a = '0' + a
modulo = 1000000007
res = res + modulo - counter(a, m, d)
res %= modulo
print(res)
def main():
import sys
if sys.version_info.major == 3:
from io import StringIO as StreamIO
else:
from io import BytesIO as StreamIO
with StreamIO(sys.stdin.read()) as ifs, StreamIO() as ofs:
_stdout = sys.stdout
sys.stdout = ofs
solver(ifs)
sys.stdout = _stdout
sys.stdout.write(ofs.getvalue())
return 0
if __name__ == '__main__':
main()
|
Python
|
[
"other"
] | 576
| 2,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
}
| 1,334
|
8a4a46710104de78bdf3b9d5462f12bf
|
One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.
|
['implementation', 'brute force']
|
read = lambda: map(int, input().split())
xy = [[0]*1002 for i in range(1002)]
n, m = read()
for i in range(m):
x, y = read()
for j in range(x-1, x+2):
for k in range(y-1, y+2):
xy[j][k] += 1
if xy[j][k] is 9:
print(i+1)
exit()
print(-1)
|
Python
|
[
"other"
] | 792
| 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,272
|
63c2142461c93ae4c962eac1ecb5b192
|
Given three distinct integers a, b, and c, find the medium number between all of them.The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of 5,2,6 is 5, since the minimum is 2 and the maximum is 6.
|
['implementation', 'sortings']
|
a=int(input())
for i in range(a):
b=list(map(int,input().split()))
c=sorted(b)
print(c[1])
|
Python
|
[
"other"
] | 315
| 106
| 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,438
|
b0561fee6236f0720f737ca41e20e382
|
Nick had received an awesome array of integers a=[a_1, a_2, \dots, a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 \cdot a_2 \cdot \dots a_n of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index i (1 \le i \le n) and do a_i := -a_i - 1.For example, he can change array [3, -1, -4, 1] to an array [-4, -1, 3, 1] after applying this operation to elements with indices i=1 and i=3. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements a_1 \cdot a_2 \cdot \dots a_n which can be received using only this operation in some order.If there are multiple answers, print any of them.
|
['implementation', 'greedy']
|
n = int(input())
if(n>0):
arr = [int(i) for i in input().strip().split(" ")]
maxMin = 0
for i in range(n):
if(arr[i] != -1):
maxMin = i
break
for i in range(n):
if(arr[i]>=0):
arr[i] = (-arr[i]-1)
if(arr[i]<arr[maxMin] and arr[i] != -1):
maxMin = i
if(len(arr)%2 != 0):
if(arr[maxMin] != -1):
arr[maxMin] = -arr[maxMin]-1
else:
arr[maxMin] = 0
arr = [str(i) for i in arr]
print(" ".join(arr))
|
Python
|
[
"other"
] | 1,334
| 433
| 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,654
|
6422a70e686c34b4b9b6b5797712998e
|
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
|
['implementation']
|
n, m, k = map(int, input().split())
cores = [1 for i in range(n)]
cells = [1 for i in range(k)]
info = []
blockings = [0 for i in range(n)]
for i in range(n):
k = list(map(int, input().split()))
for j in range(len(k)):
k[j] -= 1
info.append(k)
for i in range(m):
for j in range(n):
if cores[j] == 0:
continue
cell = info[j][i]
if cell == -1:
continue
if cells[cell] == 0:
cores[j] = 0
blockings[j] = i + 1
continue
for core in range(n):
if core != j:
cell_1 = info[core][i]
if cell_1 == cell and blockings[core] == 0:
cells[cell] = 0
cores[j] = 0
blockings[j] = i + 1
break
for elem in blockings:
print(elem)
|
Python
|
[
"other"
] | 1,401
| 860
| 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,626
|
e4381bd9f22c0e49525cc05cc5cd2399
|
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.
|
['implementation']
|
def coincount(n, S):
f = 0
x = y = 0
i = 0
cross = [0,0,0]
count = 0
while i < n:
cross[0] = cross[1]
cross[1] = cross[2]
cur_m = S[i]
if cur_m == "U":
y += 1
elif cur_m == "R":
x += 1
if x > y: f = -1
elif x < y: f = 1
else: f = 0
cross[2] = f
if cross == [-1, 0, 1] or cross == [1, 0, -1]:
count += 1
i += 1
return count
n = input()
n = int(n)
S = input()
print(coincount(n, S))
|
Python
|
[
"other"
] | 1,303
| 574
| 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,761
|
ddaf86169a79942cefce8e5b5f3d6118
|
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i \ne t_{i + 1} should be satisfied.Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
|
['dp', 'constructive algorithms', 'greedy']
|
n=int(input())
s0=input()
s=[]
res=0
for i in range(len(s0)):
s.append(s0[i])
s.append('B')
for i in range(len(s)-2):
if(s[i]==s[i+1]):
if(s[i]=='R'):
if (s[i+2] == 'R'):
s[i+1]='G'
if (s[i+2] == 'G'):
s[i+1]='B'
if (s[i+2] == 'B'):
s[i+1]='G'
if (s[i] == 'B'):
if (s[i + 2] == 'B'):
s[i + 1] = 'G'
if (s[i + 2] == 'G'):
s[i + 1] = 'R'
if (s[i + 2] == 'R'):
s[i + 1] = 'G'
if (s[i] == 'G'):
if (s[i + 2] == 'G'):
s[i + 1] = 'B'
if (s[i + 2] == 'R'):
s[i + 1] = 'B'
if (s[i + 2] == 'B'):
s[i + 1] = 'R'
res+=1
print(res)
print(''.join(map(str,s[:n])))
|
Python
|
[
"other"
] | 858
| 842
| 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
}
| 530
|
57df7947bb90328f543b984833a78e64
|
Phoenix has n blocks of height h_1, h_2, \dots, h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x. Please help Phoenix build m towers that look beautiful. Each tower must have at least one block and all blocks must be used.
|
['constructive algorithms', 'data structures', 'greedy']
|
from bisect import insort
for _ in range(int(input())):
N,M,X = map(int,input().split())
blocks_heights = map(int,input().split())
if N<M:print("NO");continue
print("YES")
towers = {}
heights = []
smallest_height = 0
smallest_towers = list(range(1,M+1))
s = ""
for block_height in blocks_heights:
smallest_tower_index = smallest_towers.pop()
print(end=f"{s}{smallest_tower_index}");s=" "
new_tower_height = smallest_height + block_height
if new_tower_height in towers:
towers[new_tower_height].append(smallest_tower_index)
else:
insort(heights,-new_tower_height)
towers[new_tower_height] = [smallest_tower_index]
if not smallest_towers:
smallest_height = -heights.pop()
smallest_towers = towers.pop(smallest_height)
print()
|
Python
|
[
"other"
] | 491
| 881
| 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,765
|
5ce39a83d27253f039f0e26045249d99
|
You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.
|
['implementation']
|
def Fuk(f,n,m):
a = []
d = 0
for j in range(0,m):
s = 0
for i in range(0,n):
s = s + int(f[i][j])
a.append(s)
for i in range(0,n):
c = 0
for j in range(0,m):
if int(a[j])-int(f[i][j]) == 0:
break
else:
c = c + 1
if c == m:
print('YES')
break
d = d + 1
if d == n:
print('NO')
[n,m] = [int(x) for x in input().split()]
f = [input() for i in range(0,n)]
Fuk(f,n,m)
|
Python
|
[
"other"
] | 944
| 538
| 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,720
|
8b007a212a940f09a9306b0c0091e2ad
|
There are n houses numbered from 1 to n on a circle. For each 1 \leq i \leq n - 1, house i and house i + 1 are neighbours; additionally, house n and house 1 are also neighbours.Initially, m of these n houses are infected by a deadly virus. Each morning, Cirno can choose a house which is uninfected and protect the house from being infected permanently.Every day, the following things happen in order: Cirno chooses an uninfected house, and protect it permanently. All uninfected, unprotected houses which have at least one infected neighbor become infected. Cirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.Note that every day Cirno always chooses a house to protect before the virus spreads. Also, a protected house will not be infected forever.
|
['greedy', 'implementation', 'sortings']
|
n=int(input())
for i in range(n):
n_,m=list(map(int,input().split()))
arr=sorted(list(map(int,input().split())))
# print(arr)
arr_=[]
arr_.append(n_-arr[-1]+arr[0]-1)
for j in range(m-1):
arr_.append(arr[j+1]-arr[j]-1)
arr_.sort(reverse=True)
# arr_.reverse()
s=0
# print(arr_)
co=0
for j in arr_:
if j>=4*co+1:
# print(j)
# print(arr_)
if j==(4*co+1):
s+=1
else:
s+=j-(4*co+1)
else:
break
co+=1
# print(s)
# if s==0 and m<n_:
# s+=1
print(n_-s)
|
Python
|
[
"other"
] | 920
| 703
| 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
}
| 162
|
55962ef2cf88c87873b996dc54cc1bf1
|
Petya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 \le c_1 \le c_2 \le \ldots \le c_m). It's not allowed to buy a single present more than once.For the i-th friend Petya can either buy them a present j \le k_i, which costs c_j dollars, or just give them c_{k_i} dollars directly.Help Petya determine the minimum total cost of hosting his party.
|
['binary search', 'dp', 'greedy', 'sortings', 'two pointers']
|
for _ in range(int(input())):
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=0
a.sort()
x=0
for i in range(n-1,-1,-1):
if x>=m:
x=m-1
ans+=min(b[a[i]-1],b[x])
x+=1
print(ans)
|
Python
|
[
"other"
] | 623
| 306
| 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
}
| 876
|
a4647cced2dc6adcb0b8abc24f2d7dce
|
Dasha has 10^{100} coins. Recently, she found a binary string s of length n and some operations that allows to change this string (she can do each operation any number of times): Replace substring 00 of s by 0 and receive a coins. Replace substring 11 of s by 1 and receive b coins. Remove 0 from any position in s and pay c coins. It turned out that while doing this operations Dasha should follow the rule: It is forbidden to do two operations with the same parity in a row. Operations are numbered by integers 1-3 in the order they are given above. Please, calculate what is the maximum profit Dasha can get by doing these operations and following this rule.
|
['data structures', 'greedy', 'implementation']
|
import sys
input = sys.stdin.readline
out = []
ssl = []
t = int(input())
for _ in range(t):
n,a,b,c = map(int,input().split())
s = input().strip()
ssl.append(s)
#if ssl[0] == '1111' and _ == 5099:
# print(n,a,b,c,s)
z = [0]
zc = 0
oc = 0
for ch in s:
if ch == '0':
z[-1] += 1
zc += 1
else:
z.append(0)
oc += 1
M1 = sum(max(0, v - 1) for v in z)
if len(z) == 1:
out.append(a if n>=2 else 0)
continue
l = z.pop(0)
r = z.pop()
poss = [0]
#StartOdd
zz = sorted(z)[::-1]
curr = 0
L1 = M1
L2 = 0
Z1 = 0
OL = oc
ZL = zc
while zz and zz[-1] == 0:
zz.pop()
L2 += 1
while zz and zz[-1] == 1:
zz.pop()
Z1 += 1
while True:
if ZL == 0:
break
if L1 > 0:
poss.append(curr + a)
if OL <= 1:
break
if L2 > 0:
if L1 > 0:
curr += a
ZL -= 1
L1 -= 1
if zz:
zz[-1] -= 1
if zz[-1] == 1:
zz.pop()
Z1 += 1
curr += b
L2 -= 1
OL -= 1
else:
curr -= c
ZL -= 1
curr += b
OL -= 1
else:
ZL -= 1
if Z1 == 0:
break
Z1 -= 1
curr -= c
OL -= 1
curr += b
poss.append(curr)
#StartEven
zz = sorted(z)[::-1]
curr = 0
L1 = M1
L2 = 0
Z1 = 0
OL = oc
ZL = zc
while zz and zz[-1] == 0:
zz.pop()
L2 += 1
while zz and zz[-1] == 1:
zz.pop()
Z1 += 1
#print(L2)
good = False
if L2:
OL -= 1
L2 -= 1
curr = b
poss.append(b)
good = True
while good:
#print(curr,L1,L2,Z1,OL,ZL,poss)
if ZL == 0:
break
if L1 > 0:
poss.append(curr + a)
if OL <= 1:
break
if L2 > 0:
if L1 > 0:
curr += a
ZL -= 1
L1 -= 1
if zz:
zz[-1] -= 1
if zz[-1] == 1:
zz.pop()
Z1 += 1
curr += b
L2 -= 1
OL -= 1
else:
curr -= c
ZL -= 1
curr += b
OL -= 1
else:
ZL -= 1
if Z1 == 0:
break
Z1 -= 1
curr -= c
OL -= 1
curr += b
poss.append(curr)
#print()
out.append(max(poss))
print('\n'.join(map(str,out)))
|
Python
|
[
"other"
] | 731
| 3,253
| 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
}
| 721
|
ffc96dc83a6fde2e83e07671a8d8ed41
|
You are given an array a_1, a_2, \dots, a_n, which is sorted in non-descending order. You decided to perform the following steps to create array b_1, b_2, \dots, b_n: Create an array d consisting of n arbitrary non-negative integers. Set b_i = a_i + d_i for each b_i. Sort the array b in non-descending order. You are given the resulting array b. For each index i, calculate what is the minimum and maximum possible value of d_i you can choose in order to get the given array b.Note that the minimum (maximum) d_i-s are independent of each other, i. e. they can be obtained from different possible arrays d.
|
['binary search', 'greedy', 'two pointers']
|
import bisect
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
maxis=[]
minis=[]
for i in a:
v=bisect.bisect_left(b,i)
minis.append(max(0,b[v]-i))
mx=[i for i in b]
for i in range(n-2,-1,-1):
v=bisect.bisect_left(b,a[i+1])
if i+1!=v:
mx[i]=mx[i+1]
else:
mx[i]=b[i]
for i in range(n):
maxis.append(mx[i]-a[i])
print(*minis)
print(*maxis)
|
Python
|
[
"other"
] | 689
| 450
| 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,289
|
93f6404a23bd2ff867d63db9ddf868ff
|
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.He's got a square 2n × 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.The beauty of a 2n × 2n-sized matrix is an integer, obtained by the following algorithm: Find the maximum element in the matrix. Let's denote it as m. If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2n - 1 × 2n - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices. As you can see, the algorithm is recursive.Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.
|
['constructive algorithms', 'implementation', 'sortings', 'greedy']
|
n = input()
ans = 0
l = sorted(map(int, raw_input().split()))[::-1]
pref = [0]*(n+1)
for i in range(n):
pref[i+1] = pref[i] + l[i]
ind = 1
while ind <= n:
ans += pref[ind]
ind <<= 2
print ans
|
Python
|
[
"other"
] | 924
| 203
| 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,088
|
c3a7d82f6c3cf8678a1c7c521e0a5f51
|
Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold: there is no actor in the cell the spotlight is placed to; there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
|
['dp', 'implementation', 'brute force']
|
n, m = map(int, input().split())
plan = [list(map(int, input().split())) for _ in range(n)]
def lc(plan):
cnt = 0
for row in plan:
os = row.count(1)
l = len(row)
if os == 1:
cnt += l - 1
elif os > 1:
ll = row.index(1)
rr = row[::-1].index(1)
cnt += ll + 2*(l-(ll+rr)-os) + rr
return cnt
print(lc(plan) + lc(list(zip(*plan))))
|
Python
|
[
"other"
] | 825
| 421
| 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,636
|
0b9be2f076cfa13cdc76c489bf1ea416
|
Let's call a string good if its length is at least 2 and all of its characters are \texttt{A} except for the last character which is \texttt{B}. The good strings are \texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots. Note that \texttt{B} is not a good string.You are given an initially empty string s_1.You can perform the following operation any number of times: Choose any position of s_1 and insert some good string in that position. Given a string s_2, can we turn s_1 into s_2 after some number of operations?
|
['constructive algorithms', 'implementation']
|
nt = int(input())
for _ in range(nt):
counter = 0
flagb = 0
flaga = 0
s2 = input()
l = len(s2)
for i in range(l-1,-1,-1):
ch = s2[i]
if ch == "B":
flagb = 1
counter += 1
else:
flaga = 1
if i == l-1:
break
if(counter != 0):
counter -= 1
if (flaga == 0 or flagb == 0 or counter != 0):
print("NO")
else:
print("YES")
|
Python
|
[
"other"
] | 572
| 358
| 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,305
|
c4d32fcacffaa5d3a4db6dfa376d0324
|
You are given a sequence b_1, b_2, \ldots, b_n. Find the lexicographically minimal permutation a_1, a_2, \ldots, a_{2n} such that b_i = \min(a_{2i-1}, a_{2i}), or determine that it is impossible.
|
['greedy']
|
import heapq
def restorePermutation(n, A):
ans = []
unUsed = set(list(range(1, 2*n + 1)))
for val in A:
if not 1 <= val <= 2*n: return -1
ans.append(val)
ans.append(-1)
unUsed.remove(val)
minHeapq = [val for val in unUsed]
heapq.heapify(minHeapq)
#idea use BST in future
#use heap for now
for i in range(1, 2*n, 2):
temp = []
while minHeapq and minHeapq[0] < ans[i - 1]:
temp.append(heapq.heappop(minHeapq))
if not minHeapq or (minHeapq and minHeapq[0] < ans[i - 1]):
return -1
ans[i] = heapq.heappop(minHeapq)
while temp:
heapq.heappush(minHeapq, temp.pop())
return ans
testCases = int(input())
while testCases:
n = int(input())
A = [int(val) for val in input().split()]
ans = restorePermutation(n, A)
if ans == -1:
print()
print(ans)
else:
for val in ans:
print(val, end = " ")
testCases -= 1
|
Python
|
[
"other"
] | 213
| 1,034
| 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
}
| 314
|
3800f4d44031aad264e43dc6b490592c
|
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the n consecutive months — in the i-th month the company had income equal to a_i (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the first \lceil \tfrac{n}{2} \rceil months income might have been completely unstable, but then everything stabilized and for the last \lfloor \tfrac{n}{2} \rfloor months the income was the same.Levian decided to tell the directors n-k+1 numbers — the total income of the company for each k consecutive months. In other words, for each i between 1 and n-k+1 he will say the value a_i + a_{i+1} + \ldots + a_{i + k - 1}. For example, if a=[-1, 0, 1, 2, 2] and k=3 he will say the numbers 0, 3, 5.Unfortunately, if at least one total income reported by Levian is not a profit (income \le 0), the directors will get angry and fire the failed accountant.Save Levian's career: find any such k, that for each k months in a row the company had made a profit, or report that it is impossible.
|
['data structures', 'constructive algorithms', 'implementation', 'greedy']
|
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
n, = rl()
a = rl()
x, = rl()
if x >= 0:
if sum(a) + (n // 2) * x > 0:
print(n)
else:
print(-1)
else:
margin = sum(a)
if margin + (1 - n % 2) * x <= 0:
print(-1)
else:
k = n
for i, ai in enumerate(a):
if margin <= 0:
print(-1)
break
max_k_i = (n + 1) // 2 - i + (margin - 1) // (-x)
if max_k_i < k:
k = max_k_i
if i + k >= n:
print(k)
break
margin -= ai
else:
print(-1)
|
Python
|
[
"other"
] | 1,202
| 684
| 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,903
|
c1eb165162df7d602c376d8555d8aef8
|
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:Define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. The two parts do not overlap. The total sum S of the scores of those two parts is maximized. This is the encryption code. Output the sum S, which is the encryption code.
|
['brute force']
|
line = input().split()
n = int(line[0])
p = int(line[1])
a = input().split()
suma = 0
for i in range(n):
a[i] = int(a[i])
suma += a[i]
Max = 0
sum = 0
for i in range(n-1):
sum += a[i]
total = (sum % p) + ((suma-sum) % p)
if (total>Max):
Max = total
print(Max)
|
Python
|
[
"other"
] | 974
| 289
| 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,596
|
926ec28d1c80e7cbe0bb6d209e664f48
|
The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 \le l_i \le r_i \le n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
|
['data structures', 'implementation', 'sortings', 'greedy']
|
#!/usr/bin/python
from collections import deque
def ir():
return int(raw_input())
def ia():
line = raw_input()
line = line.split()
return map(int, line)
n, q = ia()
a = ia(); a.sort(reverse=True)
d = [0 for i in range(n+1)]
for i in range(q):
l, r = ia(); l-=1; r-=1
d[l] += 1; d[r+1] -=1
c = [0 for i in range(n+1)]
s = 0
for i in range(n+1):
s += d[i]
c[i] = s
c.sort(reverse=True)
ans = 0
for i in range(n):
ans += a[i]*c[i]
print ans
|
Python
|
[
"other"
] | 694
| 484
| 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,276
|
0c9f2301629726870a0ab57299773fd6
|
Polycarp bought a new expensive painting and decided to show it to his n friends. He hung it in his room. n of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.It is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the n-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.Polycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three: no (response encoded with 0); yes (response encoded as 1); can't remember (response is encoded with ?). Everyone except the thief either doesn't remember or told the truth. The thief can say anything (any of the three options).Polycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.
|
['implementation']
|
for _ in range(int(input())):
s = input()
ans = 0
ll, rr = 0, len(s)
k = 0
if '0' in s:
rr = s.index('0') + 1
k += 1
if '1' in s:
ll = len(s) - s[::-1].index('1') - 1
k += 2
if k == 3:
print(rr - ll)
elif k == 1:
print(rr)
elif k == 2:
print(rr - ll)
else:
print(len(s))
|
Python
|
[
"other"
] | 1,058
| 394
| 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
}
| 535
|
02b7ff5e0b7f8cd074d9e76251c2725e
|
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.
|
['constructive algorithms']
|
a=int(input())
l=1
r=a
ans=[1]
while(len(ans)!=a):
i=len(ans)
if(i%2==1):
ans.append(r)
r-=1
else:
ans.append(l+1)
l+=1
print(*ans)
|
Python
|
[
"other"
] | 618
| 176
| 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,830
|
5b9aed235094de7de36247a3b2a34e0f
|
One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.
|
['constructive algorithms', 'implementation']
|
n, m = [int(s) for s in input().split()]
c = 0
for i in range (n):
a = [int(s) for s in input().split()]
for j in range(m):
if (a[2*j]+a[2*j+1]) != 0:
c +=1
print(c)
|
Python
|
[
"other"
] | 893
| 197
| 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,555
|
39fd7843558ed2aa6b8c997c2b8a1fad
|
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock.
|
['brute force']
|
from sys import stdin
l2i = lambda l: [int(x) for x in l.strip().split()]
n, m, k = l2i(stdin.readline())
shop = l2i(stdin.readline())
time = 0
while n != 0:
n -= 1
for commodity in l2i(stdin.readline()):
sw = commodity
pos = 0
while shop[0] != sw or pos == 0:
sw, shop[pos] = shop[pos], sw
pos += 1
time += pos
print time
|
Python
|
[
"other"
] | 940
| 405
| 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,592
|
daf675dadc8edcd6734edbf3548eb6bf
|
You are given n elements numbered from 1 to n, the element i has value a_i and color c_i, initially, c_i = 0 for all i.The following operation can be applied: Select three elements i, j and k (1 \leq i < j < k \leq n), such that c_i, c_j and c_k are all equal to 0 and a_i = a_k, then set c_j = 1. Find the maximum value of \sum\limits_{i=1}^n{c_i} that can be obtained after applying the given operation any number of times.
|
['greedy', 'greedy', 'sortings', 'two pointers']
|
n=int(input())
a=list(map(int, input().split()))
b=[[] for i in range(n+1)]
for i in range(n):
b[a[i]].append(i)
c=[]
for i in range(1, n+1):
if len(b[i])>1:
c.append([b[i][0], b[i][-1]])
c=sorted(c, key=lambda x:x[0])
d=[]
ldx=0
rdx=0
f=0
cnt=0
for i in range(len(c)):
if rdx<c[i][1]:
rdx=c[i][1]
d.append(c[i])
i=0
j=0
k=0
while i<len(d):
while i<len(d) and d[j][1]>d[i][0]:
i+=1
i-=1
if i<len(d)-1 and d[i][1]>d[i+1][0]:
f+=1
j=i
else:
if i!=k:
f+=1
cnt+=d[i][1]-d[k][0]-1-f
f=0
i+=1
j=i
k=i
asdf=0
print(cnt)
|
Python
|
[
"other"
] | 546
| 694
| 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,241
|
1b9a204dd08d61766391a3b4d2429df2
|
She is skilled in all kinds of magics, and is keen on inventing new one.—Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has n magical tokens. Their magical power can be represented with positive integers a_1, a_2, \ldots, a_n. Patchouli may perform the following two operations on the tokens. Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens. Reduction: Patchouli chooses a token with an even value of magical power x, removes it and creates a new token with magical power equal to \frac{x}{2}. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.
|
['bitmasks', 'constructive algorithms', 'greedy', 'sortings']
|
for s in[*open(0)][2::2]:b=min(a:=[x&-x for x in
map(int,s.split())]);print(len(a)+min(k:=bin(b)[::-1].find('1')-1,k*a.count(b)))
|
Python
|
[
"other"
] | 836
| 129
| 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,204
|
a26b23f2b667b7cb3d10f2389fa2cb53
|
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?
|
['data structures', 'implementation', 'greedy']
|
s = input()
n = 1
for i in range(1, len(s)):
if s[i] != s[i-1]:
n += 1
mas = [0] * n
col = [0] * n
count = 1
idx = 0
c = s[0]
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
mas[idx] = count
col[idx] = c
idx += 1
count = 1
c = s[i]
mas[idx] = count
col[idx] = c
res = 0
while n > 1:
newlen = n
idx = -1
for i in range(0, n):
if (i == 0) or (i == n - 1):
mas[i] -= 1
elif mas[i] >= 2:
mas[i] -= 2
else:
mas[i] = 0
if mas[i] == 0:
newlen -= 1
else:
if idx >= 0 and col[idx] == col[i]:
mas[idx] += mas[i]
newlen -= 1
else:
idx += 1
mas[idx] = mas[i]
col[idx] = col[i]
type = i % 2
n = newlen
res += 1
print(res)
|
Python
|
[
"other"
] | 770
| 810
| 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
}
| 381
|
6ed24fef3b7f0f0dc040fc5bed535209
|
Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, \ldots, a_{2k-1}, is the array b with elements b_1, b_2, \ldots, b_{k} such that b_i is equal to the median of a_1, a_2, \ldots, a_{2i-1} for all i. Omkar has found an array b of size n (1 \leq n \leq 2 \cdot 10^5, -10^9 \leq b_i \leq 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray?The median of a set of numbers a_1, a_2, \ldots, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, \ldots, c_{2i-1} represents a_1, a_2, \ldots, a_{2i-1} sorted in nondecreasing order.
|
['data structures', 'greedy', 'implementation']
|
def solve(n, a):
prev = a[0]
r = [10 ** 9]
l = [-r[0]]
for i in range(1, n):
if a[i] < prev:
if a[i] < l[-1]:
return False
elif a[i] == l[-1]:
l.pop()
r.append(prev)
elif a[i] > prev:
if a[i] > r[-1]:
return False
elif a[i] == r[-1]:
r.pop()
l.append(prev)
prev = a[i]
return True
t = int(input())
for w in range(t):
n = int(input())
a = list(map(int, input().split()))
if solve(n, a):
print("YES")
else:
print("NO")
|
Python
|
[
"other"
] | 842
| 660
| 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,982
|
3372948de45ea0867e8cc44dff3d635f
|
Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly V ml of water.Petya has got N tanks, i-th of them initially containing ai ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is).Also Petya has got a scoop that can contain up to K ml of water (initially the scoop is empty). This scoop can be used to get some water from some tank, and after that pour it all into some tank (it is impossible to get water from multiple tanks without pouring it, or leave some water in the scoop when pouring it). When Petya tries to get some water from a tank, he gets min(v, K) water, where v is the current volume of water in the tank.Is it possible to obtain a tank with exactly V ml of water using these operations? If it is possible, print a sequence of operations that allows to do it. If there are multiple ways to obtain needed amount of water in some tank, print any of them.
|
['dp', 'implementation', 'greedy']
|
import sys
input = raw_input
range = xrange
n,K,V = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
Acop = A[:]
if (V%K)==0:
asum = sum(A)
if asum>=V:
print 'YES'
for i in range(1,n):
A[0] += A[i]
count = (A[i]+K-1)//K
if count>0:
print count,i+1,1
A[i] = 0
if V!=0:
print V//K,1,2
sys.exit()
else:
print 'NO'
sys.exit()
B = [a%K for a in A]
take = [0]*n
BIG = 5001
found = [-1]*BIG
found[0] = -2
prev = [-1]*BIG
prev[0] = -2
used = [False]*BIG
for i in range(n):
b = B[i]
for j in range(BIG-1):
if found[j]!=-1 and not used[j]:
ind = (b+j)%K
if found[ind]==-1:
found[ind] = i
prev[ind] = j
used[ind] = True
for j in range(BIG):
used[j]=False
if found[V%K]==-1:
print 'NO'
sys.exit()
tanks = []
ind = V%K
while prev[ind]!=-2:
tanks.append(found[ind])
ind = prev[ind]
master = tanks[0]
tanks = set(tanks)
for i in range(n):
if i not in tanks:
other = i
break
else:
other = -1
outp = []
for i in range(n):
if i==master or i==other:
continue
if i in tanks:
A[master] += A[i]
count = (A[i]+K-1)//K
if count>0:
outp.append(" ".join([str(count),str(i+1),str(master+1)]))
take[i] += count
A[i] = 0
else:
A[other] += A[i]
count = (A[i]+K-1)//K
take[i] += count
if count > 0:
outp.append(" ".join([str(count),str(i+1),str(other+1)]))
A[i] = 0
if other==-1:
for i in range(n):
if i!=master:
other=i
break
if A[master]+A[other]<V:
print 'NO'
sys.exit()
elif A[master]+A[other]==V:
print 'YES'
for s in outp:
print s
count = (A[other]+K-1)//K
if count>0:
print count,other+1,master+1
sys.exit()
else:
count = A[other]//K
if count>0:
A[master] += K*(count)
A[other]%=K
outp.append(" ".join([str(count),str(other+1),str(master+1)]))
if A[master]>V:
count = (A[master]-V)//K
if count>0:
outp.append(" ".join([str(count),str(master+1),str(other+1)]))
A[master]-=count*K
A[other]+=count*K
if A[master]==V:
print 'YES'
for s in outp:
print s
else:
print 'NO'
|
Python
|
[
"other"
] | 976
| 2,495
| 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,299
|
a2d4f0182456cedbe85dff97ec0f477e
|
To satisfy his love of matching socks, Phoenix has brought his n socks (n is even) to the sock store. Each of his socks has a color c_i and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color c' (1 \le c' \le n) turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make n/2 matching pairs? Each sock must be included in exactly one matching pair.
|
['greedy', 'sortings', 'two pointers']
|
t=int(input())
# if (t==1):
# try :
# for i in range(t):
# n,l,r=map(int,input().split())
# xx=list(map(int,input().split()))
# score=0
# if(i==529):
# print(i)
# print(l)
# print(r)
# print(xx)
# if(l==0):
# xx.sort()
# for j in range(r-1):
# if(xx[j]==xx[j+1]):
# xx[j]=xx[j+1]=0
# score+=1
# score=(len(xx)-score)
# elif(r==0):
# xx.sort()
# for j in range(l-1):
# if(xx[j]==xx[j+1]):
# xx[j]=xx[j+1]=0
# score+=1
# score=(len(xx)-score)
# elif(l>=r):
# left=xx[:l]
# right=xx[l:]
# left.sort()
# right.sort()
# li=0
# ri=0
# score1=0
# score2=0
# while(ri<r and li<l):
# if(left[li]==right[ri]):
# left[li]=right[ri]=0
# score1+=1
# li+=1
# ri+=1
# elif(left[li]>right[ri]):
# ri+=1
# else:
# li+=1
# for j in range(l-1):
# if(left[j]!=0 and left[j]==left[j+1]):
# # score+=1
# score2+=1
# left[j]=left[j+1]=0
# if(score2==(abs(l-r)/2)):
# break
# score+=(l-score2-score1)
# elif(r>l):
# left=xx[:l]
# right=xx[l:]
# left.sort()
# right.sort()
# li=0
# ri=0
# score1=0
# score2=0
# while(li<l and ri<r):
# if(left[li]==right[ri]):
# left[li]=right[ri]=0
# score1+=1
# li+=1
# ri+=1
# elif(left[li]>right[ri]):
# ri+=1
# else:
# li+=1
# for j in range(r-1):
# if(right[j]!=0 and right[j]==right[j+1]):
# # score+=1
# score2+=1
# right[j]=right[j+1]=0
# if(score2==(abs(l-r)/2)):
# break
# score+=(r-score2-score1)
# except:
# # print(t)
# tjh=0
for i in range(t):
n,l,r=map(int,input().split())
xx=list(map(int,input().split()))
score=0
if(l==0):
xx.sort()
for j in range(r-1):
if(xx[j]==xx[j+1]):
xx[j]=xx[j+1]=0
score+=1
score=(len(xx)-score)
elif(r==0):
xx.sort()
for j in range(l-1):
if(xx[j]==xx[j+1]):
xx[j]=xx[j+1]=0
score+=1
score=(len(xx)-score)
elif(l>=r):
left=xx[:l]
right=xx[l:]
left.sort()
right.sort()
li=0
ri=0
score1=0
score2=0
while(ri<r and li<l):
if(left[li]==right[ri]):
left[li]=right[ri]=0
score1+=1
li+=1
ri+=1
elif(left[li]>right[ri]):
ri+=1
else:
li+=1
for j in range(l-1):
if(left[j]!=0 and left[j]==left[j+1] and l!=r):
# score+=1
score2+=1
left[j]=left[j+1]=0
if(score2==(abs(l-r)/2)):
break
score+=(l-score2-score1)
elif(r>l):
left=xx[:l]
right=xx[l:]
left.sort()
right.sort()
li=0
ri=0
score1=0
score2=0
while(li<l and ri<r):
if(left[li]==right[ri]):
left[li]=right[ri]=0
score1+=1
li+=1
ri+=1
elif(left[li]>right[ri]):
ri+=1
else:
li+=1
for j in range(r-1):
if(right[j]!=0 and right[j]==right[j+1]):
# score+=1
score2+=1
right[j]=right[j+1]=0
if(score2==(abs(l-r)/2)):
break
score+=(r-score2-score1)
print(score)
|
Python
|
[
"other"
] | 753
| 4,873
| 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,972
|
b784cebc7e50cc831fde480171b9eb84
|
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.
|
['dp', 'two pointers', 'implementation']
|
from collections import Counter
cnt = Counter()
n = int(raw_input())
a = map(int,raw_input().split())
def isOK(x):
if cnt[x-2]>0 or cnt[x+2]>0:
return False
else:
cnt[x]+=1
return True
ret = cur = 0
for i in xrange(n):
while cur < n and isOK(a[cur]):
cur+=1
ret = max(ret,cur-i)
cnt[a[i]]-=1
print ret
|
Python
|
[
"other"
] | 970
| 357
| 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,321
|
4720ca1d2f4b7a0e553a3ea07a76943c
|
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores k-lucky tickets.Pollard sais that a ticket is k-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., "+", "-", " × ") and brackets so as to obtain the correct arithmetic expression whose value would equal k. For example, ticket "224201016" is 1000-lucky as ( - 2 - (2 + 4)) × (2 + 0) + 1016 = 1000.Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for m days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram k-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these m days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly m distinct k-lucky tickets.
|
['constructive algorithms', 'brute force']
|
N,M = map(int,raw_input().split())
P = {}
Q = {}
for i in range(10001):
for j in range(1,5):
P[(i,j)] = set()
Q[(i,j)] = set()
for i in range(10):
P[(i,1)].add(i)
Q[(i,1)].add(i)
for i in range(100):
P[(i,2)].add(i)
Q[(i,2)].add(i)
a,b = i/10,i%10
next = [a+b,abs(a-b),a*b]
for j in next:
P[(j,2)].add(i)
Q[(i,2)].add(j)
for i in range(1000):
P[(i,3)].add(i)
Q[(i,3)].add(i)
candidate = [((i/100,1),(i%100,2)),((i/10,2),(i%10,1))]
next = []
for p,q in candidate:
for a in Q[p]:
for b in Q[q]:
next.append(a+b)
next.append(abs(a-b))
next.append(a*b)
next = set(next)
for j in next:
P[(j,3)].add(i)
Q[(i,3)].add(j)
for i in range(10000):
P[(i,4)].add(i)
Q[(i,4)].add(i)
candidate = [((i/1000,1),(i%1000,3)),((i/100,2),(i%100,2)),((i/10,3),(i%10,1))]
next = []
for p,q in candidate:
for a in Q[p]:
for b in Q[q]:
next.append(a+b)
next.append(abs(a-b))
next.append(a*b)
next = set(next)
for j in next:
P[(j,4)].add(i)
Q[(i,4)].add(j)
def f(n,m,p):
for i in range(10000):
for j in p[(abs(n-i),4)]:
print '%04d%04d'%(i,j)
m -= 1
if m == 0:
return
f(N,M,P)
|
Python
|
[
"other"
] | 1,343
| 1,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
}
| 4,966
|
c8cdb9f6a44e1ce9ef81a981c9b334c2
|
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string s_1s_2\ldots s_n of length n. 1 represents an apple and 0 represents an orange.Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let f(l,r) be the longest contiguous sequence of apples in the substring s_{l}s_{l+1}\ldots s_{r}. Help Zookeeper find \sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r), or the sum of f across all substrings.
|
['dp', 'two pointers', 'divide and conquer', 'data structures', 'binary search']
|
import sys
readline = sys.stdin.readline
N = int(readline())
A = list(map(int, readline().strip()))
def calc(l, r):
m = (l+r)//2
if l+1 == r:
return A[l]
if l+2 == r:
return 2*(A[l]+A[l+1])
X = A[l:m][::-1]
Y = A[m:r]
LX = len(X)
LY = len(Y)
a1 = [0]*LX
a2 = [0]*LY
pre = 1
cnt = 0
b1 = 0
b2 = 0
for i in range(LX):
if X[i]:
cnt += 1
if pre:
a1[i] = cnt
b1 = cnt
else:
a1[i] = max(a1[i-1], cnt)
else:
pre = 0
cnt = 0
a1[i] = a1[i-1]
pre = 1
cnt = 0
for i in range(LY):
if Y[i]:
cnt += 1
if pre:
a2[i] = cnt
b2 = cnt
else:
a2[i] = max(a2[i-1], cnt)
else:
pre = 0
cnt = 0
a2[i] = a2[i-1]
ra = LX-1
rb = LY-1
i = ra
j = rb
res = 0
for _ in range(LX+LY):
if a1[i] >= a2[j]:
a = a1[i]
if b1+b2 <= a:
res += a*(j+1)
elif a == b1:
res += b1*b2 + b2*(b2+1)//2 + (b1+b2)*(j+1-b2)
else:
res += a*b2 + (b1+b2-a)*(b1+b2-a+1)//2+(b1+b2)*(j+1-b2)
i -= 1
b1 = min(b1, i+1)
else:
a = a2[j]
if b1+b2 <= a:
res += a*(i+1)
elif a == b2:
res += b1*b2 + b1*(b1+1)//2 + (b1+b2)*(i+1-b1)
else:
res += a*b1 + (b1+b2-a)*(b1+b2-a+1)//2+(b1+b2)*(i+1-b1)
j -= 1
b2 = min(b2, j+1)
if i == -1 or j == -1:
break
return res + calc(l, m) + calc(m, r)
print(calc(0, N))
|
Python
|
[
"other"
] | 589
| 1,843
| 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,418
|
cb47d710361979de0f975cc34fc22c7a
|
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).
|
['dp', 'binary search', 'data structures']
|
from sys import stdin
from collections import *
def fast2():
import os, sys, atexit
range = xrange
from cStringIO import StringIO as BytesIO
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class segmenttree:
def __init__(self, arr, n):
self.tree, self.n = [0] * (2 * n), n
self.order = defaultdict(int, {arr[i]: i for i in range(self.n)})
# get interval[l,r)
def query(self, l, r):
res = 0
l = self.order[l] + self.n
r = self.order[r] + self.n
while l < r:
if l & 1:
res = add(self.tree[l], res)
l += 1
if r & 1:
r -= 1
res = add(self.tree[r], res)
l >>= 1
r >>= 1
return res
def update(self, ix, val):
ix = self.n + self.order[ix]
# set new value
self.tree[ix] = add(val, self.tree[ix])
# move up
while ix > 1:
self.tree[ix >> 1] = add(self.tree[ix], self.tree[ix ^ 1])
ix >>= 1
input = fast2()
mod = 1000000007
add = lambda a, b: (a % mod + b % mod) % mod
rints = lambda: [int(x) for x in input().split()]
n, m = rints()
bus, dis = sorted([rints() for _ in range(m)], key=lambda x: x[1]), {0, n}
for i, j in bus:
dis.add(i)
dis.add(j)
tree = segmenttree(sorted(dis), len(dis))
tree.update(0, 1)
for i, j in bus:
val = tree.query(i, j)
tree.update(j, val)
print(tree.tree[-1])
|
Python
|
[
"other"
] | 1,375
| 1,577
| 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,383
|
e95e2d21777c1d686bede1b0a5dacbf5
|
You are given a string s. You have to determine whether it is possible to build the string s out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example: aaaabbb can be built as aa + aa + bbb; bbaaaaabbb can be built as bb + aaa + aa + bbb; aaaaaa can be built as aa + aa + aa; abab cannot be built from aa, aaa, bb and/or bbb.
|
['implementation']
|
t = int(input(""))
for i in range(t):
x = input("")
count = 1
base = x[0]
answer = "YES"
for i in range(1, len(x)):
if x[i] == base:
count = count + 1
else:
if count == 1:
answer = "NO"
break
else:
base = x[i]
count = 1
if count == 1:
answer = "NO"
print(answer)
x = 2+3
|
Python
|
[
"other"
] | 483
| 426
| 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,884
|
31057c0e76e6985a68b2a298236a8ee5
|
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: employee ::= name. | name:employee1,employee2, ... ,employeek. name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
|
['data structures', 'implementation', 'expression parsing']
|
#!/usr/bin/env python3
tree = input().strip()
def get_answer(tree, start_index = 0, prev = []):
colon_index = tree.find(':', start_index)
period_index = tree.find('.', start_index)
name_end_index = colon_index if ((colon_index != -1) and (colon_index < period_index)) else period_index
name = tree[start_index:name_end_index]
answer = prev.count(name)
if ((colon_index == -1) or (period_index < colon_index)):
return (answer, period_index+1)
else:
# Recurse
prev_names = prev + [name]
next_start = colon_index
while tree[next_start] != '.':
(sub_answer, next_start) = get_answer(tree, next_start+1, prev_names)
answer += sub_answer
return (answer, next_start+1)
print(get_answer(tree)[0])
|
Python
|
[
"other"
] | 1,336
| 742
| 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,575
|
dd62b6860b6a4cf33aef89c2f674331f
|
The Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.One of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the reverse path (i. e. the path from Olymp City to Kstolop).The road from Kstolop to Olymp City is \ell kilometers long. Each point of the road has a coordinate x (0 \le x \le \ell), which is equal to the distance from Kstolop in kilometers. So, Kstolop is located in the point with coordinate 0, and Olymp City is located in the point with coordinate \ell.There are n signs along the road, i-th of which sets a speed limit a_i. This limit means that the next kilometer must be passed in a_i minutes and is active until you encounter the next along the road. There is a road sign at the start of the road (i. e. in the point with coordinate 0), which sets the initial speed limit.If you know the location of all the signs, it's not hard to calculate how much time it takes to drive from Kstolop to Olymp City. Consider an example: Here, you need to drive the first three kilometers in five minutes each, then one kilometer in eight minutes, then four kilometers in three minutes each, and finally the last two kilometers must be passed in six minutes each. Total time is 3\cdot 5 + 1\cdot 8 + 4\cdot 3 + 2\cdot 6 = 47 minutes.To optimize the road traffic, the Government of Mars decided to remove no more than k road signs. It cannot remove the sign at the start of the road, otherwise, there will be no limit at the start. By removing these signs, the Government also wants to make the time needed to drive from Kstolop to Olymp City as small as possible.The largest industrial enterprises are located in Cydonia, so it's the priority task to optimize the road traffic from Olymp City. So, the Government of Mars wants you to remove the signs in the way described above.
|
['dp']
|
# What to check if it made a difference
# Putting in result before going straight to memo
# limits[i] > s ? How is this so effective?
n, l, k = map(int, input().split())
coor = list(map(int, input().split()))+[l]
limits = list(map(int, input().split()))+[0]
memo = {}
def dfs(i, k, s): # coordinate, takes left, speed
if (i,k,s) in memo:
return memo[(i,k,s)]
if i == len(coor) - 1:
return 0
res = float("inf")
if i == 0:
res = ((coor[i+1]-coor[i]) * limits[i]) + dfs(i+1, k, limits[i])
elif k > 0 and limits[i] > s:
take = ((coor[i+1] - coor[i]) * s) + dfs(i+1, k-1, s)
leave = ((coor[i+1] - coor[i]) * limits[i]) + dfs(i+1, k, limits[i])
res = min(take, leave)
else:
leave = ((coor[i+1] - coor[i]) * limits[i]) + dfs(i+1, k, limits[i])
res = leave
memo[(i,k,s)] = res
return memo[(i,k,s)]
print(dfs(0, k, None))
# def rec(i, k, wall, cur_speed):
# serialize = (i, wall, k)
# if serialize in memo:
# return memo[serialize]
# if i == 0:
# return rec(i+1, k, wall, speed_limits[i])
# if i == len(coordinates):
# return (l - wall) * cur_speed
# if k == 0:
# memo[serialize] = ((coordinates[i] - wall) * cur_speed) + rec(i+1, k, coordinates[i], speed_limits[i])
# return memo[serialize]
# # keep_sign = ((coordinates[i] - wall) * cur_speed) + rec(i+1, k, coordinates[i], speed_limits[i])
# # remove_sign = rec(i+1, k-1, wall, cur_speed)
# memo[serialize] = min(((coordinates[i] - wall) * cur_speed) + rec(i+1, k, coordinates[i], speed_limits[i]), rec(i+1, k-1, wall, cur_speed))
# return memo[serialize]
# print(rec(0, k, 0, 0))
|
Python
|
[
"other"
] | 2,054
| 1,721
| 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,408
|
a8334846b495efbded9bb0641d6a1964
|
The only difference between this problem and the hard version is the maximum number of questions.This is an interactive problem.There is a hidden integer 1 \le x \le n which you have to find. In order to find it you can ask at most \mathbf{53} questions.In each question you can choose a non-empty integer set S and ask if x belongs to S or not, after each question, if x belongs to S, you'll receive "YES", otherwise "NO".But the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.Additionally to the questions, you can make at most 2 guesses for the answer x. Each time you make a guess, if you guess x correctly, you receive ":)" and your program should terminate, otherwise you'll receive ":(".As a part of the joking, we will not fix the value of x in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.Note that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.
|
['dp', 'interactive']
|
import sys, random
input = sys.stdin.readline
n = int(input())
good = list(range(1, n + 1))
mid = []
def query(l):
print('?',len(l),' '.join(map(str, l)))
sys.stdout.flush()
#return random.randint(0, 1)
s = input().strip()
return s == 'YES'
from functools import cache
@cache
def solveu(p, q):
if p + q <= 2:
return 0
if p == 2 and q == 1:
return 2
if p + q < 10:
uu, vv = solved(p, q, 0)
pl = uu
ql = vv
pr = p - pl
qr = q - ql
else:
pl = p // 2
pr = p - pl
qr = q // 2
ql = q - qr
#print(pl, pr, ql, qr)
return 1 + max(solveu(pl + ql, pr), solveu(pr + qr, pl))
@cache
def solve(p, q):
if p + q <= 2:
return 0
if p == 2 and q == 1:
return 2
pl = p // 2
pr = p - pl
qr = q // 2
ql = q - qr
#print(pl, pr, ql, qr)
return 1 + max(solve(pl + ql, pr), solve(pr + qr, pl))
@cache
def solved(p, q, d):
if d > 100:
return d
if p + q <= 2:
return d
if p == 2 and q == 1:
return 2 + d
poss = []
for i in range(p + 1):
for j in range(q + 1):
poss.append((max(solved(i + j, p - i, d + 1), solved(p - i + q - j, i, d + 1)), i, j))
if d == 0:
return min(poss)[1:]
return min(poss)[0]
mz = solveu(n, 0)
assert mz <= 53
ct = 0
while len(good) + len(mid) > 2:
curr = ct + solveu(len(good), len(mid))
assert curr <= mz
mz = min(curr, mz)
ct += 1
assert ct <= 53
p = len(good)
q = len(mid)
#print(good, mid)
if p == 2 and q == 1:
if query(good):
mid = []
continue
else:
mid, good = good, mid
continue
if p + q < 10:
uu, vv = solved(p, q, 0)
pl = good[:uu]
pr = good[uu:]
ql = mid[:vv]
qr = mid[vv:]
else:
pl = good[:p//2]
pr = good[p//2:]
ql = mid[q//2:]
qr = mid[:q//2]
if query(pl + ql):
good = pl + ql
mid = pr
else:
good = pr + qr
mid = pl
poss = good + mid
for v in poss:
print('!',v)
sys.stdout.flush()
s = input().strip()
if s == ':)':
exit()
|
Python
|
[
"other"
] | 1,267
| 2,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
}
| 869
|
d44542a39df3b06fa32c69d99887a2e2
|
Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: the frame's width is 1 pixel, the frame doesn't go beyond the borders of the screen, all white pixels of the monitor are located on the frame, of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is d = 3, then it consists of 8 pixels, if its size is d = 2, then it contains 4 pixels and if d = 1, then the frame is reduced to a single pixel.
|
['constructive algorithms', 'implementation', 'greedy', 'brute force']
|
from itertools import chain
# To draw square: if point isn't 'w', draw '+'
def draw_square(scr, square_a, ymin, xmin):
for i in range(square_a + 1):
if scr[ymin][xmin + i] != 'w':
scr[ymin] = scr[ymin][:xmin + i] + '+' + scr[ymin][xmin + i + 1:]
if scr[ymin + square_a][xmin + i] != 'w':
scr[ymin + square_a] = scr[ymin + square_a][:xmin + i] + '+' + scr[ymin + square_a][xmin + i + 1:]
if scr[ymin + i][xmin] != 'w':
scr[ymin + i] = scr[ymin + i][:xmin] + '+' + scr[ymin + i][xmin + 1:]
if scr[ymin + i][xmin + square_a] != 'w':
scr[ymin + i] = scr[ymin + i][:xmin + square_a] + '+' + scr[ymin + i][xmin + square_a + 1:]
return scr
# To find the side length of a square, and if there is some point beside the edge of a square it'll print '-1'
def find_a(pixel, y, x):
ymax = xmax = 0
ymin = y
xmin = x
ymaxl = []
yminl = []
xmaxl = []
xminl = []
count_pixel = len(pixel) // 2
for i in range(count_pixel):
if ymax < pixel[2 * i]:
ymax = pixel[2 * i]
if ymin > pixel[2 * i]:
ymin = pixel[2 * i]
if xmax < pixel[2 * i + 1]:
xmax = pixel[2 * i + 1]
if xmin > pixel[2 * i + 1]:
xmin = pixel[2 * i + 1]
for i in range(count_pixel):
f = True
if pixel[2 * i] == ymax:
f = False
ymaxl.append(pixel[2 * i])
ymaxl.append(pixel[2 * i + 1])
if pixel[2 * i] == ymin:
f = False
yminl.append(pixel[2 * i])
yminl.append(pixel[2 * i + 1])
if pixel[2 * i + 1] == xmax:
f = False
xmaxl.append(pixel[2 * i])
xmaxl.append(pixel[2 * i + 1])
if pixel[2 * i + 1] == xmin:
f = False
xminl.append(pixel[2 * i])
xminl.append(pixel[2 * i + 1])
# if some point beside the edge of a square: like the 'x'
# 5 7
# .......
# .+++...
# .+x+...
# .www...
# .......
if f:
print('-1')
exit()
return ymax, ymin, xmax, xmin, ymaxl, yminl, xmaxl, xminl
def main():
y, x = map(int, input().split())
scr = []
for i in range(y):
scr.append(input())
pixel = []
# To collect the point info
for i in range(y):
for j in range(x):
if scr[i][j] == 'w':
pixel.append(i)
pixel.append(j)
ymax, ymin, xmax, xmin, ymaxl, yminl, xmaxl, xminl = find_a(pixel, y, x)
count_ymax = len(ymaxl) / 2
count_ymin = len(yminl) / 2
count_xmax = len(xmaxl) / 2
count_xmin = len(xminl) / 2
countx_ymax = ymaxl[1::2].count(xmax) + ymaxl[1::2].count(xmin)
countx_ymin = yminl[1::2].count(xmax) + yminl[1::2].count(xmin)
county_xmax = xmaxl[::2].count(ymax) + xmaxl[::2].count(ymin)
county_xmin = xminl[::2].count(ymax) + xminl[::2].count(ymin)
#print('ymax:%d,ymin:%d,xmax:%d,xmin:%d'%(ymax,ymin,xmax,xmin))
#print(f'ymaxl:\n{ymaxl}\nyminl:\n{yminl}\nxmaxl:\n{xmaxl}\nxminl:\n{xminl}\ncounty_xmax:{county_xmax}\ncounty_xmin:{county_xmin}\ncountx_ymax:{countx_ymax}\ncountx_ymin:{countx_ymin}')
# There are three conditions:
# 1.height > width 2.height < width 3.height == width
# eg: 1.height > width:
# so square_a = height
if ymax - ymin > xmax - xmin:
square_a = ymax - ymin
# if the point form a rectangle:
# 5 7
# .......
# .ww....
# .wx....
# .ww....
# .......
# or
# 5 7
# .......
# .w.....
# .w.....
# .w.....
# .......
if county_xmax < count_xmax and county_xmin < count_xmin:
# 5 7
# .......
# .w++...
# .w.+...
# .w++...
# .......
if xmax == xmin:
if xmin + square_a < x:
xmax = xmin + square_a
elif xmax - square_a >= 0:
xmin = xmax - square_a
else:
print('-1')
exit()
else:
print('-1')
exit()
# if the point from the shape of [ like:
# 5 7
# .......
# .www...
# .w.....
# .www...
# .......
elif county_xmax < count_xmax and county_xmin == count_xmin:
xmin = xmax - square_a
if xmin < 0:
print('-1')
exit()
# if the point from the shape of ] like:
# 5 7
# .......
# .www...
# ...w...
# .www...
# .......
elif county_xmax == count_xmax and county_xmin < count_xmin:
xmax = xmin + square_a
if xmax >= x:
print('-1')
exit()
# if there is some point to make county_xmax == count_xmax and county_xmin == count_xmin like:
# 5 7
# .......
# .w.....
# .......
# ..w....
# .......
elif county_xmax == count_xmax and county_xmin == count_xmin:
if square_a < x:
if xmin + square_a < x:
xmax = xmin + square_a
elif xmax - square_a >= 0:
xmin = xmax - square_a
# sp:
# 5 5
# .w...
# .....
# .....
# .....
# ..w..
else:
xmin = 0
xmax = xmin + square_a
else:
print('-1')
exit()
elif ymax - ymin < xmax - xmin:
square_a = xmax - xmin
if countx_ymax < count_ymax and countx_ymin < count_ymin:
if ymax == ymin:
if ymin + square_a < y:
ymax = ymin + square_a
elif ymax - square_a >= 0:
ymin = ymax - square_a
else:
print('-1')
exit()
else:
print('-1')
exit()
elif countx_ymax < count_ymax and countx_ymin == count_ymin:
ymin = ymax - square_a
if ymin < 0:
print('-1')
exit()
elif countx_ymax == count_ymax and countx_ymin < count_ymin:
ymax = ymin + square_a
if ymax >= y:
print('-1')
exit()
elif countx_ymax == count_ymax and countx_ymin == count_ymin:
if square_a < y:
if ymin + square_a < y:
ymax = ymin + square_a
elif ymax - square_a >= 0:
ymin = ymax -square_a
else:
ymin = 0
ymax = ymin + square_a
else:
print('-1')
exit()
elif ymax - ymin == xmax - xmin:
square_a = xmax - xmin
#print('ymax:%d,ymin:%d,xmax:%d,xmin:%d,a:%d'%(ymax,ymin,xmax,xmin,square_a))
scr = draw_square(scr, square_a, ymin, xmin)
for i in range(y):
print(scr[i])
if __name__ == '__main__':
main()
#while True:
# main()
|
Python
|
[
"other"
] | 1,448
| 7,311
| 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,285
|
aeea2ca73f1b5c5b86fb508afcbec68a
|
You are given an integer n.Let's define s(n) as the string "BAN" concatenated n times. For example, s(1) = "BAN", s(3) = "BANBANBAN". Note that the length of the string s(n) is equal to 3n.Consider s(n). You can perform the following operation on s(n) any number of times (possibly zero): Select any two distinct indices i and j (1 \leq i, j \leq 3n, i \ne j). Then, swap s(n)_i and s(n)_j. You want the string "BAN" to not appear in s(n) as a subsequence. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
|
['constructive algorithms']
|
#Khushal Sindhav
#Indian Institute Of Technology, Jodhpur
# 4 Nov 2022
def exe():
global n
if n==1:
print(1)
print(1,2)
return
if n==2:
print(1)
print(2,6)
return
l=[]
i,j=1,3*n
s=["B","A","N"]*n
while i<j:
l.append([i,j])
s[i-1],s[j-1]=s[j-1],s[i-1]
i+=3
j-=3
print(len(l))
for i in l:
print(*i)
# print(s)
for i in range(int(input())):
n=int(input())
exe()
|
Python
|
[
"other"
] | 824
| 523
| 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
}
| 296
|
85453ab4eb82b894ef8941c70c6d713c
|
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi ≥ aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.
|
['data structures', 'binary search', 'sortings', 'greedy']
|
import sys
import heapq
range = xrange
input = raw_input
n,m,s = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
Bind = sorted(range(n),key=lambda i:B[i])
Aind = sorted(range(m),key=lambda i:A[i])
big = 10**9+10
def solve(days):
cheapest = []
used = [0]*n
fixes = [-1]*m
cost = 0
Ccopy = C[:]
heapq.cmp_lt = lambda i,j: Ccopy[i]<Ccopy[j]
j = len(Bind)-1
for i in reversed(Aind):
while j>=0 and B[Bind[j]]>=A[i]:
heapq.heappush(cheapest, Bind[j])
j -= 1
if not cheapest: return big,None
stud = heapq.heappop(cheapest)
cost += Ccopy[stud]
if cost >= big: return big,None
Ccopy[stud] = 0
used[stud] += 1
fixes[i] = stud
if used[stud]<days:
heapq.heappush(cheapest, stud)
return cost,fixes
l = 1
r = 10**5+1
while l<r:
mid = (l+r)//2
cost, fixes = solve(mid)
if cost<=s:
r = mid
else:
l = mid+1
if r == 10**5+1:
print 'NO'
else:
print 'YES'
_, fixes = solve(l)
print ' '.join(str(x+1) for x in fixes)
|
Python
|
[
"other"
] | 1,254
| 1,230
| 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,461
|
12c223c903544899638e47bcab88999a
|
Constanze is the smartest girl in her village but she has bad eyesight.One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe "uu" instead of "w", and if you pronounce 'm', it will inscribe "nn" instead of "m"! Since Constanze had bad eyesight, she was not able to realize what Akko did.The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.But since this number can be quite large, tell me instead its remainder when divided by 10^9+7.If there are no strings that Constanze's machine would've turned into the message I got, then print 0.
|
['dp']
|
s = raw_input()
flag = True
maxn = int(1e5+5)
fib = [0]*maxn
fib[0] = 1
fib[1] = 1
fib[2] = 2
fib[3] = 3
mod = int(1e9+7)
for i in range(4,maxn):
fib[i] = (fib[i-1]+fib[i-2])%mod
for i in range(len(s)):
if s[i] == "m" or s[i] == "w":
flag = False
if not flag:
print 0
else:
i = 0
cnt = 0
ans = 1
while i<len(s):
if s[i]!="u" and s[i]!="n":
ans = (ans*fib[cnt])%mod
cnt = 0
elif s[i] == s[i-1]:
cnt += 1
else:
ans = (ans*fib[cnt])%mod
cnt = 1
i += 1
ans = (ans*fib[cnt])%mod
print ans
|
Python
|
[
"other"
] | 1,595
| 528
| 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,823
|
224a0b09547ec1441474efbd8e06353b
|
You are given an array a consisting of n (n \ge 3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4, 11, 4, 4] all numbers except one are equal to 4).Print the index of the element that does not equal others. The numbers in the array are numbered from one.
|
['brute force', 'implementation']
|
import sys
import math
masterlist = []
numofcases = int(input())
for i in range(1, (numofcases * 2) + 1):
next = input()
if i % 2 == 0:
masterlist.append([int(x) for x in next.split(" ")])
for i in masterlist:
twonums = list(set(i))
if i.count(twonums[0]) == 1:
print(i.index(twonums[0]) + 1)
else:
print(i.index(twonums[1]) + 1)
|
Python
|
[
"other"
] | 358
| 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
}
| 1,725
|
bd40f54a1e764ba226d5387fcd6b353f
|
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
|
['implementation']
|
champion_data,points = {},[25, 18, 15, 12, 10, 8, 6, 4, 2, 1]+[0]*50
for tour in range(int(input())):
for j in range(int(input())):
player =str(input())
if player not in champion_data:
champion_data[player] = [0]*51+[player]
champion_data[player][0] += points[j]
champion_data[player][j+1] += 1
win = champion_data.values()
print(sorted(win)[-1][-1])
win= [[p[1]]+p for p in win]
print(sorted(win)[-1][-1])
|
Python
|
[
"other"
] | 1,041
| 418
| 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
}
| 841
|
10f4fc5cc2fcec02ebfb7f34d83debac
|
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
|
['binary search', 'implementation']
|
import sys
def search(Max,new,num):
if new[0]>num:
return 1
Min =0
Mid = int((Max+Min)/2)
while Min<=Max:
if new[Mid]==num:
return Mid+1
break
elif new[Min]==num:
return Min+1
break
elif new[Mid]<num and new[Mid+1]>num:
return Mid+2
break
elif new[Mid]<num:
Min=Mid+1
else:
Max=Mid-1
Mid = Min + (Max-Min) //2
n =int(sys.stdin.readline())
a=map(int, sys.stdin.readline().split())
m= int(sys.stdin.readline())
mq=map(int, sys.stdin.readline().split())
new=[a[0]]
for x in xrange(1,n):
new.append(new[x-1]+a[x])
#print new
#print mq
for x in mq:
print(search(n,new,x))
|
Python
|
[
"other"
] | 726
| 614
| 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,928
|
267c04c77f97bbdf7697dc88c7bfa4af
|
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
|
['data structures', 'implementation', 'sortings', 'greedy']
|
__author__ = 'trunghieu11'
def main():
n, s = map(int, raw_input().split())
buy = dict()
sell = dict()
for i in range(n):
line = raw_input().split()
d = str(line[0])
p = int(line[1])
q = int(line[2])
if d == "B":
if (d, p) in buy.keys():
buy[(d, p)] += q
else:
buy.setdefault((d, p), q)
else:
if (d, p) in sell.keys():
sell[(d, p)] += q
else:
sell.setdefault((d, p), q)
keyBuy = buy.keys()
keyBuy = sorted(keyBuy, key = lambda tup: tup[1], reverse = True)
keySell = sell.keys()
keySell = sorted(keySell, key = lambda tup: tup[1])
if len(keySell) > 0:
for i in range(min(s, len(keySell)) - 1, -1, -1):
print keySell[i][0], keySell[i][1], sell.get(keySell[i])
if len(keyBuy) > 0:
for i in range(min(s, len(keyBuy))):
print keyBuy[i][0], keyBuy[i][1], buy.get(keyBuy[i])
if __name__ == '__main__':
main()
|
Python
|
[
"other"
] | 1,172
| 1,049
| 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,981
|
c3ee6419adfc85c80f35ecfdea6b0d43
|
You are given an array a of n elements. Your can perform the following operation no more than n times: Select three indices x,y,z (1 \leq x < y < z \leq n) and replace a_x with a_y - a_z. After the operation, |a_x| need to be less than 10^{18}.Your goal is to make the resulting array non-decreasing. If there are multiple solutions, you can output any. If it is impossible to achieve, you should report it as well.
|
['constructive algorithms', 'greedy']
|
import array
import bisect
import heapq
import math
import collections
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
import fractions
# sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque
################## pypy deep recursion handling ##############
# Author = @pajenegod
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
################## Graphs ###################
class Graphs:
def __init__(self):
self.graph = graphDict(set)
def add_edge(self, u, v):
self.graph[u].add(v)
self.graph[v].add(u)
def dfs_utility(self, nodes, visited_nodes, colors, parity, level):
global count
if nodes == 1:
colors[nodes] = -1
else:
if len(self.graph[nodes]) == 1 and parity % 2 == 0:
if q == 1:
colors[nodes] = 1
else:
colors[nodes] = -1
count += 1
else:
if parity % 2 == 0:
colors[nodes] = -1
else:
colors[nodes] = 1
visited_nodes.add(nodes)
for neighbour in self.graph[nodes]:
new_level = level + 1
if neighbour not in visited_nodes:
self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)
def dfs(self, node):
Visited = set()
color = collections.defaultdict()
self.dfs_utility(node, Visited, color, 0, 0)
return color
def bfs(self, node, f_node):
count = float("inf")
visited = set()
level = 0
if node not in visited:
queue.append([node, level])
visited.add(node)
flag = 0
while queue:
parent = queue.popleft()
if parent[0] == f_node:
flag = 1
count = min(count, parent[1])
level = parent[1] + 1
for item in self.graph[parent[0]]:
if item not in visited:
queue.append([item, level])
visited.add(item)
return count if flag else -1
return False
################### Tree Implementaion ##############
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node, lis):
if node:
inorder(node.left, lis)
lis.append(node.data)
inorder(node.right, lis)
return lis
def leaf_node_sum(root):
if root is None:
return 0
if root.left is None and root.right is None:
return root.data
return leaf_node_sum(root.left) + leaf_node_sum(root.right)
def hight(root):
if root is None:
return -1
if root.left is None and root.right is None:
return 0
return max(hight(root.left), hight(root.right)) + 1
################## Union Find #######################
class UnionFind():
parents = []
sizes = []
count = 0
def __init__(self, n):
self.count = n
self.parents = [i for i in range(n)]
self.sizes = [1 for i in range(n)]
def find(self, i):
if self.parents[i] == i:
return i
else:
self.parents[i] = self.find(self.parents[i])
return self.parents[i]
def unite(self, i, j):
root_i = self.find(i)
root_j = self.find(j)
if root_i == root_j:
return
elif root_i < root_j:
self.parents[root_j] = root_i
self.sizes[root_i] += self.sizes[root_j]
else:
self.parents[root_i] = root_j
self.sizes[root_j] += self.sizes[root_i]
def same(self, i, j):
return self.find(i) == self.find(j)
def size(self, i):
return self.sizes[self.find(i)]
def group_count(self):
return len(set(self.find(i) for i in range(self.count)))
def answer(self, extra, p, q):
dic = collections.Counter()
for q in range(n):
dic[self.find(q)] = self.size(q)
hq = list(dic.values())
heapq._heapify_max(hq)
ans = -1
for z in range(extra + 1):
if hq:
ans += heapq._heappop_max(hq)
else:
break
return ans
#################################################
def rounding(n):
return int(decimal.Decimal(f'{n}').to_integral_value())
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), [1]))
def p_sum(array):
return list(itertools.accumulate(array))
def base_change(nn, bb):
if nn == 0:
return [0]
digits = []
while nn:
digits.append(int(nn % bb))
nn //= bb
return digits[::-1]
def diophantine(a: int, b: int, c: int):
d, x, y = extended_gcd(a, b)
r = c // d
return r * x, r * y
@bootstrap
def extended_gcd(a: int, b: int):
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = yield extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
yield d, x, y
######################################################################################
'''
Knowledge and awareness are vague, and perhaps better called illusions.
Everyone lives within their own subjective interpretation.
~Uchiha Itachi
'''
################################ <fast I/O> ###########################################
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write 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, **kwargs):
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)
#############################################<I/O Region >##############################################
def inp():
return sys.stdin.readline().strip()
def map_inp(v_type):
return map(v_type, inp().split())
def list_inp(v_type):
return list(map_inp(v_type))
def interactive():
return sys.stdout.flush()
######################################## Solution ####################################
for _ in range(int(inp())):
n = int(inp())
arr = list_inp(int)
if arr[-1] < arr[-2]:
print(-1)
elif arr == list(sorted(arr)):
print(0)
else:
arr.reverse()
maxi = arr[0]
mini = arr[1]
max_ind = n
ans = []
count = 0
for i in range(2, n):
arr[i] = arr[1] - maxi
ans.append([n - i, n - 1, n])
count += 1
arr.reverse()
if arr == list(sorted(arr)):
print(count)
for item in ans:
print(*item)
else:
print(-1)
|
Python
|
[
"other"
] | 475
| 9,131
| 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,634
|
c9744e25f92bae784c3a4833c15d03f4
|
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.
|
['implementation', 'sortings']
|
n = input()
s = map(int,raw_input().split())
l = []
r = []
for i in range(1,n-1) :
if s[i]> s[i-1] and s[i]>s[i+1] :
l.append(i+1)
if s[i]< s[i-1] and s[i]<s[i+1] :
r.append(i+1)
if ( len(l) == 1 ) and ( len(r) == 1) and (l[0] <= r[0]) and ( s[l[0]-2] < s[r[0]-1] ) and ( s[r[0]] > s[l[0]-1] ):
print 'yes'
print l[0],r[0]
elif ( len(l) == 0 ) and ( len(r) == 1 ) and ( s[0] < s[r[0]] ):
print 'yes'
print 1,r[0]
elif ( len(l) == 1 ) and ( len(r) == 0 ) and ( s[-1] > s[l[0]-2] ):
print 'yes'
print l[0],n
elif ( len(l) == 0 ) and ( len(r) == 0 ) and ( s[-1]<s[0] ):
print 'yes'
print 1,n
elif ( len(l) == 0 ) and ( len(r) == 0 ) and ( s[-1]>=s[0] ):
print 'yes'
print 1,1
else : print 'no'
|
Python
|
[
"other"
] | 469
| 721
| 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
}
| 223
|
3cb4c89b174bf5ea51e797b78103e089
|
Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0 < t2 - t1 ≤ d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.
|
['implementation', '*special', 'greedy']
|
n, d = map(int, input().split())
f = list()
m = dict()
for i in range(n):
add = False
a, b, t2 = input().split()
t2 = int(t2)
c = m.get(b + ' ' + a, 0)
if c != -1:
if c != 0:
for t1 in c:
if 0 < t2 - t1 <= d:
f.append(a + ' ' + b)
m[b + ' ' + a] = -1
m[a + ' ' + b] = -1
add = True
break
if not add:
c = m.get(a + ' ' + b, 0)
if c == 0:
m[a + ' ' + b] = [t2]
elif c[0] != t2:
m[a + ' ' + b] = [t2, c[0]]
print(len(f))
for i in f:
print(i)
|
Python
|
[
"other"
] | 737
| 675
| 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
}
| 276
|
c4c8cb860ea9a5b56bb35532989a9192
|
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.Let's define the ternary XOR operation \odot of two ternary numbers a and b (both of length n) as a number c = a \odot b of length n, where c_i = (a_i + b_i) \% 3 (where \% is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by 3. For example, 10222 \odot 11021 = 21210.Your task is to find such ternary numbers a and b both of length n and both without leading zeros that a \odot b = x and max(a, b) is the minimum possible.You have to answer t independent test cases.
|
['implementation', 'greedy']
|
t = int(input())
for i in range(t):
n = int(input())
x = input()
a = ''
b = ''
firstOne = False
for i in range(n):
if not firstOne:
if x[i] == '2':
a += '1'
b += '1'
elif x[i] == '0':
a += '0'
b += '0'
else:
a += '1'
b += '0'
firstOne = True
else:
if x[i] == '2':
a += '0'
b += '2'
elif x[i] == '1':
a += '0'
b += '1'
else:
a += '0'
b += '0'
print(a)
print(b)
|
Python
|
[
"other"
] | 972
| 689
| 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,832
|
9877f4773f34041ea60f9052a36af5a8
|
This is an interactive problem!Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 \le t \le 2), two different indices i and j (1 \le i, j \le n, i \neq j), and an integer x (1 \le x \le n - 1). Depending on t, she will answer: t = 1: \max{(\min{(x, p_i)}, \min{(x + 1, p_j)})}; t = 2: \min{(\max{(x, p_i)}, \max{(x + 1, p_j)})}. You can ask Nastia at most \lfloor \frac {3 \cdot n} { 2} \rfloor + 30 times. It is guaranteed that she will not change her permutation depending on your queries. Can you guess the permutation?
|
['constructive algorithms', 'interactive']
|
import sys
def ask(q):
print(q, flush=True)
ret = int(input())
assert ret != -1
return ret
input = lambda: sys.stdin.buffer.readline().decode().strip()
for _ in range(int(input())):
n = int(input())
ans, ix = [0] * n, n
for i in range(2, n + 1, 2):
pos = ask(f'? 1 {i - 1} {i} {n - 1}')
if pos == n:
ix = i
break
if pos == n - 1:
if ask(f'? 1 {i} {i - 1} {n - 1}') == n:
ix = i - 1
break
ans[ix - 1] = n
for i in range(1, n + 1):
if i != ix:
ans[i - 1] = ask(f'? 2 {i} {ix} 1')
print('!', *ans, flush=True)
|
Python
|
[
"other"
] | 767
| 713
| 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
}
| 117
|
9ad07b42358e7f7cfa15ea382495a8a1
|
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109.At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.Your task is to determine the k-th identifier to be pronounced.
|
['implementation']
|
n, k = [int(x) for x in raw_input().split()]
a = [int(x) for x in raw_input(). split()]
cur = 0
i = 1
while cur + i < k:
cur += i
i += 1
rem = k - cur
if rem == 0:
print a[i - 1]
else:
print a[rem - 1]
|
Python
|
[
"other"
] | 697
| 219
| 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,786
|
bcee233ddb1509a14f2bd9fd5ec58798
|
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
|
['implementation', 'brute force']
|
import sys
n, k = [int(x) for x in raw_input().split()]
elems = [int(x) for x in raw_input().split()]
k -= 1
for i in xrange(k, n):
if elems[i] != elems[k]:
print -1
sys.exit(0)
# We are good. get the last element until k which is not equal.
steps = -1
for i in xrange(k):
if elems[i] != elems[k]:
steps = i
print steps + 1
|
Python
|
[
"other"
] | 454
| 363
| 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,807
|
aab8d5a2d42b4199310f3f535a6b3bd7
|
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, \dots, c_k] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold.For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: c = [1, 2, 4]; c = [3, 5, 6, 8]; c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
|
['data structures', 'sortings']
|
x=int(input());a=list(map(int,input().split()));b={}
for i in range(x):
tem=a[i]
if tem-i in b.keys():
b[tem-i]+=tem
else:
b[tem-i]=tem
print(max(b.values()))
|
Python
|
[
"other"
] | 1,591
| 165
| 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
}
| 744
|
02d62bb1eb4cc0e373b862a980d6b29c
|
Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.
|
['dp', 'implementation', 'bitmasks', 'brute force']
|
n=int(input())
p={
"A":10**9,
"B":10**9,
"C":10**9,
"AB":10**9,
"BC":10**9,
"AC":10**9,
"ABC":10**9
}
for i in range(n):
x,y=input().split()
x=int(x)
y=''.join(sorted(y))
p[y]=min(p[y],x)
x=min(
p["A"]+p["B"]+p["C"],
p["AB"]+p["C"],
p["AC"]+p["B"],
p["BC"]+p["A"],
p["ABC"],
p["AB"]+p["BC"],
p["AB"]+p["AC"],
p["BC"]+p["AC"],
p["A"]+p["ABC"],
p["B"]+p["ABC"],
p["C"]+p["ABC"],
p["AB"]+p["ABC"],
p["AC"]+p["ABC"],
p["BC"]+p["ABC"],
)
print(x) if x<10**7 else print("-1")
|
Python
|
[
"other"
] | 524
| 642
| 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
}
| 851
|
7bbb4b9f5eccfe13741445c815a4b1ca
|
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices i and j (1 \le i, j \le n) such that |i-j|=1 and a_i>0 and apply a_i = a_i - 1, a_j = a_j + 1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 1 (i.e. to maximize a_1), and she only has d days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 1 if she acts optimally!
|
['implementation', 'greedy']
|
a=int(input())
for i in range(a):
n,d=map(int,input().split())
z=list(map(int,input().split()))
if(n==1):
print(z[0])
else:
if(z[1]>=d):
print(z[0]+d)
else:
for i in range(1,len(z)):
if(d<=0):
break;
if(d>i*z[i] or z[i]==0):
d=d-i*z[i]
z[0]=z[0]+z[i]
else:
while(d>=0):
d=d-i
if(d>=0):
z[0]=z[0]+1
else:
break;
print(z[0])
|
Python
|
[
"other"
] | 870
| 791
| 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,153
|
f3d34922baf84c534e78e283dcadc742
|
You are playing a very popular computer game. The next level consists of n consecutive locations, numbered from 1 to n, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land i to any location with land i + x, spending x coins (x \geq 0).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.
|
['implementation']
|
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int,input().split()))
x = False
start = 0
end = 0
flag = False
for i in range(n):
if a[i] == 0 and not x:
start = i-1
while i<n and a[i]!=1:
i+=1
end = i
x = True
elif a[i] == 0:
flag = True
break
print(end-start if not flag else n-a[::-1].index(0)-start)
|
Python
|
[
"other"
] | 843
| 477
| 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,472
|
12abfbe7118868a0b1237489b5c92760
|
There are n pillars aligned in a row and numbered from 1 to n.Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i.You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: there is no other pillar between pillars i and j. Formally, it means that |i - j| = 1; pillar i contains exactly one disk; either pillar j contains no disks, or the topmost disk on pillar j has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all n disks on the same pillar simultaneously?
|
['implementation', 'greedy']
|
n = int(input())
l = list(map(int,input().split()))
max1 = l.index(n)
for i in range(1,n):
if i <= max1:
if l[i-1] < l[i]:
continue
else:
print("NO")
exit()
else:
if l[i] < l[i-1]:
continue
else:
print("NO")
exit()
print("YES")
|
Python
|
[
"other"
] | 1,130
| 256
| 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,348
|
c315870f5798dfd75ddfc76c7e3f6fa5
|
Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007 (109 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!
|
['dp']
|
MOD = 1000000007
st,n,t,mp=input(),int(input()),[],{}
t.append(['',st])
for i in range(10):
mp[str(i)]=(10,i)
for i in range(n):
t.append(input().split("->"))
for i in range(n,-1,-1):
a,b=1,0
for j in t[i][1]:
a,b=a*mp[j][0]%MOD,(b*mp[j][0]+mp[j][1])%MOD
mp[t[i][0]]= a,b
print(mp[''][1])
|
Python
|
[
"other"
] | 795
| 302
| 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
}
| 339
|
857de33d75daee460206079fa2c15814
|
Given a permutation p of length n, find its subsequence s_1, s_2, \ldots, s_k of length at least 2 such that: |s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k| is as big as possible over all subsequences of p with length at least 2. Among all such subsequences, choose the one whose length, k, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence a is a subsequence of an array b if a can be obtained from b by deleting some (possibly, zero or all) elements.A permutation of length n is an array of length n in which every element from 1 to n occurs exactly once.
|
['two pointers', 'greedy']
|
def ints():
return map(int,raw_input().split())
for _ in range(input()):
n = input()
a = ints()
l = [a[0],a[1]]
low = 0
i = 2
if n==2:
print 2
for x in l:
print x,
print
continue
while i!= n:
l.append(a[i])
if a[i-2]<a[i-1]<a[i] or a[i-2]>a[i-1]>a[i]:
temp = l.pop()
l.pop()
l.append(temp)
else:
low += 1
i+=1
print len(l)
for x in l:
print x,
print
|
Python
|
[
"other"
] | 740
| 527
| 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,874
|
e3a03f3f01a77a1983121bab4218c39c
|
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
|
['implementation', 'greedy']
|
N,K = map(int, input().split())
S = input()
a = K-1
b = N-K
if a ==0:
a = 1000
if b == 0:
b =1000
pos = K-1
printed = 1
print('PRINT '+str(S[pos]))
if a<=b:
while pos!=0:
print('LEFT')
pos-=1
print('PRINT '+str(S[pos]))
printed+=1
if printed !=N:
while pos!=K-1:
print('RIGHT')
pos+=1
while pos!=N-1:
print('RIGHT')
pos+=1
print('PRINT '+str(S[pos]))
printed+=1
elif a>b:
while pos!=N-1:
print('RIGHT')
pos+=1
print('PRINT '+str(S[pos]))
printed+=1
if printed !=N:
while pos!=K-1:
print('LEFT')
pos-=1
while pos!=0:
print('LEFT')
pos-=1
print('PRINT '+str(S[pos]))
printed+=1
|
Python
|
[
"other"
] | 1,480
| 833
| 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,427
|
6d146936ab34deaee24721e53474aef0
|
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position i is strictly greater than the value at position j.Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the n arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most (at most pairs). Help Iahub, find any suitable array.
|
['two pointers', 'implementation', 'sortings', 'greedy']
|
n,m,k=map(int,raw_input().split())
for _ in range(n):
raw_input()
print (m)*(m-1)/2
for i in range(1,m):
for j in range(i+1,m+1):
if k==0:
print i,j
else:
print j,i
|
Python
|
[
"other"
] | 642
| 213
| 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,556
|
dddeb7663c948515def967374f2b8812
|
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median.A median in an array of length n is an element which occupies position number \lfloor \frac{n + 1}{2} \rfloor after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1.Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},\ldots,a_r for some 1 \leq l \leq r \leq n, its length is r - l + 1.
|
['binary search', 'data structures', 'dp']
|
a = []
n, k = 0, 0
def check(median):
mini = 2*10**5+1
part_sums = [0]
for val in a[:k]:
part_sums.append(part_sums[-1] + (val >= median) - (val < median))
for key, val in enumerate(a[k:]):
mini = min(mini, part_sums[key])
if part_sums[-1] - mini > 0:
return True
part_sums.append(part_sums[-1] + (val >= median) - (val < median))
# corner n == k
mini = min(mini, part_sums[n - k])
if part_sums[-1] - mini > 0:
return True
return False
def search(l, r) -> int:
if l == r - 1:
return l
mid = (l + r) // 2
if check(mid):
return search(mid, r)
return search(l, mid)
if __name__ == '__main__':
n, k = map(int, input().split())
a = list(map(int, input().split()))
print(search(1, 2*10**5+1))
|
Python
|
[
"other"
] | 594
| 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
}
| 1,357
|
2d988fe01f91847dcad52111c468c0ba
|
Slime has a sequence of positive integers a_1, a_2, \ldots, a_n.In one operation Orac can choose an arbitrary subsegment [l \ldots r] of this sequence and replace all values a_l, a_{l + 1}, \ldots, a_r to the value of median of \{a_l, a_{l + 1}, \ldots, a_r\}.In this problem, for the integer multiset s, the median of s is equal to the \lfloor \frac{|s|+1}{2}\rfloor-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5.Slime wants Orac to make a_1 = a_2 = \ldots = a_n = k using these operations.Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
|
['constructive algorithms', 'greedy']
|
import sys
from collections import deque
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n, k = nm()
l = nl()
if min(l) == max(l) == k:
print('yes')
return
if k not in l:
print('no')
return
l = [x >= k for x in l] + [0, 0]
print('yes' if max(sum(l[i:i+3]) for i in range(n)) > 1 else 'no')
# solve()
T = ni()
for _ in range(T):
solve()
|
Python
|
[
"other"
] | 824
| 627
| 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,876
|
c943a6413441651ec9f420ef44ea48d0
|
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.
|
['sortings', 'greedy']
|
# from random import shuffle
# f = open("out.txt", "w")
# n = 1000
# test = list(range(1, n + 1))
# shuffle(test)
# print(n, file=f)
# print(' '.join(map(str, test)), file=f)
from bisect import *
from sys import stdin
f = stdin # open("out.txt", "r")
n = int(f.readline())
primes = [1] * (n + 1)
primes[0] = 0
primes[1] = 0
for i in range(2, n + 1):
if primes[i] != 0:
for j in range(i + i, n + 1, i):
primes[j] = 0
primes = [i - 1 for i in range(n + 1) if primes[i] != 0]
a = list(map(int, f.readline().split()))
p = [0] * n
for i in range(n):
p[a[i] - 1] = i
swaps = []
for i in range(n):
if p[i] != i:
r = p[i]
while r != i:
j = bisect(primes, r - i) - 1
l = r - primes[j]
p[a[l] - 1], p[a[r] - 1] = p[a[r] - 1], p[a[l] - 1]
a[l], a[r] = a[r], a[l]
swaps += [(l, r)]
r = l
print(len(swaps))
if len(swaps) > 0:
print("\n".join("{} {}".format(l + 1, r + 1) for l, r in swaps))
|
Python
|
[
"other"
] | 602
| 945
| 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,027
|
18f44ab990ef841c947e2da831321845
|
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
|
['brute force']
|
import itertools
def check(curr_words, line):
if curr_words == []:
return True
for i in range(len(line)):
if line[i] == curr_words[0]:
return check(curr_words[1:], line[i+1:])
return False
n = int(input())
words = input().split()
m = int(input())
res, idx = 0, 0
for i in range(m):
line = input().split()[1:]
for p in itertools.permutations(range(n)):
curr_words = [words[j] for j in p]
cnt = 0
for j in range(n):
cnt += len([k for k in range(j+1, n) if p[k] < p[j]])
v = n * (n-1) // 2 - cnt + 1
if check(curr_words, line[:]) and v > res:
res, idx = v, i+1
if res > 0:
print(idx)
print('[:'+str('|'*res)+':]')
else:
print('Brand new problem!')
|
Python
|
[
"other"
] | 1,817
| 772
| 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,131
|
ce8350be138ce2061349d7f9224a5aaf
|
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point xi, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.
|
['data structures', 'dp']
|
from sys import stdin
from itertools import repeat
from bisect import bisect
def main():
n, m = map(int, stdin.readline().split())
dat = map(int, stdin.read().split(), repeat(10, 2 * n))
s = [0] * (m + 1)
for i, x in enumerate(dat):
if i & 1:
s[x] -= 1
else:
s[x-1] += 1
for i in xrange(m):
s[i+1] += s[i]
s.pop()
l = 0
b = [-1] * (m + 1)
L = [0] * m
R = [0] * m
for i in xrange(m):
p = bisect(b, s[i], 0, l)
b[p] = s[i]
if p == l:
l += 1
L[i] = p
s.reverse()
l = 0
b = [-1] * (m + 1)
for i in xrange(m):
p = bisect(b, s[i], 0, l)
b[p] = s[i]
if p == l:
l += 1
R[i] = p
R.reverse()
for i in xrange(m):
L[i] += R[i] + 1
print max(L)
main()
|
Python
|
[
"other"
] | 1,272
| 855
| 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
}
| 888
|
59d4c66892fa3157d1163225a550a368
|
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars: The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n \times m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n \cdot m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n \cdot m stars.
|
['dp', 'greedy', 'brute force']
|
n , m = [int(x) for x in input().split()]
grid = [[x for x in input()] for _ in range(n)]
star_mem = {}
astr_num = set()
def l_0 (x) :
return x < 1
def astr_size(x, y, size ):
for i in range(y,y+size+1,1):
astr_num.add((x,i))
for i in range(y,y-size-1,-1):
astr_num.add((x,i))
for i in range(x, x+size+1, 1):
astr_num.add((i,y))
for i in range(x, x-size-1,-1):
astr_num.add((i,y))
def is_star(grid, x, y):
left , right , uper , lower= (-1,-1,-1,-1)
for i in range(y,m,1):
if (x,i) in star_mem:
left += star_mem[(x,i)][0]+1
break
if grid[x][i] == '*':
left += 1
else :
break
for i in range(y, -1, -1):
if (x,i) in star_mem:
right += star_mem[(x,i)][1]+1
break
if grid[x][i] == '*':
right += 1
else :
break
for i in range(x, n, 1):
if (i,y) in star_mem:
uper += star_mem[(i,y)][2]+1
break
if grid[i][y] == '*':
uper += 1
else :
break
for i in range(x , -1, -1):
if (i,y) in star_mem:
lower += star_mem[(i,y)][3]+1
break
if grid[i][y] == '*':
lower += 1
else :
break
star_mem[(x,y)] = (left,right,uper,lower)
size = min(left,right,uper,lower)
if size > 0 :
return True,size
return False,0
solution = []
uni_astr = 0
for x in range(n):
for y in range(m):
if grid[x][y] == '*':
uni_astr += 1
con, size = is_star(grid, x, y)
if con:
astr_size(x, y, size)
solution.append((x+1,y+1,size))
if uni_astr == len(astr_num):
print(len(solution))
for i in solution:
print(*i)
else:
print(-1)
|
Python
|
[
"other"
] | 1,198
| 1,892
| 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,062
|
3d6411d67c85f6293f1999ccff2cd8ba
|
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.
|
['implementation']
|
# -*- coding: utf-8 -*-
N , K = [int(n) for n in raw_input().split(" ")]
r = []
num = raw_input().split(" ")
#N , K = 100 , 100
#num = [1 for i in xrange(100)]
for i in xrange(K):
r.append(0)
for n in num:
t = int(n)
r[t - 1] += 1
cnt = 0
while True:
i = 0
while i < K - 1 and r[i] == 0:
i += 1
if i == K - 1:
break
for i in xrange(K - 2 , -1 , -1):
#print i,
if r[i] != 0:
r[i] -= 1
r[i + 1] += 1
#print
cnt += 1
print cnt
|
Python
|
[
"other"
] | 1,282
| 518
| 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,967
|
468020848783d8e017f2d7de5b4fe940
|
A set of points on a plane is called good, if for any two points at least one of the three conditions is true: those two points lie on same horizontal line; those two points lie on same vertical line; the rectangle, with corners in these two points, contains inside or on its borders at least one point of the set, other than these two. We mean here a rectangle with sides parallel to coordinates' axes, the so-called bounding box of the two points.You are given a set consisting of n points on a plane. Find any good superset of the given set whose size would not exceed 2·105 points.
|
['constructive algorithms', 'divide and conquer']
|
s = set()
def build(l, r):
if (l >= r):
return
mid = (l+r) >> 1
for i in range(l, r):
s.add((a[mid][0], a[i][1]))
build(l, mid)
build(mid+1, r)
n = input()
a = []
for i in range(0, n):
x, y = map(int, raw_input().split())
a.append((x, y))
a.sort()
build(0, n)
print len(s)
for x in s:
print x[0], x[1]
|
Python
|
[
"other"
] | 587
| 350
| 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
}
| 665
|
6477fdad8455f57555f93c021995bb4d
|
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from the left sushi as t_i, where t_i = 1 means it is with tuna, and t_i = 2 means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment [2, 2, 2, 1, 1, 1] is valid, but subsegment [1, 2, 1, 2, 1, 2] is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.
|
['binary search', 'implementation', 'greedy']
|
n=int(input())
a=[int(x) for x in input().split()]
c1=0
c2=0
ans=[]
f=[a[0],1]
ans.append(f)
j=0
i=1
answer=0
while(i<n):
if(a[i]==a[i-1]):
ans[j][1]+=1
else:
j+=1
ans.append([a[i],1])
i+=1
for i in range(1,len(ans)):
res=2*min(ans[i-1][1],ans[i][1])
if(res>answer):
answer=res
print(answer)
|
Python
|
[
"other"
] | 891
| 344
| 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,815
|
05177408414e4056cd6b1ea46d1ac499
|
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements: choose any index i (1 \le i \le n) and move the element a[i] to the begin of the array; choose any index i (1 \le i \le n) and move the element a[i] to the end of the array. For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed: after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9]; after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4]. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] \le a[2] \le \ldots \le a[n].
|
['dp', 'two pointers', 'greedy']
|
# f = open('test.py')
# def input():
# return f.readline().replace('\n','')
def read_list():
return list(map(int,input().strip().split(' ')))
def print_list(l):
print(' '.join(map(str,l)))
N = int(input())
for _ in range(N):
n = int(input())
nums = read_list()
dic = {}
for i in range(n):
dic[nums[i]] = i
nums.sort()
res = 0
tmp = 1
for i in range(1,n):
if dic[nums[i]]<dic[nums[i-1]]:
res = max(res,tmp)
tmp = 1
else:
tmp+=1
res = max(res,tmp)
print(n-res)
|
Python
|
[
"other"
] | 1,289
| 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,330
|
cc9abcff3224118b533881335e4c582b
|
You have two binary strings a and b of length n. You would like to make all the elements of both strings equal to 0. Unfortunately, you can modify the contents of these strings using only the following operation: You choose two indices l and r (1 \le l \le r \le n); For every i that respects l \le i \le r, change a_i to the opposite. That is, a_i := 1 - a_i; For every i that respects either 1 \le i < l or r < i \le n, change b_i to the opposite. That is, b_i := 1 - b_i. Your task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations should not exceed n + 5. It can be proven that if such chain of operations exists, one exists with at most n + 5 operations.
|
['constructive algorithms', 'implementation']
|
f=open(0)
I=lambda:next(f,'0 ')[:-1]
I()
while n:=int(I()):i=int(a:=I(),2)^int(I(),2);c=[f'{i} {i}'for i,x in
enumerate(a,1)if'0'<x];c+=(len(c)+i)%2*['1 1',f'1 {n}',f'2 {n}'];print(*(['YES',len(c)]+c,['NO'])[1<i+1<1<<n])
|
Python
|
[
"other"
] | 852
| 220
| 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,595
|
2733797c5dd5b9d9e0bf9fe786c3120a
|
Let's consider the famous game called Boom (aka Hat) with simplified rules.There are n teams playing the game. Each team has two players. The purpose of the game is to explain the words to the teammate without using any words that contain the same root or that sound similarly. Player j from team i (1 ≤ i ≤ n, 1 ≤ j ≤ 2) is characterized by two numbers: aij and bij. The numbers correspondingly represent the skill of explaining and the skill of understanding this particular player has. Besides, m cards are used for the game. Each card has a word written on it. The card number k (1 ≤ k ≤ m) is characterized by number ck — the complexity of the word it contains.Before the game starts the cards are put in a deck and shuffled. Then the teams play in turns like that: the 1-st player of the 1-st team, the 1-st player of the 2-nd team, ... , the 1-st player of the n-th team, the 2-nd player of the 1-st team, ... , the 2-nd player of the n-th team, the 1-st player of the 1-st team and so on.Each turn continues for t seconds. It goes like that: Initially the time for each turn is t. While the time left to a player is more than 0, a player takes a card from the top of the deck and starts explaining the word it has to his teammate. The time needed for the j-th player of the i-th team to explain the word from the card k to his teammate (the q-th player of the i-th team) equals max(1, ck - (aij + biq) - dik) (if j = 1, then q = 2, else q = 1). The value dik is the number of seconds the i-th team has already spent explaining the word k during the previous turns. Initially, all dik equal 0. If a team manages to guess the word before the end of the turn, then the time given above is substracted from the duration of the turn, the card containing the guessed word leaves the game, the team wins one point and the game continues. If the team doesn't manage to guess the word, then the card is put at the bottom of the deck, dik increases on the amount of time of the turn, spent on explaining the word. Thus, when this team gets the very same word, they start explaining it not from the beginning, but from the point where they stopped. The game ends when words from all m cards are guessed correctly.You are given n teams and a deck of m cards. You should determine for each team, how many points it will have by the end of the game and which words the team will have guessed.
|
['implementation']
|
from collections import deque
stdin = open('input.txt', 'r')
stdout = open('output.txt', 'w')
n,t = [int(x) for x in stdin.readline().split()]
teams = []
for x in range(n):
a1,b1,a2,b2 = [int(x) for x in stdin.readline().split()]
teams.append([(a1,b1), (a2,b2)])
m = int(stdin.readline())
deck = deque()
cs = {}
for x in range(m):
word = stdin.readline().strip()
c = int(stdin.readline())
cs[word] = [c for y in range(n)]
deck.append(word)
team = 0
exp = 0
und = 1
wins = [[] for x in range(n)]
while deck:
time = t
cTeam = teams[team]
while time > 0 and deck:
word = deck.popleft()
c = cs[word][team]
val = max(c - cTeam[exp][0] - cTeam[und][1], 1)
#print(time,c,word,cTeam, exp, val)
if val <= time:
#print('win', team, word)
wins[team].append(word)
time -= val
else:
cs[word][team] -= time
deck.append(word)
time = 0
team += 1
if team == n:
team = 0
exp = (exp+1)%2
und = (und+1)%2
for x in wins:
stdout.write(str(len(x)) + ' ' + ' '.join(x) + '\n')
|
Python
|
[
"other"
] | 2,388
| 1,158
| 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,196
|
45cf60f551bd5cbb1f3df6ac3004b53c
|
Given the integer n — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of 3 platforms for 2-nd, 1-st and 3-rd places respectively. The platform for the 1-st place must be strictly higher than for the 2-nd place, and the platform for the 2-nd place must be strictly higher than for the 3-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block). Example pedestal of n=11 blocks: second place height equals 4 blocks, first place height equals 5 blocks, third place height equals 2 blocks.Among all possible pedestals of n blocks, deduce one such that the platform height for the 1-st place minimum as possible. If there are several of them, output any of them.
|
['constructive algorithms', 'greedy']
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 11 14:58:24 2022
@author: Ajay Varma
"""
# 5 9 3
# aaacc
# bbdddeeee
# aaabbcc
for i in range(int(input())):
n = int(input())
if n==7:
print(2 ,4, 1)
continue
if n%3:
a = (n//3)+1
b = (n//3)+2
c = (n//3)- (2 if n%3==1 else 1)
else:
a = (n//3)
b = (n//3)+1
c= (n//3)-1
print(a,b,c)
|
Python
|
[
"other"
] | 871
| 598
| 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,366
|
5097e92916e49cdc6fb4953b864186db
|
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
|
['sortings', 'greedy']
|
f = lambda: map(int, input().split())
n, k = f()
print(sum(sorted(f())[:k]))
|
Python
|
[
"other"
] | 534
| 76
| 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,926
|
235131226fee9d04efef4673185c1c9b
|
There are n students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive.Firstly, the first coach will choose the student with maximum programming skill among all students not taken into any team, and k closest students to the left of him and k closest students to the right of him (if there are less than k students to the left or to the right, all of them will be chosen). All students that are chosen leave the row and join the first team. Secondly, the second coach will make the same move (but all students chosen by him join the second team). Then again the first coach will make such move, and so on. This repeats until the row becomes empty (i. e. the process ends when each student becomes to some team).Your problem is to determine which students will be taken into the first team and which students will be taken into the second team.
|
['data structures', 'implementation', 'sortings']
|
n, k = tuple([int(i) for i in input().split()])
#places = [None] * (n)
data = [int(i) for i in input().split()]
nextup = {}
nextdown = {}
nextup[data[n-1]] = -1
nextdown[data[0]] = -1
for i in range(n-1):
#places[data[i] - 1] = i
nextup[data[i]] = data[i+1]
nextdown[data[i+1]] = data[i]
#results = [None] * (n)
# def take(a):
# global nextdown
# global nextup
# global l
# # print(nextup)
# # print(nextdown)
# # print(a)
# # print(char)
# # print(l)
# b = a
# c = a
# l[a-1] = char
# found = 0
# #global places
# #global data
# #places[a] = -1
# while found < k:
# #print(places)
# t = nextdown[b]
# #print(t)
# if t == -1:
# break
# found += 1
# l[t-1] = char
# b = t
# found = 0
# while found < k:
# #print(places)
# t = nextup[c]
# #print(t)
# if t == -1:
# break
# found += 1
# l[t-1] = char
# c = t
# # for i in data:
# # if type(l[i-1]) == int:
# # print('?', end='')
# # else:
# # print(l[i-1], end='')
# # # print()
# # print(b, c)
# # print('==============')
# nextdown[nextup[c]] = nextdown[b]
# nextup[nextdown[b]] = nextup[c]
# # print('------')
# # print(data)
##ups = {}
#downs = {}
#places.reverse()
l = list(range(1, n+1))
switch = {'1':'2', '2':'1'}
char = '2'
for j in range(n-1, -1, -1):
i = l[j]
if type(i) == int:
char = switch[char]
b = i
c = i
l[i-1] = char
found = 0
#global places
#global data
#places[a] = -1
while found < k:
#print(places)
t = nextdown[b]
#print(t)
if t == -1:
break
found += 1
l[t-1] = char
b = t
found = 0
while found < k:
#print(places)
t = nextup[c]
#print(t)
if t == -1:
break
found += 1
l[t-1] = char
c = t
# for i in data:
# if type(l[i-1]) == int:
# print('?', end='')
# else:
# print(l[i-1], end='')
# # print()
# print(b, c)
# print('==============')
nextdown[nextup[c]] = nextdown[b]
nextup[nextdown[b]] = nextup[c]
#print(l)
for i in data:
print(l[i-1], end='')
print()
|
Python
|
[
"other"
] | 1,099
| 2,606
| 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
}
| 997
|
1f4dfaff6d9d0e95573f272f71b0fd45
|
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions.The attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.Tell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.
|
['meet-in-the-middle']
|
import copy
def fill(k):
global di
for i in range(3):
x = [tasks[k][0], tasks[k][1], tasks[k][2]]
x[i] = 0
mi = min(x)
x[0],x[1],x[2] = x[0]-mi, x[1]-mi, x[2]-mi
for p in di[k+1]:
u,v,w = x[0]+p[0],x[1]+p[1],x[2]+p[2]
mi = min(u,v,w)
u,v,w = u-mi, v-mi, w-mi
di[k][(u,v,w)] = 1
def recurse(k):
global cp, tot, best, bits, n, n_count, func_count, m, di
#print k
# func_count+=1
# if func_count%1000000 == 0:
# print bits
if k==n:
# n_count+=1
# if n_count%1000 == 0:
# print n_count
#print bits
#print tot
if tot[0]==tot[1] and tot[1]==tot[2]:
if tot[0] > best:
best = tot[0]
cp = copy.deepcopy(bits)
#print best
# print cp
# print bits
return 1
return 0
#bound:
if n > 14 and k > m:
M = max(tot[0], tot[1], tot[2])
#t0, t1, t2 = M-tot[0], M-tot[1], M-tot[2]
if (M-tot[0], M-tot[1], M-tot[2]) not in di[k]:
return 0
# for i in range(3):
# for j in range(3):
# if i != j and tot[i] + sp[k][i] < tot[j] + sn[k][j]:
# return 0
# if tot[0]+sp[k][0] < tot[1]+sn[k][1] or tot[0]+sp[k][0] < tot[2]+sn[k][2]:
# return 0
for i in range(3):
tot[i] += tasks[k][i]
for i in range(3):
bits[k] = i
tot[i] -= tasks[k][i]
recurse(k+1)
tot[i] += tasks[k][i]
for i in range(3):
tot[i] -= tasks[k][i]
#print 'start'
n_count = 0
func_count = 0
n = int(raw_input())
tasks = [ [0,0,0,i] for i in range(n) ]
tl = ['L', 'M', 'W'] #task labels
bits = [-1 for i in range(n)]
best = -10**9
cp = []
tot = [0,0,0]
for i in range(n):
tasks[i][0], tasks[i][1], tasks[i][2] = map(int, raw_input().split())
#tasks = sorted(tasks, lambda x,y: cmp(x[0],y[0]))
#print tasks_s
#sp = [ [0,0,0] for i in range(n) ]
#sn = [ [0,0,0] for i in range(n) ]
#for i in range(n):
# for j in range(3):
# sp[i][j] = sum([tasks[k][j] for k in range(i,n) if tasks[k][j]>0])
# sn[i][j] = sum([tasks[k][j] for k in range(i,n) if tasks[k][j]<0])
#print sp
#print sn
di = [ {} for i in range(n+1) ]
if n > 13:
di[n][(0,0,0)] = 1
m = n-12
for j in range(n-1, m, -1):
fill(j)
recurse(0)
if best == -10**9:
print 'Impossible'
exit()
#print cp
for i in range(n):
s = ''
for j in range(3):
if j!=cp[i]:
s+=tl[j]
print s
|
Python
|
[
"other"
] | 749
| 2,202
| 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
}
| 555
|
667e8938b964d7a24500003f6b89717b
|
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 \cdot n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from left to right. Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all 2n students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.
|
['dp']
|
n = int(input())
masiv = []
for i in range(2):
lst = [0] + list(map(int, input().split()))
masiv.append(lst)
lst_1 = [0] * (n + 1)
lst_2 = [0] * (n + 1)
lst_1[1] = masiv[0][1]
lst_2[1] = masiv[1][1]
for j in range(2, n + 1):
lst_1[j] = max(lst_2[j - 1], lst_2[j - 2]) + masiv[0][j]
lst_2[j] = max(lst_1[j - 1], lst_1[j - 2]) + masiv[1][j]
ans = 0
for f in lst_1:
ans = max(ans, f)
for k in lst_2:
ans = max(ans, k)
print(ans)
|
Python
|
[
"other"
] | 1,144
| 450
| 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
}
| 219
|
51113dfdbf9f59152712b60e7a14368a
|
You are given a sequence a_1, a_2, \dots, a_n consisting of n integers.You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.
|
['greedy', 'constructive algorithms', 'two pointers', 'sortings', 'binary search', 'ternary search']
|
n, k = [int(x) for x in input().split()]
d = {}
b = []
for i in map(int, input().split()):
if i not in d:
b.append(i)
d[i] = 1
else:
d[i] += 1
b.sort()
mi, ma = 0, len(b) - 1
left, right = b[mi], b[ma]
am_left, am_right = d[b[mi]], d[b[ma]]
mi, ma = 1, len(b) - 2
while right - left > 0:
if am_left <= am_right:
if (b[mi] - left)*am_left <= k:
k -= (b[mi] - left)*am_left
left = b[mi]
am_left += d[b[mi]]
mi += 1
else:
left += k // am_left
break
else:
if (right - b[ma])*am_right <= k:
k -= (right - b[ma])*am_right
right = b[ma]
am_right += d[b[ma]]
ma -= 1
else:
right -= k // am_right
break
print(right - left)
|
Python
|
[
"other"
] | 388
| 859
| 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
}
| 617
|
61fb771f915b551a9bcce90c74e0ef64
|
Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.Help Eugene to calculate the number of nonempty good subarrays of a given array a.
|
['data structures', 'two pointers', 'implementation', 'binary search']
|
n = int(input())
seen = dict()
seen[0] = 0
out = 0
l = list(map(int,input().split()))
curr = 0
bestCurr = 0
for i in range(n):
curr += l[i]
if curr in seen:
bestCurr = min(bestCurr + 1, i - seen[curr])
else:
bestCurr += 1
out += bestCurr
seen[curr] = i + 1
print(out)
|
Python
|
[
"other"
] | 829
| 303
| 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
}
| 947
|
c8747882ea0a79c0f821a6b9badd2625
|
This is the hard version of the problem. The only difference is that in this version q = n.You are given an array of integers a_1, a_2, \ldots, a_n.The cost of a subsegment of the array [l, r], 1 \leq l \leq r \leq n, is the value f(l, r) = \operatorname{sum}(l, r) - \operatorname{xor}(l, r), where \operatorname{sum}(l, r) = a_l + a_{l+1} + \ldots + a_r, and \operatorname{xor}(l, r) = a_l \oplus a_{l+1} \oplus \ldots \oplus a_r (\oplus stands for bitwise XOR).You will have q queries. Each query is given by a pair of numbers L_i, R_i, where 1 \leq L_i \leq R_i \leq n. You need to find the subsegment [l, r], L_i \leq l \leq r \leq R_i, with maximum value f(l, r). If there are several answers, then among them you need to find a subsegment with the minimum length, that is, the minimum value of r - l + 1.
|
['binary search', 'bitmasks', 'brute force', 'greedy', 'implementation', 'two pointers']
|
from bisect import bisect_left, bisect_right
import sys
import io
import os
# region IO
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = io.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(io.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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip('\r\n')
def read_int_list():
return list(map(int, input().split()))
def read_int_tuple():
return tuple(map(int, input().split()))
def read_int():
return int(input())
# endregion
# region local test
# if 'AW' in os.environ.get('COMPUTERNAME', ''):
# test_no = 1
# f = open(os.path.dirname(__file__) + f'\\in{test_no}.txt', 'r')
# def input():
# return f.readline().rstrip("\r\n")
# endregion
def solve():
n, q = read_int_tuple()
A = read_int_list()
pre = [0] * (n + 1)
pxr = [0] * (n + 1)
for i, x in enumerate(A, 1):
pre[i] = x + pre[i - 1]
pxr[i] = x ^ pxr[i - 1]
idx = [i for i, x in enumerate(A) if x]
for _ in range(q):
L, R = read_int_tuple()
li, ri = bisect_left(idx, L - 1), bisect_right(idx, R - 1) - 1
if not (0 <= li <= ri < len(idx)):
print(L, L)
continue
L, R = idx[li], idx[ri]
tx = pxr[R + 1] ^ pxr[L]
hi = pre[R + 1] - pre[L] - tx
if hi == 0:
print(L + 1, L + 1)
continue
tl, tr = L, R
for dd in range(1, min(bin(tx).count('1') + 1, ri - li + 1)):
for dl in range(dd + 1):
dr = dd - dl
i, j = idx[li + dl], idx[ri - dr]
cur = pre[j + 1] - pre[i] - (pxr[j + 1] ^ pxr[i])
if cur == hi and tr - tl > j - i:
tl, tr = i, j
print(tl + 1, tr + 1)
T = read_int() # 1
for t in range(T):
solve()
|
Python
|
[
"other"
] | 907
| 3,857
| 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,480
|
d1f4872924f521b6cc206ee1e8f2dd3a
|
You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n.You have to connect all n rooms to the Internet.You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.
|
['dp', 'greedy', 'data structures']
|
def solve(N, K, S):
nxt = [0] * (N+1)
cur = 1 << 30
for i in xrange(N, 0, -1):
if S[i-1] == '1':
cur = i
nxt[i] = cur
dp = [0]
for i in xrange(1, N+1):
dp.append(dp[-1] + i)
c = nxt[max(i-K, 1)]
if c <= i+K:
dp[i] = min(dp[i], dp[max(1,c-K)-1] + c)
return dp[N]
N, K = map(int, raw_input().split())
print solve(N, K, raw_input())
|
Python
|
[
"other"
] | 977
| 433
| 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,337
|
87045c4df69110642122f2c114476947
|
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
|
['greedy']
|
R=lambda:map(int,raw_input().split())
n=input()
a=sorted(R(),reverse=True)
for i in xrange(1,n):a[i]+=a[i-1]
t=[a[n-1]-a[0]]*100100
for k in xrange(1,n+1):
s,u,p,d=0,0,1,0
while u<n:
p*=k
d+=1
s+=(a[min(u+p,n-1)]-a[u])*d
u+=p
t[k]=s
q=input()
print ' '.join(map(lambda x:str(t[x]),R()))
|
Python
|
[
"other"
] | 795
| 310
| 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
}
| 157
|
5278cb48aca6fc84e2df393cd8723ecb
|
A binary string is a string consisting only of the characters 0 and 1. You are given a binary string s_1 s_2 \ldots s_n. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following: Select an arbitrary index 1 \leq i \leq n in the string; For all j \geq i, change the value in the j-th position to the opposite, that is, if s_j = 1, then make s_j = 0, and vice versa.What is the minimum number of operations needed to make the string non-decreasing?
|
['brute force', 'dp', 'greedy', 'implementation']
|
from sys import stdin, stdout
t = int(stdin.readline())
for p in range(t):
n = int(stdin.readline())
listA = [int(x) for x in str(stdin.readline().strip())]
count = 0
i = 0
while i < n-1:
#print(i, count)
if listA[i] == 1 and listA[i+1] == 0:
if i+2 < n:
for j in range(i+2,n):
if listA[j] == 1:
i = j
count += 2
break
if j == n-1:
i = j +1
count += 1
else:
i = i+2
count += 1
else:
i += 1
print(count)
|
Python
|
[
"other"
] | 623
| 730
| 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,076
|
4931c42108f487b81b702db3617f0af6
|
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.
|
['dp', 'binary search', 'greedy']
|
__author__ = 'Darren'
def solve():
original = input()
temp = [original[0]]
for i in range(1, len(original)):
if original[i] == original[i-1] != 'X':
temp.append('X')
temp.append(original[i])
augmented = ''.join(temp)
answer = 0
if augmented[0] == augmented[-1] != 'X':
answer = max(rate(augmented+'X'), rate('X'+augmented))
else:
answer = rate(augmented)
print('%d.%06d' % (answer / 1000000, answer % 1000000))
def rate(seq):
correct, total, unknown, indicator = 0, 0, 0, 0
left_step = True
for action in seq:
if action == 'X':
total += 1
left_step = not left_step
else:
if left_step and action == 'L' or not left_step and action == 'R':
correct += 1
total += 1
indicator = 0
left_step = not left_step
else:
correct += 1
total += 2
unknown += indicator
indicator = 1 - indicator
if total % 2 == 1:
total += 1
unknown += indicator
if correct * 2 > total:
correct -= unknown
total -= unknown * 2
return correct * 100000000 // total
if __name__ == '__main__':
solve()
|
Python
|
[
"other"
] | 1,652
| 1,299
| 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,406
|
e12d86f0c8645424b942d3dd9038e04d
|
Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.
|
['implementation', 'brute force']
|
n = int(input())
laptops = []
for i in range(n):
speed, ram, hdd, cost = map(int, input().split())
laptops.append([False, speed, ram, hdd, cost])
for i in range(n):
for j in range(n):
if laptops[i][1] < laptops[j][1] and laptops[i][2] < laptops[j][2] and laptops[i][3] < laptops[j][3]:
laptops[i][0] = True
minPrice = 1001
best = 1
for i in range(n):
if not laptops[i][0]:
if laptops[i][4] < minPrice:
minPrice = laptops[i][4]
best = i+1
print(best)
|
Python
|
[
"other"
] | 657
| 519
| 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,155
|
4abdd16670a796be3a0bff63b9798fed
|
Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?
|
['sortings', 'greedy']
|
n=int(input())
c=[]
value=0
count=1
for i in range(n):
a,b=map(int,input().split())
if b!=0:
value+=a
count+=b-1
else:
c.append(a)
c.sort()
if len(c)>0:
index=len(c)-1
for i in range(count):
value+=c[index]
index-=1
if index==-1:
break
print(value)
elif len(c)==n:
print(c[-1])
else:
print(value)
|
Python
|
[
"other"
] | 1,168
| 402
| 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,807
|
ae7c80e068e267673a5f910bb0b121ec
|
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are n cards with k features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k = 4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.
|
['data structures', 'implementation', 'brute force']
|
n=int(input().split()[0])
s={input()for _ in[0]*n}
a=[['SET'.find(x)for x in y]for y in s]
print(sum(''.join('SET '[(3-x-y,x)[x==y]]for x,y in
zip(a[i],a[j]))in s for i in range(n)for j in range(i))//3)
|
Python
|
[
"other"
] | 1,114
| 203
| 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
}
| 35
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.