contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
---|---|---|---|
817 | Really Big Numbers | Title: Really Big Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number *x* is really big if the difference between *x* and the sum of its digits (in decimal representation) is not less than *s*. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are — in fact, he needs to calculate the quantity of really big numbers that are not greater than *n*.
Ivan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.
Input Specification:
The first (and the only) line contains two integers *n* and *s* (1<=≤<=*n*,<=*s*<=≤<=1018).
Output Specification:
Print one integer — the quantity of really big numbers that are not greater than *n*.
Demo Input:
['12 1\n', '25 20\n', '10 9\n']
Demo Output:
['3\n', '0\n', '1\n']
Note:
In the first example numbers 10, 11 and 12 are really big.
In the second example there are no really big numbers that are not greater than 25 (in fact, the first really big number is 30: 30 - 3 ≥ 20).
In the third example 10 is the only really big number (10 - 1 ≥ 9). | ```python
def main():
def sumofdigit(n):
temp=0
while(n>0):
temp+=n%10
n=n//10
return temp
def F(x):
return x-sumofdigit(x)
def findout(s):
test=s-s%10+10
while(1):
if F(test)>=s:
break
else:
test+=10
return test
n,s=list(map(int,input().strip().split(' ')))
L=findout(s)
ans=n-L+1
if ans<0:
print(0)
else:
print(ans)
main()
``` |
893 | Credit Card | Title: Credit Card
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recenlty Luba got a credit card and started to use it. Let's consider *n* consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of *i*-th day a transaction *a**i* occurs. If *a**i*<=><=0, then *a**i* bourles are deposited to Luba's account. If *a**i*<=<<=0, then *a**i* bourles are withdrawn. And if *a**i*<==<=0, then the amount of money on Luba's account is checked.
In the morning of any of *n* days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed *d*.
It can happen that the amount of money goes greater than *d* by some transaction in the evening. In this case answer will be «-1».
Luba must not exceed this limit, and also she wants that every day her account is checked (the days when *a**i*<==<=0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
Input Specification:
The first line contains two integers *n*, *d* (1<=≤<=*n*<=≤<=105, 1<=≤<=*d*<=≤<=109) —the number of days and the money limitation.
The second line contains *n* integer numbers *a*1,<=*a*2,<=... *a**n* (<=-<=104<=≤<=*a**i*<=≤<=104), where *a**i* represents the transaction in *i*-th day.
Output Specification:
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
Demo Input:
['5 10\n-1 5 0 -5 3\n', '3 4\n-10 0 20\n', '5 10\n-5 0 10 -11 0\n']
Demo Output:
['0\n', '-1\n', '2\n']
Note:
none | ```python
def main():
n, d = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
cur = 0
balance = 0
lows = [0] * n
rigs = [0] * n
for i in range(n):
balance += a[i]
if a[i] == 0:
lows[i] = -balance
rigs[i] = d - balance
for i in range(1, n):
lows[i] = max(lows[i], lows[i - 1])
for i in range(n - 2, -1, -1):
rigs[i] = min(rigs[i], rigs[i + 1])
for i in range(n):
if lows[i] > rigs[i]:
print("-1")
return
if cur < lows[i]:
cur = rigs[i]
ans += 1
print(ans)
if __name__ == "__main__":
main()# 1692038411.5287888
``` |
977 | Cyclic Components | Title: Cyclic Components
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
- the first vertex is connected with the second vertex by an edge, - the second vertex is connected with the third vertex by an edge, - ... - the last vertex is connected with the first vertex by an edge, - all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
Input Specification:
The first line contains two integer numbers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 2 \cdot 10^5$) — number of vertices and edges.
The following $m$ lines contains edges: edge $i$ is given as a pair of vertices $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$). There is no multiple edges in the given graph, i.e. for each pair ($v_i, u_i$) there no other pairs ($v_i, u_i$) and ($u_i, v_i$) in the list of edges.
Output Specification:
Print one integer — the number of connected components which are also cycles.
Demo Input:
['5 4\n1 2\n3 4\n5 4\n3 5\n', '17 15\n1 8\n1 12\n5 11\n11 9\n9 15\n15 5\n4 13\n3 13\n4 3\n10 16\n7 10\n16 7\n14 3\n14 4\n17 6\n']
Demo Output:
['1\n', '2\n']
Note:
In the first example only component $[3, 4, 5]$ is also a cycle.
The illustration above corresponds to the second example. | ```python
n, m = map(int, input().split())
grafo = [[] for i in range(n + 1)]
for i in range(m):
v_i, u_i = map(int, input().split())
grafo[v_i].append(u_i)
grafo[u_i].append(v_i)
conjunto = set(i for i in range(n + 1) if len(grafo[i]) == 2)
res = 0
while conjunto:
i = conjunto.pop()
v, u = grafo[i]
while u in conjunto:
conjunto.remove(u)
v_i, u_i = grafo[u]
if v_i in conjunto:
u = v_i
elif u_i in conjunto:
u = u_i
else:
break
if v == u:
res += 1
print(res)
``` |
1,003 | Coins and Queries | Title: Coins and Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some non-negative integer number $d$).
Polycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the query is the minimum number of coins that is necessary to obtain the value $b_j$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $b_j$, the answer to the $j$-th query is -1.
The queries are independent (the answer on the query doesn't affect Polycarp's coins).
Input Specification:
The first line of the input contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) — the number of coins and the number of queries.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ — values of coins ($1 \le a_i \le 2 \cdot 10^9$). It is guaranteed that all $a_i$ are integer powers of $2$ (i.e. $a_i = 2^d$ for some non-negative integer number $d$).
The next $q$ lines contain one integer each. The $j$-th line contains one integer $b_j$ — the value of the $j$-th query ($1 \le b_j \le 10^9$).
Output Specification:
Print $q$ integers $ans_j$. The $j$-th integer must be equal to the answer on the $j$-th query. If Polycarp can't obtain the value $b_j$ the answer to the $j$-th query is -1.
Demo Input:
['5 4\n2 4 8 2 4\n8\n5\n14\n10\n']
Demo Output:
['1\n-1\n3\n2\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
def main():
n, q = map(int, input().split())
A = list(map(int, input().split()))
cnt = [0] * 35
bi = [1]
for _ in range(34): bi.append(bi[-1] * 2)
for a in A:
cnt[a.bit_length() - 1] += 1
for _ in range(q):
b = int(input())
c = 0
for i in range(34, -1, -1):
p = min(cnt[i], b // bi[i])
c += p
b -= bi[i] * p
if b == 0:
print(c)
else:
print(-1)
for _ in range(1):
main()
``` |
961 | Tufurama | Title: Tufurama
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
TV series have *n* seasons (numbered 1 through *n*), the *i*-th season has *a**i* episodes (numbered 1 through *a**i*). Polycarp thinks that if for some pair of integers *x* and *y* (*x*<=<<=*y*) exist both season *x* episode *y* and season *y* episode *x* then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
Input Specification:
The first line contains one integer *n* (1<=<=≤<=*n*<=<=≤<=<=2·105) — the number of seasons.
The second line contains *n* integers separated by space *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — number of episodes in each season.
Output Specification:
Print one integer — the number of pairs *x* and *y* (*x*<=<<=*y*) such that there exist both season *x* episode *y* and season *y* episode *x*.
Demo Input:
['5\n1 2 3 4 5\n', '3\n8 12 7\n', '3\n3 2 1\n']
Demo Output:
['0\n', '3\n', '2\n']
Note:
Possible pairs in the second example:
1. *x* = 1, *y* = 2 (season 1 episode 2 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 2 episode 1); 1. *x* = 2, *y* = 3 (season 2 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 2); 1. *x* = 1, *y* = 3 (season 1 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 1).
In the third example:
1. *x* = 1, *y* = 2 (season 1 episode 2 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 2 episode 1); 1. *x* = 1, *y* = 3 (season 1 episode 3 <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8774ca35b6e628888a4670e4539d47857e5e5841.png" style="max-width: 100.0%;max-height: 100.0%;"/> season 3 episode 1). | ```python
from collections import defaultdict
import sys
input = sys.stdin.readline
def make_tree(n):
tree = [0] * (n + 1)
return tree
def get_sum(i):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
def get_sum_segment(s, t):
if s > t:
return 0
ans = get_sum(t) - get_sum(s - 1)
return ans
def add(i, x):
while i <= n:
tree[i] += x
i += i & -i
n = int(input())
a = list(map(int, input().split()))
d = defaultdict(lambda : [])
tree = make_tree(n)
for i in range(n):
a[i] = min(a[i], n)
d[a[i]].append(i)
add(i + 1, 1)
ans = 0
for i in range(n):
ans += get_sum_segment(i + 2, a[i])
for j in d[i + 1]:
add(j + 1, -1)
print(ans)
``` |
946 | Timetable | Title: Timetable
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan is a student at Berland State University (BSU). There are *n* days in Berland week, and each of these days Ivan might have some classes at the university.
There are *m* working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during *i*-th hour, and last lesson is during *j*-th hour, then he spends *j*<=-<=*i*<=+<=1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.
Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than *k* lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.
Given *n*, *m*, *k* and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than *k* lessons?
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=500, 0<=≤<=*k*<=≤<=500) — the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively.
Then *n* lines follow, *i*-th line containing a binary string of *m* characters. If *j*-th character in *i*-th line is 1, then Ivan has a lesson on *i*-th day during *j*-th hour (if it is 0, there is no such lesson).
Output Specification:
Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than *k* lessons.
Demo Input:
['2 5 1\n01001\n10110\n', '2 5 0\n01001\n10110\n']
Demo Output:
['5\n', '8\n']
Note:
In the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.
In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | ```python
from heapq import heapify, heappop, heappush
from itertools import cycle
from math import sqrt,ceil
import os
import sys
from collections import defaultdict,deque
from io import BytesIO, IOBase
from collections import Counter
from functools import lru_cache
from collections import deque
def main():
n,m,k=map(int,input().split())
mn=[[float("inf")]*(m+1) for _ in range(n+1)]
arr=[]
for _ in range(n):
temp=[i for i,el in enumerate(input()) if el=="1"]
arr.append(temp[:])
for i in range(n):
t=arr[i]
mn[i][0]=0
for j in range(1,len(t)+1):
start=0
end=j-1
p=float("inf")
while end<len(t):
p=min(p,t[end]-t[start]+1)
end+=1
start+=1
mn[i][j]=p
dp=[[float("inf")]*(k+1) for _ in range(n+1)]
dp[0][0]=0
for i in range(1,n+1):
le=len(arr[i-1])
for j in range(k+1):
for lec in range(le+1):
bunk=le-lec
if bunk<=j:
dp[i][j]=min(dp[i][j],mn[i-1][lec]+dp[i-1][j-bunk])
print(min(dp[-1]))
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):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
main()
``` |
762 | USB vs. PS/2 | Title: USB vs. PS/2
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!
The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.
You have found a price list of a certain computer shop. In it, for *m* mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.
You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.
Input Specification:
The first line contains three integers *a*, *b* and *c* (0<=≤<=*a*,<=*b*,<=*c*<=≤<=105) — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively.
The next line contains one integer *m* (0<=≤<=*m*<=≤<=3·105) — the number of mouses in the price list.
The next *m* lines each describe another mouse. The *i*-th line contains first integer *val**i* (1<=≤<=*val**i*<=≤<=109) — the cost of the *i*-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.
Output Specification:
Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.
Demo Input:
['2 1 1\n4\n5 USB\n6 PS/2\n3 PS/2\n7 PS/2\n']
Demo Output:
['3 14\n']
Note:
In the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports. | ```python
usb, ps, both = map(int, input().split())
a, b = [], []
max_, total = 0, 0
for _ in range(int(input())):
cost, type = input().split()
if type == 'USB':
a.append(int(cost))
else:
b.append(int(cost))
a = sorted(a, reverse=True)
b = sorted(b, reverse=True)
while usb and a:
usb -= 1
total += a.pop()
max_ += 1
while ps and b:
ps -= 1
total += b.pop()
max_ += 1
rem = sorted(a + b, reverse=True)
while both and rem:
both -= 1
total += rem.pop()
max_ += 1
print(max_, total)
``` |
598 | Chocolate Bar | Title: Chocolate Bar
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have a rectangular chocolate bar consisting of *n*<=×<=*m* single squares. You want to eat exactly *k* squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2<=×<=3 unit squares then you can break it horizontally and get two 1<=×<=3 pieces (the cost of such breaking is 32<==<=9), or you can break it vertically in two ways and get two pieces: 2<=×<=1 and 2<=×<=2 (the cost of such breaking is 22<==<=4).
For several given values *n*, *m* and *k* find the minimum total cost of breaking. You can eat exactly *k* squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to *k* squares. The remaining *n*·*m*<=-<=*k* squares are not necessarily form a single rectangular piece.
Input Specification:
The first line of the input contains a single integer *t* (1<=≤<=*t*<=≤<=40910) — the number of values *n*, *m* and *k* to process.
Each of the next *t* lines contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=30,<=1<=≤<=*k*<=≤<=*min*(*n*·*m*,<=50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
Output Specification:
For each *n*, *m* and *k* print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly *k* squares.
Demo Input:
['4\n2 2 1\n2 2 3\n2 2 2\n2 2 4\n']
Demo Output:
['5\n5\n4\n0\n']
Note:
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2<sup class="upper-index">2</sup> = 4), - to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1<sup class="upper-index">2</sup> = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample. | ```python
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(1000000)
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
dp = [[[0 for k in range (51)] for j in range (31)] for i in range (31)]
def calc (n, m, k) :
#print(n,m,k)
if (dp[n][m][k] != 0) or (n*m == k) or (k == 0) :
return dp[n][m][k]
ans = 10**9
for i in range (1,n//2 + 1) :
for j in range (k+1) :
#print(i,j,'a')
if (i*m >= (k-j)) and ((n-i)*m >= j) :
ans = min(ans, m*m + calc(i,m,k-j) + calc(n-i,m,j))
for i in range (1,m//2 + 1) :
for j in range (k+1) :
#print(i,j,'b')
if (i*n >= (k-j)) and ((m-i)*n >= j) :
ans = min(ans, n*n + calc(n,i,k-j) + calc(n,m-i,j))
dp[n][m][k] = ans
return ans
for _ in range (getN()):
N, M, K = getNM()
print(calc(N, M, K))
``` |
678 | Another Sith Tournament | Title: Another Sith Tournament
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The rules of Sith Tournament are well known to everyone. *n* Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.
Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=18) — the number of participants of the Sith Tournament.
Each of the next *n* lines contains *n* real numbers, which form a matrix *p**ij* (0<=≤<=*p**ij*<=≤<=1). Each its element *p**ij* is the probability that the *i*-th participant defeats the *j*-th in a duel.
The elements on the main diagonal *p**ii* are equal to zero. For all different *i*, *j* the equality *p**ij*<=+<=*p**ji*<==<=1 holds. All probabilities are given with no more than six decimal places.
Jedi Ivan is the number 1 in the list of the participants.
Output Specification:
Output a real number — the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10<=-<=6.
Demo Input:
['3\n0.0 0.5 0.8\n0.5 0.0 0.4\n0.2 0.6 0.0\n']
Demo Output:
['0.680000000000000\n']
Note:
none | ```python
n = int(input())
cnt = [0] * (1 << n)
p = [[0] * n for _ in range(n)]
f = [[0] * (1 << n) for _ in range(n)]
for i in range(n):
p[i] = list(map(float, input().split()))
for i in range(1, 1 << n):
cnt[i] = cnt[i & (i - 1)] + 1
f[0][1] = 1
for i in range(1, 1 << n):
if cnt[i] < 2:
continue
for j in range(n):
for k in range(n):
if j != k and (i >> k & 1):
f[j][i] = max(f[j][i], p[j][k] * f[j][i ^ (1 << k)] + p[k][j] * f[k][i ^ (1 << j)])
res = 0
for i in range(n):
res = max(res, f[i][(1 << n) - 1])
print("{:.12f}".format(res))# 1691522133.880112
``` |
952 | Puzzling Language | Title: Puzzling Language
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: [https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp](https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp) (use C++11 to compile the code). Note several implementation details:
- The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.- The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.- The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.- Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.- Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input Specification:
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output Specification:
Output a program in the described language which, when executed, will print the given message.
Demo Input:
['$$$']
Demo Output:
['.......X.......\n......XXX......\n.....XXXXX.....\n....XXXXXXX....\n...XXXXXXXXX...\n..XXXXXXXXXXX..\n.XXXXXXXXXXXXX.\n...............\nX.............X\nX..............\nX..............\nX..............\n']
Note:
The example corresponds to the following Brainfuck program:
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times. | ```python
from sys import stdin,stdout
# from os import _exit
# from bisect import bisect_left,bisect
# from heapq import heapify,heappop,heappush
# from sys import setrecursionlimit
# from collections import defaultdict,Counter
# from itertools import permutations
# from math import gcd,ceil,sqrt,factorial
# setrecursionlimit(int(1e5))
input,print = stdin.readline,stdout.write
s = input().strip()
for i in range(len(s)):
k = s[i]
a = ord(k)
print(270*"."+"\n")
print("...")
print(a*"X"+(267-a)*"."+"\nX.X")
print(a*"X"+"X."+(265-a)*"X"+"\n")
print(270*"."+"\nX")
print(268*"."+"X\nX")
print(269*"."+"\n")
print(270*"."+"\n")
print(a*"X.")
print((270-2*a)*"."+"\n")
``` |
575 | Tablecity | Title: Tablecity
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.
Tablecity can be represented as 1000<=×<=2 grid, where every cell represents one district. Each district has its own unique name “(*X*,<=*Y*)”, where *X* and *Y* are the coordinates of the district in the grid. The thief’s movement is as
Every hour the thief will leave the district (*X*,<=*Y*) he is currently hiding in, and move to one of the districts: (*X*<=-<=1,<=*Y*), (*X*<=+<=1,<=*Y*), (*X*<=-<=1,<=*Y*<=-<=1), (*X*<=-<=1,<=*Y*<=+<=1), (*X*<=+<=1,<=*Y*<=-<=1), (*X*<=+<=1,<=*Y*<=+<=1) as long as it exists in Tablecity.
Below is an example of thief’s possible movements if he is located in district (7,1):
Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.
Input Specification:
There is no input for this problem.
Output Specification:
The first line of output contains integer *N* – duration of police search in hours. Each of the following *N* lines contains exactly 4 integers *X**i*1, *Y**i*1, *X**i*2, *Y**i*2 separated by spaces, that represent 2 districts (*X**i*1, *Y**i*1), (*X**i*2, *Y**i*2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement.
- *N*<=≤<=2015 - 1<=≤<=*X*<=≤<=1000 - 1<=≤<=*Y*<=≤<=2
Demo Input:
["В этой задаче нет примеров ввода-вывода.\nThis problem doesn't have sample input and output."]
Demo Output:
['Смотрите замечание ниже.\nSee the note below.']
Note:
Let's consider the following output:
2
5 1 50 2
8 1 80 2
This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.
Consider the following initial position and thief’s movement:
In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.
At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.
Since there is no further investigation by the police, the thief escaped! | ```python
print(1999)
for i in range(1, 1001):
print(i, 1, i, 2)
p = 1000
while p != 1:
print(p, 1, p, 2)
p-=1
``` |
952 | I'm Feeling Lucky! | Title: I'm Feeling Lucky!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have one chip and one chance to play roulette. Are you feeling lucky?
Input Specification:
none
Output Specification:
Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).
Note:
none | ```python
print("odd")
# ihgfuierhqfwerbvg qgjiowehfuebhwlgho;shg;ohawf;wohf;woehfa;wlfh
``` |
808 | Selling Souvenirs | Title: Selling Souvenirs
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has *n* different souvenirs to sell; *i*th souvenir is characterised by its weight *w**i* and cost *c**i*. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than *m*, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100000, 1<=≤<=*m*<=≤<=300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then *n* lines follow. *i*th line contains two integers *w**i* and *c**i* (1<=≤<=*w**i*<=≤<=3, 1<=≤<=*c**i*<=≤<=109) — the weight and the cost of *i*th souvenir.
Output Specification:
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Demo Input:
['1 1\n2 1\n', '2 2\n1 3\n2 2\n', '4 3\n3 10\n2 7\n2 8\n1 1\n']
Demo Output:
['0\n', '3\n', '10\n']
Note:
none | ```python
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
n, m = map(int, input().split())
c1, c2, c3 = [0], [0], [0]
for _ in range(n):
x, y = map(int, input().split())
if x == 3:
c3.append(y)
elif x == 2:
c2.append(y)
else:
c1.append(y)
c1.sort(reverse=True)
c2.sort(reverse=True)
c3.sort(reverse=True)
dp = [None for i in range(m+1)]
dp[0] = (0, 0, 0)
dp[1] = (c1[0], 1, 0)
for i in range(2, m+1):
if dp[i-1][1] == len(c1):
x1 = (dp[i-1][0], dp[i-1][1], dp[i-1][2])
else:
x1 = (dp[i-1][0]+c1[dp[i-1][1]], dp[i-1][1]+1, dp[i-1][2])
if dp[i-2][2] == len(c2):
x2 = (dp[i-2][0], dp[i-2][1], dp[i-2][2])
else:
x2 = (dp[i-2][0]+c2[dp[i-2][2]], dp[i-2][1], dp[i-2][2]+1)
if x1[0] > x2[0]:
dp[i] = x1
else:
dp[i] = x2
ans = 0
cost3 = 0
for i in range(len(c3)):
cost3 += c3[i-1]
cap = m - 3*i
if cap < 0: break
ans = max(ans, cost3+dp[cap][0])
print(ans)
``` |
409 | On a plane | Title: On a plane
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of points on a plane.
Each of the next *n* lines contains two real coordinates *x**i* and *y**i* of the point, specified with exactly 2 fractional digits. All coordinates are between <=-<=1000 and 1000, inclusive.
Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10<=-<=2.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of points on a plane.
Each of the next *n* lines contains two real coordinates *x**i* and *y**i* of the point, specified with exactly 2 fractional digits. All coordinates are between <=-<=1000 and 1000, inclusive.
Output Specification:
Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10<=-<=2.
Demo Input:
['8\n-2.14 2.06\n-1.14 2.04\n-2.16 1.46\n-2.14 0.70\n-1.42 0.40\n-0.94 -0.48\n-1.42 -1.28\n-2.16 -1.62\n', '5\n2.26 1.44\n2.28 0.64\n2.30 -0.30\n1.58 0.66\n3.24 0.66\n', '8\n6.98 2.06\n6.40 1.12\n5.98 0.24\n5.54 -0.60\n7.16 0.30\n7.82 1.24\n8.34 0.24\n8.74 -0.76\n', '5\n10.44 2.06\n10.90 0.80\n11.48 -0.48\n12.06 0.76\n12.54 2.06\n', '8\n16.94 2.42\n15.72 2.38\n14.82 1.58\n14.88 0.50\n15.76 -0.16\n16.86 -0.20\n17.00 0.88\n16.40 0.92\n', '7\n20.62 3.00\n21.06 2.28\n21.56 1.36\n21.66 0.56\n21.64 -0.52\n22.14 2.32\n22.62 3.04\n']
Demo Output:
['5.410\n', '5.620\n', '5.480\n', '6.040\n', '6.040\n', '6.720\n']
Note:
none | ```python
# LUOGU_RID: 112712157
n = int(input())
Sum = 0
for _ in range(n):
[x, y] = [float(i) for i in input().split()]
Sum += y
print(5 + Sum / n)
``` |
847 | Sum of Nestings | Title: Sum of Nestings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the following sequences are regular: "()()()", "(())" and "()". The following sequences are not regular bracket sequences: ")(", "(()" and "())(()".
In this problem you are given two integers *n* and *k*. Your task is to construct a regular bracket sequence consisting of round brackets with length 2·*n* with total sum of nesting of all opening brackets equals to exactly *k*. The nesting of a single opening bracket equals to the number of pairs of brackets in which current opening bracket is embedded.
For example, in the sequence "()(())" the nesting of first opening bracket equals to 0, the nesting of the second opening bracket equals to 0 and the nesting of the third opening bracket equal to 1. So the total sum of nestings equals to 1.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=3·105, 0<=≤<=*k*<=≤<=1018) — the number of opening brackets and needed total nesting.
Output Specification:
Print the required regular bracket sequence consisting of round brackets.
If there is no solution print "Impossible" (without quotes).
Demo Input:
['3 1\n', '4 6\n', '2 5\n']
Demo Output:
['()(())', '(((())))', 'Impossible\n']
Note:
The first example is examined in the statement.
In the second example the answer is "(((())))". The nesting of the first opening bracket is 0, the nesting of the second is 1, the nesting of the third is 2, the nesting of fourth is 3. So the total sum of nestings equals to 0 + 1 + 2 + 3 = 6.
In the third it is impossible to construct a regular bracket sequence, because the maximum possible total sum of nestings for two opening brackets equals to 1. This total sum of nestings is obtained for the sequence "(())". | ```python
import sys
input = sys.stdin.buffer.readline
def ints():
return map(int, input().split())
n, k=ints()
if k > (n-1)*n//2:
print("Impossible")
exit(0)
sum=0
ans=''
for i in range(n+1):
if sum+i>k:
ans+='('*(i)
ans+=')'*(i-(k-sum))
if i!=n:
ans+='('
ans+=')'*(k-sum+1)
ans+='()'*(n-i-1)
else:
ans+=')'*(k-sum)
break
sum+=i
print(ans)
``` |
509 | Restoring Numbers | Title: Restoring Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya had two arrays consisting of non-negative integers: *a* of size *n* and *b* of size *m*. Vasya chose a positive integer *k* and created an *n*<=×<=*m* matrix *v* using the following formula:
Vasya wrote down matrix *v* on a piece of paper and put it in the table.
A year later Vasya was cleaning his table when he found a piece of paper containing an *n*<=×<=*m* matrix *w*. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix *v* from those days. Your task is to find out if the matrix *w* that you've found could have been obtained by following these rules and if it could, then for what numbers *k*,<=*a*1,<=*a*2,<=...,<=*a**n*,<=*b*1,<=*b*2,<=...,<=*b**m* it is possible.
Input Specification:
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100), separated by a space — the number of rows and columns in the found matrix, respectively.
The *i*-th of the following lines contains numbers *w**i*,<=1,<=*w**i*,<=2,<=...,<=*w**i*,<=*m* (0<=≤<=*w**i*,<=*j*<=≤<=109), separated by spaces — the elements of the *i*-th row of matrix *w*.
Output Specification:
If the matrix *w* could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output.
Otherwise, print four lines.
In the first line print "YES" (without quotes).
In the second line print an integer *k* (1<=≤<=*k*<=≤<=1018). Note that each element of table *w* should be in range between 0 and *k*<=-<=1 inclusively.
In the third line print *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=1018), separated by spaces.
In the fourth line print *m* integers *b*1,<=*b*2,<=...,<=*b**m* (0<=≤<=*b**i*<=≤<=1018), separated by spaces.
Demo Input:
['2 3\n1 2 3\n2 3 4\n', '2 2\n1 2\n2 0\n', '2 2\n1 2\n2 1\n']
Demo Output:
['YES\n1000000007\n0 1 \n1 2 3 ', 'YES\n3\n0 1 \n1 2 ', 'NO\n']
Note:
By <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e4ee2bc16f1508a982cfc739e1c7ddc442223116.png" style="max-width: 100.0%;max-height: 100.0%;"/> we denote the remainder of integer division of *b* by *c*.
It is guaranteed that if there exists some set of numbers *k*, *a*<sub class="lower-index">1</sub>, ..., *a*<sub class="lower-index">*n*</sub>, *b*<sub class="lower-index">1</sub>, ..., *b*<sub class="lower-index">*m*</sub>, that you could use to make matrix *w*, then there also exists a set of numbers that meets the limits 1 ≤ *k* ≤ 10<sup class="upper-index">18</sup>, 1 ≤ *a*<sub class="lower-index">*i*</sub> ≤ 10<sup class="upper-index">18</sup>, 1 ≤ *b*<sub class="lower-index">*i*</sub> ≤ 10<sup class="upper-index">18</sup> in the output format. In other words, these upper bounds are introduced only for checking convenience purposes. | ```python
def main():
n, m = map(int, input().split())
l = list(tuple(map(int, input().split())) for _ in range(n))
ma = max(x for _ in l for x in _)
bb = l[0]
x = bb[0]
aa = [_[0] - x for _ in l]
err = set(map(abs, filter(None, (a + b - x for a, row in zip(aa, l) for b, x in zip(bb, row)))))
if err:
k = err.pop()
if err or k <= ma:
print('NO')
return
else:
k = ma + 1
for i in range(n):
aa[i] %= k
print('YES')
print(k)
print(*aa)
print(*bb)
if __name__ == '__main__':
main()
``` |
784 | Numbers Joke | Title: Numbers Joke
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=30).
Output a single integer.
Input Specification:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=30).
Output Specification:
Output a single integer.
Demo Input:
['3\n']
Demo Output:
['27\n']
Note:
none | ```python
#-------------Program--------------
#----Kuzlyaev-Nikita-Codeforces----
#-------------Training-------------
#----------------------------------
r=[4, 22, 27, 58, 85, 94, 121, 166,
202, 265, 274, 319, 346, 355, 378,
382, 391, 438, 454, 483, 517, 526,
535, 562, 576, 588, 627, 634, 636,
645, 648, 654, 663, 666, 690, 706,
728, 729, 762, 778, 825, 852, 861,
895, 913, 915, 922, 958, 985, 1086,
1111, 1165]
n=int(input())
print(r[n-1])
``` |
825 | Tree Queries | Title: Tree Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a tree consisting of *n* vertices (numbered from 1 to *n*). Initially all vertices are white. You have to process *q* queries of two different types:
1. 1 *x* — change the color of vertex *x* to black. It is guaranteed that the first query will be of this type. 1. 2 *x* — for the vertex *x*, find the minimum index *y* such that the vertex with index *y* belongs to the simple path from *x* to some black vertex (a simple path never visits any vertex more than once).
For each query of type 2 print the answer to it.
Note that the queries are given in modified way.
Input Specification:
The first line contains two numbers *n* and *q* (3<=≤<=*n*,<=*q*<=≤<=106).
Then *n*<=-<=1 lines follow, each line containing two numbers *x**i* and *y**i* (1<=≤<=*x**i*<=<<=*y**i*<=≤<=*n*) and representing the edge between vertices *x**i* and *y**i*.
It is guaranteed that these edges form a tree.
Then *q* lines follow. Each line contains two integers *t**i* and *z**i*, where *t**i* is the type of *i*th query, and *z**i* can be used to restore *x**i* for this query in this way: you have to keep track of the answer to the last query of type 2 (let's call this answer *last*, and initially *last*<==<=0); then *x**i*<==<=(*z**i*<=+<=*last*)<=*mod*<=*n*<=+<=1.
It is guaranteed that the first query is of type 1, and there is at least one query of type 2.
Output Specification:
For each query of type 2 output the answer to it.
Demo Input:
['4 6\n1 2\n2 3\n3 4\n1 2\n1 2\n2 2\n1 3\n2 2\n2 2\n']
Demo Output:
['3\n2\n1\n']
Note:
none | ```python
from collections import deque
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def bfs(s):
q = deque()
q.append(s)
dp = [inf] * (n + 1)
dp[s] = s
while q:
i = q.popleft()
for j in G[i]:
if dp[j] ^ inf:
continue
dp[j] = min(j, dp[i])
q.append(j)
return dp
n, q = map(int, input().split())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = map(int, input().split())
G[x].append(y)
G[y].append(x)
last = 0
inf = pow(10, 9) + 1
_, z = map(int, input().split())
s = (z + last) % n + 1
dp = bfs(s)
ans = []
mi = inf
for _ in range(q - 1):
t, z = map(int, input().split())
x = (z + last) % n + 1
if t == 1:
mi = min(mi, dp[x])
else:
ans0 = min(mi, dp[x])
ans.append(ans0)
last = ans0
sys.stdout.write("\n".join(map(str, ans)))
``` |
730 | Delete Them | Title: Delete Them
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp is a beginner programmer. He is studying how to use a command line.
Polycarp faced the following problem. There are *n* files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the pattern and all other files shouldn't match the pattern.
Polycarp doesn't know about an asterisk '*', the only special character he knows is a question mark '?' which matches any single character. All other characters in the pattern match themselves only.
Formally, a pattern matches a filename if and only if they have equal lengths and all characters in the corresponding positions are equal except when the character in the pattern is '?', in which case the corresponding filename character does not matter.
For example, the filename pattern "a?ba?":
- matches filenames "aabaa", "abba.", "a.ba9" and "a.ba."; - does not match filenames "aaba", "abaab", "aabaaa" and "aabaa.".
Help Polycarp find a pattern which matches files to be deleted and only them or report if there is no such pattern.
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=100) — the total number of files and the number of files to be deleted.
The following *n* lines contain filenames, single filename per line. All filenames are non-empty strings containing only lowercase English letters, digits and dots ('.'). The length of each filename doesn't exceed 100. It is guaranteed that all filenames are distinct.
The last line of the input contains *m* distinct integer numbers in ascending order *a*1,<=*a*2,<=...,<=*a**m* (1<=≤<=*a**i*<=≤<=*n*) — indices of files to be deleted. All files are indexed from 1 to *n* in order of their appearance in the input.
Output Specification:
If the required pattern exists, print "Yes" in the first line of the output. The second line should contain the required pattern. If there are multiple solutions, print any of them.
If the required pattern doesn't exist, print the only line containing "No".
Demo Input:
['3 2\nab\nac\ncd\n1 2\n', '5 3\ntest\ntezt\ntest.\n.est\ntes.\n1 4 5\n', '4 4\na\nb\nc\ndd\n1 2 3 4\n', '6 3\n.svn\n.git\n....\n...\n..\n.\n1 2 3\n']
Demo Output:
['Yes\na?\n', 'Yes\n?es?\n', 'No\n', 'Yes\n.???\n']
Note:
none | ```python
n,m=map(int,input().split())
a=[]
b=[]
for i in range(n):
a.append(input())
t=list(map(int,input().split()))
flag=0
x=len(a[t[0]-1])
for i in t:
b.append(a[i-1])
if len(a[i-1])!=x:
flag=1
break
s=''
if flag!=1:
for i in range(x):
l=b[0][i]
abc=0
for j in range(m):
if b[j][i]!=l:
abc=1
break
if(abc==0):
s+=l
else:
s+='?'
for i in range(n):
if i+1 not in t:
if len(a[i])==x:
flag=1
for j in range(x):
if(s[j]=='?'):
pass
elif(s[j]!=a[i][j]):
flag=0
break
if flag==1:
break
if flag==1:
print("No")
else:
print("Yes")
print(s)
else:
print("No")
``` |
863 | Yet Another Array Queries Problem | Title: Yet Another Array Queries Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* of size *n*, and *q* queries to it. There are queries of two types:
- 1 *l**i* *r**i* — perform a cyclic shift of the segment [*l**i*,<=*r**i*] to the right. That is, for every *x* such that *l**i*<=≤<=*x*<=<<=*r**i* new value of *a**x*<=+<=1 becomes equal to old value of *a**x*, and new value of *a**l**i* becomes equal to old value of *a**r**i*; - 2 *l**i* *r**i* — reverse the segment [*l**i*,<=*r**i*].
There are *m* important indices in the array *b*1, *b*2, ..., *b**m*. For each *i* such that 1<=≤<=*i*<=≤<=*m* you have to output the number that will have index *b**i* in the array after all queries are performed.
Input Specification:
The first line contains three integer numbers *n*, *q* and *m* (1<=≤<=*n*,<=*q*<=≤<=2·105, 1<=≤<=*m*<=≤<=100).
The second line contains *n* integer numbers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109).
Then *q* lines follow. *i*-th of them contains three integer numbers *t**i*, *l**i*, *r**i*, where *t**i* is the type of *i*-th query, and [*l**i*,<=*r**i*] is the segment where this query is performed (1<=≤<=*t**i*<=≤<=2, 1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
The last line contains *m* integer numbers *b*1, *b*2, ..., *b**m* (1<=≤<=*b**i*<=≤<=*n*) — important indices of the array.
Output Specification:
Print *m* numbers, *i*-th of which is equal to the number at index *b**i* after all queries are done.
Demo Input:
['6 3 5\n1 2 3 4 5 6\n2 1 3\n2 3 6\n1 1 6\n2 2 1 5 3\n']
Demo Output:
['3 3 1 5 2 \n']
Note:
none | ```python
import sys
#Library Info(ACL for Python/Pypy) -> https://github.com/not522/ac-library-python
def input():
return sys.stdin.readline().rstrip()
DXY = [(0, -1), (1, 0), (0, 1), (-1, 0)] # L,D,R,Uの順番
def main():
n, q, m = map(int, input().split())
a = list(map(int, input().split()))
query = [tuple(map(int, input().split())) for i in range(q)]
indices = list(map(int, input().split()))
for t,l,r in query[::-1]:
if t == 1:
for i,idx in enumerate(indices):
if l <= idx <= r:
if idx > l:
indices[i] = idx - 1
else:
indices[i] = r
else:
for i,idx in enumerate(indices):
if l <= idx <= r:
indices[i] = l + r - idx
ans = [a[idx - 1] for idx in indices]
print(*ans)
return 0
if __name__ == "__main__":
main()
``` |
1,005 | Median on Segments (Permutations Edition) | Title: Median on Segments (Permutations Edition)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a permutation $p_1, p_2, \dots, p_n$. A permutation of length $n$ is a sequence such that each integer between $1$ and $n$ occurs exactly once in the sequence.
Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$.
The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.
For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.
Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$.
Input Specification:
The first line contains integers $n$ and $m$ ($1 \le n \le 2\cdot10^5$, $1 \le m \le n$) — the length of the given sequence and the required value of the median.
The second line contains a permutation $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$). Each integer between $1$ and $n$ occurs in $p$ exactly once.
Output Specification:
Print the required number.
Demo Input:
['5 4\n2 4 5 3 1\n', '5 5\n1 2 3 4 5\n', '15 8\n1 15 2 14 3 13 4 8 12 5 11 6 10 7 9\n']
Demo Output:
['4\n', '1\n', '48\n']
Note:
In the first example, the suitable pairs of indices are: $(1, 3)$, $(2, 2)$, $(2, 3)$ and $(2, 4)$. | ```python
n, m = map(int,input().split())
a = list(map(int,input().split()))
d = {0: 1}
check, q, ans = 0,0,0
for i in a:
if i < m:
q -= 1
elif i > m:
q += 1
else:
check = 1
if check:
ans += d.get(q,0)+d.get(q-1,0)
else:
new = d.get(q,0) + 1
d[q] = new
print(ans)
``` |
616 | Longest k-Good Segment | Title: Longest k-Good Segment
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The array *a* with *n* integers is given. Let's call the sequence of one or more consecutive elements in *a* segment. Also let's call the segment k-good if it contains no more than *k* different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input Specification:
The first line contains two integers *n*,<=*k* (1<=≤<=*k*<=≤<=*n*<=≤<=5·105) — the number of elements in *a* and the parameter *k*.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=106) — the elements of the array *a*.
Output Specification:
Print two integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in *a* are numbered from 1 to *n* from left to right.
Demo Input:
['5 5\n1 2 3 4 5\n', '9 3\n6 5 1 2 3 2 1 4 5\n', '3 1\n1 2 3\n']
Demo Output:
['1 5\n', '3 7\n', '1 1\n']
Note:
none | ```python
n,k = [int(i) for i in input().split()]
d = [int(i) for i in input().split()]
l,r=0,0
s= dict()
ans = 0
ll,rr=0,0
while r<n:
while len(s)>=k:
s[d[l]]-=1
if s[d[l]]==0:
s.pop(d[l])
l+=1
while r<n:
if d[r] not in s:
if len(s)<k:
s[d[r]]=1
else:
break
else:
s[d[r]]+=1
r+=1
if r-l>ans:
ans=r-l
ll,rr=l,r
print(ll+1,rr)
``` |
990 | Bracket Sequences Concatenation Problem | Title: Bracket Sequences Concatenation Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A bracket sequence is a string containing only characters "(" and ")".
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
You are given $n$ bracket sequences $s_1, s_2, \dots , s_n$. Calculate the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. "()(" + ")()" = "()()()".
If $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer.
Input Specification:
The first line contains one integer $n \, (1 \le n \le 3 \cdot 10^5)$ — the number of bracket sequences. The following $n$ lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed $3 \cdot 10^5$.
Output Specification:
In the single line print a single integer — the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence.
Demo Input:
['3\n)\n()\n(\n', '2\n()\n()\n']
Demo Output:
['2\n', '4\n']
Note:
In the first example, suitable pairs are $(3, 1)$ and $(2, 2)$.
In the second example, any pair is suitable, namely $(1, 1), (1, 2), (2, 1), (2, 2)$. | ```python
n = int(input())
pos=[0]*(3*100001)
neg=[0]*(3*100001)
for i in range(n):
a=list(input())
c1=c2=0
th=1
b1=b2=0
for j in a:
if j=='(':
c1+=1
else:
c1-=1
if c1<0:
b1=1
break
if b1!=0:
for j in a[::-1]:
if j ==')':
c2+=1
else:
c2-=1
if c2<0:
b2=1
break
if b1==0:
pos[c1]+=1
elif b2==0:
neg[c2]+=1
ans=pos[0]**2
for i in range(1,300001):
ans+=pos[i]*neg[i]
print(ans)
``` |
717 | R3D3’s Summer Adventure | Title: R3D3’s Summer Adventure
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.
There are *n* letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.
Given the costs *c*0 and *c*1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.
Input Specification:
The first line of input contains three integers *n* (2<=≤<=*n*<=≤<=108), *c*0 and *c*1 (0<=≤<=*c*0,<=*c*1<=≤<=108) — the number of letters in the alphabet, and costs of '0' and '1', respectively.
Output Specification:
Output a single integer — minimum possible total a cost of the whole alphabet.
Demo Input:
['4 1 2\n']
Demo Output:
['12\n']
Note:
There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12. | ```python
import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,a,b=map(int,input().split())
if a<b: a,b=b,a
if b==0:
# 1 01 001 0001 ... is optimal, plus a long series of 0's
print((n-1)*a)
else:
# pascal's triangle thing
pascal=[[1]*20005]
for i in range(20004):
newrow=[1]
for j in range(1,20005):
newrow.append(newrow[-1]+pascal[-1][j])
if newrow[-1]>n: break
pascal.append(newrow)
def getcom(a,b):
# return a+b choose b
# if larger than n, return infinite
if len(pascal[a])>b: return pascal[a][b]
if b==0: return 1
if b==1: return a
return 100000005
# start with the null node (prefix cost 0)
# can split a node into two other nodes with added cost c+a+b
# new nodes have prefix costs c+a, c+b
# want n-1 splits in total
remain=n-1
ans=0
possible=[[a+b,1]] # [c,count]
while 1:
# cost u, v leaves
u,v=heapq.heappop(possible)
while possible and possible[0][0]==u:
v+=possible[0][1]
heapq.heappop(possible)
if remain<=v:
ans+=u*remain
break
ans+=u*v
remain-=v
heapq.heappush(possible,[u+a,v])
heapq.heappush(possible,[u+b,v])
print(ans)
``` |
911 | Tree Destruction | Title: Tree Destruction
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an unweighted tree with *n* vertices. Then *n*<=-<=1 following operations are applied to the tree. A single operation consists of the following steps:
1. choose two leaves; 1. add the length of the simple path between them to the answer; 1. remove one of the chosen leaves from the tree.
Initial answer (before applying operations) is 0. Obviously after *n*<=-<=1 such operations the tree will consist of a single vertex.
Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!
Input Specification:
The first line contains one integer number *n* (2<=≤<=*n*<=≤<=2·105) — the number of vertices in the tree.
Next *n*<=-<=1 lines describe the edges of the tree in form *a**i*,<=*b**i* (1<=≤<=*a**i*, *b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*). It is guaranteed that given graph is a tree.
Output Specification:
In the first line print one integer number — maximal possible answer.
In the next *n*<=-<=1 lines print the operations in order of their applying in format *a**i*,<=*b**i*,<=*c**i*, where *a**i*,<=*b**i* — pair of the leaves that are chosen in the current operation (1<=≤<=*a**i*, *b**i*<=≤<=*n*), *c**i* (1<=≤<=*c**i*<=≤<=*n*, *c**i*<==<=*a**i* or *c**i*<==<=*b**i*) — choosen leaf that is removed from the tree in the current operation.
See the examples for better understanding.
Demo Input:
['3\n1 2\n1 3\n', '5\n1 2\n1 3\n2 4\n2 5\n']
Demo Output:
['3\n2 3 3\n2 1 1\n', '9\n3 5 5\n4 3 3\n4 1 1\n4 2 2\n']
Note:
none | ```python
# optimal answer must be to choose the diameter then remove leaves not on
# the diameter then remove the diameter
# for every leaf removed, the answer is maximal since otherwise we did not choose
# the diameter. When removing the diameter, clearly the maximal answer is
# # nodes left - 1 and this is achieved everytime
import sys
input = sys.stdin.buffer.readline
n = int(input())
adj =[[] for i in range(n+1)]
for i in range(n-1):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
dist1 = [0]*(n+1)
dist2 = [0]*(n+1)
diameter = []
on_diameter = [0]*(n+1)
s = [1]
path = []
vis = [0]*(n+1)
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
path.append(c)
dist1[c] = len(path)-1
for ne in adj[c]:
if not vis[ne]:
s.append(ne)
else:
path.pop()
s.pop()
mx_dist = 0
endpoint1 = 0
for i in range(1,n+1):
if dist1[i] > mx_dist:
mx_dist = dist1[i]
endpoint1 = i
s = [endpoint1]
path = []
vis = [0] * (n + 1)
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
path.append(c)
dist1[c] = len(path) - 1
for ne in adj[c]:
if not vis[ne]:
s.append(ne)
else:
path.pop()
s.pop()
mx_dist = 0
endpoint2 = 0
for i in range(1, n + 1):
if dist1[i] > mx_dist:
mx_dist = dist1[i]
endpoint2 = i
s = [endpoint2]
path = []
vis = [0] * (n + 1)
while s:
c = s[-1]
if not vis[c]:
vis[c] = 1
path.append(c)
if c == endpoint1:
diameter = path.copy()
dist2[c] = len(path) - 1
for ne in adj[c]:
if not vis[ne]:
s.append(ne)
else:
path.pop()
s.pop()
for i in diameter:
on_diameter[i] = 1
mx_answer = 0
operations = []
leaves = []
for i in range(1,n+1):
if len(adj[i]) == 1 and not on_diameter[i]:
leaves.append(i)
degree = [len(adj[i]) for i in range(n+1)]
while leaves:
c = leaves.pop()
if dist1[c] > dist2[c]:
mx_answer += dist1[c]
operations.append([endpoint1,c,c])
else:
mx_answer += dist2[c]
operations.append([endpoint2,c,c])
for ne in adj[c]:
degree[ne] -= 1
if degree[ne] == 1:
leaves.append(ne)
while len(diameter) > 1:
c = diameter.pop()
mx_answer += dist2[c]
operations.append([endpoint2,c,c])
print(mx_answer)
for operation in operations:
print(*operation)
``` |
847 | Preparing for Merge Sort | Title: Preparing for Merge Sort
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan has an array consisting of *n* different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.
Ivan represent his array with increasing sequences with help of the following algorithm.
While there is at least one unused number in array Ivan repeats the following procedure:
- iterate through array from the left to the right; - Ivan only looks at unused numbers on current iteration; - if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.
For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].
Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of elements in Ivan's array.
The second line contains a sequence consisting of distinct integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — Ivan's array.
Output Specification:
Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.
Demo Input:
['5\n1 3 2 5 4\n', '4\n4 3 2 1\n', '4\n10 30 50 101\n']
Demo Output:
['1 3 5 \n2 4 \n', '4 \n3 \n2 \n1 \n', '10 30 50 101 \n']
Note:
none | ```python
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
p = []
result = []
for x in a:
r = bisect_left(p, -x)
if r == len(result):
result.append([])
p.append(0)
result[r].append(x)
p[r] = -x
for arr in result:
for i in range(len(arr)-1):
print(arr[i], end=" ")
print(arr[-1])
``` |
690 | Collective Mindsets (hard) | Title: Collective Mindsets (hard)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the *N* attendees love to play a very risky game...
Every zombie gets a number *n**i* (1<=≤<=*n**i*<=≤<=*N*) written on his forehead. Although no zombie can see his own number, he can see the numbers written on the foreheads of all *N*<=-<=1 fellows. Note that not all numbers have to be unique (they can even all be the same). From this point on, no more communication between zombies is allowed. Observation is the only key to success. When the cuckoo clock strikes midnight, all attendees have to simultaneously guess the number on their own forehead. If at least one of them guesses his number correctly, all zombies survive and go home happily. On the other hand, if not a single attendee manages to guess his number correctly, all of them are doomed to die!
Zombies aren't very bright creatures though, and Heidi has to act fast if she does not want to jeopardize her life. She has one single option: by performing some quick surgery on the brain she managed to get from the chest, she has the ability to remotely reprogram the decision-making strategy of all attendees for their upcoming midnight game! Can you suggest a sound strategy to Heidi which, given the rules of the game, ensures that at least one attendee will guess his own number correctly, for any possible sequence of numbers on the foreheads?
Given a zombie's rank *R* and the *N*<=-<=1 numbers *n**i* on the other attendees' foreheads, your program will have to return the number that the zombie of rank *R* shall guess. Those answers define your strategy, and we will check if it is flawless or not.
Input Specification:
The first line of input contains a single integer *T* (1<=≤<=*T*<=≤<=50000): the number of scenarios for which you have to make a guess.
The *T* scenarios follow, described on two lines each:
- The first line holds two integers, *N* (2<=≤<=*N*<=≤<=6), the number of attendees, and *R* (1<=≤<=*R*<=≤<=*N*), the rank of the zombie who has to make the guess. - The second line lists *N*<=-<=1 integers: the numbers on the foreheads of all other attendees, listed in increasing order of the attendees' rank. (Every zombie knows the rank of every other zombie.)
Output Specification:
For every scenario, output a single integer: the number that the zombie of rank *R* shall guess, based on the numbers *n**i* on his *N*<=-<=1 fellows' foreheads.
Demo Input:
['4\n2 1\n1\n2 2\n1\n2 1\n2\n2 2\n2\n', '2\n5 2\n2 2 2 2\n6 4\n3 2 6 1 2\n']
Demo Output:
['1\n2\n2\n1\n', '5\n2\n']
Note:
For instance, if there were *N* = 2 two attendees, a successful strategy could be:
- The zombie of rank 1 always guesses the number he sees on the forehead of the zombie of rank 2. - The zombie of rank 2 always guesses the opposite of the number he sees on the forehead of the zombie of rank 1. | ```python
t = int(input())
for i in range(t):
n, r = map(int, input().split())
l = list(map(int, input().split()))
if r == 1:
s = sum(l) % n
if s == 0:
s = n
print(s)
else:
s = 2 * l[0] - r + 1 - sum(l)
s = s % n
if s == 0:
s = n
print(s)
``` |
660 | Different Subsets For All Tuples | Title: Different Subsets For All Tuples
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
For a sequence *a* of *n* integers between 1 and *m*, inclusive, denote *f*(*a*) as the number of distinct subsequences of *a* (including the empty subsequence).
You are given two positive integers *n* and *m*. Let *S* be the set of all sequences of length *n* consisting of numbers from 1 to *m*. Compute the sum *f*(*a*) over all *a* in *S* modulo 109<=+<=7.
Input Specification:
The only line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=106) — the number of elements in arrays and the upper bound for elements.
Output Specification:
Print the only integer *c* — the desired sum modulo 109<=+<=7.
Demo Input:
['1 3\n', '2 2\n', '3 3\n']
Demo Output:
['6\n', '14\n', '174\n']
Note:
none | ```python
n,m=map(int,input().split())
x,y,M=0,1,1000000007
for i in range(n):
x=((2*m-1)*x+y)%M;y=y*m%M
print((y+m*x)%M)
``` |
985 | Pencils and Boxes | Title: Pencils and Boxes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence *a*1,<=*a*2,<=...,<=*a**n* of *n* integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:
- Each pencil belongs to exactly one box; - Each non-empty box has at least *k* pencils in it; - If pencils *i* and *j* belong to the same box, then |*a**i*<=-<=*a**j*|<=≤<=*d*, where |*x*| means absolute value of *x*. Note that the opposite is optional, there can be pencils *i* and *j* such that |*a**i*<=-<=*a**j*|<=≤<=*d* and they belong to different boxes.
Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".
Input Specification:
The first line contains three integer numbers *n*, *k* and *d* (1<=≤<=*k*<=≤<=*n*<=≤<=5·105, 0<=≤<=*d*<=≤<=109) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — saturation of color of each pencil.
Output Specification:
Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".
Demo Input:
['6 3 10\n7 2 7 7 4 2\n', '6 2 3\n4 5 3 13 4 10\n', '3 2 5\n10 16 22\n']
Demo Output:
['YES\n', 'YES\n', 'NO\n']
Note:
In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.
In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box. | ```python
n, k, d = map(int, input().split())
A = [0]*(n + 1)
B = sorted(map(int, input().split()))
for i in range(1, n + 1):
A[i] = B[i - 1]
A.sort()
dp = [0]*(n + 1)
dp[0] = 1
cnt= 0
l=0
for i in range (k, n + 1):
if dp[i - k] : cnt += 1
while i - l + 1 > k and A[i]-A[l+1] > d:
if dp[l] : cnt-=1
l +=1
if cnt and A[i] -A[l+1] <= d and i - l + 1> k :
dp[i]=1
if dp[n]:
print('YES')
else:
print('NO')
``` |
710 | Two Arithmetic Progressions | Title: Two Arithmetic Progressions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two arithmetic progressions: *a*1*k*<=+<=*b*1 and *a*2*l*<=+<=*b*2. Find the number of integers *x* such that *L*<=≤<=*x*<=≤<=*R* and *x*<==<=*a*1*k*'<=+<=*b*1<==<=*a*2*l*'<=+<=*b*2, for some integers *k*',<=*l*'<=≥<=0.
Input Specification:
The only line contains six integers *a*1,<=*b*1,<=*a*2,<=*b*2,<=*L*,<=*R* (0<=<<=*a*1,<=*a*2<=≤<=2·109,<=<=-<=2·109<=≤<=*b*1,<=*b*2,<=*L*,<=*R*<=≤<=2·109,<=*L*<=≤<=*R*).
Output Specification:
Print the desired number of integers *x*.
Demo Input:
['2 0 3 3 5 21\n', '2 4 3 0 6 17\n']
Demo Output:
['3\n', '2\n']
Note:
none | ```python
def exgcd(i, j):
if j == 0:
return 1, 0, i
u, v, d = exgcd(j, i % j)
return v, u - v * (i // j), d
ma, ra, mb, rb, L, R = map(int, input().split(' '))
L = max(L, ra, rb)
if L > R:
print(0)
exit(0)
if ra > rb:
ma, ra, mb, rb = mb, rb, ma, ra
_, _, md = exgcd(ma, mb)
if md != 1:
if (rb - ra) % md != 0:
print(0)
exit(0)
m = ma * mb // md
rev, _, _ = exgcd(ma // md, mb // md)
rev = (rev % (mb // md) + mb // md) % (mb // md)
r = ma * (rb - ra) // md * rev + ra
r = (r % m + m) % m
else:
m = ma * mb
bv, av, _ = exgcd(ma, mb)
r = ra * mb * av + rb * ma * bv
r = (r % m + m) % m
def calc(i):
return (i - r) // m
print(calc(R) - calc(L - 1))
``` |
977 | Less or Equal | Title: Less or Equal
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence of integers of length $n$ and integer number $k$. You should print any integer number $x$ in the range of $[1; 10^9]$ (i.e. $1 \le x \le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$.
Note that the sequence can contain equal elements.
If there is no such $x$, print "-1" (without quotes).
Input Specification:
The first line of the input contains integer numbers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $0 \le k \le n$). The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the sequence itself.
Output Specification:
Print any integer number $x$ from range $[1; 10^9]$ such that exactly $k$ elements of given sequence is less or equal to $x$.
If there is no such $x$, print "-1" (without quotes).
Demo Input:
['7 4\n3 7 5 1 10 3 20\n', '7 2\n3 7 5 1 10 3 20\n']
Demo Output:
['6', '-1\n']
Note:
In the first example $5$ is also a valid answer because the elements with indices $[1, 3, 4, 6]$ is less than or equal to $5$ and obviously less than or equal to $6$.
In the second example you cannot choose any number that only $2$ elements of the given sequence will be less than or equal to this number because $3$ elements of the given sequence will be also less than or equal to this number. | ```python
n,k = map(int,input().split())
l = sorted(list(map(int,input().split())))
a = [1] + l
print(a[k] if k == n or a[k + 1] - a[k] else -1)
``` |
180 | Name | Title: Name
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.
Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string *s*. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name *t*.
On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name *t* and lexicographically minimum at that.
The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string *p* of length *n* is lexicographically less than string *q* of length *m*, if one of the two statements is correct:
- *n*<=<<=*m*, and *p* is the beginning (prefix) of string *q* (for example, "aba" is less than string "abaa"), - *p*1<==<=*q*1, *p*2<==<=*q*2, ..., *p**k*<=-<=1<==<=*q**k*<=-<=1, *p**k*<=<<=*q**k* for some *k* (1<=≤<=*k*<=≤<=*min*(*n*,<=*m*)), here characters in strings are numbered starting from 1.
Write a program that, given string *s* and the heighbours' child's name *t* determines the string that is the result of permutation of letters in *s*. The string should be lexicographically strictly more than *t* and also, lexicographically minimum.
Input Specification:
The first line contains a non-empty string *s* (1<=≤<=|*s*|<=≤<=5000), where |*s*| is its length. The second line contains a non-empty string *t* (1<=≤<=|*t*|<=≤<=5000), where |*t*| is its length. Both strings consist of lowercase Latin letters.
Output Specification:
Print the sought name or -1 if it doesn't exist.
Demo Input:
['aad\naac\n', 'abad\nbob\n', 'abc\ndefg\n', 'czaaab\nabcdef\n']
Demo Output:
['aad\n', 'daab\n', '-1\n', 'abczaa\n']
Note:
In the first sample the given string *s* is the sought one, consequently, we do not need to change the letter order there. | ```python
from sys import stdin, stdout
words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
s = stdin.readline().strip()
f = stdin.readline().strip()
ans = -1
d = {}
for v in s:
if v in d:
d[v] += 1
else:
d[v] = 1
for i in range(min(len(s), len(f))):
if f[i] in d and d[f[i]]:
d[f[i]] -= 1
else:
break
for v in words:
if v in d and d[v] and (i == len(f) - 1 or v > f[i + 1]):
ans = i
break
if ans == -1 and max(list(s)) > f[0]:
s = sorted(list(s))
first = ''
for i in range(len(s)):
if s[i] > f[0]:
first += s[i]
s[i] = '_'
break
first += ''.join(sorted(list(s))[1:])
elif ans == -1:
first = '-1'
else:
s = sorted(list(s))
d = {}
first = ''
for i in range(ans + 1):
first += f[i]
if f[i] in d:
d[f[i]] += 1
else:
d[f[i]] = 1
for i in range(len(s)):
if s[i] in d and d[s[i]]:
d[s[i]] -= 1
s[i] = '_'
for i in range(len(s)):
if s[i] != '_' and (ans + 1 == len(f) or s[i] > f[ans + 1]):
first += s[i]
s[i] = '_'
break
for i in range(len(s)):
if s[i] != '_':
first += s[i]
stdout.write(first)
``` |
600 | Lomsat gelral | Title: Lomsat gelral
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour *c* dominating in the subtree of vertex *v* if there are no other colours that appear in the subtree of vertex *v* more times than colour *c*. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex *v* is the vertex *v* and all other vertices that contains vertex *v* in each path to the root.
For each vertex *v* find the sum of all dominating colours in the subtree of vertex *v*.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of vertices in the tree.
The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=*n*), *c**i* — the colour of the *i*-th vertex.
Each of the next *n*<=-<=1 lines contains two integers *x**j*,<=*y**j* (1<=≤<=*x**j*,<=*y**j*<=≤<=*n*) — the edge of the tree. The first vertex is the root of the tree.
Output Specification:
Print *n* integers — the sums of dominating colours for each vertex.
Demo Input:
['4\n1 2 3 4\n1 2\n2 3\n2 4\n', '15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13\n']
Demo Output:
['10 9 3 4\n', '6 5 4 3 2 3 3 1 1 3 2 2 1 2 3\n']
Note:
none | ```python
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 有向木のDFS帰りがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][:-1]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# counts = {}
def add(sub_root, val):
stack = [sub_root]
while stack:
v = stack.pop()
vals = st[colors[v]]
st[colors[v]] = (vals[0] + val, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + val
for chi_v in di_tree[v]:
stack.append(chi_v)
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 1:
add(chi_v, 1)
vals = st[colors[v]]
st[colors[v]] = (vals[0] + 1, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + 1
ans[v] = st.all_fold()[1]
if keeps[v] == 1:
add(v, -1)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
ans = [0] * n
dsu_on_tree(tree, 0)
print(*ans)
``` |
926 | Mobile Communications | Title: Mobile Communications
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A sum of *p* rubles is charged from Arkady's mobile phone account every day in the morning. Among the following *m* days, there are *n* days when Arkady will top up the account: in the day *d**i* he will deposit *t**i* rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following *m* days.
Determine the number of days starting from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.
Input Specification:
The first line contains three integers *n*, *p* and *m* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*p*<=≤<=109, 1<=≤<=*m*<=≤<=109, *n*<=≤<=*m*) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check.
The *i*-th of the following *n* lines contains two integers *d**i* and *t**i* (1<=≤<=*d**i*<=≤<=*m*, 1<=≤<=*t**i*<=≤<=109) — the index of the day when Arkady will make the *i*-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. *d**i*<=><=*d**i*<=-<=1 for all *i* from 2 to *n*.
Output Specification:
Print the number of days from the 1-st to the *m*-th such that the account will have a negative amount on it after the daily payment.
Demo Input:
['3 6 7\n2 13\n4 20\n7 9\n', '5 4 100\n10 70\n15 76\n21 12\n30 100\n67 85\n']
Demo Output:
['3\n', '26\n']
Note:
In the first example the balance will change as following (remember, initially the balance is zero):
1. in the first day 6 rubles will be charged, the balance in the evening will be equal to - 6; 1. in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; 1. in the third day 6 rubles will be charged, the balance in the evening will be equal to - 5; 1. in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; 1. in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; 1. in the sixth day 6 rubles will be charged, the balance in the evening will be equal to - 3; 1. in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0.
Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day. | ```python
n, p, m = input().split()
n = int(n)
p = int(p)
m = int(m)
ans = 0
curb = 0
curd = 1
for i in range(0, n):
#print(curb)
tday, tplus = input().split()
tday = int(tday)
tplus = int(tplus)
if curb < 0:
ans += (tday - curd)
curb -= p * (tday - curd)
elif curb - p * (tday - curd) < 0:
curb -= p * (tday - curd)
x = -curb
xx = x // p
if xx * p < x:
xx += 1
x = xx
ans += x
else:
curb -= p * (tday - curd)
curd = tday
#print(curb)
curb += tplus
tday = m + 1
if curb < 0:
ans += (tday - curd)
curb -= p * (tday - curd)
elif curb - p * (tday - curd) < 0:
curb -= p * (tday - curd)
x = -curb
xx = x // p
if xx * p < x:
xx += 1
x = xx
ans += x
print(ans)
``` |
632 | Longest Subsequence | Title: Longest Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given array *a* with *n* elements and the number *m*. Consider some subsequence of *a* and the value of least common multiple (LCM) of its elements. Denote LCM as *l*. Find any longest subsequence of *a* with the value *l*<=≤<=*m*.
A subsequence of *a* is an array we can get by erasing some elements of *a*. It is allowed to erase zero or all elements.
The LCM of an empty array equals 1.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=106) — the size of the array *a* and the parameter from the problem statement.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the elements of *a*.
Output Specification:
In the first line print two integers *l* and *k**max* (1<=≤<=*l*<=≤<=*m*,<=0<=≤<=*k**max*<=≤<=*n*) — the value of LCM and the number of elements in optimal subsequence.
In the second line print *k**max* integers — the positions of the elements from the optimal subsequence in the ascending order.
Note that you can find and print any subsequence with the maximum length.
Demo Input:
['7 8\n6 2 9 2 7 2 3\n', '6 4\n2 2 2 3 3 3\n']
Demo Output:
['6 5\n1 2 4 6 7\n', '2 3\n1 2 3\n']
Note:
none | ```python
from time import time
import sys
t = time()
def logger(s):
print(s, time() - t, file = sys.stderr)
global t
t = time()
n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B, C = [0]*(m+1), [0]*(m+1)
logger('initialization: ')
for a in A:
if a <= m: B[a] += 1
logger('B: ')
for i in range(2, m + 1):
for j in range(i, m+1, i):
C[j] += B[i]
logger('C: ')
k, l = 1, 0
for i in range(2, m+1):
if C[i] > l:
l = C[i]
k = i
logger('finding lcm: ')
print(k, l + B[1])
for i, a in enumerate(A):
if k%a == 0: sys.stdout.write(str(i+1) + ' ')
logger('print: ')
``` |
730 | Olympiad in Programming and Sports | Title: Olympiad in Programming and Sports
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* students at Berland State University. Every student has two skills, each measured as a number: *a**i* — the programming skill and *b**i* — the sports skill.
It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track.
There should be exactly *p* students in the programming team and exactly *s* students in the sports team. A student can't be a member of both teams.
The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all *a**i* and the strength of the sports team is the sum of all *b**i* over corresponding team members.
Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad.
Input Specification:
The first line contains three positive integer numbers *n*, *p* and *s* (2<=≤<=*n*<=≤<=3000, *p*<=+<=*s*<=≤<=*n*) — the number of students, the size of the programming team and the size of the sports team.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=3000), where *a**i* is the programming skill of the *i*-th student.
The third line contains *n* positive integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=3000), where *b**i* is the sports skill of the *i*-th student.
Output Specification:
In the first line, print the the maximum strength of the university on the Olympiad. In the second line, print *p* numbers — the members of the programming team. In the third line, print *s* numbers — the members of the sports team.
The students are numbered from 1 to *n* as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order.
If there are multiple solutions, print any of them.
Demo Input:
['5 2 2\n1 3 4 5 2\n5 3 2 1 4\n', '4 2 2\n10 8 8 3\n10 7 9 4\n', '5 3 1\n5 2 5 1 7\n6 3 1 6 3\n']
Demo Output:
['18\n3 4 \n1 5 \n', '31\n1 2 \n3 4 \n', '23\n1 3 5 \n4 \n']
Note:
none | ```python
#!/usr/bin/env python3
from itertools import accumulate
from heapq import heappop, heappush
def top(ppl_indices, vals, start):
Q = []
res = [0 for i in range(len(ppl_indices))]
for k, idx in enumerate(ppl_indices):
heappush(Q, -vals[idx])
if k >= start:
res[k] = res[k-1] - heappop(Q)
return res
n, a_size, b_size = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
conversion_gain = [y - x for x, y in zip(a, b)]
ordered_by_a = sorted(zip(a, range(n)), reverse=True)
prefix_sums_a = list(accumulate([x for x, y in ordered_by_a]))
conversions = top([idx for val, idx in ordered_by_a], conversion_gain, a_size)
rest_of_bs = list(reversed(top([idx for val, idx in reversed(ordered_by_a[a_size:])],
b, n - a_size - b_size))) + [0]
sol, top_k = max([(prefix_a + convert + add_bs, idx)
for idx, (prefix_a, convert, add_bs)
in enumerate(zip(prefix_sums_a[a_size-1:a_size+b_size],
conversions[a_size-1:a_size+b_size],
rest_of_bs))])
top_k += a_size
conversion_ordered_by_a = [(conversion_gain[idx], idx) for val, idx in ordered_by_a]
conversion_sorted = sorted(conversion_ordered_by_a[:top_k], reverse=True)
converted = [idx for val, idx in conversion_sorted[:top_k-a_size]]
team_a = list(set(idx for val, idx in ordered_by_a[:top_k]) - set(converted))
b_ordered_by_a = [(b[idx], idx) for val, idx in ordered_by_a]
b_sorted = sorted(b_ordered_by_a[top_k:], reverse=True)
team_b = converted + [idx for val, idx in b_sorted[:(a_size+b_size) - top_k]]
print(sol)
print(" ".join(str(idx+1) for idx in team_a))
print(" ".join(str(idx+1) for idx in team_b))
``` |
954 | Fight Against Traffic | Title: Fight Against Traffic
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little town Nsk consists of *n* junctions connected by *m* bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction *s* to work located near junction *t*. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between *s* and *t* won't decrease.
Input Specification:
The firt line of the input contains integers *n*, *m*, *s* and *t* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*m*<=≤<=1000, 1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The *i*-th of the following *m* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), meaning that this road connects junctions *u**i* and *v**i* directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output Specification:
Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions *s* and *t*.
Demo Input:
['5 4 1 5\n1 2\n2 3\n3 4\n4 5\n', '5 4 3 5\n1 2\n2 3\n3 4\n4 5\n', '5 6 1 5\n1 2\n1 3\n1 4\n4 5\n3 5\n2 5\n']
Demo Output:
['0\n', '5\n', '3\n']
Note:
none | ```python
import sys
from collections import defaultdict,deque
inp=sys.stdin.readline
n,m,s,t=map(int,inp().split())
s-=1
t-=1
graph=defaultdict(list)
edges=set()
for _ in range(m):
u,v=map(int,inp().split())
u-=1
v-=1
graph[u].append(v)
graph[v].append(u)
u,v=min(u,v),max(u,v)
edges.add((u,v))
ans=0
def bfs(start):
dist=[sys.maxsize]*n
dist[start]=0
q=deque()
q.append((start,0))
while q:
node,wt=q.popleft()
for nei in graph[node]:
if wt+1<dist[nei]:
dist[nei]=wt+1
q.append((nei,wt+1))
return dist
dist_s,dist_t=bfs(s),bfs(t)
mmin=dist_s[t]
for i in range(n):
for j in range(i+1,n):
if (i,j) not in edges and dist_s[i]+dist_t[j]+1>=mmin and dist_s[j]+dist_t[i]+1>=mmin and (i,j)!=(s,t):
ans+=1
print(ans)
``` |
818 | Sofa Thief | Title: Sofa Thief
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?
Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!
The storehouse is represented as matrix *n*<=×<=*m*. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.
Sofa *A* is standing to the left of sofa *B* if there exist two such cells *a* and *b* that *x**a*<=<<=*x**b*, *a* is covered by *A* and *b* is covered by *B*. Sofa *A* is standing to the top of sofa *B* if there exist two such cells *a* and *b* that *y**a*<=<<=*y**b*, *a* is covered by *A* and *b* is covered by *B*. Right and bottom conditions are declared the same way.
Note that in all conditions *A*<=≠<=*B*. Also some sofa *A* can be both to the top of another sofa *B* and to the bottom of it. The same is for left and right conditions.
The note also stated that there are *cnt**l* sofas to the left of Grandpa Maks's sofa, *cnt**r* — to the right, *cnt**t* — to the top and *cnt**b* — to the bottom.
Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.
Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.
Input Specification:
The first line contains one integer number *d* (1<=≤<=*d*<=≤<=105) — the number of sofas in the storehouse.
The second line contains two integer numbers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the size of the storehouse.
Next *d* lines contains four integer numbers *x*1, *y*1, *x*2, *y*2 (1<=≤<=*x*1,<=*x*2<=≤<=*n*, 1<=≤<=*y*1,<=*y*2<=≤<=*m*) — coordinates of the *i*-th sofa. It is guaranteed that cells (*x*1,<=*y*1) and (*x*2,<=*y*2) have common side, (*x*1,<=*y*1) <=≠<= (*x*2,<=*y*2) and no cell is covered by more than one sofa.
The last line contains four integer numbers *cnt**l*, *cnt**r*, *cnt**t*, *cnt**b* (0<=≤<=*cnt**l*,<=*cnt**r*,<=*cnt**t*,<=*cnt**b*<=≤<=*d*<=-<=1).
Output Specification:
Print the number of the sofa for which all the conditions are met. Sofas are numbered 1 through *d* as given in input. If there is no such sofa then print -1.
Demo Input:
['2\n3 2\n3 1 3 2\n1 2 2 2\n1 0 0 1\n', '3\n10 10\n1 2 1 1\n5 5 6 5\n6 4 5 4\n2 1 2 0\n', '2\n2 2\n2 1 1 1\n1 2 2 2\n1 0 0 0\n']
Demo Output:
['1\n', '2\n', '-1\n']
Note:
Let's consider the second example.
- The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below). - The second sofa has *cnt*<sub class="lower-index">*l*</sub> = 2, *cnt*<sub class="lower-index">*r*</sub> = 1, *cnt*<sub class="lower-index">*t*</sub> = 2 and *cnt*<sub class="lower-index">*b*</sub> = 0. - The third sofa has *cnt*<sub class="lower-index">*l*</sub> = 2, *cnt*<sub class="lower-index">*r*</sub> = 1, *cnt*<sub class="lower-index">*t*</sub> = 1 and *cnt*<sub class="lower-index">*b*</sub> = 1.
So the second one corresponds to the given conditions.
In the third example
- The first sofa has *cnt*<sub class="lower-index">*l*</sub> = 1, *cnt*<sub class="lower-index">*r*</sub> = 1, *cnt*<sub class="lower-index">*t*</sub> = 0 and *cnt*<sub class="lower-index">*b*</sub> = 1. - The second sofa has *cnt*<sub class="lower-index">*l*</sub> = 1, *cnt*<sub class="lower-index">*r*</sub> = 1, *cnt*<sub class="lower-index">*t*</sub> = 1 and *cnt*<sub class="lower-index">*b*</sub> = 0.
And there is no sofa with the set (1, 0, 0, 0) so the answer is -1. | ```python
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
d = int(input())
n, m = map(int, input().split())
L = []
R = []
T = []
B = []
XY = []
for i in range(d):
x1, y1, x2, y2 = map(int, input().split())
L.append((min(x1, x2)))
R.append(-max(x1, x2))
T.append(min(y1, y2))
B.append(-max(y1, y2))
XY.append((x1, y1, x2, y2))
cntl, cntr, cntt, cntb = map(int, input().split())
cnt = [cntl, cntr, cntt, cntb]
L.sort()
R.sort()
T.sort()
B.sort()
import bisect
for i in range(d):
x1, y1, x2, y2 = XY[i]
if x1 != x2:
l = bisect.bisect_left(L, max(x1, x2))-1
else:
l = bisect.bisect_left(L, max(x1, x2))
if x1 != x2:
r = bisect.bisect_left(R, -min(x1, x2))-1
else:
r = bisect.bisect_left(R, -min(x1, x2))
if y1 != y2:
t = bisect.bisect_left(T, max(y1, y2))-1
else:
t = bisect.bisect_left(T, max(y1, y2))
if y1 != y2:
b = bisect.bisect_left(B, -min(y1, y2))-1
else:
b = bisect.bisect_left(B, -min(y1, y2))
if cnt == [l, r, t, b]:
print(i+1)
exit()
print(-1)
``` |
988 | Equal Sums | Title: Equal Sums
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$.
You have to choose exactly two sequences $i$ and $j$ ($i \ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals to the sum of the changed sequence $j$ (its length will be equal to $n_j - 1$).
Note that it's required to remove exactly one element in each of the two chosen sequences.
Assume that the sum of the empty (of the length equals $0$) sequence is $0$.
Input Specification:
The first line contains an integer $k$ ($2 \le k \le 2 \cdot 10^5$) — the number of sequences.
Then $k$ pairs of lines follow, each pair containing a sequence.
The first line in the $i$-th pair contains one integer $n_i$ ($1 \le n_i < 2 \cdot 10^5$) — the length of the $i$-th sequence. The second line of the $i$-th pair contains a sequence of $n_i$ integers $a_{i, 1}, a_{i, 2}, \dots, a_{i, n_i}$.
The elements of sequences are integer numbers from $-10^4$ to $10^4$.
The sum of lengths of all given sequences don't exceed $2 \cdot 10^5$, i.e. $n_1 + n_2 + \dots + n_k \le 2 \cdot 10^5$.
Output Specification:
If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers $i$, $x$ ($1 \le i \le k, 1 \le x \le n_i$), in the third line — two integers $j$, $y$ ($1 \le j \le k, 1 \le y \le n_j$). It means that the sum of the elements of the $i$-th sequence without the element with index $x$ equals to the sum of the elements of the $j$-th sequence without the element with index $y$.
Two chosen sequences must be distinct, i.e. $i \ne j$. You can print them in any order.
If there are multiple possible answers, print any of them.
Demo Input:
['2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1\n', '3\n1\n5\n5\n1 1 1 1 1\n2\n2 3\n', '4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2\n']
Demo Output:
['YES\n2 6\n1 2\n', 'NO\n', 'YES\n2 2\n4 1\n']
Note:
In the first example there are two sequences $[2, 3, 1, 3, 2]$ and $[1, 1, 2, 2, 2, 1]$. You can remove the second element from the first sequence to get $[2, 1, 3, 2]$ and you can remove the sixth element from the second sequence to get $[1, 1, 2, 2, 2]$. The sums of the both resulting sequences equal to $8$, i.e. the sums are equal. | ```python
from collections import defaultdict
import sys
input = sys.stdin.readline
k = int(input())
lst = []
for i in range(k):
n = int(input())
arr = list(map(int, input().split()))
s = sum(arr)
for j, e in enumerate(arr):
lst.append((s-e, i+1, j+1))
lst.sort(key=lambda x: (x[0], x[1]))
for i in range(0, len(lst)-1):
if lst[i][0] == lst[i+1][0] and lst[i][1] != lst[i+1][1]:
print("YES")
print(lst[i][1], lst[i][2])
print(lst[i+1][1], lst[i+1][2])
exit()
print("NO")
``` |
847 | Union of Doubly Linked Lists | Title: Union of Doubly Linked Lists
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given *n* memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to *n*.
For each cell *i* you are given two values:
- *l**i* — cell containing previous element for the element in the cell *i*; - *r**i* — cell containing next element for the element in the cell *i*.
If cell *i* contains information about the element which has no previous element then *l**i*<==<=0. Similarly, if cell *i* contains information about the element which has no next element then *r**i*<==<=0.
For example, for the picture above the values of *l* and *r* are the following: *l*1<==<=4, *r*1<==<=7; *l*2<==<=5, *r*2<==<=0; *l*3<==<=0, *r*3<==<=0; *l*4<==<=6, *r*4<==<=1; *l*5<==<=0, *r*5<==<=2; *l*6<==<=0, *r*6<==<=4; *l*7<==<=1, *r*7<==<=0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values *l**i*, *r**i*.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of memory cells where the doubly linked lists are located.
Each of the following *n* lines contains two integers *l**i*, *r**i* (0<=≤<=*l**i*,<=*r**i*<=≤<=*n*) — the cells of the previous and the next element of list for cell *i*. Value *l**i*<==<=0 if element in cell *i* has no previous element in its list. Value *r**i*<==<=0 if element in cell *i* has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of *n* given cells.
Output Specification:
Print *n* lines, the *i*-th line must contain two integers *l**i* and *r**i* — the cells of the previous and the next element of list for cell *i* after all lists from the input are united in a single list. If there are many solutions print any of them.
Demo Input:
['7\n4 7\n5 0\n0 0\n6 1\n0 2\n0 4\n1 0\n']
Demo Output:
['4 7\n5 6\n0 5\n6 1\n3 2\n2 4\n1 0\n']
Note:
none | ```python
import sys
import math
data = sys.stdin.read().split()
data_ptr = 0
def data_next():
global data_ptr, data
data_ptr += 1
return data[data_ptr - 1]
N = int(data_next())
pre = [0] + list(map(int, data[1::2]))
nxt = [0] + list(map(int, data[2::2]))
vis = [False] * (N + 1)
def find_last(u, nxt):
while nxt[u] != 0:
u = nxt[u]
vis[u] = True
return u
pre_last = -1
for i in range(1, N + 1):
if not(vis[i]):
vis[i] = True
first = find_last(i, pre)
last = find_last(i, nxt)
if pre_last != -1:
nxt[pre_last] = first
pre[first] = pre_last
pre_last = last
for i in range(1, N + 1):
print(pre[i], nxt[i])
``` |
846 | Math Show | Title: Math Show
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp takes part in a math show. He is given *n* tasks, each consists of *k* subtasks, numbered 1 through *k*. It takes him *t**j* minutes to solve the *j*-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.
By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all *k* of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is *k*<=+<=1.
Polycarp has *M* minutes of time. What is the maximum number of points he can earn?
Input Specification:
The first line contains three integer numbers *n*, *k* and *M* (1<=≤<=*n*<=≤<=45, 1<=≤<=*k*<=≤<=45, 0<=≤<=*M*<=≤<=2·109).
The second line contains *k* integer numbers, values *t**j* (1<=≤<=*t**j*<=≤<=1000000), where *t**j* is the time in minutes required to solve *j*-th subtask of any task.
Output Specification:
Print the maximum amount of points Polycarp can earn in *M* minutes.
Demo Input:
['3 4 11\n1 2 3 4\n', '5 5 10\n1 2 4 8 16\n']
Demo Output:
['6\n', '7\n']
Note:
In the first example Polycarp can complete the first task and spend 1 + 2 + 3 + 4 = 10 minutes. He also has the time to solve one subtask of the second task in one minute.
In the second example Polycarp can solve the first subtask of all five tasks and spend 5·1 = 5 minutes. Also he can solve the second subtasks of two tasks and spend 2·2 = 4 minutes. Thus, he earns 5 + 2 = 7 points in total. | ```python
n,k,M = [int(i) for i in input().split(' ')]
tasks = [int(i) for i in input().split(' ')]
tasks = sorted(tasks)
ans = 0
for i in range(n+1):
remaining_time = M - i*sum(tasks)
if(remaining_time < 0):
break
value = (k+1)*i
for j in range(k):
for take in range(n-i):
if(remaining_time >= tasks[j]):
value += 1
remaining_time -= tasks[j]
ans = max(ans,value)
print(ans)
``` |
774 | Bars | Title: Bars
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp's workday lasts exactly $n$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $k$ bars at the beginning of the workday.
In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $k$ is strictly greater than $1$.
Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.
Consider that Polycarp eats a bar in the minute $x$ and the next bar in the minute $y$ ($x < y$). Then the break time is equal to $y - x - 1$ minutes. It is not necessary for Polycarp to eat all bars he has.
Input Specification:
The first line contains two integers $n$ and $k$ ($2 \le n \le 200\,000$, $2 \le k \le n$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday.
The second line contains the string with length $n$ consisting of zeros and ones. If the $i$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $i$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $i$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.
Output Specification:
Print the minimum possible break in minutes between eating chocolate bars.
Demo Input:
['3 3\n010\n', '8 3\n01010110\n']
Demo Output:
['1\n', '3\n']
Note:
In the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.
In the second example Polycarp will eat bars in the minutes $1$ and $8$ anyway, also he needs to eat the chocolate bar in the minute $5$, so that the time of the maximum break will be equal to $3$ minutes. | ```python
import sys
from math import *
from fractions import gcd
from random import * # randint(inclusive,inclusive)
readints=lambda:map(int, input().strip('\n').split())
from itertools import permutations, combinations
s = "abcdefghijklmnopqrstuvwxyz"
# print('', end=" ")
# for i in {1..5}; do echo "hi"; done
n,k=readints()
s=input()
lo=-1
hi=n+1
hop = [0]*n
for i in range(n):
if s[i]=='0':
hop[i]=i
else:
hop[i]=hop[i-1]
def test(jump):
at=0
used=0
while used < k-2:
if at+jump<n:
to = hop[at+jump]
if to == at:
break
at = to
used += 1
else:
break
if n-1-at>jump:
return False
return True
while hi-lo>1:
mid=(lo+hi)//2
if test(mid):
hi=mid
else:
lo=mid
print(hi-1)
``` |
730 | Bottles | Title: Bottles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nick has *n* bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda *a**i* and bottle volume *b**i* (*a**i*<=≤<=*b**i*).
Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends *x* seconds to pour *x* units of soda from one bottle to another.
Nick asks you to help him to determine *k* — the minimal number of bottles to store all remaining soda and *t* — the minimal time to pour soda into *k* bottles. A bottle can't store more soda than its volume. All remaining soda should be saved.
Input Specification:
The first line contains positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of bottles.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=100), where *a**i* is the amount of soda remaining in the *i*-th bottle.
The third line contains *n* positive integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=100), where *b**i* is the volume of the *i*-th bottle.
It is guaranteed that *a**i*<=≤<=*b**i* for any *i*.
Output Specification:
The only line should contain two integers *k* and *t*, where *k* is the minimal number of bottles that can store all the soda and *t* is the minimal time to pour the soda into *k* bottles.
Demo Input:
['4\n3 3 4 3\n4 7 6 5\n', '2\n1 1\n100 100\n', '5\n10 30 5 6 24\n10 41 7 8 24\n']
Demo Output:
['2 6\n', '1 1\n', '3 11\n']
Note:
In the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it. | ```python
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
sa = sum(a)
z = list(zip(a, b))
z.sort(key=lambda a : a[1])
z.reverse()
sb, m = 0, 0
for i, (a, b) in enumerate(z):
sb += b
if sb >= sa:
m = i+1
break
f = [[-1e9 for i in range(10001)] for j in range(101)]
f[0][0], s = 0, 0
for i in range(n-1, -1, -1):
p = z[i]
s = min(s + p[1], sb)
for j in range(m, 0, -1):
for k in range(s, p[1]-1, -1):
f[j][k] = max(f[j][k], f[j - 1][k - p[1]] + p[0])
ans = 0
for _, save in enumerate(f[m][sa:]):
ans = max(ans, save)
print(m, sa-ans)
``` |
774 | Repairing Of String | Title: Repairing Of String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan had a favorite string *s* which consisted of the lowercase letters of the Latin alphabet.
After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers *c*1,<=*c*2,<=...,<=*c**n*, where *n* equals the length of the string *s*, and *c**i* equals the number of substrings in the string *s* with the length *i*, consisting of the same letters. The substring is a sequence of consecutive characters in the string *s*.
For example, if the Stepan's favorite string is equal to "tttesst", the sequence *c* looks like: *c*<==<=[7,<=3,<=1,<=0,<=0,<=0,<=0].
Stepan asks you to help to repair his favorite string *s* according to the given sequence *c*1,<=*c*2,<=...,<=*c**n*.
Input Specification:
The first line contains the integer *n* (1<=≤<=*n*<=≤<=2000) — the length of the Stepan's favorite string.
The second line contains the sequence of integers *c*1,<=*c*2,<=...,<=*c**n* (0<=≤<=*c**i*<=≤<=2000), where *c**i* equals the number of substrings of the string *s* with the length *i*, consisting of the same letters.
It is guaranteed that the input data is such that the answer always exists.
Output Specification:
Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.
Demo Input:
['6\n6 3 1 0 0 0\n', '4\n4 0 0 0\n']
Demo Output:
['kkrrrq', 'abcd\n']
Note:
In the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3). | ```python
import sys
data = sys.stdin.read().split()
data.reverse()
def read(): return int(data.pop())
def readStr(): return data.pop()
n = read()
C = [0] + [read() for i in range(n)]
ans = ""
ch, cht = 'a', 'b'
for i in range(n, 0, -1) :
while C[i] > 0 :
for j in range(i) :
ans += ch
ch, cht = cht, ch
for j in range(1, i+1) :
C[j] -= i-j+1
print(ans)
``` |
977 | Divide by three, multiply by two | Title: Divide by three, multiply by two
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds:
- divide the number $x$ by $3$ ($x$ must be divisible by $3$); - multiply the number $x$ by $2$.
After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all.
You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.
Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.
It is guaranteed that the answer exists.
Input Specification:
The first line of the input contatins an integer number $n$ ($2 \le n \le 100$) — the number of the elements in the sequence. The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3 \cdot 10^{18}$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.
Output Specification:
Print $n$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board.
It is guaranteed that the answer exists.
Demo Input:
['6\n4 8 6 3 12 9\n', '4\n42 28 84 126\n', '2\n1000000000000000000 3000000000000000000\n']
Demo Output:
['9 3 6 12 4 8 \n', '126 42 84 28 \n', '3000000000000000000 1000000000000000000 \n']
Note:
In the first example the given sequence can be rearranged in the following way: $[9, 3, 6, 12, 4, 8]$. It can match possible Polycarp's game which started with $x = 9$. | ```python
from collections import defaultdict
n=int(input())
a=list(map(int,input().split()))
def top(mp=defaultdict(int),x=1,n=1):
if n==1 and mp[x]==1 or n==0:
return [x]
if mp[x]==0:
return -1
mp[x]-=1
k=top(mp,2*x,n-1)
mp[x]+=1
if k!=-1:
return k+[x]
if x%3==0:
mp[x]-=1
k=top(mp,x//3,n-1)
mp[x]+=1
return k if k==-1 else k+[x]
return -1
mp=defaultdict(int)
for i in a:
mp[i]+=1
for i in a:
arr=top(mp,i,n)
# print(arr)
if arr!=-1:
print(*arr[::-1])
break
# print(mp)
``` |
290 | WTF? | Title: WTF?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains between 1 and 10 lines, *i*-th line contains an integer number *x**i* (0<=≤<=*x**i*<=≤<=9).
Output Specification:
Output a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10<=-<=4.
Demo Input:
['3\n0\n1\n1\n']
Demo Output:
['0.666667\n']
Note:
none | ```python
TUX=int(input())
FOO=0
BAR=0
BAZ=0
QUZ=1
for i in range(TUX):
PUR=int(input())
FOO=FOO+PUR
BAR=BAR+1
if FOO*QUZ>BAZ*BAR:
BAZ=FOO
QUZ=BAR
print(BAZ/QUZ)
``` |
622 | The Sum of the k-th Powers | Title: The Sum of the k-th Powers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.
Find the value of the sum modulo 109<=+<=7 (so you should find the remainder after dividing the answer by the value 109<=+<=7).
Input Specification:
The only line contains two integers *n*,<=*k* (1<=≤<=*n*<=≤<=109,<=0<=≤<=*k*<=≤<=106).
Output Specification:
Print the only integer *a* — the remainder after dividing the value of the sum by the value 109<=+<=7.
Demo Input:
['4 1\n', '4 2\n', '4 3\n', '4 0\n']
Demo Output:
['10\n', '30\n', '100\n', '4\n']
Note:
none | ```python
import os
import sys
import time
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregionS
def inv():
pass
def main():
n, k = map(int, input().split())
mod = 10**9 + 7
pref = [1] * (k + 4)
suff = [1] * (k + 4)
f = [1] * (k+4)
pref[1] = n-1
f[1] = 1
for i in range(2, k+4):
pref[i] = pref[i-1] * (n-i) % mod
f[i] = f[i-1] + pow(i, k, mod)
suff[k+2] = n-k-2
for i in range(k+1, -1, -1):
suff[i] = suff[i+1] * (n-i) % mod
fact = [0] * (k+4)
inv = [0] * (k+4)
invfact = [0] * (k+4)
inv[1] = invfact[1] = invfact[0] = fact[1] = fact[0] = 1
for i in range(2, k+4):
fact[i] = fact[i-1] * i % mod
inv[i] = mod - (mod // i) * inv[mod % i] % mod
invfact[i] = invfact[i-1] * inv[i] % mod
ret = 0
for i in range(1, k+3):
numerator = pref[i-1] * suff[i+1] % mod
denominator = invfact[k+2-i] * invfact[i-1]
if (k+2-i) % 2 == 1:
denominator = -denominator
frac = numerator * denominator % mod
ret = (ret + frac * f[i] % mod) % mod
print(ret)
if __name__ == "__main__":
start_time = time.time()
main()
print(f'Execution time: {time.time() - start_time} s', file=sys.stderr)
``` |
926 | Endless Roses Most Beautiful | Title: Endless Roses Most Beautiful
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is *n*. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly *k* roses. For each rose in the shop he knows its beauty and color: the beauty of the *i*-th rose is *b**i*, and its color is *c**i* ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of *k* roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=200<=000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=10<=000), where *b**i* equals the beauty of the *i*-th rose.
The third line contains a string *c* of length *n*, consisting of uppercase English letters 'W', 'O' and 'R', where *c**i* denotes the color of the *i*-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output Specification:
Print the maximum possible total beauty of a bouquet of *k* roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Demo Input:
['5 3\n4 3 4 1 6\nRROWW\n', '5 2\n10 20 14 20 11\nRRRRR\n', '11 5\n5 6 3 2 3 4 7 5 4 5 6\nRWOORWORROW\n']
Demo Output:
['11\n', '-1\n', '28\n']
Note:
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | ```python
import sys
def solve(first_color, second_color, need):
if need < 2 or min(len(first_color), len(second_color)) < 1 or len(first_color) + len(second_color) < need:
return -1
total = -first_color[0] - second_color[0]
temp = []
for cur_iter in range(1, len(first_color)):
temp.append(first_color[cur_iter])
for cur_iter in range(1, len(second_color)):
temp.append(second_color[cur_iter])
temp.sort()
for cur_iter in range(need - 2):
total -= temp[cur_iter]
return total
n, k = map(int, sys.stdin.readline().strip().split())
costs = list(map(int, sys.stdin.readline().strip().split()))
colors = list(sys.stdin.readline().strip())
colored_costs = dict()
colored_costs['R'] = []
colored_costs['O'] = []
colored_costs['W'] = []
for i in range(n):
colored_costs[colors[i]].append(-costs[i])
for key in colored_costs.keys():
colored_costs[key].sort()
ans = solve(colored_costs['R'], colored_costs['O'], k)
ans = max(ans, solve(colored_costs['W'], colored_costs['O'], k))
print(ans)
``` |
1,005 | Median on Segments (General Case Edition) | Title: Median on Segments (General Case Edition)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an integer sequence $a_1, a_2, \dots, a_n$.
Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.
The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.
For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.
Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.
Input Specification:
The first line contains integers $n$ and $m$ ($1 \le n,m \le 2\cdot10^5$) — the length of the given sequence and the required value of the median.
The second line contains an integer sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2\cdot10^5$).
Output Specification:
Print the required number.
Demo Input:
['5 4\n1 4 5 60 4\n', '3 1\n1 1 1\n', '15 2\n1 2 3 1 2 3 1 2 3 1 2 3 1 2 3\n']
Demo Output:
['8\n', '6\n', '97\n']
Note:
In the first example, the suitable pairs of indices are: $(1, 3)$, $(1, 4)$, $(1, 5)$, $(2, 2)$, $(2, 3)$, $(2, 5)$, $(4, 5)$ and $(5, 5)$. | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
from typing import List, Union
class FenwickTree:
'''Build a new FenwickTree. / O(N)'''
def __init__(self, _n_or_a: Union[List[int], int]):
if isinstance(_n_or_a, int):
self._size = _n_or_a
self._tree = [0] * (self._size+1)
else:
a = list(_n_or_a)
self._size = len(a)
self._tree = [0] + a
for i in range(1, self._size):
if i + (i & -i) <= self._size:
self._tree[i + (i & -i)] += self._tree[i]
self._s = 1 << (self._size-1).bit_length()
'''Return sum([0, r)) of a. / O(logN)'''
def pref(self, r: int) -> int:
# assert r <= self._size
ret = 0
while r > 0:
ret += self._tree[r]
r -= r & -r
return ret
'''Return sum([l, n)) of a. / O(logN)'''
def suff(self, l: int) -> int:
# assert 0 <= l < self._size
return self.pref(self._size) - self.pref(l)
'''Return sum([l, r)] of a. / O(logN)'''
def sum(self, l: int, r: int) -> int:
# assert 0 <= l <= r <= self._size
return self.pref(r) - self.pref(l)
def __getitem__(self, k: int) -> int:
return self.sum(k, k+1)
'''Add x to a[k]. / O(logN)'''
def add(self, k: int, x: int) -> None:
# assert 0 <= k < self._size
k += 1
while k <= self._size:
self._tree[k] += x
k += k & -k
'''Update A[k] to x. / O(logN)'''
def set(self, k: int, x: int) -> None:
pre = self.get(k)
self.add(k, x - pre)
'''bisect_left(acc)'''
def bisect_left(self, w: int) -> int:
i = 0
s = self._s
while s:
if i + s <= self._size and self._tree[i + s] < w:
w -= self._tree[i + s]
i += s
s >>= 1
return i if w else None
'''bisect_right(acc)'''
def bisect_right(self, w: int) -> int:
i = 0
s = self._s
while s:
if i + s <= self._size and self._tree[i + s] <= w:
w -= self._tree[i + s]
i += s
s >>= 1
return i
def show(self) -> None:
print('[' + ', '.join(map(str, (self.pref(i) for i in range(self._size+1)))) + ']')
def tolist(self) -> List[int]:
return [self.__getitem__(i) for i in range(self._size)]
@classmethod
def inversion_num(self, a: List[int], compress: bool=False) -> int:
ans = 0
if compress:
a_ = sorted(set(a))
z = {e: i for i, e in enumerate(a_)}
fw = FenwickTree(len(a_))
for i, e in enumerate(a):
ans += i - fw.pref(z[e])
fw.add(z[e], 1)
else:
fw = FenwickTree(len(a))
for i, e in enumerate(a):
ans += i - fw.pref(e)
fw.add(e, 1)
return ans
def __str__(self):
sub = [self.pref(i) for i in range(self._size+1)]
return '[' + ', '.join(map(str, (sub[i+1]-sub[i] for i in range(self._size)))) + ']'
def __repr__(self):
return 'FenwickTree(' + str(self) + ')'
# ----------------------- #
n, m = map(int, input().split())
A = list(map(int, input().split()))
def f(k):
# 中央値がk以上である区間の個数
ans = 0
fw = FenwickTree(2*n+10)
acc = 0
for i in range(n):
fw.add(acc+n, 1)
acc += 1 if A[i] >= k else -1
ans += fw.pref(acc+n)
return ans
ans = f(m) - f(m+1)
print(ans)
``` |
784 | Crunching Numbers Just for You | Title: Crunching Numbers Just for You
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...
You are given an array of integers. Sort it in non-descending order.
Input Specification:
The input consists of a single line of space-separated integers. The first number is *n* (1<=≤<=*n*<=≤<=10) — the size of the array. The following *n* numbers are the elements of the array (1<=≤<=*a**i*<=≤<=100).
Output Specification:
Output space-separated elements of the sorted array.
Demo Input:
['3 3 1 2\n']
Demo Output:
['1 2 3 \n']
Note:
Remember, this is a very important feature, and you have to make sure the customers appreciate it! | ```python
a = [int(x) for x in input().split()]
del a[0]
k = 7777777 ** 66666
k = 7777777 ** 66666
k = 7777777 ** 66666
k = 7777777 ** 66666
k = 7777777 ** 66666
print(*sorted(a))
``` |
915 | Almost Acyclic Graph | Title: Almost Acyclic Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of *n* vertices and *m* edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic_graph) by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
Input Specification:
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=500, 1<=≤<=*m*<=≤<=*min*(*n*(*n*<=-<=1),<=100000)) — the number of vertices and the number of edges, respectively.
Then *m* lines follow. Each line contains two integers *u* and *v* denoting a directed edge going from vertex *u* to vertex *v* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*). Each ordered pair (*u*,<=*v*) is listed at most once (there is at most one directed edge from *u* to *v*).
Output Specification:
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Demo Input:
['3 4\n1 2\n2 3\n3 2\n3 1\n', '5 6\n1 2\n2 3\n3 2\n3 1\n2 1\n4 5\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first example you can remove edge <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/420322fe5fba4eb3e3eba6886a2edb31f15762ce.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/>) in order to make the graph acyclic. | ```python
def my_solve(n, m, graph, mask):
if do_dfs_bool(n,graph,mask.copy()):
c = get_cyclic(n, graph, mask)
for u,v in c:
graph[u].remove(v)
if not do_dfs_bool(n,graph,mask.copy()):
return 'YES'
graph[u].append(v)
return "NO"
return "YES"
def get_cyclic(n, graph, mask):
c,v = do_dfs(n,graph,mask)
path = []
i = 0
begin = False
if c:
for u in c.keys():
if c[u] == v:
begin = True
path.append((c[u],u))
elif begin:
path.append((c[u],u))
tmp = list(c.keys())
if len(tmp):
path.append((tmp[-1],v))
return path
def do_dfs_bool(n, graph, mask):
colors = [0]*(n+5)
for u in graph.keys():
if not u in mask.keys():
if dfs_bool(u,graph,mask,colors):
return True
return False
def dfs_bool(u, graph, mask,colors):
colors[u] = 1
mask[u] = True
for v in graph[u]:
if colors[v] == 1:
return True
if colors[v] == 0:
if dfs_bool(v,graph,mask,colors):
return True
colors[u] = 2
return False
def do_dfs(n, graph, mask):
colors = [0]*(n+5)
c = {}
for u in graph.keys():
if not u in mask.keys():
c = {}
p, v = dfs(u,graph,mask,c,colors)
if p and v:
return (p,v)
def dfs(u, graph, mask, c, colors):
colors[u] = 1
for v in graph[u]:
if colors[v] == 1:
return (c, v)
if colors[v] == 0:
c[v] = u
p,w = dfs(v,graph,mask,c,colors)
if w:
return (p,w)
colors[u] = 2
if len(c) > 0:
if u in c.keys():
del c[u]
return (c, None)
def test(n, m, edges):
graph = {}
mask = {}
for u,v in edges:
if u not in graph.keys():
graph[u] = []
graph[u].append(v)
if v not in graph.keys():
graph[v] = []
return my_solve(n, m, graph, mask)
if __name__ == '__main__':
n,m = [int(x) for x in input().split()]
edges = []
for i in range(0,m):
u,v = [int(x) for x in input().split()]
edges.append((u,v))
print(test(n, m, edges))
``` |
180 | Divisibility Rules | Title: Divisibility Rules
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya studies divisibility rules at school. Here are some of them:
- Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even.- Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3.- Divisibility by 4. A number is divisible by 4 if and only if its last two digits form a number that is divisible by 4.- Divisibility by 5. A number is divisible by 5 if and only if its last digit equals 5 or 0.- Divisibility by 6. A number is divisible by 6 if and only if it is divisible by 2 and 3 simultaneously (that is, if the last digit is even and the sum of all digits is divisible by 3).- Divisibility by 7. Vasya doesn't know such divisibility rule.- Divisibility by 8. A number is divisible by 8 if and only if its last three digits form a number that is divisible by 8.- Divisibility by 9. A number is divisible by 9 if and only if the sum of its digits is divisible by 9.- Divisibility by 10. A number is divisible by 10 if and only if its last digit is a zero.- Divisibility by 11. A number is divisible by 11 if and only if the sum of digits on its odd positions either equals to the sum of digits on the even positions, or they differ in a number that is divisible by 11.
Vasya got interested by the fact that some divisibility rules resemble each other. In fact, to check a number's divisibility by 2, 4, 5, 8 and 10 it is enough to check fulfiling some condition for one or several last digits. Vasya calls such rules the 2-type rules.
If checking divisibility means finding a sum of digits and checking whether the sum is divisible by the given number, then Vasya calls this rule the 3-type rule (because it works for numbers 3 and 9).
If we need to find the difference between the sum of digits on odd and even positions and check whether the difference is divisible by the given divisor, this rule is called the 11-type rule (it works for number 11).
In some cases we should divide the divisor into several factors and check whether rules of different types (2-type, 3-type or 11-type) work there. For example, for number 6 we check 2-type and 3-type rules, for number 66 we check all three types. Such mixed divisibility rules are called 6-type rules.
And finally, there are some numbers for which no rule works: neither 2-type, nor 3-type, nor 11-type, nor 6-type. The least such number is number 7, so we'll say that in such cases the mysterious 7-type rule works, the one that Vasya hasn't discovered yet.
Vasya's dream is finding divisibility rules for all possible numbers. He isn't going to stop on the decimal numbers only. As there are quite many numbers, ha can't do it all by himself. Vasya asked you to write a program that determines the divisibility rule type in the *b*-based notation for the given divisor *d*.
Input Specification:
The first input line contains two integers *b* and *d* (2<=≤<=*b*,<=*d*<=≤<=100) — the notation system base and the divisor. Both numbers are given in the decimal notation.
Output Specification:
On the first output line print the type of the rule in the *b*-based notation system, where the divisor is *d*: "2-type", "3-type", "11-type", "6-type" or "7-type". If there are several such types, print the one that goes earlier in the given sequence. If a number belongs to the 2-type, print on the second line the least number of the last *b*-based digits that we will need to use to check the divisibility.
Demo Input:
['10 10\n', '2 3\n']
Demo Output:
['2-type\n1\n', '11-type\n']
Note:
The divisibility rule for number 3 in binary notation looks as follows: "A number is divisible by 3 if and only if the sum of its digits that occupy the even places differs from the sum of digits that occupy the odd places, in a number that is divisible by 3". That's an 11-type rule. For example, 21<sub class="lower-index">10</sub> = 10101<sub class="lower-index">2</sub>. For it the sum of digits on odd positions equals 1 + 1 + 1 = 3, an on even positions — 0 + 0 = 0. The rule works and the number is divisible by 3.
In some notations a number can fit into the 3-type rule and the 11-type rule. In this case the correct answer is "3-type". | ```python
import math
from collections import defaultdict
import itertools
PRIME = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def int_sqrt(n):
return int(round(math.sqrt(n)))
def is_2_type(base, divisor):
return [k for k in range(1, 7) if base ** k % divisor == 0]
def is_3_type(base, divisor):
return (base - 1) % divisor == 0
def is_11_type(base, divisor):
return (base + 1) % divisor == 0
def calculate_divisibility_type(base, divisor):
base_factors = defaultdict(int)
divisor_factors = defaultdict(int)
tmp_b = base
tmp_d = divisor
for p in PRIME:
while tmp_b % p == 0:
base_factors[p] += 1
tmp_b //= p
while tmp_d % p == 0:
divisor_factors[p] += 1
tmp_d //= p
k = is_2_type(base, divisor)
if k:
return (2, k[0])
if is_3_type(base, divisor):
return (3, 0)
if is_11_type(base, divisor):
return (11, 0)
if len(base_factors) == len(divisor_factors) and list(base_factors.keys()) == list(divisor_factors.keys()):
return (2, max(0, max(divisor_factors[p] - base_factors[p] for p in base_factors.keys())) + 1)
sqrt_divisor = int_sqrt(divisor)
for d1 in range(2, sqrt_divisor+1):
if divisor % d1 == 0:
q = divisor // d1
if math.gcd(d1, q) == 1:
d2 = q
if is_2_type(base, d1) and (is_3_type(base, d2) or is_11_type(base, d2)):
# print(d1, d2)
return (6, 0)
if is_3_type(base, d1) and (is_2_type(base, d2) or is_11_type(base, d2)):
# print(d1, d2)
return (6, 0)
if is_11_type(base, d1) and (is_2_type(base, d2) or is_3_type(base, d2)):
# print(d1, d2)
return (6, 0)
d2d3 = q
sqrt_d2d3 = int_sqrt(d2d3)
for d2 in range(d1+1, sqrt_d2d3+1):
if d2d3 % d2 == 0 and math.gcd(d1, d2) == 1:
d3 = d2d3 // d2
if math.gcd(d1, d3) == math.gcd(d2, d3) == 1:
possible_cases = [
(dx, dy, dz)
for dx, dy, dz in itertools.permutations([d1, d2, d3])
if is_2_type(base, dx) and is_3_type(base, dy) and is_11_type(base, dz)
]
if len(possible_cases) == 1:
return (6, 0)
# print(base_factors, divisor_factors)
if len(base_factors) == 2 and len(divisor_factors) == 1 and set(base_factors.values()) == {1}:
p1, p2 = base_factors.keys()
if any(p in divisor_factors for p in base_factors.keys()):
return (2, max(divisor_factors[p1], divisor_factors[p2]))
if len(base_factors) == 1 and len(divisor_factors) == 2 and set(divisor_factors.values()) == {1}:
p1, p2 = divisor_factors.keys()
if any(p in base_factors for p in base_factors.keys()):
return (6, 0)
return (7, 0)
if __name__ == '__main__':
base, divisor = map(int, input().split())
div_type, div_last_digit = calculate_divisibility_type(base, divisor)
print("%d-type%s" % (div_type, "" if div_last_digit == 0 else ("\n%d" % div_last_digit)))
``` |
620 | Professor GukiZ and Two Arrays | Title: Professor GukiZ and Two Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a *s**a* as close as possible to the sum of the elements in the array b *s**b*. So he wants to minimize the value *v*<==<=|*s**a*<=-<=*s**b*|.
In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5,<=1,<=3,<=2,<=4] and the array b is [3,<=3,<=2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2,<=1,<=3,<=2,<=4] and the new array b [3,<=3,<=5].
Professor doesn't want to make more than two swaps. Find the minimal value *v* and some sequence of no more than two swaps that will lead to the such value *v*. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of elements in the array a.
The second line contains *n* integers *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the elements of the array a.
The third line contains integer *m* (1<=≤<=*m*<=≤<=2000) — the number of elements in the array b.
The fourth line contains *m* integers *b**j* (<=-<=109<=≤<=*b**j*<=≤<=109) — the elements of the array b.
Output Specification:
In the first line print the minimal value *v*<==<=|*s**a*<=-<=*s**b*| that can be got with no more than two swaps.
The second line should contain the number of swaps *k* (0<=≤<=*k*<=≤<=2).
Each of the next *k* lines should contain two integers *x**p*,<=*y**p* (1<=≤<=*x**p*<=≤<=*n*,<=1<=≤<=*y**p*<=≤<=*m*) — the index of the element in the array a and the index of the element in the array b in the *p*-th swap.
If there are several optimal solutions print any of them. Print the swaps in order the professor did them.
Demo Input:
['5\n5 4 3 2 1\n4\n1 1 1 1\n', '5\n1 2 3 4 5\n1\n15\n', '5\n1 2 3 4 5\n4\n1 2 3 4\n']
Demo Output:
['1\n2\n1 1\n4 2\n', '0\n0\n', '1\n1\n3 1\n']
Note:
none | ```python
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
sum_a, sum_b = sum(a), sum(b)
delta = sum_b - sum_a
ans = abs(delta)
ans_swap = []
for i in range(n):
for j in range(m):
if abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j])) < ans:
ans = abs((sum_a - a[i] + b[j]) - (sum_b + a[i] - b[j]))
ans_swap = [(i+1, j+1)]
d = dict()
for i in range(m):
for j in range(i+1, m):
d[b[i]+b[j]] = (i+1, j+1)
minf, inf = -10**13, 10**13
val = [minf, minf] + sorted(d.keys()) + [inf, inf]
for i in range(n):
for j in range(i+1, n):
ap = a[i] + a[j]
req = (delta + ap*2) >> 1
k = bisect_left(val, req)
for k in range(k-1, k+2):
if abs(delta + ap*2 - val[k]*2) < ans:
ans = abs(delta + ap*2 - val[k]*2)
ans_swap = [(i+1, d[val[k]][0]), (j+1, d[val[k]][1])]
print(ans)
print(len(ans_swap))
for x, y in ans_swap:
print(x, y)
``` |
837 | Vasya's Function | Title: Vasya's Function
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya is studying number theory. He has denoted a function *f*(*a*,<=*b*) such that:
- *f*(*a*,<=0)<==<=0; - *f*(*a*,<=*b*)<==<=1<=+<=*f*(*a*,<=*b*<=-<=*gcd*(*a*,<=*b*)), where *gcd*(*a*,<=*b*) is the greatest common divisor of *a* and *b*.
Vasya has two numbers *x* and *y*, and he wants to calculate *f*(*x*,<=*y*). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.
Input Specification:
The first line contains two integer numbers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=1012).
Output Specification:
Print *f*(*x*,<=*y*).
Demo Input:
['3 5\n', '6 3\n']
Demo Output:
['3\n', '1\n']
Note:
none | ```python
'''
Python3(PyPy3) Template for Programming-Contest.
'''
import math
import sys
def input():
return sys.stdin.readline().rstrip()
DXY = [(0, -1), (1, 0), (0, 1), (-1, 0)] # LDRU
mod = 998244353
inf = 1 << 64
def fact(n: int):
res = []
for p in range(2, n + 1):
if p * p > n:
break
if n % p == 0:
while n % p == 0:
n //= p
res.append(p)
if n > 1:
res.append(n)
return res
sys.setrecursionlimit(10)
def main():
x, y = map(int, input().split())
def f(a: int, b: int) -> int:
if b == 0:
return 0
if a == 1:
return b
g = math.gcd(a, b)
a, b = a // g, b // g
rem = inf
for p in fact(a):
rem = min(rem, b % p)
return rem + f(a, b - rem)
ans = f(x, y)
print(ans)
return 0
if __name__ == "__main__":
main()
``` |
938 | Constructing Tests | Title: Constructing Tests
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's denote a *m*-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size *m*<=×<=*m* of this matrix contains at least one zero.
Consider the following problem:
You are given two integers *n* and *m*. You have to construct an *m*-free square matrix of size *n*<=×<=*n* such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.
You don't have to solve this problem. Instead, you have to construct a few tests for it.
You will be given *t* numbers *x*1, *x*2, ..., *x**t*. For every , find two integers *n**i* and *m**i* (*n**i*<=≥<=*m**i*) such that the answer for the aforementioned problem is exactly *x**i* if we set *n*<==<=*n**i* and *m*<==<=*m**i*.
Input Specification:
The first line contains one integer *t* (1<=≤<=*t*<=≤<=100) — the number of tests you have to construct.
Then *t* lines follow, *i*-th line containing one integer *x**i* (0<=≤<=*x**i*<=≤<=109).
Note that in hacks you have to set *t*<==<=1.
Output Specification:
For each test you have to construct, output two positive numbers *n**i* and *m**i* (1<=≤<=*m**i*<=≤<=*n**i*<=≤<=109) such that the maximum number of 1's in a *m**i*-free *n**i*<=×<=*n**i* matrix is exactly *x**i*. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer <=-<=1.
Demo Input:
['3\n21\n0\n1\n']
Demo Output:
['5 2\n1 1\n-1\n']
Note:
none | ```python
def main():
t = int(input())
for _ in range(t):
num = int(input())
if num == 0:
print(1, 1)
else:
ok = False
div = 1
while div * div <= num:
if num % div == 0:
add = max(num // div, div)
sub = min(num // div, div)
if (add + sub) % 2 == 0:
n = (add + sub) // 2
num_zeros = (add - sub) // 2
if num_zeros != 0:
k = n // num_zeros
if n ** 2 - (n // k) ** 2 == num:
ok = True
break
div += 1
if ok:
print(n, k)
else:
print(-1)
if __name__ == '__main__':
main()
``` |
1,006 | Xor-Paths | Title: Xor-Paths
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a rectangular grid of size $n \times m$. Each cell has a number written on it; the number on the cell ($i, j$) is $a_{i, j}$. Your task is to calculate the number of paths from the upper-left cell ($1, 1$) to the bottom-right cell ($n, m$) meeting the following constraints:
- You can move to the right or to the bottom only. Formally, from the cell ($i, j$) you may move to the cell ($i, j + 1$) or to the cell ($i + 1, j$). The target cell can't be outside of the grid. - The xor of all the numbers on the path from the cell ($1, 1$) to the cell ($n, m$) must be equal to $k$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal).
Find the number of such paths in the given grid.
Input Specification:
The first line of the input contains three integers $n$, $m$ and $k$ ($1 \le n, m \le 20$, $0 \le k \le 10^{18}$) — the height and the width of the grid, and the number $k$.
The next $n$ lines contain $m$ integers each, the $j$-th element in the $i$-th line is $a_{i, j}$ ($0 \le a_{i, j} \le 10^{18}$).
Output Specification:
Print one integer — the number of paths from ($1, 1$) to ($n, m$) with xor sum equal to $k$.
Demo Input:
['3 3 11\n2 1 5\n7 10 0\n12 6 4\n', '3 4 2\n1 3 3 3\n0 3 3 2\n3 0 1 1\n', '3 4 1000000000000000000\n1 3 3 3\n0 3 3 2\n3 0 1 1\n']
Demo Output:
['3\n', '5\n', '0\n']
Note:
All the paths from the first example:
- $(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3)$; - $(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3)$; - $(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3)$.
All the paths from the second example:
- $(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$; - $(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$; - $(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (3, 4)$; - $(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$; - $(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$. | ```python
n,m,k = map(int,input().split())
mat = []
for _ in range(n):
arr = list(map(int,input().split()))
mat.append(arr)
from collections import defaultdict
memo = defaultdict(lambda:0)
def forw(i,j,cnt,val):
val = val^mat[i][j]
if cnt == half:
memo[i,j,val]+=1
return
if i+1<n:
forw(i+1,j,cnt+1,val)
if j+1<m:
forw(i,j+1,cnt+1,val)
def back(i,j,val,cnt):
if cnt == ohalf:
ans[0]+=memo[i,j,val^k]
return
if i-1>=0:
back(i-1,j,val^mat[i][j],cnt+1)
if j-1>=0:
back(i,j-1,val^mat[i][j],cnt+1)
ans =[0]
total= n+m-2
half = total//2
ohalf = total-half
forw(0,0,0,0)
back(n-1,m-1,0,0)
print(ans[0])
``` |
409 | Dome | Title: Dome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains a single floating-point number *x* with exactly 6 decimal places (0<=<<=*x*<=<<=5).
Output Specification:
Output two integers separated by a single space. Each integer should be between 1 and 10, inclusive. If several solutions exist, output any of them. Solution will exist for all tests.
Demo Input:
['1.200000\n', '2.572479\n', '4.024922\n']
Demo Output:
['3 2\n', '10 3\n', '9 9\n']
Note:
none | ```python
import sys
x = float(sys.stdin.readline())
diff = x
for a in range(1, 11):
for h in range(1, 11):
t = pow((a*a*h*h)/(a*a+4*h*h), 0.5)
if diff > abs(x - t):
diff = abs(x-t)
ans_a = a
ans_h = h
print(ans_a, ans_h)
``` |
884 | Bertown Subway | Title: Bertown Subway
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are *n* stations in the subway. It was built according to the Bertown Transport Law:
1. For each station *i* there exists exactly one train that goes from this station. Its destination station is *p**i*, possibly *p**i*<==<=*i*; 1. For each station *i* there exists exactly one station *j* such that *p**j*<==<=*i*.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (*x*,<=*y*) such that person can start at station *x* and, after taking some subway trains (possibly zero), arrive at station *y* (1<=≤<=*x*,<=*y*<=≤<=*n*).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of *p**i* for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input Specification:
The first line contains one integer number *n* (1<=≤<=*n*<=≤<=100000) — the number of stations.
The second line contains *n* integer numbers *p*1, *p*2, ..., *p**n* (1<=≤<=*p**i*<=≤<=*n*) — the current structure of the subway. All these numbers are distinct.
Output Specification:
Print one number — the maximum possible value of convenience.
Demo Input:
['3\n2 1 3\n', '5\n1 5 4 3 2\n']
Demo Output:
['9\n', '17\n']
Note:
In the first example the mayor can change *p*<sub class="lower-index">2</sub> to 3 and *p*<sub class="lower-index">3</sub> to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change *p*<sub class="lower-index">2</sub> to 4 and *p*<sub class="lower-index">3</sub> to 5. | ```python
from sys import stdin
def main():
n = int(stdin.readline())
ar = list(map(int, stdin.readline().split()))
check = [False] * n
ans_list = []
for i in range(n):
if not check[i]:
count = 0
curr = i
while not check[curr]:
check[curr] = True
count += 1
curr = ar[curr] - 1
ans_list.append(count)
ans_list.sort(reverse=True)
ans = 0
if len(ans_list) >= 2:
ans += (ans_list[0] + ans_list[1]) ** 2
for i in range(2, len(ans_list)):
ans += ans_list[i] ** 2
else:
ans = ans_list[0] ** 2
print(ans)
if __name__ == '__main__':
main()
``` |
691 | Swaps in Permutation | Title: Swaps in Permutation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a permutation of the numbers 1,<=2,<=...,<=*n* and *m* pairs of positions (*a**j*,<=*b**j*).
At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?
Let *p* and *q* be two permutations of the numbers 1,<=2,<=...,<=*n*. *p* is lexicographically smaller than the *q* if a number 1<=≤<=*i*<=≤<=*n* exists, so *p**k*<==<=*q**k* for 1<=≤<=*k*<=<<=*i* and *p**i*<=<<=*q**i*.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=106) — the length of the permutation *p* and the number of pairs of positions.
The second line contains *n* distinct integers *p**i* (1<=≤<=*p**i*<=≤<=*n*) — the elements of the permutation *p*.
Each of the last *m* lines contains two integers (*a**j*,<=*b**j*) (1<=≤<=*a**j*,<=*b**j*<=≤<=*n*) — the pairs of positions to swap. Note that you are given a positions, not the values to swap.
Output Specification:
Print the only line with *n* distinct integers *p*'*i* (1<=≤<=*p*'*i*<=≤<=*n*) — the lexicographically maximal permutation one can get.
Demo Input:
['9 6\n1 2 3 4 5 6 7 8 9\n1 4\n4 7\n2 5\n5 8\n3 6\n6 9\n']
Demo Output:
['7 8 9 4 5 6 1 2 3\n']
Note:
none | ```python
from collections import defaultdict
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
parent = [i for i in range(N)]
rank = [0] * N
def find(i):
if parent[i] == i:
return i
else:
parent[i] = find(parent[i])
return parent[i]
def same(x, y):
return find(x) == find(y)
def unite(x, y):
x = find(x)
y = find(y)
if x == y:
return
if rank[x] > rank[y]:
parent[y] = x
else:
parent[x] = y
if rank[x] == rank[y]:
rank[y] += 1
P = list(map(int, input().split()))
for i in range(M):
a, b = map(int, input().split())
a, b = a - 1, b - 1
unite(a, b)
d = defaultdict(list)
cnt = defaultdict(int)
for i in range(N):
d[find(i)].append(P[i])
for i in range(N):
if find(i) == i:
d[i] = sorted(d[i], reverse=True)
ans = []
for i in range(N):
k = find(i)
ans.append(d[k][cnt[k]])
cnt[k] += 1
print(' '.join(map(str, ans)))
``` |
652 | Ants on a Circle | Title: Ants on a Circle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*n* ants are on a circle of length *m*. An ant travels one unit of distance per one unit of time. Initially, the ant number *i* is located at the position *s**i* and is facing in the direction *d**i* (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are distinct.
All the ants move simultaneously, and whenever two ants touch, they will both switch their directions. Note that it is possible for an ant to move in some direction for a half of a unit of time and in opposite direction for another half of a unit of time.
Print the positions of the ants after *t* time units.
Input Specification:
The first line contains three integers *n*, *m* and *t* (2<=≤<=*n*<=≤<=3·105,<=2<=≤<=*m*<=≤<=109,<=0<=≤<=*t*<=≤<=1018) — the number of ants, the length of the circle and the number of time units.
Each of the next *n* lines contains integer *s**i* and symbol *d**i* (1<=≤<=*s**i*<=≤<=*m* and *d**i* is either L or R) — the position and the direction of the *i*-th ant at the start. The directions L and R corresponds to the clockwise and counterclockwise directions, respectively.
It is guaranteed that all positions *s**i* are distinct.
Output Specification:
Print *n* integers *x**j* — the position of the *j*-th ant after *t* units of time. The ants are numbered from 1 to *n* in order of their appearing in input.
Demo Input:
['2 4 8\n1 R\n3 L\n', '4 8 6\n6 R\n5 L\n1 R\n8 L\n', '4 8 2\n1 R\n5 L\n6 L\n8 R\n']
Demo Output:
['1 3\n', '7 4 2 7\n', '3 3 4 2\n']
Note:
none | ```python
import sys
n,m,t=[int(i)for i in sys.stdin.readline().split()]
a,b,k,c=[0]*n,[0]*n,[0]*n,0
for i in range(n):x,y=sys.stdin.readline().split();a[i]=int(x)-1;b[i]=(a[i],i);d=1 if y=="R"else -1;w,u=divmod(a[i]+t*d,m);a[i],c=u,c+w
a,b=sorted(a),sorted(b)
for i in range(n):k[b[i][1]]=a[(i+c)%n]+1
print(" ".join(str(x)for x in k))
``` |
852 | Bathroom terminal | Title: Bathroom terminal
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:
"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle.
You are given *N* strings which represent words. Each word is of the maximum length *L* and consists of characters 'a'-'e'. You are also given *M* strings which represent patterns. Pattern is a string of length <=≤<= *L* and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."
Help Smith escape.
Input Specification:
The first line of input contains two integers *N* and *M* (1<=≤<=*N*<=≤<= 100 000, 1<=≤<=*M*<=≤<= 5000), representing the number of words and patterns respectively.
The next *N* lines represent each word, and after those *N* lines, following *M* lines represent each pattern. Each word and each pattern has a maximum length *L* (1<=≤<=*L*<=≤<=50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.
Output Specification:
Output contains *M* lines and each line consists of one integer, representing the number of words that match the corresponding pattern.
Demo Input:
['3 1\nabc\naec\nac\na?c\n']
Demo Output:
['3\n']
Note:
If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively. | ```python
import sys
from itertools import product
from collections import defaultdict
r=sys.stdin.readline
N,M=map(int,r().split())
words=defaultdict(int)
tb=['a','b','c','d','e']
st=set()
cnt=0
res=""
def dfs(u):
global res,cnt
if u==l:
if res in st:
return
if words[res]>0: cnt+=words[res]
st.add(res)
return
if pattern[u]=='?':
for i in range(6):
if i!=5:res+=tb[i]
dfs(u+1)
if i!=5:res=res[:-1]
else:
res+=pattern[u]
dfs(u+1)
res=res[:-1]
for _ in range(N):
word=r().strip()
words[word]+=1
for _ in range(M):
cnt=0
st.clear()
pattern=r().strip()
l=len(pattern)
res=""
dfs(0)
print(cnt)
``` |
616 | Sum of Remainders | Title: Sum of Remainders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Calculate the value of the sum: *n* mod 1 + *n* mod 2 + *n* mod 3 + ... + *n* mod *m*. As the result can be very large, you should print the value modulo 109<=+<=7 (the remainder when divided by 109<=+<=7).
The modulo operator *a* mod *b* stands for the remainder after dividing *a* by *b*. For example 10 mod 3 = 1.
Input Specification:
The only line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=1013) — the parameters of the sum.
Output Specification:
Print integer *s* — the value of the required sum modulo 109<=+<=7.
Demo Input:
['3 4\n', '4 4\n', '1 1\n']
Demo Output:
['4\n', '1\n', '0\n']
Note:
none | ```python
#n,m=list(map(int,input().split()))
#Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m.
# As the result can be very large,
# you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).
# for i in range(1,151):
# print(f"100 %{i}={100%i}")
# import sys, math
# input=sys.stdin.readline
# INF=int(1e9)+7
# def solve():
# n,m=map(int,input().split())
# result=n*m
# result%=INF
# cur=min(n,m)
# while cur:
# now=n//cur
# next_cur=n//(now+1)
# result-=((cur-next_cur)*(cur+next_cur+1)//2)*now
# result%=INF
# print(now,cur,next_cur,result,((cur-next_cur)*(cur+next_cur+1)//2)*now)
# cur=next_cur
n,m=list(map(int,input().split()))
res=n*m
cur=min(n,m)
while cur:
now=n//cur
next_cur=n//(now+1)
res-=((cur-next_cur)*(cur+next_cur+1)//2)*now
cur=next_cur
print(res%(10**9+7))
``` |
863 | 1-2-3 | Title: 1-2-3
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".
So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set {1,<=2,<=3} and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: 3 beats 2, 2 beats 1 and 1 beats 3.
Both robots' programs make them choose their numbers in such a way that their choice in (*i*<=+<=1)-th game depends only on the numbers chosen by them in *i*-th game.
Ilya knows that the robots will play *k* games, Alice will choose number *a* in the first game, and Bob will choose *b* in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all *k* games, so he asks you to predict the number of points they will have after the final game.
Input Specification:
The first line contains three numbers *k*, *a*, *b* (1<=≤<=*k*<=≤<=1018, 1<=≤<=*a*,<=*b*<=≤<=3).
Then 3 lines follow, *i*-th of them containing 3 numbers *A**i*,<=1, *A**i*,<=2, *A**i*,<=3, where *A**i*,<=*j* represents Alice's choice in the game if Alice chose *i* in previous game and Bob chose *j* (1<=≤<=*A**i*,<=*j*<=≤<=3).
Then 3 lines follow, *i*-th of them containing 3 numbers *B**i*,<=1, *B**i*,<=2, *B**i*,<=3, where *B**i*,<=*j* represents Bob's choice in the game if Alice chose *i* in previous game and Bob chose *j* (1<=≤<=*B**i*,<=*j*<=≤<=3).
Output Specification:
Print two numbers. First of them has to be equal to the number of points Alice will have, and second of them must be Bob's score after *k* games.
Demo Input:
['10 2 1\n1 1 1\n1 1 1\n1 1 1\n2 2 2\n2 2 2\n2 2 2\n', '8 1 1\n2 2 1\n3 3 1\n3 1 3\n1 1 1\n2 1 1\n1 2 3\n', '5 1 1\n1 2 2\n2 2 2\n2 2 2\n1 2 2\n2 2 2\n2 2 2\n']
Demo Output:
['1 9\n', '5 2\n', '0 0\n']
Note:
In the second example game goes like this:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/1e21b6e200707470571d69c9946ace6b56f5279b.png" style="max-width: 100.0%;max-height: 100.0%;"/>
The fourth and the seventh game are won by Bob, the first game is draw and the rest are won by Alice. | ```python
k,a,b = map(int,input().split())
A = []
B = []
check = {}
for i in range(3):
A.append(list(map(int,input().split())))
for i in range(3):
B.append(list(map(int, input().split())))
countA = 0
countB = 0
been = True
i = 0
while(i<k):
if (a, b) in check and been:
been =False
razn = i - check[(a, b)][0]
checkA = 0
checkB = 0
for i in range(razn):
if (a == 3 and b == 2) or (a == 2 and b == 1) or (a == 1 and b == 3):
checkA += 1
if (b == 3 and a == 2) or (b == 2 and a == 1) or (b == 1 and a == 3):
checkB += 1
previous_a = a
previous_b = b
a = A[previous_a - 1][previous_b - 1]
b = B[previous_a - 1][previous_b - 1]
countA+=(checkA)*(((k-check[(a, b)][0])//razn)-1)
countB += (checkB) * (((k - check[(a, b)][0]) // razn)-1)
if (k - check[(a, b)][0]) % razn == 0:
break
else:
i = k - (k - check[(a, b)][0]) % razn
if (a == 3 and b == 2) or (a==2 and b == 1) or (a==1 and b==3):
countA+=1
if (b == 3 and a == 2) or (b == 2 and a == 1) or (b == 1 and a == 3):
countB += 1
previous_a = a
previous_b = b
if (a, b) not in check:
check[(a,b)] = [0,0,0]
check[(a,b)][0] = i
check[(a, b)][1] = countA
check[(a, b)][2] = countB
a = A[previous_a-1][previous_b-1]
b = B[previous_a-1][previous_b-1]
i+=1
print(countA,countB)
``` |
784 | INTERCALC | Title: INTERCALC
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
DO YOU EXPECT ME TO FIND THIS OUT?
WHAT BASE AND/XOR LANGUAGE INCLUDES string?
DON'T BYTE OF MORE THAN YOU CAN CHEW
YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR
SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD
THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!
I HAVE NO ARRAY AND I MUST SCREAM
ELEMENTS MAY NOT BE STORED IN WEST HYPERSPACE
Input Specification:
The first line of input data contains a single integer *n* (1<=≤<=*n*<=≤<=10).
The second line of input data contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=11).
Output Specification:
Output a single integer.
Demo Input:
['4\n2 5 3 1\n']
Demo Output:
['4\n']
Note:
none | ```python
#!/usr/bin/env python
# coding=utf-8
'''
Author: Deean
Date: 2021-11-30 23:20:25
LastEditTime: 2021-11-30 23:22:04
Description: INTERCALC
FilePath: CF784C.py
'''
def func():
n = int(input())
lst = list(map(int, input().strip().split()))
print(max(lst) ^ lst[-1])
if __name__ == '__main__':
func()
``` |
171 | ucyhf | Title: ucyhf
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input Specification:
jxu ydfkj sediyiji ev q iydwbu ydjuwuh *d* (1<=≤<=*d*<=≤<=11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output Specification:
ekjfkj q iydwbu dkcruh.
Demo Input:
['1\n']
Demo Output:
['13\n']
Note:
none | ```python
import sys
#input functions
readint = lambda: int(sys.stdin.readline())
readints = lambda: map(int,sys.stdin.readline().split())
readar = lambda: list(map(int,sys.stdin.readline().split()))
flush = lambda: sys.stdout.flush()
from math import sqrt, floor
def sieve(n: int) -> list[bool]:
ar = [True]*max(2,(n+1))
ar[0] = False
ar[1] = False
for i in range(2,floor(sqrt(n))+1):
if ar[i]: #i is prime
for j in range(i,n//i+1):
ar[i*j] = False
return ar
def fsieve(n: int) -> list[int]:
ar = [1]*max(2,(n+1))
ar[0] = 0
for i in range(2,floor(sqrt(n))+1):
if ar[i] == 1: #i is prime
for j in range(i,n//i+1):
if ar[i*j] == 1: ar[i*j] = i
return ar
pre = sieve(1000000)
ar = list()
for snth in range(1000000):
if pre[snth]:
x = int(str(snth)[::-1])
if x != snth and pre[x]: ar.append(snth)
print(ar[readint()-1])
#print(len(ar))
``` |
883 | Palindromic Cut | Title: Palindromic Cut
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kolya has a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
He wants to rearrange the symbols in *s* and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.
Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut *s* into, if it is allowed to rearrange letters in *s* before cuttings.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=4·105) — the length of string *s*.
The second line contains a string *s* of length *n* consisting of lowercase and uppercase Latin letters and digits.
Output Specification:
Print to the first line an integer *k* — minimum number of palindromes into which you can cut a given string.
Print to the second line *k* strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.
Demo Input:
['6\naabaac\n', '8\n0rTrT022\n', '2\naA\n']
Demo Output:
['2\naba aca ', '1\n02TrrT20 ', '2\na A \n']
Note:
none | ```python
n = int(input())
string = input()
char = []
charPair = []
charImpair = []
for car in string:
if car not in char:
z = string.count(car)
while z>1:
charPair.append(car)
z-=2
if(z==1):
charImpair.append(car)
char.append(car)
if len(charImpair) ==0 :
String1 = ''
for x in charPair:
String1+= x
if len(charImpair) ==1 :
String1 += charImpair[0]
for x in charPair[::-1]:
String1 += x
print('1')
print(String1)
else :
nbPalin = len(charImpair)
while len(charPair)%nbPalin != 0 :
nbPalin += 2
charImpair.append(charPair[-1])
charImpair.append(charPair[-1])
del(charPair[-1])
lenPalindrome = n/nbPalin
Palin = []
for i in range(nbPalin):
String2 = ''
indice = i * int(((lenPalindrome-1)/2))
for x in charPair[indice : int(indice + ((lenPalindrome-1)/2))]:
String2 += x
String2 += charImpair[i]
for x in range(indice + int(((lenPalindrome-1)/2))-1, indice-1 ,-1): # charPair[i + int(((lenPalindrome-1)/2))-1: i-1 :-1]:
String2 += charPair[x]
Palin.append(String2)
print(nbPalin)
String3 = ' '.join(Palin)
print(String3)
``` |
1,000 | Yet Another Problem On a Subsequence | Title: Yet Another Problem On a Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ — are not.
A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ — are not.
For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.
Input Specification:
The first line contains the number $n~(1 \le n \le 10^3)$ — the length of the initial sequence. The following line contains $n$ integers $a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$ — the sequence itself.
Output Specification:
In the single line output one integer — the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.
Demo Input:
['3\n2 1 1\n', '4\n1 1 1 1\n']
Demo Output:
['2\n', '7\n']
Note:
In the first test case, two good subsequences — $[a_1, a_2, a_3]$ and $[a_2, a_3]$.
In the second test case, seven good subsequences — $[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$ and $[a_3, a_4]$. | ```python
from heapq import heappush, heappop
from collections import defaultdict, Counter, deque
import threading
import sys
import bisect
input = sys.stdin.readline
def ri(): return int(input())
def rs(): return input()
def rl(): return list(map(int, input().split()))
def rls(): return list(input().split())
# threading.stack_size(10**8)
# sys.setrecursionlimit(10**6)
class Factorial:
def __init__(self, N, mod) -> None:
N += 1
self.mod = mod
self.f = [1 for _ in range(N)]
self.g = [1 for _ in range(N)]
for i in range(1, N):
self.f[i] = self.f[i - 1] * i % self.mod
self.g[-1] = pow(self.f[-1], mod - 2, mod)
for i in range(N - 2, -1, -1):
self.g[i] = self.g[i + 1] * (i + 1) % self.mod
def fac(self, n):
return self.f[n]
def fac_inv(self, n):
return self.g[n]
def comb(self, n, m):
if n < m:
return 0
return self.f[n] * self.g[m] % self.mod * self.g[n - m] % self.mod
def perm(self, n, m):
return self.f[n] * self.g[n - m] % self.mod
def catalan(self, n):
return (self.comb(2 * n, n) - self.comb(2 * n, n - 1)) % self.mod
def inv(self, n):
return self.f[n-1] * self.g[n] % mod
def main():
mod = 998244353
n = ri()
a = rl()
f = Factorial(10**3, mod)
dp = [0]*(n+1)
dp[-1] = 1
for i in range(n-1, -1, -1):
if a[i] > 0 and i+a[i] < n:
for j in range(i+a[i]+1, n+1):
dp[i] += f.comb(j-i-1, a[i])*dp[j]
dp[i] %= mod
print((sum(dp)-1) % mod)
pass
main()
# threading.Thread(target=main).start()
``` |
838 | Binary Blocks | Title: Binary Blocks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an image, that can be represented with a 2-d *n* by *m* grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer *k*<=><=1 and split the image into *k* by *k* blocks. If *n* and *m* are not divisible by *k*, the image is padded with only zeros on the right and bottom so that they are divisible by *k*. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some *k*. More specifically, the steps are to first choose *k*, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this *k*. The image must be compressible in that state.
Input Specification:
The first line of input will contain two integers *n*,<=*m* (2<=≤<=*n*,<=*m*<=≤<=2<=500), the dimensions of the image.
The next *n* lines of input will contain a binary string with exactly *m* characters, representing the image.
Output Specification:
Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.
Demo Input:
['3 5\n00100\n10110\n11001\n']
Demo Output:
['5\n']
Note:
We first choose *k* = 2.
The image is padded as follows:
We can toggle the image to look as follows:
We can see that this image is compressible for *k* = 2. | ```python
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
from sys import stdin
def run(n, m, pixels):
ans = 1 << 30
acc = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
acc[i + 1][j + 1] = acc[i + 1][j] + int(pixels[i][j])
for j in range(m):
acc[i + 1][j + 1] += acc[i][j + 1]
# print(acc)
for k in range(2, max(n, m) + 1):
r, c = (n + k - 1) // k, (m + k - 1) // k
res = 0
for i in range(r):
for j in range(c):
x, y = i * k, j * k
x2, y2 = min(x + k - 1, n - 1), min(y + k - 1, m - 1)
zero = acc[x2 + 1][y2 + 1] - acc[x][y2 + 1] - acc[x2 + 1][y] + acc[x][y]
# print(x, y, k, zero, k * k - zero)
res += min(zero, k * k - zero)
# print(k, res)
ans = min(ans, res)
print(ans)
def main():
n, m = [int(x) for x in stdin.readline().split()]
pixels = []
for i in range(n):
pixels.append(stdin.readline().strip())
run(n, m, pixels)
if __name__ == '__main__':
import os
if os.path.exists('tmp.in'):
stdin = open('tmp.in')
main()
``` |
990 | Flow Control | Title: Flow Control
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$.
The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \cdot 10^9$ to $2 \cdot 10^9$.
In order for the system to work properly, there are some constraints: for every $i \in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be exactly $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions).
Can you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied?
Input Specification:
The first line contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of junctions.
The second line contains $n$ integers $s_1, s_2, \dots, s_n$ ($-10^4 \le s_i \le 10^4$) — constraints for the junctions.
The third line contains an integer $m$ ($0 \le m \le 2 \cdot 10^5$) — the number of pipes.
$i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) — the description of $i$-th pipe. It is guaranteed that each unordered pair $(x, y)$ will appear no more than once in the input (it means that there won't be any pairs $(x, y)$ or $(y, x)$ after the first occurrence of $(x, y)$). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them.
Output Specification:
If you can choose such integer numbers $f_1, f_2, \dots, f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output $m$ lines, $i$-th line should contain $f_i$ — the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input.
Otherwise output "Impossible" in the only line.
Demo Input:
['4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n', '4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n']
Demo Output:
['Possible\n4\n-6\n8\n-7\n7\n', 'Impossible\n']
Note:
none | ```python
import sys
from time import time
def i_ints():
return list(map(int, sys.stdin.readline().split()))
def main():
limit =10**10
n, = i_ints()
s = [0] + i_ints()
if sum(s):
print("Impossible")
return
print("Possible")
m, = i_ints()
es = [i_ints() for _ in range(m)]
nb = [[] for i in range(n+1)]
for i, (x, y) in enumerate(es):
nb[x].append((y, i, 1))
nb[y].append((x, i, -1))
path = []
def make_path():
stack = []
seen = [False] * (n+1)
stack.append(1)
seen[1] = True
while stack:
x = stack.pop()
for y, i, factor in nb[x]:
if not seen[y]:
seen[y] = True
stack.append(y)
path.append((x, y, i, factor))
make_path()
f = [0] * m
for x, y, i,factor in reversed(path):
f[i] = factor * s[y]
s[x] += s[y]
s[y] = 0
print("\n".join(map(str, f)))
return
main()
``` |
290 | Mysterious strings | Title: Mysterious strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=40).
Output a single string.
Input Specification:
The input contains a single integer *a* (1<=≤<=*a*<=≤<=40).
Output Specification:
Output a single string.
Demo Input:
['2\n', '8\n', '29\n']
Demo Output:
['Adams\n', 'Van Buren\n', 'Harding\n']
Note:
none | ```python
pres = ["Washington",
"Adams",
"Jefferson",
"Madison",
"Monroe",
"Adams",
"Jackson",
"Van Buren",
"Harrison",
"Tyler",
"Polk",
"Taylor",
"Fillmore",
"Pierce",
"Buchanan",
"Lincoln",
"Johnson",
"Grant",
"Hayes",
"Garfield",
"Arthur",
"Cleveland",
"Harrison",
"Cleveland",
"McKinley",
"Roosevelt",
"Taft",
"Wilson",
"Harding",
"Coolidge",
"Hoover",
"Roosevelt",
"Truman",
"Eisenhower",
"Kennedy",
"Johnson",
"Nixon",
"Ford",
"Carter",
"Reagan",
"Bush",
"Clinton",
"Bush",
"Obama",
"Trump",
"Biden"]
print(pres[int(input())-1])
``` |
954 | Water Taps | Title: Water Taps
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider a system of *n* water taps all pouring water into the same container. The *i*-th water tap can be set to deliver any amount of water from 0 to *a**i* ml per second (this amount may be a real number). The water delivered by *i*-th tap has temperature *t**i*.
If for every you set *i*-th tap to deliver exactly *x**i* ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0).
You have to set all the water taps in such a way that the resulting temperature is exactly *T*. What is the maximum amount of water you may get per second if its temperature has to be *T*?
Input Specification:
The first line contains two integers *n* and *T* (1<=≤<=*n*<=≤<=200000, 1<=≤<=*T*<=≤<=106) — the number of water taps and the desired temperature of water, respectively.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) where *a**i* is the maximum amount of water *i*-th tap can deliver per second.
The third line contains *n* integers *t*1, *t*2, ..., *t**n* (1<=≤<=*t**i*<=≤<=106) — the temperature of water each tap delivers.
Output Specification:
Print the maximum possible amount of water with temperature exactly *T* you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0).
Your answer is considered correct if its absolute or relative error doesn't exceed 10<=-<=6.
Demo Input:
['2 100\n3 10\n50 150\n', '3 9\n5 5 30\n6 6 10\n', '2 12\n1 3\n10 15\n']
Demo Output:
['6.000000000000000\n', '40.000000000000000\n', '1.666666666666667\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, t0 = map(int, input().split())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
l = pow(10, 6) + 1
c = [0] * l
s = 0
for i, j in zip(a, t):
c[j] += i
s += (j - t0) * i
ans = sum(a)
if s < 0:
u, v, w = 1, l, 1
elif s > 0:
u, v, w = l - 1, 0, -1
if s:
s = abs(s)
for i in range(u, v, w):
ci = c[i]
x = abs(i - t0)
if s - ci * x > 0:
s -= ci * x
ans -= ci
else:
ans -= s / x
break
print(ans)
``` |
803 | Periodic RMQ Problem | Title: Periodic RMQ Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* consisting of positive integers and *q* queries to this array. There are two types of queries:
- 1 *l* *r* *x* — for each index *i* such that *l*<=≤<=*i*<=≤<=*r* set *a**i*<==<=*x*. - 2 *l* *r* — find the minimum among such *a**i* that *l*<=≤<=*i*<=≤<=*r*.
We decided that this problem is too easy. So the array *a* is given in a compressed form: there is an array *b* consisting of *n* elements and a number *k* in the input, and before all queries *a* is equal to the concatenation of *k* arrays *b* (so the size of *a* is *n*·*k*).
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105, 1<=≤<=*k*<=≤<=104).
The second line contains *n* integers — elements of the array *b* (1<=≤<=*b**i*<=≤<=109).
The third line contains one integer *q* (1<=≤<=*q*<=≤<=105).
Then *q* lines follow, each representing a query. Each query is given either as 1 *l* *r* *x* — set all elements in the segment from *l* till *r* (including borders) to *x* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*·*k*, 1<=≤<=*x*<=≤<=109) or as 2 *l* *r* — find the minimum among all elements in the segment from *l* till *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*·*k*).
Output Specification:
For each query of type 2 print the answer to this query — the minimum on the corresponding segment.
Demo Input:
['3 1\n1 2 3\n3\n2 1 3\n1 1 2 4\n2 1 3\n', '3 2\n1 2 3\n5\n2 4 4\n1 4 4 5\n2 4 4\n1 1 6 1\n2 6 6\n']
Demo Output:
['1\n3\n', '1\n5\n1\n']
Note:
none | ```python
import sys
import random
input = sys.stdin.readline
rd = random.randint(10 ** 9, 2 * 10 ** 9)
class SegmentTree():
def __init__(self, init, unitX, f):
self.f = f # (X, X) -> X
self.unitX = unitX
self.f = f
if type(init) == int:
self.n = init
self.n = 1 << (self.n - 1).bit_length()
self.X = [unitX] * (self.n * 2)
else:
self.n = len(init)
self.n = 1 << (self.n - 1).bit_length()
# len(init)が2の累乗ではない時UnitXで埋める
self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init))
# 配列のindex1まで埋める
for i in range(self.n - 1, 0, -1):
self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1])
def update(self, i, x):
"""0-indexedのi番目の値をxで置換"""
# 最下段に移動
i += self.n
self.X[i] = x
# 上向に更新
i >>= 1
while i:
self.X[i] = self.f(self.X[i * 2], self.X[i * 2 | 1])
i >>= 1
def getvalue(self, i):
"""元の配列のindexの値を見る"""
return self.X[i + self.n]
def getrange(self, l, r):
"""区間[l, r)でのfを行った値"""
l += self.n
r += self.n
al = self.unitX
ar = self.unitX
while l < r:
# 左端が右子ノードであれば
if l & 1:
al = self.f(al, self.X[l])
l += 1
# 右端が右子ノードであれば
if r & 1:
r -= 1
ar = self.f(self.X[r], ar)
l >>= 1
r >>= 1
return self.f(al, ar)
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
q = int(input())
queries = [list(map(int, input().split())) for _ in range(q)]
min_tree = SegmentTree(a, 10 ** 9, min)
p = []
for qq in queries:
p.append(qq[1] - 1)
p.append(qq[2] - 1)
p.sort()
cur = 0
pre = -1
new = []
d = dict()
for i in range(len(p)):
if p[i] == pre:
continue
if p[i] - pre > 1:
if p[i] - pre > n:
mi = min_tree.getrange(0, n)
elif pre % n < p[i] % n:
mi = min_tree.getrange(pre % n + 1, p[i] % n)
else:
mi = min(min_tree.getrange(pre % n + 1, n), min_tree.getrange(0, p[i] % n))
new.append(mi)
cur += 1
new.append(a[p[i] % n])
d[p[i]] = cur
cur += 1
pre = p[i]
def push_lazy(node, left, right):
if lazy[node] != 0:
tree[node] = lazy[node]
if left != right:
lazy[node * 2] = lazy[node]
lazy[node * 2 + 1] = lazy[node]
lazy[node] = 0
def update(node, left, right, l, r, val):
push_lazy(node, left, right)
if r < left or l > right:
return
if l <= left and r >= right:
lazy[node] = val
push_lazy(node, left, right)
return
mid = (left + right) // 2
update(node * 2, left, mid, l, r, val)
update(node * 2 + 1, mid + 1, right, l, r, val)
tree[node] = min(tree[node * 2], tree[node * 2 + 1])
def query(node, left, right, l, r):
push_lazy(node, left, right)
if r < left or l > right:
return 10**18
if l <= left and r >= right:
return tree[node]
mid = (left + right) // 2
sum_left = query(node * 2, left, mid, l, r)
sum_right = query(node * 2 + 1, mid + 1, right, l, r)
return min(sum_left, sum_right)
tree = [10 ** 18] * (4 * len(new))
lazy = [0] * (4 * len(new))
for i in range(len(new)):
update(1, 0, len(new) - 1, i, i, new[i])
for qq in queries:
if qq[0] == 1:
l, r = qq[1] - 1, qq[2] - 1
update(1, 0, len(new) - 1, d[l], d[r], qq[3])
else:
l, r = qq[1] - 1, qq[2] - 1
print(query(1, 0, len(new) - 1, d[l], d[r]))
``` |
813 | The Tag Game | Title: The Tag Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of *n* vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex *x* (*x*<=≠<=1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input Specification:
The first line contains two integer numbers *n* and *x* (2<=≤<=*n*<=≤<=2·105, 2<=≤<=*x*<=≤<=*n*).
Each of the next *n*<=-<=1 lines contains two integer numbers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output Specification:
Print the total number of moves Alice and Bob will make.
Demo Input:
['4 3\n1 2\n2 3\n2 4\n', '5 2\n1 2\n2 3\n3 4\n2 5\n']
Demo Output:
['4\n', '6\n']
Note:
In the first example the tree looks like this:
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4 | ```python
#!/usr/bin/pypy3
from sys import stdin,stderr
from collections import defaultdict
def readInts(): return map(int,stdin.readline().strip().split())
def print_err(*args,**kwargs): print(*args,file=stderr,**kwargs)
def dfs(n,g,b):
s = [(1,0,1)]
b_depth = 0
parents = [ None for _ in range(n+1) ]
while s:
node,depth,pn = s.pop()
parents[node] = pn
if node==b:
b_depth = depth
break
depth += 1
for nn in g[node]:
if nn == pn: continue
s.append( (nn,depth,node) )
anc_node = b
for _ in range((b_depth-1)//2):
anc_node = parents[anc_node]
s = [(1,False,0,1)]
best = 0
while s:
node,bd,depth,pn = s.pop()
bd |= node==anc_node
if bd and best < depth:
best = depth
depth += 1
for nn in g[node]:
if nn == pn: continue
s.append( (nn,bd,depth,node) )
return best
def run():
n,x = readInts()
g = defaultdict(list)
for _ in range(n-1):
a,b = readInts()
g[a].append(b)
g[b].append(a)
print(dfs(n,g,x)*2)
run()
``` |
509 | Pretty Song | Title: Pretty Song
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.
Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.
More formally, let's define the function *vowel*(*c*) which is equal to 1, if *c* is a vowel, and to 0 otherwise. Let *s**i* be the *i*-th character of string *s*, and *s**i*..*j* be the substring of word *s*, staring at the *i*-th character and ending at the *j*-th character (*s**is**i*<=+<=1... *s**j*, *i*<=≤<=*j*).
Then the simple prettiness of *s* is defined by the formula:
The prettiness of *s* equals
Find the prettiness of the given song title.
We assume that the vowels are *I*,<=*E*,<=*A*,<=*O*,<=*U*,<=*Y*.
Input Specification:
The input contains a single string *s* (1<=≤<=|*s*|<=≤<=5·105) — the title of the song.
Output Specification:
Print the prettiness of the song with the absolute or relative error of at most 10<=-<=6.
Demo Input:
['IEAIAIO\n', 'BYOB\n', 'YISVOWEL\n']
Demo Output:
['28.0000000\n', '5.8333333\n', '17.0500000\n']
Note:
In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28. | ```python
def process(S):
n = len(S)
answer = 0
harmonic_sums = [0]
for i in range(1, n+2):
x = harmonic_sums[-1]
harmonic_sums.append(x+1/i)
for i in range(n):
if S[i] in 'AEIOUY':
if i <= n-1-i:
answer1 = (i+1)
h1 = harmonic_sums[i+1]
h2 = harmonic_sums[n-i]
answer2 = (i+1)*(h2-h1)
h3 = harmonic_sums[n+1]
answer3 = (n+1)*(h3-h2)-(i+1)
answer+=(answer1+answer2+answer3)
else:
answer1 = (n-i)
h1 = harmonic_sums[n-i]
h2 = harmonic_sums[i+1]
answer2 = (n-i)*(h2-h1)
h3 = harmonic_sums[n+1]
answer3 = (n+1)*(h3-h2)-(n-i)
answer+=(answer1+answer2+answer3)
return answer
S = input()
print(process(S))
``` |
774 | Stepan's Series | Title: Stepan's Series
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Well, the series which Stepan watched for a very long time, ended. In total, the series had *n* episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not.
Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch.
Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to *k*.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=*n*) — the number of episodes in the series and the dissatisfaction which should be checked.
The second line contains the sequence which consists of *n* symbols "Y", "N" and "?". If the *i*-th symbol equals "Y", Stepan remembers that he has watched the episode number *i*. If the *i*-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number *i*. If the *i*-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number *i* or not.
Output Specification:
If Stepan's dissatisfaction can be exactly equal to *k*, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes).
Demo Input:
['5 2\nNYNNY\n', '6 1\n????NN\n']
Demo Output:
['YES\n', 'NO\n']
Note:
In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because *k* = 2.
In the second test *k* = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. | ```python
import sys
n, k = map(int, input().split(' '))
s = input()
def max_streak(s):
result = 0
for i in range(len(s)):
j = i
while j < len(s) and s[j] == 'N':
j += 1
result = max(result, j - i)
return result
for i in range(n - k + 1):
cur = list(s)
for j in range(i, i + k):
if cur[j] == '?':
cur[j] = 'N'
for j in range(i):
if cur[j] == '?':
cur[j] = 'Y'
for j in range(i + k, n):
if cur[j] == '?':
cur[j] = 'Y'
if max_streak(cur) == k:
print('YES')
sys.exit(0)
print('NO')
``` |
847 | Travel Cards | Title: Travel Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the evening Polycarp decided to analyze his today's travel expenses on public transport.
The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.
Polycarp made *n* trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.
It is known that one trip on any bus costs *a* burles. In case when passenger makes a transshipment the cost of trip decreases to *b* burles (*b*<=<<=*a*). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.
For example, if Polycarp made three consecutive trips: "BerBank" "University", "University" "BerMall", "University" "BerBank", then he payed *a*<=+<=*b*<=+<=*a*<==<=2*a*<=+<=*b* burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.
Also Polycarp can buy no more than *k* travel cards. Each travel card costs *f* burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.
What is the smallest amount of money Polycarp could have spent today if he can buy no more than *k* travel cards?
Input Specification:
The first line contains five integers *n*,<=*a*,<=*b*,<=*k*,<=*f* (1<=≤<=*n*<=≤<=300, 1<=≤<=*b*<=<<=*a*<=≤<=100, 0<=≤<=*k*<=≤<=300, 1<=≤<=*f*<=≤<=1000) where:
- *n* — the number of Polycarp trips, - *a* — the cost of a regualar single trip, - *b* — the cost of a trip after a transshipment, - *k* — the maximum number of travel cards Polycarp can buy, - *f* — the cost of a single travel card.
The following *n* lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space — the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different.
Output Specification:
Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than *k* travel cards.
Demo Input:
['3 5 3 1 8\nBerBank University\nUniversity BerMall\nUniversity BerBank\n', '4 2 1 300 1000\na A\nA aa\naa AA\nAA a\n']
Demo Output:
['11\n', '5\n']
Note:
In the first example Polycarp can buy travel card for the route "BerBank <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ecc94b07e73defe233bfe831f3977337706a2d27.png" style="max-width: 100.0%;max-height: 100.0%;"/> University" and spend 8 burles. Note that his second trip "University" <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles.
In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles. | ```python
n, a, b, k, f = map(int, input().split())
slov = dict()
temp = input().split()
slov[frozenset(temp)] = a
for i in range(1, n):
temp2 = input().split()
try:
if temp2[0] == temp[1]:
slov[frozenset(temp2)] += b
else:
slov[frozenset(temp2)] += a
except KeyError:
if temp2[0] == temp[1]:
slov[frozenset(temp2)] = b
else:
slov[frozenset(temp2)] = a
temp = temp2
costs = sorted(list(slov.values()), reverse=True)
for i in range(min(k, len(costs))):
if costs[i] > f:
costs[i] = f
else:
break
print(sum(costs))
``` |
612 | Simba on the Circle | Title: Simba on the Circle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a circular array with *n* elements. The elements are numbered from some element with values from 1 to *n* in clockwise order. The *i*-th cell contains the value *a**i*. The robot Simba is in cell *s*.
Each moment of time the robot is in some of the *n* cells (at the begin he is in *s*). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time.
Simba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.
Input Specification:
The first line contains two integers *n* and *s* (1<=≤<=*s*<=≤<=*n*<=≤<=2000) — the number of cells in the circular array and the starting position of Simba.
The second line contains *n* integers *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the number written in the *i*-th cell. The numbers are given for cells in order from 1 to *n*. Some of numbers *a**i* can be equal.
Output Specification:
In the first line print the number *t* — the least number of time units.
Each of the next *n* lines should contain the direction of robot movement and the number of cells to move in that direction. After that movement the robot writes out the number from the cell in which it turns out. The direction and the number of cells should be printed in the form of +x in case of clockwise movement and -x in case of counterclockwise movement to *x* cells (0<=≤<=*x*<=≤<=*n*<=-<=1).
Note that the sum of absolute values of *x* should be equal to *t*.
Demo Input:
['9 1\n0 1 2 2 2 1 0 1 1\n', '8 1\n0 1 0 1 0 1 0 1\n', '8 1\n1 2 3 4 5 6 7 8\n', '8 1\n0 0 0 0 0 0 0 0\n']
Demo Output:
['12\n+0\n-3\n-1\n+2\n+1\n+2\n+1\n+1\n+1\n', '13\n+0\n+2\n+2\n+2\n-1\n+2\n+2\n+2\n', '7\n+0\n+1\n+1\n+1\n+1\n+1\n+1\n+1\n', '7\n+0\n+1\n+1\n+1\n+1\n+1\n+1\n+1\n']
Note:
none | ```python
import os
from re import M
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def solve():
n, s = map(int, input().split())
A = list(map(int, input().split()))
s -= 1
se = set(A)
dic = {l:i for i, l in enumerate(sorted(se))}
le = len(se)
A = [dic[a] for a in A]
lst = [[] for _ in range(le + 1)]
for i, a in enumerate(A):
lst[a + 1].append(i)
lst[0] = [s]
dp = [[] for _ in range(le + 1)]
bef = [[] for _ in range(le + 1)]
dp[0] = [0]
inf = 1 << 30
for ii in range(le):
l1 = lst[ii]
l2 = lst[ii + 1]
le1 = len(l1)
le2 = len(l2)
bdp = dp[ii]
ndp = [inf] * le2
bef_ = [None] * le2
if le2 == 1:
for i in range(le1):
tmp = abs(l1[i] - l2[0])
tmp = min(tmp, n - tmp)
d = bdp[i] + tmp
if d < ndp[0]:
ndp[0] = d
bef_[0] = i
else:
for i in range(le1):
for j in range(le2):
tmp = abs(l1[i] - l2[j])
tmp = min(tmp, n - tmp)
d = bdp[i] + tmp
if j == 0:
dd = d + l2[le2 - 1] - l2[j]
if dd < ndp[le2 - 1]:
ndp[le2 - 1] = dd
bef_[le2 - 1] = (i, 0)
else:
dd = d + n - (l2[j] - l2[j - 1])
if dd < ndp[j - 1]:
ndp[j - 1] = dd
bef_[j - 1] = (i, 0)
if j == le2 - 1:
dd = d + l2[j] - l2[0]
if dd < ndp[0]:
ndp[0] = dd
bef_[0] = (i, 1)
else:
dd = d + n - (l2[j + 1] - l2[j])
if dd < ndp[j + 1]:
ndp[j + 1] = dd
bef_[j + 1] = (i, 1)
dp[ii + 1] = ndp
bef[ii + 1] = bef_
min_ = 1 << 30
t = -1
for i, d in enumerate(dp[-1]):
if d < min_:
min_ = d
t = i
print(min_)
ans = []
for i in range(le, 0, -1):
if type(bef[i][t]) == int:
j = bef[i][t]
tmp = lst[i][t] - lst[i - 1][j]
if tmp < 0:
tmp += n
if tmp <= n - tmp:
ans.append(f"+{tmp}")
else:
ans.append(f"-{n - tmp}")
t = j
else:
j, k = bef[i][t]
l = len(lst[i])
if k == 1:
r = t + 1
if r == l:
r = 0
for _ in range(l - 1):
d = lst[i][r] - lst[i][t]
if d < 0:
d += n
ans.append(f"-{d}")
t = r
r = t + 1
if r == l:
r = 0
else:
r = t - 1
if r == -1:
r = l - 1
for _ in range(l - 1):
d = lst[i][t] - lst[i][r]
if d < 0:
d += n
ans.append(f"+{d}")
t = r
r = t - 1
if r == -1:
r = l - 1
tmp = lst[i][t] - lst[i - 1][j]
if tmp < 0:
tmp += n
if tmp <= n - tmp:
ans.append(f"+{tmp}")
else:
ans.append(f"-{n - tmp}")
t = j
print(*ans[::-1], sep="\n")
for _ in range(1):
solve()
``` |
730 | Minimum and Maximum | Title: Minimum and Maximum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().
In this problem, you need to find maximal and minimal elements of an array. What could be simpler?
You can imagine that the jury has an array, and initially you know the only number *n* — array's length.
Array's elements are numbered from 1 to *n*. You are allowed to compare two elements of the array by using their indices *i* and *j*. There are three possible responses to this query: '<' (if *a**i* is less than *a**j*), '=' (if *a**i* is equal to *a**j*) and finally '>' (if *a**i* is greater than *a**j*).
It's known that it's always possible to find both maximal and minimal elements of the array by using no more than comparisons, where ⌈ *x*⌉ is the result of rounding *x* up.
Write the program that will find positions of the minimum and the maximum in the jury's array of length *n*, by using no more than *f*(*n*) comparisons.
Input Specification:
none
Output Specification:
none
Demo Input:
['2\n2\n\xa0\n>\n\xa0\n3\n\xa0\n=\n\xa0\n=\n\xa0']
Demo Output:
['? 1 2\n\xa0\n! 2 1\n\xa0\n? 3 1\n\xa0\n? 2 1\n\xa0\n! 2 3']
Note:
none | ```python
import sys
def find_min_max(l, d=None):
#print(l)
n = len(l)
if n == 1:
return (l[0], l[0])
lesser = []
greater = []
for i in range(n//2):
first = l[2*i]
second = l[2*i + 1]
print("? {} {}".format(first, second))
sys.stdout.flush()
answer = input()
if answer == '<':
lesser.append(first)
greater.append(second)
else:
lesser.append(second)
greater.append(first)
if n%2 == 1:
lesser.append(l[-1])
greater.append(l[-1])
mn = None
mx = None
if d != 'max':
mn = find_min_max(lesser, 'min')[0]
if d != 'min':
mx = find_min_max(greater, 'max')[1]
return (mn, mx)
t = input()
t = int(t)
for k in range(t):
n = input()
n = int(n)
l = list(range(1, n+1))
mn, mx = find_min_max(l)
print("! {} {}".format(mn, mx))
sys.stdout.flush()
``` |
1,003 | Abbreviation | Title: Abbreviation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a text consisting of $n$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $w_i$ is the $i$-th word of text. All words consist only of lowercase Latin letters.
Let's denote a segment of words $w[i..j]$ as a sequence of words $w_i, w_{i + 1}, \dots, w_j$. Two segments of words $w[i_1 .. j_1]$ and $w[i_2 .. j_2]$ are considered equal if $j_1 - i_1 = j_2 - i_2$, $j_1 \ge i_1$, $j_2 \ge i_2$, and for every $t \in [0, j_1 - i_1]$ $w_{i_1 + t} = w_{i_2 + t}$. For example, for the text "to be or not to be" the segments $w[1..2]$ and $w[5..6]$ are equal, they correspond to the words "to be".
An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words $w[2..4]$ and $w[6..8]$ with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words $w[2..5]$ and $w[6..9]$ with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".
What is the minimum length of the text after at most one abbreviation?
Input Specification:
The first line of the input contains one integer $n$ ($1 \le n \le 300$) — the number of words in the text.
The next line contains $n$ space-separated words of the text $w_1, w_2, \dots, w_n$. Each word consists only of lowercase Latin letters.
It is guaranteed that the length of text does not exceed $10^5$.
Output Specification:
Print one integer — the minimum length of the text after at most one abbreviation.
Demo Input:
['6\nto be or not to be\n', '10\na ab a a b ab a a b c\n', '6\naa bb aa aa bb bb\n']
Demo Output:
['12\n', '13\n', '11\n']
Note:
In the first example you can obtain the text "TB or not TB".
In the second example you can obtain the text "a AAAB AAAB c".
In the third example you can obtain the text "AB aa AB bb". | ```python
# https://codeforces.com/contest/1003
import sys
input = lambda: sys.stdin.readline().rstrip() # faster!
n = int(input())
s = input()
# word list
w = s.split()
# dict: word to index
wd = {}
for x in w:
if x not in wd:
wd[x] = len(wd)
# number of distinct words
nw = len(wd)
# length of i-th word
wl = [0] * nw
for word, idx in wd.items():
wl[idx] = len(word)
# translate word list to list of word indices
w = [wd[x] for x in w]
max_savings = 0
def next_segment(orig, k, start):
while start + k <= n:
ok = True
for i in range(k):
if w[orig + i] != w[start + i]:
ok = False
break
if ok:
return start
start += 1
return -1
for i in range(n):
for k in range(1, n // 2 + 1):
if i + k >= n:
break
c = 1
pos = i + k
while True:
j = next_segment(i, k, pos)
if j == -1:
break
c += 1
pos = j + k
if c >= 2:
savings = c * (sum(wl[w[i + j]] for j in range(k)) - 1)
max_savings = max(max_savings, savings)
print(len(s) - max_savings)
``` |
656 | Out of Controls | Title: Out of Controls
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input Specification:
The first line of the input contains a single integer *N* (3<=≤<=*N*<=≤<=10).
The following *N* lines each contain *N* space-separated integers. *j*th integer in *i*th line *a**ij* is the length of the edge that connects vertices *i* and *j*. *a**ij*<==<=*a**ji*, *a**ii*<==<=0, 1<=≤<=*a**ij*<=≤<=100 for *i*<=≠<=*j*.
Output Specification:
Output the maximum length of the shortest path between any pair of vertices in the graph.
Demo Input:
['3\n0 1 1\n1 0 4\n1 4 0\n', '4\n0 1 2 3\n1 0 4 5\n2 4 0 6\n3 5 6 0\n']
Demo Output:
['2\n', '5\n']
Note:
You're running short of keywords, so you can't use some of them: | ```python
from functools import reduce
from itertools import chain
n = int(input())
print(max(map(
max,
reduce(
lambda a, k: reduce(
lambda a, i: reduce(
lambda a, j: list(chain(
a[:i],
[list(chain(
a[i][:j],
[min(a[i][j], a[i][k] + a[k][j])],
a[i][j+1:],
))],
a[i+1:],
)),
range(n),
a,
),
range(n),
a,
),
range(n),
list(map(
lambda i: list(map(int, input().split())),
range(n)))))))
``` |
976 | Degree Set | Title: Degree Set
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a sequence of *n* positive integers *d*1,<=*d*2,<=...,<=*d**n* (*d*1<=<<=*d*2<=<<=...<=<<=*d**n*). Your task is to construct an undirected graph such that:
- there are exactly *d**n*<=+<=1 vertices; - there are no self-loops; - there are no multiple edges; - there are no more than 106 edges; - its degree set is equal to *d*.
Vertices should be numbered 1 through (*d**n*<=+<=1).
Degree sequence is an array *a* with length equal to the number of vertices in a graph such that *a**i* is the number of vertices adjacent to *i*-th vertex.
Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence.
It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 106 edges.
Print the resulting graph.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=300) — the size of the degree set.
The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=1000, *d*1<=<<=*d*2<=<<=...<=<<=*d**n*) — the degree set.
Output Specification:
In the first line print one integer *m* (1<=≤<=*m*<=≤<=106) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 106 edges.
Each of the next *m* lines should contain two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*d**n*<=+<=1) — the description of the *i*-th edge.
Demo Input:
['3\n2 3 4\n', '3\n1 2 3\n']
Demo Output:
['8\n3 1\n4 2\n4 5\n2 5\n5 1\n3 2\n2 1\n5 3\n', '4\n1 2\n1 3\n1 4\n2 3\n']
Note:
none | ```python
n=int(input())
a=list(map(int,input().split()))
def solve(d):
if len(d)==0:
return []
if len(d)==1:
edge=[]
m=d[0]
for i in range(1,m+2):
for j in range(i+1,m+2):
edge.append((i,j))
return edge
e=[]
m=len(d)
d0=d[0]
for i in range(1,m-1):
e.append(d[i]-d0)
edge=solve(e)
s=d[-1]+1
for i in range(s-d0+1,s+1):
for j in range(1,s+1):
if i>j:
edge.append((i,j))
return edge
ans=solve(a)
print(len(ans))
for x,y in ans:
print(x,y)
``` |
977 | Consecutive Subsequence | Title: Consecutive Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an integer array of length $n$.
You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $[x, x + 1, \dots, x + k - 1]$ for some value $x$ and length $k$.
Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $[5, 3, 1, 2, 4]$ the following arrays are subsequences: $[3]$, $[5, 3, 1, 2, 4]$, $[5, 1, 4]$, but the array $[1, 3]$ is not.
Input Specification:
The first line of the input containing integer number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array. The second line of the input containing $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the array itself.
Output Specification:
On the first line print $k$ — the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers.
On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers.
Demo Input:
['7\n3 3 4 7 5 6 8\n', '6\n1 3 5 2 4 6\n', '4\n10 9 8 7\n', '9\n6 7 8 3 4 5 9 10 11\n']
Demo Output:
['4\n2 3 5 6 \n', '2\n1 4 \n', '1\n1 \n', '6\n1 2 3 7 8 9 \n']
Note:
All valid answers for the first example (as sequences of indices):
- $[1, 3, 5, 6]$ - $[2, 3, 5, 6]$
All valid answers for the second example:
- $[1, 4]$ - $[2, 5]$ - $[3, 6]$
All valid answers for the third example:
- $[1]$ - $[2]$ - $[3]$ - $[4]$
All valid answers for the fourth example:
- $[1, 2, 3, 7, 8, 9]$ | ```python
n = int(input())
nums = list(map(int, input().split()))
# 存储以每个数字结尾的最长连续序列长度
seq_len = {}
# 构建连续序列长度的字典
for num in nums:
seq_len[num] = seq_len.get(num - 1, 0) + 1
# 寻找最长序列的结束数字和长度
end, max_len = max(seq_len, key=seq_len.get), max(seq_len.values())
# 回溯找到序列索引
indices = []
while n:
if nums[n - 1] == end:
indices.append(n)
end -= 1
n -= 1
# 反转索引列表并输出
print(max_len)
print(*indices[::-1])
``` |
774 | Perfectionist Arkadiy | Title: Perfectionist Arkadiy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Arkadiy has lots square photos with size *a*<=×<=*a*. He wants to put some of them on a rectangular wall with size *h*<=×<=*w*.
The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and columns of photos to the nearest bound of the wall must be equal to *x*, where *x* is some non-negative real number. Look on the picture below for better understanding of the statement.
Arkadiy haven't chosen yet how many photos he would put on the wall, however, he want to put at least one photo. Your task is to determine the minimum value of *x* which can be obtained after putting photos, or report that there is no way to put positive number of photos and satisfy all the constraints. Suppose that Arkadiy has enough photos to make any valid arrangement according to the constraints.
Note that Arkadiy wants to put at least one photo on the wall. The photos should not overlap, should completely lie inside the wall bounds and should have sides parallel to the wall sides.
Input Specification:
The first line contains three integers *a*, *h* and *w* (1<=≤<=*a*,<=*h*,<=*w*<=≤<=109) — the size of photos and the height and the width of the wall.
Output Specification:
Print one non-negative real number — the minimum value of *x* which can be obtained after putting the photos on the wall. The absolute or the relative error of the answer must not exceed 10<=-<=6.
Print -1 if there is no way to put positive number of photos and satisfy the constraints.
Demo Input:
['2 18 13\n', '4 4 4\n', '3 4 3\n']
Demo Output:
['0.5\n', '0\n', '-1\n']
Note:
In the first example Arkadiy can put 7 rows of photos with 5 photos in each row, so the minimum value of *x* equals to 0.5.
In the second example Arkadiy can put only 1 photo which will take the whole wall, so the minimum value of *x* equals to 0.
In the third example there is no way to put positive number of photos and satisfy the constraints described in the statement, so the answer is -1. | ```python
def gcd(n,m):
if m==0:return n
else:return gcd(m,n%m)
a,h,w=map(int,input().split())
g=gcd(a+h,a+w)
s=(a+w)//g
t=((w//a+1)//s)*s-1
if t<=0:print(-1)
else:print("%.10lf"%((w-t*a)/(t+1)))
``` |
978 | Almost Arithmetic Progression | Title: Almost Arithmetic Progression
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged.
Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals $0$.
Input Specification:
The first line contains a single integer $n$ $(1 \le n \le 100\,000)$ — the number of elements in $b$.
The second line contains a sequence $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 10^{9})$.
Output Specification:
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
Demo Input:
['4\n24 21 14 10\n', '2\n500 500\n', '3\n14 5 1\n', '5\n1 3 6 9 12\n']
Demo Output:
['3\n', '0\n', '-1\n', '1\n']
Note:
In the first example Polycarp should increase the first number on $1$, decrease the second number on $1$, increase the third number on $1$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $[25, 20, 15, 10]$, which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $[0, 3, 6, 9, 12]$, which is an arithmetic progression. | ```python
n = int(input())
sequence = list(map(int, input().split()))
sequences = list()
if(n < 3):
print(0)
else:
bigFlag = True
minCount = float('inf')
for i in [0,1,-1]:
for j in [0,1,-1]:
seq = sequence.copy()
seq[0] = seq[0] + i
seq[1] = seq[1] + j
diff = seq[1] - seq[0]
count = 0
flag = True
for k in range(1,n-1):
if((seq[k+1] - seq[k])==1 + diff):
seq[k+1] = seq[k+1] - 1
count = count + 1
elif((seq[k+1] - seq[k])==-1 + diff):
seq[k+1] = seq[k+1] + 1
count = count + 1
elif((seq[k+1] - seq[k])==diff):
continue
else:
flag = False
break
if flag:
bigFlag = False
if not i ==0:
count = count + 1
if not j == 0:
count = count + 1
if count<minCount:
minCount = count
else:
continue
if bigFlag:
print(-1)
else:
print(minCount)
``` |
409 | The Great Game | Title: The Great Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two teams meet in The Game World Championship. Some scientists consider this game to be the most intellectually challenging game in the world. You are given two strings describing the teams' actions in the final battle. Figure out who became the champion.
Input Specification:
The input contains two strings of equal length (between 2 and 20 characters, inclusive). Each line describes the actions of one team.
Output Specification:
Output "TEAM 1 WINS" if the first team won, "TEAM 2 WINS" if the second team won, and "TIE" if there was a tie.
Demo Input:
['[]()[]8<\n8<[]()8<\n', '8<8<()\n[]8<[]\n']
Demo Output:
['TEAM 2 WINS\n', 'TIE\n']
Note:
none | ```python
s = input()
t = input()
n = len(s)
d = {'([': [0, 1], '((': [0, 0], '[[': [0, 0], '88': [0, 0], '(8': [1, 0],
'8(': [0, 1], '[8': [0, 1], '8[': [1, 0], '[(': [1, 0]}
p, q = 0, 0
for i in range(0, n, 2):
p += d[s[i] + t[i]][0]
q += d[s[i] + t[i]][1]
if p == q:
print('TIE')
elif p > q:
print('TEAM 1 WINS')
else:
print('TEAM 2 WINS')
``` |
802 | April Fools' Problem (medium) | Title: April Fools' Problem (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The marmots need to prepare *k* problems for HC2 over *n* days. Each problem, once prepared, also has to be printed.
The preparation of a problem on day *i* (at most one per day) costs *a**i* CHF, and the printing of a problem on day *i* (also at most one per day) costs *b**i* CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).
What is the minimum cost of preparation and printing?
Input Specification:
The first line of input contains two space-separated integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2200). The second line contains *n* space-separated integers *a*1,<=...,<=*a**n* () — the preparation costs. The third line contains *n* space-separated integers *b*1,<=...,<=*b**n* () — the printing costs.
Output Specification:
Output the minimum cost of preparation and printing *k* problems — that is, the minimum possible sum *a**i*1<=+<=*a**i*2<=+<=...<=+<=*a**i**k*<=+<=*b**j*1<=+<=*b**j*2<=+<=...<=+<=*b**j**k*, where 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**k*<=≤<=*n*, 1<=≤<=*j*1<=<<=*j*2<=<<=...<=<<=*j**k*<=≤<=*n* and *i*1<=≤<=*j*1, *i*2<=≤<=*j*2, ..., *i**k*<=≤<=*j**k*.
Demo Input:
['8 4\n3 8 7 9 9 4 6 8\n2 5 9 4 3 8 9 1\n']
Demo Output:
['32']
Note:
In the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | ```python
from collections import deque
from heapq import heappop, heappush
class Edge(object):
__slots__ = ('x', 'y', 'cap', 'cost', 'inv')
def __repr__(self):
return '{e.x}-->{e.y} ({e.cap} , {e.cost})'.format(e=self)
class MCFP(list):
def add(G, x, y, cap, cost):
n = max(x, y) + 1
while len(G)<n: G.append([])
e = Edge() ; G[x].append(e)
w = Edge() ; G[y].append(w)
e.x=x ; e.y=y; e.cap=cap; e.cost=cost ; w.inv=e
w.x=y ; w.y=x; w.cap=0; w.cost=-cost ; e.inv=w
def solve(G, src, tgt, flowStop=float('inf'), inf=float('inf')):
flowVal = flowCost = 0
n = len(G)
G.inQ = [0]*n
G.phi = h = [0]*n
G.prev = p = [None]*n
G.dist = d = [inf]*n
G.SPFA(src)
while p[tgt]!=None and flowVal<flowStop:
b = [] ; x = tgt
while x!=src: b.append(p[x]) ; x=p[x].x
z = min(e.cap for e in b)
for e in b: e.cap-=z ; e.inv.cap+=z
flowVal += z
flowCost += z * (d[tgt] - h[src] + h[tgt])
for i in range(n):
if p[i]!=None: h[i]+=d[i] ; d[i]=inf
p[tgt] = None
G.SPFA(src)
return flowVal, flowCost
def SPFA(G, src):
inQ = G.inQ ; prev = G.prev
d = G.dist ; h = G.phi
d[src] = 0
Q = deque([src])
while Q:
x = Q.popleft()
inQ[x] = 0
for e in G[x]:
if e.cap <= 0: continue
y = e.y ; dy = d[x] + h[x] + e.cost - h[y]
if dy < d[y]:
d[y] = dy ; prev[y] = e
if inQ[y]==0:
inQ[y] = 1
if not Q or dy > d[Q[0]]: Q.append(y)
else: Q.appendleft(y)
return
import sys, random
ints = (int(x) for x in sys.stdin.read().split())
sys.setrecursionlimit(3000)
def main():
n, k = (next(ints) for i in range(2))
a = [next(ints) for i in range(n)]
b = [next(ints) for i in range(n)]
G = MCFP()
src, tgt = 2*n+1, 2*n+2
for i in range(n):
G.add(src, i, 1, 0)
G.add(i, i+n, 1, a[i])
G.add(i+n, tgt, 1, b[i])
if i+1<n:
G.add(i, i+1, n, 0)
G.add(i+n, i+n+1, n, 0)
flowVal, ans = G.solve(src, tgt, k)
assert flowVal == k
print(ans)
#print(G)
return
def test(n,k):
R = random.Random(0)
yield n ; yield k
for i in range(n): yield R.randint(1, 10**9)
for i in range(n): yield R.randint(1, 10**9)
#ints=test(1000, 800)
main()
``` |
792 | Colored Balls | Title: Colored Balls
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* boxes with colored balls on the table. Colors are numbered from 1 to *n*. *i*-th box contains *a**i* balls, all of which have color *i*. You have to write a program that will divide all balls into sets such that:
- each ball belongs to exactly one of the sets, - there are no empty sets, - there is no set containing two (or more) balls of different colors (each set contains only balls of one color), - there are no two sets such that the difference between their sizes is greater than 1.
Print the minimum possible number of sets.
Input Specification:
The first line contains one integer number *n* (1<=≤<=*n*<=≤<=500).
The second line contains *n* integer numbers *a*1,<=*a*2,<=... ,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Output Specification:
Print one integer number — the minimum possible number of sets.
Demo Input:
['3\n4 7 8\n', '2\n2 7\n']
Demo Output:
['5\n', '4\n']
Note:
In the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color. | ```python
def judge(lists, x):
ans = 0
for i in lists:
t = i//x
d = i%x
if d == 0:
ans += t
elif t+d >= x-1:
ans += t+1
else:
return -1
return ans
while True:
try:
n = input()
balls = list(map(int, input().split()))
minn = min(balls)
for i in range(1, minn+1):
if judge(balls, minn//i + 1) >= 0:
ans = judge(balls, minn//i + 1)
break
elif judge(balls, minn//i) >= 0:
ans = judge(balls, minn//i)
break
print(ans)
except EOFError:
break
``` |
622 | Ants in Leaves | Title: Ants in Leaves
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.
You are given a tree with *n* vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.
Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=5·105) — the number of vertices in the tree.
Each of the next *n*<=-<=1 lines contains two integers *x**i*,<=*y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) — the ends of the *i*-th edge. It is guaranteed that you are given the correct undirected tree.
Output Specification:
Print the only integer *t* — the minimal time required for all ants to be in the root of the tree.
Demo Input:
['12\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n3 9\n8 10\n8 11\n8 12\n', '2\n2 1\n']
Demo Output:
['6\n', '1\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
edge=[[] for i in range(n)]
for i in range(n-1):
a,b=map(lambda x:int(x)-1,input().split())
edge[a].append(b)
edge[b].append(a)
leaf=[0]*n
for i in range(1,n):
if len(edge[i])==1:
leaf[i]=1
depth=[0]*n
def calc(r):
todo=[(r,0)]
d=[]
while todo:
v,p=todo.pop()
if leaf[v]:
d.append(depth[v])
for u in edge[v]:
if u!=p:
todo.append((u,v))
depth[u]=depth[v]+1
d.sort()
now=-1
for i in d:
now+=1
now=max(now,i)
return now
ans=0
for v in edge[0]:
ans=max(ans,calc(v)+1)
print(ans)
``` |
847 | Packmen | Title: Packmen
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A game field is a strip of 1<=×<=*n* square cells. In some cells there are Packmen, in some cells — asterisks, other cells are empty.
Packman can move to neighboring cell in 1 time unit. If there is an asterisk in the target cell then Packman eats it. Packman doesn't spend any time to eat an asterisk.
In the initial moment of time all Packmen begin to move. Each Packman can change direction of its move unlimited number of times, but it is not allowed to go beyond the boundaries of the game field. Packmen do not interfere with the movement of other packmen; in one cell there can be any number of packmen moving in any directions.
Your task is to determine minimum possible time after which Packmen can eat all the asterisks.
Input Specification:
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=105) — the length of the game field.
The second line contains the description of the game field consisting of *n* symbols. If there is symbol '.' in position *i* — the cell *i* is empty. If there is symbol '*' in position *i* — in the cell *i* contains an asterisk. If there is symbol 'P' in position *i* — Packman is in the cell *i*.
It is guaranteed that on the game field there is at least one Packman and at least one asterisk.
Output Specification:
Print minimum possible time after which Packmen can eat all asterisks.
Demo Input:
['7\n*..P*P*\n', '10\n.**PP.*P.*\n']
Demo Output:
['3\n', '2\n']
Note:
In the first example Packman in position 4 will move to the left and will eat asterisk in position 1. He will spend 3 time units on it. During the same 3 time units Packman in position 6 will eat both of neighboring with it asterisks. For example, it can move to the left and eat asterisk in position 5 (in 1 time unit) and then move from the position 5 to the right and eat asterisk in the position 7 (in 2 time units). So in 3 time units Packmen will eat all asterisks on the game field.
In the second example Packman in the position 4 will move to the left and after 2 time units will eat asterisks in positions 3 and 2. Packmen in positions 5 and 8 will move to the right and in 2 time units will eat asterisks in positions 7 and 10, respectively. So 2 time units is enough for Packmen to eat all asterisks on the game field. | ```python
'''
pacman->food
pacman->food->food :hmmge:
larges smaller val
smallest larger val
'''
def check(mid,p,f):
u=0
for i in range(len(p)):
left=p[i]-f[u]
left=max(0,left)
if mid<left:
return 0
right=max(mid-2*left,0)
right=max(right,(mid-left)//2)
while u<len(f) and (f[u]<=p[i]+right): #bich mai fas ra
u+=1
if u==len(f):
return 1
return 0
def f(s,n):
p=[]
f=[]
for i in range(n):
if s[i]=="*":
f.append(i)
if s[i]=="P":
p.append(i)
lo=0
hi=10**9
while lo<=hi:
mid=(lo+hi)//2
if check(mid,p,f):
hi=mid-1
else:
lo=mid+1
return lo
n=int(input())
s=list(input().strip())
print(f(s,n))
``` |
171 | A polyline | Title: A polyline
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains two integers *a*,<=*b* (1<=≤<=*a*<=≤<=10,<=0<=≤<=*b*<=≤<=22·*a*<=-<=1) separated by a single space.
Output Specification:
Output two integers separated by a single space.
Demo Input:
['1 0\n', '2 15\n', '4 160\n']
Demo Output:
['0 0\n', '3 0\n', '12 12\n']
Note:
none | ```python
replacements = {
"A":"+BF-AFA-FB+",
"B":"-AF+BFB+FA-",
"+":"+",
"-":"-",
"F":"F",
}
def curve_sequence(n):
if n==0:
yield "A"
return
for t in curve_sequence(n-1):
yield from replacements[t]
a, b = map(int, input().split())
def location(a, b):
i = 0
x, y = 0, 0
direction = 0
for move in curve_sequence(a):
if i == b:
return x, y
if move == "+":
direction += 1
direction %= 4
elif move == "-":
direction -= 1
direction %= 4
if move != "F":
continue
i += 1
if direction == 0:
x += 1
elif direction == 1:
y += 1
elif direction == 2:
x -= 1
else:
y -= 1
print(*location(a, b))
``` |
938 | Max History | Title: Max History
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* of length *n*. We define *f**a* the following way:
- Initially *f**a*<==<=0, *M*<==<=1; - for every 2<=≤<=*i*<=≤<=*n* if *a**M*<=<<=*a**i* then we set *f**a*<==<=*f**a*<=+<=*a**M* and then set *M*<==<=*i*.
Calculate the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7.
Note: two elements are considered different if their indices differ, so for every array *a* there are exactly *n*! permutations.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=<=1 000 000) — the size of array *a*.
Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=<=*a**i*<=≤<=<=109).
Output Specification:
Print the only integer, the sum of *f**a* over all *n*! permutations of the array *a* modulo 109<=+<=7.
Demo Input:
['2\n1 3\n', '3\n1 1 2\n']
Demo Output:
['1', '4']
Note:
For the second example all the permutations are:
- *p* = [1, 2, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [1, 3, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 1, 3] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [2, 3, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 1; - *p* = [3, 1, 2] : *f*<sub class="lower-index">*a*</sub> is equal to 0; - *p* = [3, 2, 1] : *f*<sub class="lower-index">*a*</sub> is equal to 0.
Where *p* is the array of the indices of initial array *a*. The sum of *f*<sub class="lower-index">*a*</sub> is equal to 4. | ```python
import sys
input = sys.stdin.buffer.readline
p = 10**9+7
def process(A):
n = len(A)
fact_dict = [1]
for i in range(1, n+1):
x = fact_dict[-1]
fact_dict.append((i*x) % p)
A.sort()
m = A[-1]
curr = 0
answer = 0
for i in range(n):
if i==0 or A[i] > A[i-1]:
smaller = curr
if A[i] < m:
entry = fact_dict[n]*pow(n-smaller, p-2, p)
answer = (answer+entry*A[i]) % p
curr+=1
print(answer)
n = int(input())
A = [int(x) for x in input().split()]
process(A)
``` |
976 | Well played! | Title: Well played!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:
Max owns *n* creatures, *i*-th of them can be described with two numbers — its health *hp**i* and its damage *dmg**i*. Max also has two types of spells in stock:
1. Doubles health of the creature (*hp**i* := *hp**i*·2); 1. Assigns value of health of the creature to its damage (*dmg**i* := *hp**i*).
Spell of first type can be used no more than *a* times in total, of the second type — no more than *b* times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.
Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.
Input Specification:
The first line contains three integers *n*, *a*, *b* (1<=≤<=*n*<=≤<=2·105, 0<=≤<=*a*<=≤<=20, 0<=≤<=*b*<=≤<=2·105) — the number of creatures, spells of the first type and spells of the second type, respectively.
The *i*-th of the next *n* lines contain two number *hp**i* and *dmg**i* (1<=≤<=*hp**i*,<=*dmg**i*<=≤<=109) — description of the *i*-th creature.
Output Specification:
Print single integer — maximum total damage creatures can deal.
Demo Input:
['2 1 1\n10 15\n6 1\n', '3 0 3\n10 8\n7 11\n5 2\n']
Demo Output:
['27\n', '26\n']
Note:
In the first example Max should use the spell of the first type on the second creature, then the spell of the second type on the same creature. Then total damage will be equal to 15 + 6·2 = 27.
In the second example Max should use the spell of the second type on the first creature, then the spell of the second type on the third creature. Total damage will be equal to 10 + 11 + 5 = 26. | ```python
from sys import stdin,exit
#Parsea una línea
def parser():
return map(int, stdin.readline().split())
#Recibiendo los valores de n, a y b
n,a,b=parser()
#Máximo de hechizos de tipo 2 que tiene sentido utilizar
b=min(b,n)
#Inicializando las listas de vida y daño
hp=[]
dmg=[]
#Recibiendo los parámetros de las criaturas
for creature in range(n):
h,d=parser()
hp.append(h)
dmg.append(d)
#Si no hay hechizos de tipo 2 solo se pueden usar los daños de las criaturas
if b==0:
print(sum(dmg))
exit()
#Ordenar las criaturas por vida menos daño
ordered_creatures=sorted(range(n),key=lambda i: hp[i]-dmg[i],reverse=True)
#Inicializando el daño total
max_damage=0
#Recorriendo las criaturas
#Si es una de las primeras b criaturas ver si es mejor utilizar un hechizo de tipo 2 o no
for i in range(0,b):
max_damage+=max(hp[ordered_creatures[i]],dmg[ordered_creatures[i]])
#Si no es una de las primeras b criaturas sumar su daño
for i in range(b,n):
max_damage+=dmg[ordered_creatures[i]]
#Guardar el valor auxiliar de la solución óptima del primer subproblema
aux=max_damage
#Restar lo aportado por la b-ésima criatura y sumar su daño
change=max(hp[ordered_creatures[b-1]],dmg[ordered_creatures[b-1]])-dmg[ordered_creatures[b-1]]
#Recorriendo las criaturas para ver a cuál aplicar los hechizos tipo 1
#Si pertenece a las primeras b criaturas restar daño aportado anteriormente y sumar el daño que causará con los hechizos de tipo 1
#Quedarse con el máximo valor entre lo antes calculado y lo calculado actualmente
for i in range(0,b):
max_damage=max(max_damage,aux-max(hp[ordered_creatures[i]],dmg[ordered_creatures[i]])+hp[ordered_creatures[i]]*2**a)
#Si no pertenece a las primeras b criaturas restar el daño aportado por la b-ésima criatura y sumar su daño. Luego restar el daño aportado por la criatura actual y sumar el daño que causará con los hechizos de tipo 1
for i in range(b,n):
max_damage=max(max_damage,aux-change-dmg[ordered_creatures[i]]+hp[ordered_creatures[i]]*2**a)
#Imprimir el máximo daño total
print(max_damage)
``` |
802 | Heidi and Library (easy) | Title: Heidi and Library (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are *n* different books, numbered 1 through *n*.
We will look at the library's operation during *n* consecutive days. Heidi knows in advance that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) precisely one person will come to the library, request to borrow the book *a**i*, read it in a few hours, and return the book later on the same day.
Heidi desperately wants to please all her guests, so she will make sure to always have the book *a**i* available in the library on the *i*-th day. During the night before the *i*-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books.
There is a problem, though. The capacity of the library is *k* – this means that at any time, there can be at most *k* books at the library. If buying a new book would cause Heidi to have more than *k* books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again.
You are given *k* and the sequence of requests for books *a*1,<=*a*2,<=...,<=*a**n*. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?
Input Specification:
The first line of input will contain two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=80). The second line will contain *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) – the sequence of book requests.
Output Specification:
On a single line print the minimum cost of buying books at the store so as to satisfy all requests.
Demo Input:
['4 80\n1 2 2 1\n', '4 1\n1 2 2 1\n', '4 2\n1 2 3 1\n']
Demo Output:
['2\n', '3\n', '3\n']
Note:
In the first test case, Heidi is able to keep all books forever. Therefore, she only needs to buy the book 1 before the first day and the book 2 before the second day.
In the second test case, she can only keep one book at a time. Therefore she will need to buy new books on the first, second and fourth day.
In the third test case, before buying book 3 on the third day, she must decide which of the books 1 and 2 she should get rid of. Of course, she should keep the book 1, which will be requested on the fourth day. | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
inventory = set()
bought = 0
for i in range(n):
if a[i] not in inventory:
if len(inventory) == k:
farthest_time = 0
farthest = 0
for v in inventory:
try:
far = a.index(v, i + 1)
if far > farthest_time:
farthest_time = far
farthest = v
except ValueError:
farthest_time = 10000
farthest = v
inventory.remove(farthest)
inventory.add(a[i])
bought += 1
print(bought)
``` |
120 | Brevity is Soul of Wit | Title: Brevity is Soul of Wit
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As we communicate, we learn much new information. However, the process of communication takes too much time. It becomes clear if we look at the words we use in our everyday speech.
We can list many simple words consisting of many letters: "information", "technologies", "university", "construction", "conservatoire", "refrigerator", "stopwatch", "windowsill", "electricity", "government" and so on. Of course, we can continue listing those words ad infinitum.
Fortunately, the solution for that problem has been found. To make our speech clear and brief, we should replace the initial words with those that resemble them but are much shorter. This idea hasn't been brought into life yet, that's why you are chosen to improve the situation.
Let's consider the following formal model of transforming words: we shall assume that one can use *n* words in a chat. For each words we shall introduce a notion of its shorter variant. We shall define shorter variant of an arbitrary word *s* as such word *t*, that meets the following conditions:
- it occurs in *s* as a subsequence, - its length ranges from one to four characters.
In other words, the word *t* consists at least of one and at most of four characters that occur in the same order in the word *s*. Note that those characters do not necessarily follow in *s* immediately one after another. You are allowed not to shorten the initial word if its length does not exceed four characters.
You are given a list of *n* different words. Your task is to find a set of their shortened variants. The shortened variants of all words from the list should be different.
Input Specification:
The first line of the input file contains the only integer *n* (1<=≤<=*n*<=≤<=200). Then *n* lines contain a set of different non-empty words that consist of lowercase Latin letters. The length of each word does not exceed 10 characters.
Output Specification:
If the solution exists, print in the output file exactly *n* lines, where the *i*-th line represents the shortened variant of the *i*-th word from the initial set. If there are several variants to solve the problem, print any of them. If there is no solution, print -1.
Demo Input:
['6\nprivet\nspasibo\ncodeforces\njava\nmarmelad\nnormalno\n', '5\naaa\naa\na\naaaa\naaaaa\n']
Demo Output:
['pret\nsps\ncdfs\njava\nmama\nnorm\n', '-1\n']
Note:
none | ```python
import sys
from itertools import combinations
in_file = open("input.txt", "r") #
out_file = open("output.txt", "w")
n = int(in_file.readline().strip())
U = []
for i in range(n):
U.append(in_file.readline().strip())
A = [set() for u in U]
l = len(U)
V_inv = {}
for i in range(1, 5):
for j in range(len(U)):
u = U[j]
for v in combinations(u, i):
v = "".join(v)
if v not in V_inv:
V_inv[v] = l
l += 1
A.append(set())
A[j].add(V_inv[v])
A[V_inv[v]].add(j)
V = [-1 for i in range(len(V_inv))]
for v in V_inv:
V[V_inv[v]-len(U)] = v
inf = len(V)+len(U)
match = [inf for i in range(len(V)+len(U))]
dist = [-1 for i in range(inf+1)]
def bfs():
Q = []
i = 0
for u in range(len(U)):
if match[u] == inf:
dist[u] = 0
Q.append(u)
else:
dist[u] = inf
dist[inf] = inf
while i < len(Q):
u = Q[i]
if dist[u] < dist[inf]:
for v in A[u]:
if dist[match[v]] == inf:
dist[match[v]] = dist[u]+1
Q.append(match[v])
i += 1
return dist[inf] != inf
def dfs(u):
if u != inf:
for v in A[u]:
if dist[match[v]] == dist[u]+1:
if dfs(match[v]):
match[v] = u
match[u] = v
return True
dist[u] = inf
return False
return True
matches = 0
while bfs():
for u in range(len(U)):
if match[u] == inf:
if dfs(u):
matches += 1
if matches == len(U):
for i in range(len(U)):
out_file.write(V[match[i]-len(U)]+"\n")
else:
out_file.write("-1\n")
out_file.flush()
in_file.close()
out_file.close()
``` |
958 | Lightsabers (medium) | Title: Lightsabers (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.
Heidi has *n* Jedi Knights standing in front of her, each one with a lightsaber of one of *m* possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly *k*1 knights with lightsabers of the first color, *k*2 knights with lightsabers of the second color, ..., *k**m* knights with lightsabers of the *m*-th color.
However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.
Input Specification:
The first line of the input contains *n* (1<=≤<=*n*<=≤<=2·105) and *m* (1<=≤<=*m*<=≤<=*n*). The second line contains *n* integers in the range {1,<=2,<=...,<=*m*} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains *m* integers *k*1,<=*k*2,<=...,<=*k**m* (with ) – the desired counts of Jedi Knights with lightsabers of each color from 1 to *m*.
Output Specification:
Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output <=-<=1.
Demo Input:
['8 3\n3 3 1 2 2 1 1 3\n3 1 1\n']
Demo Output:
['1\n']
Note:
none | ```python
n, m = map(int, input().split())
c = list(map(int, input().split()))
k = list(map(int, input().split()))
p = [0] * m
c = [i -1 for i in c]
s = sum(k)
cnt = k.count(0)
l = 0
r = 0
while r < n and cnt < m:
p[c[r]] += 1
if p[c[r]] == k[c[r]]:
cnt += 1
r += 1
if cnt != m:
print(-1)
exit(0)
ans = r-l
while l < n:
p[c[l]] -= 1
while r < n and p[c[l]] < k[c[l]]:
p[c[r]] += 1
r += 1
if p[c[l]] >= k[c[l]]:
ans = min(ans, r-l-1)
elif r == n:
break
l += 1
print(ans-s)
``` |
962 | Byteland, Berland and Disputed Cities | Title: Byteland, Berland and Disputed Cities
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities:
- the cities of Byteland, - the cities of Berland, - disputed cities.
Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.
The countries agreed to connect the pairs of cities with BNET cables in such a way that:
- If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, - If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.
Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.
The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.
Each city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.
Input Specification:
The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^{5}$) — the number of cities.
The following $n$ lines contains an integer $x_i$ and the letter $c_i$ ($-10^{9} \le x_i \le 10^{9}$) — the coordinate of the city and its type. If the city belongs to Byteland, $c_i$ equals to 'B'. If the city belongs to Berland, $c_i$ equals to «R». If the city is disputed, $c_i$ equals to 'P'.
All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.
Output Specification:
Print the minimal total length of such set of cables, that if we delete all Berland cities ($c_i$='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities ($c_i$='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.
Demo Input:
['4\n-5 R\n0 P\n3 P\n7 B\n', '5\n10 R\n14 B\n16 B\n21 R\n32 R\n']
Demo Output:
['12\n', '24\n']
Note:
In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be $5 + 3 + 4 = 12$.
In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates $10, 21, 32$, so to connect them you need two cables of length $11$ and $11$. The cities of Byteland have coordinates $14$ and $16$, so to connect them you need one cable of length $2$. Thus, the total length of all cables is $11 + 11 + 2 = 24$. | ```python
n=int(input())
last_r=None
last_b=None
last_p=None
ans=0
max_r=0
max_b=0
max_p=0
for _ in range(n):
s=input().split()
x=int(s[0])
c=s[1]
if c=='B':
if last_b!=None:
ans+=x-last_b
max_b=max(max_b,x-last_b)
last_b=x
if c=='R':
if last_r!=None:
ans+=x-last_r
max_r=max(max_r,x-last_r)
last_r=x
if c=='P':
if last_b!=None:
ans+=x-last_b
max_b=max(max_b,x-last_b)
last_b=x
if last_r!=None:
ans+=x-last_r
max_r=max(max_r,x-last_r)
last_r=x
if last_p!=None:
new_ans=(x-last_p)*3
new_ans-=max_r
new_ans-=max_b
if new_ans<(x-last_p)*2:
ans-=(x-last_p)*2-new_ans
last_p=x
max_b=0
max_r=0
print(ans)
``` |
802 | Marmots (hard) | Title: Marmots (hard)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population *P* from their random number before responding to Heidi's request.
Also, there are now villages with as few as a single inhabitant, meaning that .
Can you help Heidi find out whether a village follows a Poisson or a uniform distribution?
Input Specification:
Same as for the easy and medium versions. But remember that now 1<=≤<=*P*<=≤<=1000 and that the marmots may provide positive as well as negative integers.
Output Specification:
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution.
Note:
none | ```python
for i in range(int(input())):
a=list(map(int,input().split()))
mx=max(list(map(abs,a)))
std=(sum(list(map(lambda x:x*x,a)))/len(a))**0.5
print('poisson'if mx/std>2 else'uniform')
``` |
717 | Underfail | Title: Underfail
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and P’pairus, who decided to accompany you and give you some puzzles for seemingly unknown reasons.
One day, Sanz has created a crossword for you. Not any kind of crossword, but a 1D crossword! You are given *m* words and a string of length *n*. You are also given an array *p*, which designates how much each word is worth — the *i*-th word is worth *p**i* points. Whenever you find one of the *m* words in the string, you are given the corresponding number of points. Each position in the crossword can be used at most *x* times. A certain word can be counted at different places, but you cannot count the same appearance of a word multiple times. If a word is a substring of another word, you can count them both (presuming you haven’t used the positions more than *x* times).
In order to solve the puzzle, you need to tell Sanz what’s the maximum achievable number of points in the crossword. There is no need to cover all postions, just get the maximal score! Crossword and words contain only lowercase English letters.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=500) — the length of the crossword. The second line contains the crossword string. The third line contains a single integer *m* (1<=≤<=*m*<=≤<=100) — the number of given words, and next *m* lines contain description of words: each line will have a string representing a non-empty word (its length doesn't exceed the length of the crossword) and integer *p**i* (0<=≤<=*p**i*<=≤<=100). Last line of the input will contain *x* (1<=≤<=*x*<=≤<=100) — maximum number of times a position in crossword can be used.
Output Specification:
Output single integer — maximum number of points you can get.
Demo Input:
['6\nabacba\n2\naba 6\nba 3\n3\n']
Demo Output:
['12\n']
Note:
For example, with the string "abacba", words "aba" (6 points) and "ba" (3 points), and *x* = 3, you can get at most 12 points - the word "aba" appears once ("abacba"), while "ba" appears two times ("abacba"). Note that for *x* = 1, you could get at most 9 points, since you wouldn’t be able to count both "aba" and the first appearance of "ba". | ```python
import sys
from heapq import heappop, heappush
class Edge:
def __init__(self, u, v, cap, flow, cost, rev) -> None:
self.u = u
self.v = v
self.cap = cap
self.flow = flow
self.cost = cost
self.rev = rev
def add_edge(adj, u, v, capv, flowv, costv):
if u == 6 and v == 7:
foo = 0
adj[u].append(Edge(u, v, capv, flowv, costv, len(adj[v])))
adj[v].append(Edge(v, u, 0, flowv, -costv, len(adj[u])-1))
def match(crossword, cw_idx, word):
for k in range(len(word)):
if crossword[cw_idx + k] != word[k]:
return False
return True
def read_input():
'''
6
abacba
5
aba 6
ba 3
bac 4
cb 3
c 6
2
'''
n = int(sys.stdin.readline())
# n = int('6\n')
crossword = sys.stdin.readline()[:-1]
# crossword = 'abacba\n'[:-1]
m = int(sys.stdin.readline())
# m = int('5\n')
adj = [[] for _ in range(n+2)]
# foo
m_words = ["aba 6\n", "ba 3\n", "bac 4\n", "cb 3\n", "c 6"]
# print(len(cost))
for idx in range(m):
word, p = sys.stdin.readline().split()
# word, p = m_words[idx].split()
p = int(p)
i = 0
while i + len(word) <= n:
if match(crossword, i, word):
u, v = i + 1, i + 1 + len(word)
# print((u, v))
add_edge(adj, u, v, 1, 0, -p)
i += 1
x = int(sys.stdin.readline())
# x = int('2\n')
for i in range(n + 1):
u, v = i, i + 1
# print((u, v))
add_edge(adj, u, v, x, 0, 0)
return adj
def bellman_ford(adj, potencial):
for _ in range(len(adj)):
for u in range(len(adj)):
for e in adj[u]:
reduced_cost = potencial[e.u] + e.cost - potencial[e.v]
if e.cap > 0 and reduced_cost < 0:
potencial[e.v] += reduced_cost
def dijkstra(adj, potencial, dist, pi, s, t):
oo = float('inf')
for u in range(len(adj)):
dist[u] = +oo
pi[u] = None
dist[s] = 0
heap = [(0, s)]
while heap:
du, u = heappop(heap)
if dist[u] < du: continue
if u == t: break
for e in adj[u]:
reduced_cost = potencial[e.u] + e.cost - potencial[e.v]
if e.flow < e.cap and dist[e.v] > dist[e.u] + reduced_cost:
dist[e.v] = dist[e.u] + reduced_cost
heappush(heap, (dist[e.v], e.v))
pi[e.v] = e
def min_cost_max_flow(adj):
min_cost, max_flow = 0, 0
potencial, oo = [0] * len(adj), float('inf')
dist, pi = [+oo] * len(adj), [None] * len(adj)
bellman_ford(adj, potencial)
s, t = 0, len(adj) - 1
while True:
dijkstra(adj, potencial, dist, pi, s, t)
if dist[t] == +oo:
break
for u in range(len(adj)):
if dist[u] < dist[t]:
potencial[u] += dist[u] - dist[t]
limit, v = +oo, t
while v:
e = pi[v]
limit = min(limit, e.cap - e.flow)
v = e.u
v = t
while v:
e = pi[v]
e.flow += limit
try:
adj[v][e.rev].flow -= limit
except:
adj[v][e.rev].flow -= limit
v = e.u
min_cost += limit * (potencial[t] - potencial[s])
max_flow += limit
# path = []
# v = t
# while v:
# path.append(v)
# v = pi[v]
# path.reverse()
# print(path)
return min_cost, max_flow
adj = read_input()
# print({
# 'len(adj)': len(adj),
# 'len(cap)': len(cap),
# 'len(cost)': len(cost)
# })
# print({ 'adj': adj})
# print({ 'cap': cap})
# print({ 'cost': cost})
min_cost, _ = min_cost_max_flow(adj)
print(-min_cost)
``` |
616 | Expensive Strings | Title: Expensive Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* strings *t**i*. Each string has cost *c**i*.
Let's define the function of string , where *p**s*,<=*i* is the number of occurrences of *s* in *t**i*, |*s*| is the length of the string *s*. Find the maximal value of function *f*(*s*) over all strings.
Note that the string *s* is not necessarily some string from *t*.
Input Specification:
The first line contains the only integer *n* (1<=≤<=*n*<=≤<=105) — the number of strings in *t*.
Each of the next *n* lines contains contains a non-empty string *t**i*. *t**i* contains only lowercase English letters.
It is guaranteed that the sum of lengths of all strings in *t* is not greater than 5·105.
The last line contains *n* integers *c**i* (<=-<=107<=≤<=*c**i*<=≤<=107) — the cost of the *i*-th string.
Output Specification:
Print the only integer *a* — the maximal value of the function *f*(*s*) over all strings *s*. Note one more time that the string *s* is not necessarily from *t*.
Demo Input:
['2\naa\nbb\n2 1\n', '2\naa\nab\n2 1\n']
Demo Output:
['4\n', '5\n']
Note:
none | ```python
def SA_IS(S):
S += [0]
k = max(S) + 1
n = len(S)
def induce_l(sa, a, n, k, stype):
bucket = get_buckets(a, k, 1)
for i in range(n):
j = sa[i] - 1
if j >= 0 and (not stype[j]):
sa[bucket[a[j]]] = j
bucket[a[j]] += 1
def induce_s(sa, a, n, k, stype):
bucket = get_buckets(a, k, 0)
for i in range(n)[::-1]:
j = sa[i] - 1
if j >= 0 and stype[j]:
bucket[a[j]] -= 1
sa[bucket[a[j]]] = j
def get_buckets(a, k, start=0):
bucket = [0] * k
for item in a:
bucket[item] += 1
s = 0
for i in range(k):
s += bucket[i]
bucket[i] = s - (bucket[i] if start else 0)
return bucket
def set_lms(a, n, k, default_order):
bucket = get_buckets(a, k)
sa = [-1] * n
for i in default_order[::-1]:
bucket[a[i]] -= 1
sa[bucket[a[i]]] = i
return sa
def induce(a, n, k, stype, default_order):
sa = set_lms(a, n, k, default_order)
induce_l(sa, a, n, k, stype)
induce_s(sa, a, n, k, stype)
return sa
def rename_LMS_substring(sa, a, n, stype, LMS, l):
sa = [_s for _s in sa if LMS[_s]]
tmp = [-1] * (n // 2) + [0]
dupl = 0
for t in range(1, l):
i, j = sa[t - 1], sa[t]
for ii in range(n):
if a[i + ii] != a[j + ii] or stype[i + ii] != stype[j + ii]:
break
if ii and (LMS[i + ii] or LMS[j + ii]):
dupl += 1
break
tmp[j // 2] = t - dupl
tmp = [t for t in tmp if t >= 0]
return tmp, dupl
def calc(a, n, k):
stype = [1] * n
for i in range(n - 1)[::-1]:
if a[i] > a[i + 1] or (a[i] == a[i + 1] and stype[i + 1] == 0):
stype[i] = 0
LMS = [1 if stype[i] and not stype[i - 1] else 0 for i in range(n - 1)] + [1]
l = sum(LMS)
lms = [i for i in range(n) if LMS[i]]
sa = induce(a, n, k, stype, lms)
renamed_LMS, dupl = rename_LMS_substring(sa, a, n, stype, LMS, l)
if dupl:
sub_sa = calc(renamed_LMS, l, l - dupl)
else:
sub_sa = [0] * l
for i in range(l):
sub_sa[renamed_LMS[i]] = i
lms = [lms[sub_sa[i]] for i in range(l)]
sa = induce(a, n, k, stype, lms)
return sa
sa = calc(S, n, k)
S.pop()
return sa
def LCP(s, n, sa):
lcp = [-1] * (n + 1)
rank = [0] * (n + 1)
for i in range(n + 1):
rank[sa[i]] = i
h = 0
lcp[0] = 0
for i in range(n):
j = sa[rank[i] - 1]
if h > 0:
h -= 1
while j + h < n and i + h < n and s[j + h] == s[i + h]:
h += 1
lcp[rank[i] - 1] = h
return lcp
class SparseTable:
def __init__(self, A, op):
self.n = len(A)
logn = (self.n - 1).bit_length()
self.logn = logn
if self.n == 1:
logn = 1
self.op = op
self.table = [None] * (self.n * logn)
for i in range(self.n):
self.table[i] = A[i]
for i in range(1, logn):
ma = self.n - (1 << i) + 1
d = 1 << (i - 1)
for j in range(ma):
self.table[i * self.n + j] = op(self.table[(i - 1) * self.n + j], self.table[(i - 1) * self.n + j + d])
def prod(self, l, r):
if l == r:
return 1 << 30
d = r - l
if d == 1:
return self.table[l]
logn = (d - 1).bit_length() - 1
return self.op(self.table[logn * self.n + l], self.table[logn * self.n + r - (1 << logn)])
n = int(input())
S = []
le = []
kl = []
for i in range(n):
T = input()
le.append(len(T))
for j, t in enumerate(T):
kl.append((i, j))
S.append(ord(t) - 90)
S.append(1)
kl.append((-1, -1))
sa = SA_IS(S)
lcp = LCP(S, len(S), sa)
C = list(map(int, input().split())) + [0]
cum = [0]
for s in sa[1:]:
k, l = kl[s]
cum.append(cum[-1] + C[k])
l = 1
while S[sa[l]] == 1:
l += 1
st = SparseTable(lcp, min)
dist = 0
tot = 0
ans = 0
while l < len(sa):
kk, ll = kl[sa[l]]
r = l
nd = 1 << 30
for i in range(st.logn - 1, -1, -1):
v = st.table[i * st.n + r]
if v is not None and v > dist:
nd = min(nd, v)
r += 1 << i
nd = min(nd, le[kk] - ll)
if dist == nd:
dist = min(dist, lcp[l])
l += 1
continue
ans = max(ans, nd * (cum[r] - cum[l - 1]))
ntot = tot + (r - l + 1) * (nd - dist)
tot = ntot
dist = nd
print(ans)
``` |
774 | Big Number and Remainder | Title: Big Number and Remainder
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan has a very big positive integer.
Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.
Stepan wants to know the minimum remainder of the division by the given number *m* among all good shifts. Your task is to determine the minimum remainder of the division by *m*.
Input Specification:
The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200<=000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.
The second line contains the integer *m* (2<=≤<=*m*<=≤<=108) — the number by which Stepan divides good shifts of his integer.
Output Specification:
Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number *m*.
Demo Input:
['521\n3\n', '1001\n5\n', '5678901234567890123456789\n10000\n']
Demo Output:
['2\n', '0\n', '123\n']
Note:
In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.
In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder. | ```python
n=input()
m=int(input())
res=0
pw=1
for i in range(len(n)-1, -1, -1):
res=(res+pw*int(n[i]))%m
if (i>0):
pw=(pw*10)%m
partial=res
for x in n:
if (int(x)!=0):
res=min(res, partial)
partial=(partial-int(x)*pw)%m
partial=(partial*10+int(x))%m
print(res)
``` |