contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
---|---|---|---|
120 | Luck is in Numbers | Title: Luck is in Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of 2*n* digits. Let's regard each digit as written as is shown on the picture:
You have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the *n*<=+<=1-th one, the second digit coincides with the *n*<=+<=2-th one, ..., the *n*-th digit coincides with the 2*n*-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six.
You are given the number of a ticket containing 2*n* digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of 2*n* digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.
Input Specification:
The first line contains the number of the ticket that consists of *k* characters (*k*<==<=2*n*,<=1<=≤<=*n*<=≤<=105).
Output Specification:
Print the number of the sought ticket or "-1" (without the quotes) if no such ticket exists.
Demo Input:
['13\n', '2345\n', '88\n']
Demo Output:
['20\n', '2348\n', '-1\n']
Note:
none | ```python
import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
s = input()
n = len(s) // 2
lines = ["1111110", "0110000", "1101101", "1111001", "0110011", "1011011", "1011111", "1110000", "1111111", "1111011"]
common = [[0] * 10 for _ in range(10)]
for i in range(10):
for j in range(10):
for k in range(7):
common[i][j] += 1 if lines[i][k] == '1' and lines[j][k] == '1' else 0
left = list(map(int, list(s[:n])))
right = list(map(int, list(s[n:])))
start = 0
startVals = [0] * (n + 1)
for i in range(n):
start += common[left[i]][right[i]]
startVals[i + 1] = start
cur = start
maxVals = [0] * (n + 1)
for k in reversed(range(n)):
maxVals[k] = maxVals[k+1] + max(common[left[k]])
for k in reversed(range(n)):
for num in range(right[k] + 1, 10):
if common[left[k]][num] + maxVals[k + 1] + startVals[k] > start:
startVals[k + 1] = startVals[k] + common[left[k]][num]
right[k] = num
for j in range(k + 1, n):
for num2 in range(0, 10):
if common[left[j]][num2] + maxVals[j + 1] + startVals[j] > start:
startVals[j + 1] = startVals[j] + common[left[j]][num2]
right[j] = num2
break
print("".join(map(str, left)) + "".join(map(str, right)))
exit()
maxVals = [0] * (n + 1)
for k in range(n):
maxVals[k + 1] = maxVals[k] + max(common[left[k]])
for k in reversed(range(n)):
for num in range(left[k] + 1, 10):
if max(common[num]) + maxVals[k] + 7 * (n - 1 - k) > start:
maxVals[k + 1] = maxVals[k] + max(common[num])
left[k] = num
for j in range(k + 1, n):
for num2 in range(0, 10):
if max(common[num2]) + maxVals[j] + 7 * (n - 1 - j) > start:
maxVals[j + 1] = maxVals[j] + max(common[num2])
left[j] = num2
break
maxVals = [0] * (n + 1)
for j in reversed(range(n)):
maxVals[j] = maxVals[j + 1] + max(common[left[j]])
for j in range(n):
for num2 in range(0, 10):
if common[left[j]][num2] + maxVals[j + 1] + startVals[j] > start:
startVals[j + 1] = startVals[j] + common[left[j]][num2]
right[j] = num2
break
print("".join(map(str, left)) + "".join(map(str, right)))
exit()
print(-1)
``` |
837 | Prefix Sums | Title: Prefix Sums
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*).
You have an infinite sequence of arrays *A*0,<=*A*1,<=*A*2..., where *A*0 is given in the input, and for each *i*<=≥<=1 *A**i*<==<=*p*(*A**i*<=-<=1). Also you have a positive integer *k*. You have to find minimum possible *i* such that *A**i* contains a number which is larger or equal than *k*.
Input Specification:
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=200000, 1<=≤<=*k*<=≤<=1018). *n* is the size of array *A*0.
The second line contains *n* integers *A*00,<=*A*01... *A*0*n*<=-<=1 — the elements of *A*0 (0<=≤<=*A*0*i*<=≤<=109). At least two elements of *A*0 are positive.
Output Specification:
Print the minimum *i* such that *A**i* contains a number which is larger or equal than *k*.
Demo Input:
['2 2\n1 1\n', '3 6\n1 1 1\n', '3 1\n1 0 1\n']
Demo Output:
['1\n', '2\n', '0\n']
Note:
none | ```python
import sys
from collections import deque
input = sys.stdin.readline
def fgh():
return [int(xx) for xx in input().split()]
def fg():
return int(input())
n, ok = fgh()
a = fgh()
if max(a) >= ok:
print(0)
quit()
if n == 2:
print((ok - a[1] + a[0] - 1) // a[0])
quit()
fac = [1]
for i in range(1, 200):
fac.append(fac[-1] * i)
l = 0
r = 10 ** 18 + 7
while r - l > 1:
m = (l + r) // 2
ans = 0
for i in range(n):
if a[i]:
nm = m - 1 + n - i - 1
k = n - i - 1
if nm - k <= 10:
q = 1
for ii in range(nm, nm - (nm - k), -1):
q *= ii
ans += q // fac[nm - k] * a[i]
elif k <= 10:
q = 1
for ii in range(nm, nm - k, -1):
q *= ii
ans += q // fac[k] * a[i]
else:
if nm >= 200:
r = m
break
else:
ans += fac[nm] // fac[k] // fac[nm - k] * a[i]
else:
if ans >= ok:
r = m
else:
l = m
print(r)
``` |
961 | Partitions | Title: Partitions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a set of *n* elements indexed from 1 to *n*. The weight of *i*-th element is *w**i*. The weight of some subset of a given set is denoted as . The weight of some partition *R* of a given set into *k* subsets is (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).
Calculate the sum of weights of all partitions of a given set into exactly *k* non-empty subsets, and print it modulo 109<=+<=7. Two partitions are considered different iff there exist two elements *x* and *y* such that they belong to the same set in one of the partitions, and to different sets in another partition.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=2·105) — the number of elements and the number of subsets in each partition, respectively.
The second line contains *n* integers *w**i* (1<=≤<=*w**i*<=≤<=109)— weights of elements of the set.
Output Specification:
Print one integer — the sum of weights of all partitions of a given set into *k* non-empty subsets, taken modulo 109<=+<=7.
Demo Input:
['4 2\n2 3 2 3\n', '5 2\n1 2 3 4 5\n']
Demo Output:
['160\n', '645\n']
Note:
Possible partitions in the first sample:
1. {{1, 2, 3}, {4}}, *W*(*R*) = 3·(*w*<sub class="lower-index">1</sub> + *w*<sub class="lower-index">2</sub> + *w*<sub class="lower-index">3</sub>) + 1·*w*<sub class="lower-index">4</sub> = 24; 1. {{1, 2, 4}, {3}}, *W*(*R*) = 26; 1. {{1, 3, 4}, {2}}, *W*(*R*) = 24; 1. {{1, 2}, {3, 4}}, *W*(*R*) = 2·(*w*<sub class="lower-index">1</sub> + *w*<sub class="lower-index">2</sub>) + 2·(*w*<sub class="lower-index">3</sub> + *w*<sub class="lower-index">4</sub>) = 20; 1. {{1, 3}, {2, 4}}, *W*(*R*) = 20; 1. {{1, 4}, {2, 3}}, *W*(*R*) = 20; 1. {{1}, {2, 3, 4}}, *W*(*R*) = 26;
Possible partitions in the second sample:
1. {{1, 2, 3, 4}, {5}}, *W*(*R*) = 45; 1. {{1, 2, 3, 5}, {4}}, *W*(*R*) = 48; 1. {{1, 2, 4, 5}, {3}}, *W*(*R*) = 51; 1. {{1, 3, 4, 5}, {2}}, *W*(*R*) = 54; 1. {{2, 3, 4, 5}, {1}}, *W*(*R*) = 57; 1. {{1, 2, 3}, {4, 5}}, *W*(*R*) = 36; 1. {{1, 2, 4}, {3, 5}}, *W*(*R*) = 37; 1. {{1, 2, 5}, {3, 4}}, *W*(*R*) = 38; 1. {{1, 3, 4}, {2, 5}}, *W*(*R*) = 38; 1. {{1, 3, 5}, {2, 4}}, *W*(*R*) = 39; 1. {{1, 4, 5}, {2, 3}}, *W*(*R*) = 40; 1. {{2, 3, 4}, {1, 5}}, *W*(*R*) = 39; 1. {{2, 3, 5}, {1, 4}}, *W*(*R*) = 40; 1. {{2, 4, 5}, {1, 3}}, *W*(*R*) = 41; 1. {{3, 4, 5}, {1, 2}}, *W*(*R*) = 42. | ```python
def read_data():
n, m = map(int, list(input().strip().split()))
a = list(map(int, list(input().strip().split())))
return n, m, a
def get_modinv(m):
modinv = [-1 for _ in range(m+1)]
modinv[1] = 1
for i in range(2,m+1):
modinv[i] = (-(div//i) * modinv[div%i]) % div
return modinv
def partitions(n,k):
if k >n :
return 0
val = 0
sign = 1
if k%2 == 1:
sign = -1
for i in range(k+1):
v = (fact[k] * factinv[i] * factinv[k-i] * pow(i,n,div)) % div
val += v * sign
val %= div
sign *= -1
val *= factinv[k]
return val % div
def solve():
modinv = get_modinv(n+1)
for i in range(1,n+2):
fact.append(fact[-1]*i%div)
factinv.append(factinv[-1] * modinv[i] % div)
return ((partitions(n,k) + (n-1)*partitions(n-1,k))*sum(a)) % div
div = 10**9 + 7
n, k, a = read_data()
fact, factinv = [1], [1]
print(solve())
``` |
630 | Challenge Pennants | Title: Challenge Pennants
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.
Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.
Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.
In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.
One man can have several pennants of one type and of course he can have pennants of both types on his table. There are *n* tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.
Input Specification:
The only line of the input contains one integer *n* (1<=≤<=*n*<=≤<=500) — the number of tables in the IT company.
Output Specification:
Output one integer — the amount of ways to place the pennants on *n* tables.
Demo Input:
['2\n']
Demo Output:
['24']
Note:
none | ```python
n=int(input())
print(((n+4)*(n+3)*(n+2)*(n+1)*n*(n+2)*(n+1)*n)//720)
``` |
690 | Collective Mindsets (medium) | Title: Collective Mindsets (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?
The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the *N*<=-<=1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.
Input Specification:
The only line of input contains one integer: *N*, the number of attendees (1<=≤<=*N*<=≤<=109).
Output Specification:
Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
Demo Input:
['1\n', '3\n', '99\n']
Demo Output:
['0\n', '1\n', '49\n']
Note:
none | ```python
n = int(input())
if n & 1:
print(n//2)
else:
k = 1
while k <= n:
k *= 2
print((n - k//2)//2)
``` |
609 | Minimum spanning tree for each edge | Title: Minimum spanning tree for each edge
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains *n* vertices and *m* edges.
For each edge (*u*,<=*v*) find the minimal possible weight of the spanning tree that contains the edge (*u*,<=*v*).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input Specification:
First line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=2·105,<=*n*<=-<=1<=≤<=*m*<=≤<=2·105) — the number of vertices and edges in graph.
Each of the next *m* lines contains three integers *u**i*,<=*v**i*,<=*w**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=*u**i*<=≠<=*v**i*,<=1<=≤<=*w**i*<=≤<=109) — the endpoints of the *i*-th edge and its weight.
Output Specification:
Print *m* lines. *i*-th line should contain the minimal possible weight of the spanning tree that contains *i*-th edge.
The edges are numbered from 1 to *m* in order of their appearing in input.
Demo Input:
['5 7\n1 2 3\n1 3 1\n1 4 5\n2 3 2\n2 5 3\n3 4 2\n4 5 4\n']
Demo Output:
['9\n8\n11\n8\n8\n8\n9\n']
Note:
none | ```python
from sys import stdin, stdout
def main():
n, m = map(int, stdin.readline().split())
d = []
ev = [set() for _ in range(n + 1)]
ans = [0] * m
for i in range(m):
u, v, w = map(int, stdin.readline().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
d.sort()
par = [i for i in range(n + 1)]
st = []
push = st.append
g = 0
for w, u, v in d:
while par[u] != u:
push(u)
u = par[u]
while par[v] != v:
push(v)
v = par[v]
if u != v:
g += w
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
for x in st:
par[x] = u
del st[:]
for i in range(m):
ans[i] += g
stdout.write('\n'.join(map(str, ans)))
main()
``` |
628 | Bear and Fair Set | Title: Bear and Fair Set
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.
It's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set:
- The elements of the set are distinct positive integers. - The number of elements in the set is *n*. The number *n* is divisible by 5. - All elements are between 1 and *b*, inclusive: bears don't know numbers greater than *b*. - For each *r* in {0,<=1,<=2,<=3,<=4}, the set contains exactly elements that give remainder *r* when divided by 5. (That is, there are elements divisible by 5, elements of the form 5*k*<=+<=1, elements of the form 5*k*<=+<=2, and so on.)
Limak smiles mysteriously and gives you *q* hints about his set. The *i*-th hint is the following sentence: "If you only look at elements that are between 1 and *upTo**i*, inclusive, you will find exactly *quantity**i* such elements in my set."
In a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear?
Given *n*, *b*, *q* and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair". Otherwise, print ''unfair".
Input Specification:
The first line contains three integers *n*, *b* and *q* (5<=≤<=*n*<=≤<=*b*<=≤<=104, 1<=≤<=*q*<=≤<=104, *n* divisible by 5) — the size of the set, the upper limit for numbers in the set and the number of hints.
The next *q* lines describe the hints. The *i*-th of them contains two integers *upTo**i* and *quantity**i* (1<=≤<=*upTo**i*<=≤<=*b*, 0<=≤<=*quantity**i*<=≤<=*n*).
Output Specification:
Print ''fair" if there exists at least one set that has all the required properties and matches all the given hints. Otherwise, print ''unfair".
Demo Input:
['10 20 1\n10 10\n', '10 20 3\n15 10\n5 0\n10 5\n', '10 20 2\n15 3\n20 10\n']
Demo Output:
['fair\n', 'fair\n', 'unfair\n']
Note:
In the first example there is only one set satisfying all conditions: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
In the second example also there is only one set satisfying all conditions: {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}.
Easy to see that there is no set satisfying all conditions from the third example. So Limak lied to you :-( | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
n,b,q=map(int,input().split())
t=[(b,n)]
for _ in range(q):
x,y=map(int,input().split())
t.append((x,y))
t.sort(key=lambda x:x[0])
task=[]
tmp=1
now=0
ng=False
for x,y in t:
if x+1==tmp:
if y==now:
pass
else:
ng=True
continue
if y-now<0:
ng=True
cnt=[0]*5
for i in range(tmp,x+1):
cnt[i%5]+=1
task.append((cnt,y-now))
tmp=x+1
now=y
for bit in range(1,1<<5):
use=[]
for i in range(5):
if (bit>>i)&1:
use.append(i)
tmp=0
for cnt,m in task:
res=0
for i in use:
res+=cnt[i]
tmp+=min(m,res)
if tmp<len(use)*n//5:
ng=True
if ng:
print('unfair')
else:
print('fair')
``` |
762 | Maximum path | Title: Maximum path
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rectangular table 3<=×<=*n*. Each cell contains an integer. You can move from one cell to another if they share a side.
Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of columns in the table.
Next three lines contain *n* integers each — the description of the table. The *j*-th number in the *i*-th line corresponds to the cell *a**ij* (<=-<=109<=≤<=*a**ij*<=≤<=109) of the table.
Output Specification:
Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.
Demo Input:
['3\n1 1 1\n1 -1 1\n1 1 1\n', '5\n10 10 10 -1 -1\n-1 10 10 10 10\n-1 10 10 10 10\n']
Demo Output:
['7\n', '110\n']
Note:
The path for the first example:
The path for the second example: | ```python
import sys
input = sys.stdin.readline
n = int(input())
a1 = list(map(int, input().split()))
a2 = list(map(int, input().split()))
a3 = list(map(int, input().split()))
inf = pow(10, 15)
for _ in range(2):
a1.append(-inf)
a2.append(-inf)
a3.append(0)
dp1 = [-inf] * (n + 2)
dp2 = [-inf] * (n + 2)
dp3 = [-inf] * (n + 2)
dp1[0] = a1[0]
s = a1[0] + a2[0] + a3[0]
for i in range(n):
s += a1[i + 1] + a2[i + 1] + a3[i + 1]
dp1[i + 1] = max(dp1[i + 1], dp1[i] + a1[i + 1])
dp1[i + 1] = max(dp1[i + 1], dp2[i] + a1[i] + a1[i + 1])
dp1[i + 1] = max(dp1[i + 1], dp3[i] + a2[i] + a1[i] + a1[i + 1])
dp2[i + 1] = max(dp2[i + 1], dp1[i] + a2[i] + a2[i + 1])
dp2[i + 1] = max(dp2[i + 1], dp2[i] + a2[i + 1])
dp2[i + 1] = max(dp2[i + 1], dp3[i] + a2[i] + a2[i + 1])
dp3[i + 1] = max(dp3[i + 1], dp1[i] + a2[i] + a3[i] + a3[i + 1])
dp3[i + 1] = max(dp3[i + 1], dp2[i] + a3[i] + a3[i + 1])
dp3[i + 1] = max(dp3[i + 1], dp3[i] + a3[i + 1])
dp1[i + 2] = max(dp1[i + 2], dp3[i] + s - a3[i] + a1[i + 2])
dp3[i + 2] = max(dp3[i + 2], dp1[i] + s - a1[i] + a3[i + 2])
s -= a1[i] + a2[i] + a3[i]
ans = dp3[n]
print(ans)
``` |
1,003 | Tree Constructing | Title: Tree Constructing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given three integers $n$, $d$ and $k$.
Your task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible.
An undirected tree is a connected undirected graph with $n - 1$ edges.
Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.
Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $u$ it is the number of edges $(u, v)$ that belong to the tree, where $v$ is any other vertex of a tree).
Input Specification:
The first line of the input contains three integers $n$, $d$ and $k$ ($1 \le n, d, k \le 4 \cdot 10^5$).
Output Specification:
If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).
Otherwise in the first line print "YES" (without quotes), and then print $n - 1$ lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from $1$ to $n$. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1
Demo Input:
['6 3 3\n', '6 2 3\n', '10 4 3\n', '8 5 3\n']
Demo Output:
['YES\n3 1\n4 1\n1 2\n5 2\n2 6\n', 'NO\n', 'YES\n2 9\n2 10\n10 3\n3 1\n6 10\n8 2\n4 3\n5 6\n6 7\n', 'YES\n2 5\n7 2\n3 7\n3 1\n1 6\n8 7\n4 3\n']
Note:
none | ```python
n,d,k=map(int,input().strip().split())
ans=[]
if (d>n-1):
print ("NO")
exit(0)
if (k<2 and n>2):
print ("NO")
exit(0)
l1=[0 for i in range(d+2)]
count=d
cnt=d+2
def insert(par,v,r,e):
global count
global cnt
if count==n-1:
print ("YES")
for o in ans:
print (o[0],o[1])
exit(0)
else:
ans.append([par,v])
cnt=cnt+1
count=count+1
if (e==0):
return
while(r!=0):
insert(v,cnt,k-1,e-1)
r=r-1
return
for i in range(1,d+1):
ans.append([i,i+1])
for i in range(1,d+2):
l1[i]=min(i-1,d+1-i)
for i in range(2,d+1):
r=k-2
while(r!=0):
insert(i,cnt,k-1,l1[i]-1)
r=r-1
if (count<n-1):
print ("NO")
else:
print ("YES")
for o in ans:
print (o[0],o[1])
exit(0)
``` |
690 | Recover Polygon (easy) | Title: Recover Polygon (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.
As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides).
Input Specification:
The first line of each test case contains one integer *N*, the size of the lattice grid (5<=≤<=*N*<=≤<=50). The next *N* lines each contain *N* characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of *y* coordinate, and in one row cells go in the order of increasing *x* coordinate. This means that the first row corresponds to cells with coordinates (1,<=*N*),<=...,<=(*N*,<=*N*) and the last row corresponds to cells with coordinates (1,<=1),<=...,<=(*N*,<=1).
Output Specification:
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
Demo Input:
['6\n000000\n000000\n012100\n024200\n012100\n000000\n']
Demo Output:
['Yes\n']
Note:
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">1</sub>, *y*<sub class="lower-index">2</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">1</sub>), (*x*<sub class="lower-index">2</sub>, *y*<sub class="lower-index">2</sub>)), has a non-zero area and be contained inside of the grid (that is, 0 ≤ *x*<sub class="lower-index">1</sub> < *x*<sub class="lower-index">2</sub> ≤ *N*, 0 ≤ *y*<sub class="lower-index">1</sub> < *y*<sub class="lower-index">2</sub> ≤ *N*), and result in the levels of Zombie Contamination as reported in the input. | ```python
import os, sys
from io import BytesIO, IOBase
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, 8192))
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, 8192))
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")
inp = lambda dtype: dtype(input().strip())
inp_d = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp_d(dtype))]
inp_enus = lambda dtype, n: [[i, inp_d(dtype)] for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
valid = lambda x, y: -1 < x < n and -1 < y < n
dx, dy = (0, 1, 0, -1, 1, -1, 1, -1), (1, 0, -1, 0, 1, -1, -1, 1)
def find_rect():
coor = [float('inf'), float('inf'), -float('inf'), -float('inf')]
for i in range(n):
for j in range(n):
if grid[i][j] == '4':
coor = [min(coor[0], i), min(coor[1], j), max(coor[2], i), max(coor[3], j)]
try:
for i in range(coor[0], coor[2] + 1):
for j in range(coor[1], coor[3] + 1):
if grid[i][j] != '4':
exit(print('No'))
except:
exit(print('No'))
def check():
for i in range(n):
for j in range(n):
mem = {(i, j): False, (i, j + 1): False, (i + 1, j): False, (i + 1, j + 1): False}
for k in range(8):
x, y = i + dx[k], j + dy[k]
if valid(x, y) and grid[x][y] == '4':
if (x, y) in mem:
mem[(x, y)] = True
if (x, y + 1) in mem:
mem[(x, y + 1)] = True
if (x + 1, y) in mem:
mem[(x + 1, y)] = True
if (x + 1, y + 1) in mem:
mem[(x + 1, y + 1)] = True
if grid[i][j] != '4' and sum(mem.values()) != int(grid[i][j]):
exit(print('No'))
n = inp(int)
grid = inp_2d(str, n)
find_rect()
check()
print('Yes')
``` |
180 | Cubes | Title: Cubes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's imagine that you're playing the following simple computer game. The screen displays *n* lined-up cubes. Each cube is painted one of *m* colors. You are allowed to delete not more than *k* cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score.
Remember, you may delete no more than *k* any cubes. It is allowed not to delete cubes at all.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=2·105,<=1<=≤<=*m*<=≤<=105,<=0<=≤<=*k*<=<<=*n*). The second line contains *n* integers from 1 to *m* — the numbers of cube colors. The numbers of colors are separated by single spaces.
Output Specification:
Print the maximum possible number of points you can score.
Demo Input:
['10 3 2\n1 2 1 1 3 2 1 1 2 2\n', '10 2 2\n1 2 1 2 1 1 2 1 1 2\n', '3 1 2\n1 1 1\n']
Demo Output:
['4\n', '5\n', '3\n']
Note:
In the first sample you should delete the fifth and the sixth cubes.
In the second sample you should delete the fourth and the seventh cubes.
In the third sample you shouldn't delete any cubes. | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
x = [[] for _ in range(m + 1)]
for i in range(n):
x[a[i]].append(i)
ans = 0
for y in x:
if not y:
continue
r = 0
for l in range(len(y)):
while r < len(y) and y[r] - y[l] - (r - l) <= k:
r += 1
ans = max(ans, r - l)
print(ans)
``` |
818 | Card Game Again | Title: Card Game Again
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of *n* cards and a magic number *k*. The order of the cards in the deck is fixed. Each card has a number written on it; number *a**i* is written on the *i*-th card in the deck.
After receiving the deck and the magic number, Vova removes *x* (possibly *x*<==<=0) cards from the top of the deck, *y* (possibly *y*<==<=0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards *x*<=+<=1, *x*<=+<=2, ... *n*<=-<=*y*<=-<=1, *n*<=-<=*y* from the original deck.
Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by *k*. So Vova received a deck (possibly not a valid one) and a number *k*, and now he wonders, how many ways are there to choose *x* and *y* so the deck he will get after removing *x* cards from the top and *y* cards from the bottom is valid?
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000, 1<=≤<=*k*<=≤<=109).
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109) — the numbers written on the cards.
Output Specification:
Print the number of ways to choose *x* and *y* so the resulting deck is valid.
Demo Input:
['3 4\n6 2 8\n', '3 6\n9 1 14\n']
Demo Output:
['4\n', '1\n']
Note:
In the first example the possible values of *x* and *y* are:
1. *x* = 0, *y* = 0; 1. *x* = 1, *y* = 0; 1. *x* = 2, *y* = 0; 1. *x* = 0, *y* = 1. | ```python
R,G=lambda:map(int,input().split()),range
n,k=R();a=[0]+[*R()];z,l,p=0,1,1
for r in G(1,n+1):
p=p*a[r]%k
if p==0:
p=1;i=r
while p*a[i]%k:p=p*a[i]%k;i-=1
z+=(n-r+1)*(i-l+1);l=i+1
print(z)
``` |
120 | Three Sons | Title: Three Sons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Three sons inherited from their father a rectangular corn fiend divided into *n*<=×<=*m* squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing *A*, *B* and *C* tons of corn.
The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square.
Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew *A* tons of corn, *B* on another one and *C* on the remaining one.
Input Specification:
The first line contains space-separated integers *n* and *m* — the sizes of the original (1<=≤<=*n*,<=*m*<=≤<=50,<=*max*(*n*,<=*m*)<=≥<=3). Then the field's description follows: *n* lines, each containing *m* space-separated integers *c**ij*, (0<=≤<=*c**ij*<=≤<=100) — the number of tons of corn each square contains. The last line contains space-separated integers *A*,<=*B*,<=*C* (0<=≤<=*A*,<=*B*,<=*C*<=≤<=106).
Output Specification:
Print the answer to the problem: the number of ways to divide the father's field so that one of the resulting parts contained *A* tons of corn, another one contained *B* tons, and the remaining one contained *C* tons. If no such way exists, print 0.
Demo Input:
['3 3\n1 1 1\n1 1 1\n1 1 1\n3 3 3\n', '2 5\n1 1 1 1 1\n2 2 2 2 2\n3 6 6\n', '3 3\n1 2 3\n3 1 2\n2 3 1\n5 6 7\n']
Demo Output:
['2\n', '3\n', '0\n']
Note:
The lines dividing the field can be horizontal or vertical, but they should be parallel to each other. | ```python
import sys
input = sys.stdin.readline
from itertools import permutations
f = open('input.txt', 'r')
n, m = map(int, f.readline().split())
g = [list(map(int, f.readline().split())) for _ in range(n)]
w = list(zip(*g))
g = [sum(i) for i in g]
w = [sum(i) for i in w]
s = set(permutations(map(int, f.readline().split()), 3))
x = 0
for i in range(1, n-1):
for j in range(i+1, n):
a = sum(g[:i])
b = sum(g[i:j])
c = sum(g[j:])
if (a, b, c) in s:
x += 1
for i in range(1, m-1):
for j in range(i+1, m):
a = sum(w[:i])
b = sum(w[i:j])
c = sum(w[j:])
if (a, b, c) in s:
x += 1
f = open('output.txt', 'w')
print(x, file=f)
``` |
988 | Divisibility by 25 | Title: Divisibility by 25
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes.
In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.
What is the minimum number of moves you have to make to obtain a number that is divisible by $25$? Print -1 if it is impossible to obtain a number that is divisible by $25$.
Input Specification:
The first line contains an integer $n$ ($1 \le n \le 10^{18}$). It is guaranteed that the first (left) digit of the number $n$ is not a zero.
Output Specification:
If it is impossible to obtain a number that is divisible by $25$, print -1. Otherwise print the minimum number of moves required to obtain such number.
Note that you can swap only adjacent digits in the given number.
Demo Input:
['5071\n', '705\n', '1241367\n']
Demo Output:
['4\n', '1\n', '-1\n']
Note:
In the first example one of the possible sequences of moves is 5071 $\rightarrow$ 5701 $\rightarrow$ 7501 $\rightarrow$ 7510 $\rightarrow$ 7150. | ```python
n = int(input())
s = list(str(n))
s = [int(i) for i in s]
l = len(s)
if l == 1:
print(-1)
exit()
import copy
INF = 10**18
ans = INF
for i in range(l):
for j in range(l):
t = copy.copy(s)
if i == j:
continue
temp = 0
for k in range(i, l-1):
t[k], t[k+1] = t[k+1], t[k]
temp += 1
if j < i:
for k in range(j, l-2):
t[k], t[k+1] = t[k+1], t[k]
temp += 1
else:
for k in range(j-1, l-2):
t[k], t[k+1] = t[k+1], t[k]
temp += 1
for k in range(l):
if t[k] != 0:
break
temp += k
x = t[-2]*10+t[-1]
if x%25 == 0:
ans = min(ans, temp)
if ans < INF:
print(ans)
else:
print(-1)
``` |
915 | Imbalance Value of a Tree | Title: Imbalance Value of a Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a tree *T* consisting of *n* vertices. A number is written on each vertex; the number written on vertex *i* is *a**i*. Let's denote the function *I*(*x*,<=*y*) as the difference between maximum and minimum value of *a**i* on a simple path connecting vertices *x* and *y*.
Your task is to calculate .
Input Specification:
The first line contains one integer number *n* (1<=≤<=*n*<=≤<=106) — the number of vertices in the tree.
The second line contains *n* integer numbers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the numbers written on the vertices.
Then *n*<=-<=1 lines follow. Each line contains two integers *x* and *y* denoting an edge connecting vertex *x* and vertex *y* (1<=≤<=*x*,<=*y*<=≤<=*n*, *x*<=≠<=*y*). It is guaranteed that these edges denote a tree.
Output Specification:
Print one number equal to .
Demo Input:
['4\n2 2 3 1\n1 2\n1 3\n1 4\n']
Demo Output:
['6\n']
Note:
none | ```python
import sys
RI = lambda: map(int, sys.stdin.buffer.readline().split())
RILST = lambda: list(RI())
def find(x):
# 不会被卡爆栈的并查集find函数 省空间
t = x
while fa[x] != x:
x = fa[x]
while t != x:
fa[t], t = x, fa[t]
return x
n, = RI()
a = RILST()
mns = [[] for _ in range(10**6 + 1)]
mis = [[] for _ in range(10**6 + 1)]
for _ in range(n - 1):
u,v = RILST()
u -= 1
v -= 1
if a[u] > a[v]:
u,v = v,u
mns[a[v]].append((u,v))
mis[a[u]].append((v,u))
fa = [i for i in range(n)]
val = [1]*n
ans = 0
for i in range(10**6 + 1):
for u,v in mns[i]:
fu = find(u)
fv = find(v)
if fu == fv:
continue
fa[fu] = fv
ans += val[fu]*val[fv]*i
val[fv] += val[fu]
# print(ans)
fa = [i for i in range(n)]
val = [1]*n
for i in range(10**6,-1,-1):
for u,v in mis[i]:
fu = find(u)
fv = find(v)
if fu == fv:
continue
fa[fu] = fv
ans -= val[fu]*val[fv]*i
val[fv] += val[fu]
print(ans)
``` |
837 | Round Subset | Title: Round Subset
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call the roundness of the number the number of zeros to which it ends.
You have an array of *n* numbers. You need to choose a subset of exactly *k* numbers so that the roundness of the product of the selected numbers will be maximum possible.
Input Specification:
The first line contains two integer numbers *n* and *k* (1<=≤<=*n*<=≤<=200,<=1<=≤<=*k*<=≤<=*n*).
The second line contains *n* space-separated integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1018).
Output Specification:
Print maximal roundness of product of the chosen subset of length *k*.
Demo Input:
['3 2\n50 4 20\n', '5 3\n15 16 3 25 9\n', '3 3\n9 77 13\n']
Demo Output:
['3\n', '3\n', '0\n']
Note:
In the first example there are 3 subsets of 2 numbers. [50, 4] has product 200 with roundness 2, [4, 20] — product 80, roundness 1, [50, 20] — product 1000, roundness 3.
In the second example subset [15, 16, 25] has product 6000, roundness 3.
In the third example all subsets has product with roundness 0. | ```python
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
m = 30 * n
a = list(map(int, input().split()))
inf = 114514
dp = [[-inf] * (m + 1) for _ in range(n + 1)]
dp[0][0] = 0
dp0 = [0] * (n + 1)
for i in range(n):
ai = a[i]
x, y = 0, 0
while not ai % 2:
y += 1
ai //= 2
while not ai % 5:
x += 1
ai //= 5
for j in range(i, -1, -1):
for l in range(dp0[i] + 1):
if l + x <= m:
dp[j + 1][l + x] = max(dp[j + 1][l + x], dp[j][l] + y)
for j in range(i, -1, -1):
dp0[j + 1] = max(dp0[j] + x, dp0[j + 1])
ans = 0
for i in range(dp0[k] + 1):
ans = max(ans, min(i, dp[k][i]))
print(ans)
``` |
903 | Swapping Characters | Title: Swapping Characters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We had a string *s* consisting of *n* lowercase Latin letters. We made *k* copies of this string, thus obtaining *k* identical strings *s*1,<=*s*2,<=...,<=*s**k*. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given *k* strings *s*1,<=*s*2,<=...,<=*s**k*, and you have to restore any string *s* so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, *k*·*n*<=≤<=5000).
Input Specification:
The first line contains two integers *k* and *n* (1<=≤<=*k*<=≤<=2500,<=2<=≤<=*n*<=≤<=5000,<=*k* · *n*<=≤<=5000) — the number of strings we obtained, and the length of each of these strings.
Next *k* lines contain the strings *s*1,<=*s*2,<=...,<=*s**k*, each consisting of exactly *n* lowercase Latin letters.
Output Specification:
Print any suitable string *s*, or -1 if such string doesn't exist.
Demo Input:
['3 4\nabac\ncaab\nacba\n', '3 4\nkbbu\nkbub\nubkb\n', '5 4\nabcd\ndcba\nacbd\ndbca\nzzzz\n']
Demo Output:
['acab\n', 'kbub\n', '-1\n']
Note:
In the first example *s*<sub class="lower-index">1</sub> is obtained by swapping the second and the fourth character in acab, *s*<sub class="lower-index">2</sub> is obtained by swapping the first and the second character, and to get *s*<sub class="lower-index">3</sub>, we swap the third and the fourth character.
In the second example *s*<sub class="lower-index">1</sub> is obtained by swapping the third and the fourth character in kbub, *s*<sub class="lower-index">2</sub> — by swapping the second and the fourth, and *s*<sub class="lower-index">3</sub> — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations. | ```python
import sys
k, n = map(int, input().split())
s = [list(word.rstrip()) for word in sys.stdin]
double = True if max(s[0].count(chr(i+97)) for i in range(26)) > 1 else False
diff = [set() for _ in range(k)]
diff_cnt = [0]*k
for i in range(1, k):
for j in range(n):
if s[0][j] != s[i][j]:
diff[i].add(j)
diff_cnt[i] += 1
if diff_cnt[i] > 4:
print(-1)
exit()
for i in range(n):
for j in range(i+1, n):
s[0][i], s[0][j] = s[0][j], s[0][i]
for x in range(1, k):
w = [y for y in diff[x] | {i, j} if s[0][y] != s[x][y]]
if double and len(w) == 0:
continue
if len(w) == 2 and s[0][w[0]] == s[x][w[1]] and s[0][w[1]] == s[x][w[0]]:
continue
break
else:
print(''.join(s[0]))
exit()
s[0][i], s[0][j] = s[0][j], s[0][i]
print(-1)
``` |
1,000 | We Need More Bosses | Title: We Need More Bosses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $n$ locations connected by $m$ two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location $s$ and end in location $t$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $s$ to $t$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $s$ or as $t$.
Input Specification:
The first line contains two integers $n$ and $m$ ($2 \le n \le 3 \cdot 10^5$, $n - 1 \le m \le 3 \cdot 10^5$) — the number of locations and passages, respectively.
Then $m$ lines follow, each containing two integers $x$ and $y$ ($1 \le x, y \le n$, $x \ne y$) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output Specification:
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for $s$ and $t$.
Demo Input:
['5 5\n1 2\n2 3\n3 1\n4 1\n5 2\n', '4 3\n1 2\n4 3\n3 2\n']
Demo Output:
['2\n', '3\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
def lowlink(links):
n = len(links)
order = [-1] * n
low = [n] * n
parent = [-1] * n
child = [[] for _ in range(n)]
roots = set()
x = 0
for root in range(n):
if order[root] != -1:
continue
roots.add(root)
stack = [root]
parent[root] = -2
while stack:
i = stack.pop()
if i >= 0:
if order[i] != -1:
continue
order[i] = x
low[i] = x
x += 1
if i != root:
child[parent[i]].append(i)
stack.append(~i)
check_p = 0
for j in links[i]:
if j == parent[i] and check_p == 0:
check_p += 1
continue
elif order[j] != -1:
low[i] = min(low[i], order[j])
else:
parent[j] = i
stack.append(j)
else:
i = ~i
if i == root:
continue
p = parent[i]
low[p] = min(low[p], low[i])
return order,low,roots,child
def get_articulation(links):
n = len(links)
order,low,roots,child = lowlink(links)
articulation = [0] * n
for i in range(n):
if i in roots:
if len(child[i]) >= 2:
articulation[i] = 1
continue
for j in child[i]:
if order[i] <= low[j]:
articulation[i] = 1
break
return articulation
def get_bridge(links):
n = len(links)
order,low,roots,child = lowlink(links)
bridge = []
for root in roots:
stack = [root]
while stack:
i = stack.pop()
for j in child[i]:
if order[i] < low[j]:
bridge.append([i,j])
stack.append(j)
return bridge
def two_edge_connected_componets(links):
n = len(links)
order,low,roots,child = lowlink(links)
components = [-1] * n
new_edges = []
x = 0
for root in roots:
components[root] = x
stack = [root]
while stack:
i = stack.pop()
for j in child[i]:
if order[i] < low[j]:
x += 1
components[j] = x
new_edges.append([components[i],x])
else:
components[j] = components[i]
stack.append(j)
x += 1
return components,new_edges
from sys import stdin
input=lambda :stdin.readline()[:-1]
n,m=map(int,input().split())
edge=[[] for i in range(n)]
for _ in range(m):
x,y=map(lambda x:int(x)-1,input().split())
edge[x].append(y)
edge[y].append(x)
components,new_edges = two_edge_connected_componets(edge)
N=max(components)+1
edge2=[[] for i in range(N)]
for x,y in new_edges:
edge2[x].append(y)
edge2[y].append(x)
def dfs(start):
dist=[-1]*N
dist[start]=0
todo=[start]
while todo:
v=todo.pop()
for u in edge2[v]:
if dist[u]==-1:
dist[u]=dist[v]+1
todo.append(u)
mx=max(dist)
idx=dist.index(mx)
return mx,idx
_,v0=dfs(0)
ans,_=dfs(v0)
print(ans)
``` |
630 | A rectangle | Title: A rectangle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.
More formally, if a game designer selected cells having coordinates (*x*1,<=*y*1) and (*x*2,<=*y*2), where *x*1<=≤<=*x*2 and *y*1<=≤<=*y*2, then all cells having center coordinates (*x*,<=*y*) such that *x*1<=≤<=*x*<=≤<=*x*2 and *y*1<=≤<=*y*<=≤<=*y*2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to *OX* axis, all hexagon centers have integer coordinates and for each integer *x* there are cells having center with such *x* coordinate and for each integer *y* there are cells having center with such *y* coordinate. It is guaranteed that difference *x*2<=-<=*x*1 is divisible by 2.
Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.
Help him implement counting of these units before painting.
Input Specification:
The only line of input contains four integers *x*1,<=*y*1,<=*x*2,<=*y*2 (<=-<=109<=≤<=*x*1<=≤<=*x*2<=≤<=109,<=<=-<=109<=≤<=*y*1<=≤<=*y*2<=≤<=109) — the coordinates of the centers of two cells.
Output Specification:
Output one integer — the number of cells to be filled.
Demo Input:
['1 1 5 5\n']
Demo Output:
['13']
Note:
none | ```python
x1,y1,x2,y2 = map(int,input().split())
print((x2-x1)//2*(y2-y1+1)+(y2-x1)//2-(y1-x1)//2+1)
``` |
797 | Array Queries | Title: Array Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*a* is an array of *n* positive integers, all of which are not greater than *n*.
You have to process *q* queries to this array. Each query is represented by two numbers *p* and *k*. Several operations are performed in each query; each operation changes *p* to *p*<=+<=*a**p*<=+<=*k*. There operations are applied until *p* becomes greater than *n*. The answer to the query is the number of performed operations.
Input Specification:
The first line contains one integer *n* (1<=≤<=*n*<=≤<=100000).
The second line contains *n* integers — elements of *a* (1<=≤<=*a**i*<=≤<=*n* for each *i* from 1 to *n*).
The third line containts one integer *q* (1<=≤<=*q*<=≤<=100000).
Then *q* lines follow. Each line contains the values of *p* and *k* for corresponding query (1<=≤<=*p*,<=*k*<=≤<=*n*).
Output Specification:
Print *q* integers, *i*th integer must be equal to the answer to *i*th query.
Demo Input:
['3\n1 1 1\n3\n1 1\n2 1\n3 1\n']
Demo Output:
['2\n1\n1\n']
Note:
Consider first example:
In first query after first operation *p* = 3, after second operation *p* = 5.
In next two queries *p* is greater than *n* after the first operation. | ```python
from heapq import heappush, heappop, heapify
from collections import defaultdict, Counter, deque
from functools import lru_cache
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)
def main():
n=ri()
a=[0]+rl()
mx=150
dp=[[1<<33 for i in range(n+1)] for i in range(mx)]
for i in range(1,mx):
for j in range(n,0,-1):
nx=i+j+a[j]
if nx>n:dp[i][j]=1
else:dp[i][j]=min(dp[i][j],dp[i][nx]+1)
for _ in range(ri()):
p,k=rl()
if k<mx:print(dp[k][p])
else:
res=0
ptr=p
while ptr<=n:
res+=1
ptr+=k+a[ptr]
print(res)
pass
# for _ in range(ri()):
main()
# threading.Thread(target=main).start()
``` |
691 | Couple Cover | Title: Couple Cover
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with *n* balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball — the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold *p* square meters, the players win. Otherwise, they lose.
The organizers of the game are trying to select an appropriate value for *p* so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of *p*. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.
Input Specification:
The input begins with a single positive integer *n* in its own line (1<=≤<=*n*<=≤<=106).
The second line contains *n* positive integers — the *i*-th number in this line is equal to *a**i* (1<=≤<=*a**i*<=≤<=3·106), the number written on the *i*-th ball.
The next line contains an integer *m* (1<=≤<=*m*<=≤<=106), the number of questions you are being asked.
Then, the following line contains *m* positive integers — the *j*-th number in this line is equal to the value of *p* (1<=≤<=*p*<=≤<=3·106) in the *j*-th question you are being asked.
Output Specification:
For each question, print the number of winning pairs of balls that exist for the given value of *p* in the separate line.
Demo Input:
['5\n4 2 6 1 3\n4\n1 3 5 8\n', '2\n5 6\n2\n30 31\n']
Demo Output:
['20\n18\n14\n10\n', '2\n0\n']
Note:
none | ```python
import sys
input = sys.stdin.buffer.readline
n = int(input())
l = 3 * pow(10, 6) + 5
cnt = [0] * l
for i in list(map(int, input().split())):
cnt[i] += 1
c1, c2 = [0] * l, [0] * l
m0 = pow(10, 8)
for i in range(1, l):
ci = cnt[i]
if i * i < l:
j = i * i
c1[j] += ci * (ci - 1) // m0
c2[j] += ci * (ci - 1) % m0
if c2[j] > m0:
c1[j] += 1
c2[j] %= m0
else:
break
j = i * (i + 1)
while j < l:
cj = cnt[j // i]
c1[j] += 2 * ci * cj // m0
c2[j] += 2 * ci * cj % m0
if c2[j] > m0:
c1[j] += 1
c2[j] %= m0
j += i
n0 = n * (n - 1)
for i in range(1, l):
c1[i] += c1[i - 1]
c2[i] += c2[i - 1]
if c2[i] > m0:
c1[i] += 1
c2[i] %= m0
m = int(input())
for i in list(map(int, input().split())):
ans = n0 - (m0 * c1[i - 1] + c2[i - 1])
print(ans)
``` |
802 | Fake News (medium) | Title: Fake News (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she wants the phrase to appear *n* times in the post. She is asking you to design a post (string) *s* and a hidden phrase *p* such that *p* appears in *s* as a subsequence exactly *n* times.
Input Specification:
The first and only line of input contains a single integer *n* (1<=≤<=*n*<=≤<=1<=000<=000).
Output Specification:
The output should contain two nonempty strings *s* and *p* separated by a single space. Each string should be composed of letters (a-z and A-Z: both lowercase and uppercase are allowed) and have length at most 200. The number of occurrences of *p* in *s* as a subsequence should be exactly *n*. If there are many possible solutions, output any of them. It is guaranteed that at least one solution exists.
Demo Input:
['2\n', '4\n', '6\n']
Demo Output:
['hHheidi Hei', 'bbbba ba', 'aaabb ab']
Note:
An occurrence of *p* as a subsequence in *s* should be thought of as a set of positions in *s* such that the letters at these positions, in order, form *p*. The number of occurences is thus the number of such sets. For example, ab appears 6 times as a subsequence in aaabb, for the following sets of positions: {1, 4}, {1, 5}, {2, 4}, {2, 5}, {3, 4}, {3, 5} (that is, we should choose one of the a's and one of the b's). | ```python
from sys import stdin
inp = stdin.readline
n = int(inp())
arr = [0 for i in range(47)]
s = "aaa"
for i in range(46, -1, -1):
while n >= (i+1)*(i+2)*(i+3)*(i+4)/24:
arr[i] += 1
n -= (i+1)*(i+2)*(i+3)*(i+4)/24
for i in range(47):
s += "a"
for j in range(arr[i]):
s += "b"
print(s, "aaaab")
``` |
938 | Buy a Ticket | Title: Buy a Ticket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.
There are *n* cities in Berland. People can travel between cities using two-directional train routes; there are exactly *m* routes, *i*-th route can be used to go from city *v**i* to city *u**i* (and from *u**i* to *v**i*), and it costs *w**i* coins to use this route.
Each city will be visited by "Flayer", and the cost of the concert ticket in *i*-th city is *a**i* coins.
You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city *i* you have to compute the minimum number of coins a person from city *i* has to spend to travel to some city *j* (or possibly stay in city *i*), attend a concert there, and return to city *i* (if *j*<=≠<=*i*).
Formally, for every you have to calculate , where *d*(*i*,<=*j*) is the minimum number of coins you have to spend to travel from city *i* to city *j*. If there is no way to reach city *j* from city *i*, then we consider *d*(*i*,<=*j*) to be infinitely large.
Input Specification:
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=2·105, 1<=≤<=*m*<=≤<=2·105).
Then *m* lines follow, *i*-th contains three integers *v**i*, *u**i* and *w**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*,<=*v**i*<=≠<=*u**i*, 1<=≤<=*w**i*<=≤<=1012) denoting *i*-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (*v*,<=*u*) neither extra (*v*,<=*u*) nor (*u*,<=*v*) present in input.
The next line contains *n* integers *a*1,<=*a*2,<=... *a**k* (1<=≤<=*a**i*<=≤<=1012) — price to attend the concert in *i*-th city.
Output Specification:
Print *n* integers. *i*-th of them must be equal to the minimum number of coins a person from city *i* has to spend to travel to some city *j* (or possibly stay in city *i*), attend a concert there, and return to city *i* (if *j*<=≠<=*i*).
Demo Input:
['4 2\n1 2 4\n2 3 7\n6 20 1 25\n', '3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20\n']
Demo Output:
['6 14 1 25 \n', '12 10 12 \n']
Note:
none | ```python
from sys import stdin, stdout
from heapq import heapify,heappop,heappush,heappushpop
n, m = map(int, stdin.readline().split())
ady = [[] for i in range(n)]
for i in range(m):
u,v,w = map(int,stdin.readline().split())
ady[u-1].append((v-1,2*w))
ady[v-1].append((u-1,2*w))
c_xcity = list(map(int,stdin.readline().split()))
pq = [(c_xcity[i],i) for i in range(n)]
heapify(pq)
while len(pq)>0:
wu,u = heappop(pq)
if c_xcity[u] != wu:
continue
for v,w in ady[u]:
if c_xcity[v] > c_xcity[u] + w:
#pq.remove((c_xcity[v],v))
c_xcity[v] = c_xcity[u] + w
heappush(pq,(c_xcity[v],v))
stdout.write(' '.join(map(str,c_xcity)))
``` |
628 | Zbazi in Zeydabad | Title: Zbazi in Zeydabad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).
The country Zeydabad is a rectangular table consisting of *n* rows and *m* columns. Each cell on the country is either 'z' or '.'.
The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern"s in the country. A ''Z-pattern" is a square which anti-diagonal is completely filled with 'z' and its upper and lower rows are also completely filled with 'z'. All other cells of a square can be arbitrary.
Note that a ''Z-pattern" can consist of only one cell (see the examples).
So he wants to count the number of ''Z-pattern"s in the country (a necessary skill for Zbazi).
Now your task is to help tourist with counting number of ''Z-pattern"s.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/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*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=3000) — the number of rows and columns respectively.
Each of the next *n* lines contains *m* characters 'z' or '.' — the description of Zeydabad.
Output Specification:
Print the only integer *a* — the number of ''Z-pattern"s in Zeydabad.
Demo Input:
['4 4\nzzzz\nzzz.\n.z..\nzzzz\n', '1 4\nz.z.\n', '2 2\nzz\nzz\n']
Demo Output:
['16\n', '2\n', '5\n']
Note:
none | ```python
import sys
ni = lambda :int(input())
na = lambda :list(map(int,input().split()))
yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES")
no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO")
#######################################################################
# Binary Indexed Tree (Fenwick Tree)
# 0-indexed
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
assert 0 <= i < self.n
i = i+1
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def set(self, i, x):
assert 0 <= i <= self.n
self.add(i,x-self.get(i))
def get(self, i, j=None):# j=Noneのときiを取得, [i, j)の和を取得
if j is None:
return self.el[i+1]
return self.sum(j) - self.sum(i)
from collections import defaultdict
def solve(f):
n = len(f)
if len(f) == 0:
return 0
a,b = zip(*f)
d = defaultdict(list)
bit = BIT(n)
for i in range(n):
d[a[i] + i].append(i)
for i in range(n):
bit.add(i, 1)
res = 0
for i in range(n):
for j in d[i]:
bit.add(j, -1)
#print(n,0,b[i]-i-1)
res += bit.get(i-b[i]+1, i+1)
#print(a,b,res)
return res
h,w = na()
c = [input() for i in range(h)]
"""h = 1000
w = 3000
from random import randint
c = [[["z","."][randint(0,1)]for j in range(w)] for i in range(h)]"""
m = min(h, w)
ans = 0
f = [[w + 1 for i in range(w)]for j in range(h)]
for i in range(h):
if c[i][0] == "z":
f[i][0] = 0
for i in range(h):
for j in range(1, w):
if c[i][j] == "z":
f[i][j] = min(j, f[i][j-1])
g = [[-1 for i in range(w)]for j in range(h)]
for i in range(h):
if c[i][-1] == "z":
g[i][-1] = w-1
for i in range(h):
for j in range(w-2,-1,-1):
if c[i][j] == "z":
g[i][j] = max(j, g[i][j+1])
for t in range(h+w-1):
sy = min(t, w-1)
sx = t-sy
x,y = sx,sy
i = 0
l = 0
ff = []
while sx < h and sy >= 0:
if c[sx][sy] == "z":
ff.append((sy-f[sx][sy]+1, g[sx][sy]-sy+1))
else:
ans += solve(ff)
ff = []
sx += 1
sy -= 1
i += 1
ans += solve(ff)
print(ans)
``` |
818 | Four Melodies | Title: Four Melodies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult!
Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks.
This time Alice wants to form four melodies for her tracks.
Alice has a sheet with *n* notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7.
You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.
Input Specification:
The first line contains one integer number *n* (4<=≤<=*n*<=≤<=3000).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — notes written on a sheet.
Output Specification:
Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.
Demo Input:
['5\n1 3 5 7 9\n', '5\n1 3 5 7 2\n']
Demo Output:
['4\n', '5\n']
Note:
In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note).
In the second example it is possible to compose one melody with 2 notes — {1, 2}. Remaining notes are used in other three melodies (one note per each melody). | ```python
import heapq
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def add_edge(u, v, cost, f):
G[u].append([v, cost, f, len(R[v])])
R[v].append([u, -cost, 0, len(G[u]) - 1])
def dijkstra(s):
inf = pow(10, 9) + 1
dist = [inf] * l
dist[s] = 0
parent = [-1] * l
p = []
heapq.heappush(p, (0, s))
while p:
d, i = heapq.heappop(p)
if dist[i] < d:
continue
di = dist[i] + h[i]
for j, c, f, _ in G[i]:
if not f:
continue
nd = di + c - h[j]
if dist[j] > nd:
parent[j] = i
dist[j] = nd
heapq.heappush(p, (nd, j))
for j, c, f, _ in R[i]:
if not f:
continue
nd = di + c - h[j]
if dist[j] > nd:
parent[j] = i
dist[j] = nd
heapq.heappush(p, (nd, j))
return dist, parent
def min_cost_flow(s, t, f):
ans = 0
while f:
dist, parent = dijkstra(s)
for i in range(l):
h[i] += dist[i]
if not parent[t] ^ -1:
return -1
ma = f
u = t
x, y = [], []
while u ^ s:
v = parent[u]
ok = 0
Gv = G[v]
for i in range(len(Gv)):
if not Gv[i][0] ^ u:
ma = min(ma, Gv[i][2])
ok = 1
x.append((v, i))
break
if not ok:
Rv = R[v]
for i in range(len(Rv)):
if not Rv[i][0] ^ u:
ma = min(ma, Rv[i][2])
ok = 1
y.append((v, i))
break
u = v
f -= ma
for i, j in x:
Gi = G[i]
Gi[j][2] -= ma
R[Gi[j][0]][Gi[j][3]][2] += ma
for i, j in y:
Ri = R[i]
Ri[j][2] -= ma
G[Ri[j][0]][Ri[j][3]][2] += ma
ans += h[t] * ma
return ans
n = int(input())
a = list(map(int, input().split()))
l = 3 * n + 2
G = [[] for _ in range(l)]
R = [[] for _ in range(l)]
h = [0] * l
s, t = l - 2, l - 1
m = pow(10, 5) + 5
x, y = [-1] * m, [-1] * 7
inf = pow(10, 9) + 1
for i in range(n):
add_edge(s, i, 0, 1)
add_edge(i, i + n, -1, 1)
add_edge(i, i + 2 * n, 0, inf)
add_edge(i + n, i + 2 * n, 0, 1)
add_edge(i + 2 * n, t, 0, 1)
ai = a[i]
for j in [x[ai - 1], x[ai + 1], y[ai % 7]]:
if j == -1:
continue
add_edge(j + 2 * n, i, 0, inf)
x[ai], y[ai % 7] = i, i
ans = -min_cost_flow(s, t, 4)
print(ans)
``` |
920 | List Of Integers | Title: List Of Integers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's denote as *L*(*x*,<=*p*) an infinite sequence of integers *y* such that *gcd*(*p*,<=*y*)<==<=1 and *y*<=><=*x* (where *gcd* is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of *L*(*x*,<=*p*) are 1-indexed; for example, 9, 13 and 15 are the first, the second and the third elements of *L*(7,<=22), respectively.
You have to process *t* queries. Each query is denoted by three integers *x*, *p* and *k*, and the answer to this query is *k*-th element of *L*(*x*,<=*p*).
Input Specification:
The first line contains one integer *t* (1<=≤<=*t*<=≤<=30000) — the number of queries to process.
Then *t* lines follow. *i*-th line contains three integers *x*, *p* and *k* for *i*-th query (1<=≤<=*x*,<=*p*,<=*k*<=≤<=106).
Output Specification:
Print *t* integers, where *i*-th integer is the answer to *i*-th query.
Demo Input:
['3\n7 22 1\n7 22 2\n7 22 3\n', '5\n42 42 42\n43 43 43\n44 44 44\n45 45 45\n46 46 46\n']
Demo Output:
['9\n13\n15\n', '187\n87\n139\n128\n141\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
m=10**6+10
divs=[[1] for i in range(m)]
p=list(range(m))
p2=[1]*m
mebius=[0]*m
mebius[1]=1
for i in range(2,m):
if p[i]==i:
for j in range(i,m,i):
p2[j]=i
for j in range(i*i,m,i):
p[j]=i
for j in range(i*i,m,i*i):
p[j]=0
if p[i]!=0:
mebius[i]=-mebius[i//p[i]]
def make_div(n):
now=[1]
x=n
while x!=1:
q=p2[x]
e=0
while x%q==0:
e+=1
x//=q
e=min(e,2)
nxt=[]
for i in now:
for j in range(e+1):
nxt.append(i*(q**j))
now=nxt
return now
def count(y,x_div):
# i<=y and gcd(x,i)=1
res=0
for i in x_div:
res+=mebius[i]*(y//i)
return res
for _ in range(int(input())):
x,p,k=map(int,input().split())
div=make_div(p)
c=count(x,div)
ng,ok=x,10**7
while ok-ng>1:
mid=(ok+ng)//2
if count(mid,div)-c>=k:
ok=mid
else:
ng=mid
print(ok)
``` |
797 | Broken BST | Title: Broken BST
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let *T* be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree *T*:
1. Set pointer to the root of a tree. 1. Return success if the value in the current vertex is equal to the number you are looking for 1. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for 1. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for 1. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input Specification:
First line contains integer number *n* (1<=≤<=*n*<=≤<=105) — number of vertices in the tree.
Each of the next *n* lines contains 3 numbers *v*, *l*, *r* (0<=≤<=*v*<=≤<=109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number <=-<=1 is set instead. Note that different vertices of the tree may contain the same values.
Output Specification:
Print number of times when search algorithm will fail.
Demo Input:
['3\n15 -1 -1\n10 1 3\n5 -1 -1\n', '8\n6 2 3\n3 4 5\n12 6 7\n1 -1 8\n4 -1 -1\n5 -1 -1\n14 -1 -1\n2 -1 -1\n']
Demo Output:
['2\n', '1\n']
Note:
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for. | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
par=[-1]*n
left=[-1]*n
right=[-1]*n
a=[0]*n
for i in range(n):
v,l,r=map(int,input().split())
a[i]=v
l-=1
r-=1
if l!=-2:
par[l]=i
left[i]=l
if r!=-2:
par[r]=i
right[i]=r
root=-1
for i in range(n):
if par[i]==-1:
root=i
ok=set()
todo=[(root,0,10**9+10)]
while todo:
v,L,R=todo.pop()
if L>R:
continue
if L<=a[v]<=R:
ok.add(a[v])
if left[v]!=-1:
todo.append((left[v],L,min(R,a[v]-1)))
if right[v]!=-1:
todo.append((right[v],max(a[v]+1,L),R))
ans=n
for i in a:
if i in ok:
ans-=1
print(ans)
``` |
847 | Dog Show | Title: Dog Show
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!
On the show a dog needs to eat as many bowls of dog food as possible (bottomless stomach helps here). Dogs compete separately of each other and the rules are as follows:
At the start of the show the dog and the bowls are located on a line. The dog starts at position *x*<==<=0 and *n* bowls are located at positions *x*<==<=1,<=*x*<==<=2,<=...,<=*x*<==<=*n*. The bowls are numbered from 1 to *n* from left to right. After the show starts the dog immediately begins to run to the right to the first bowl.
The food inside bowls is not ready for eating at the start because it is too hot (dog's self-preservation instinct prevents eating). More formally, the dog can eat from the *i*-th bowl after *t**i* seconds from the start of the show or later.
It takes dog 1 second to move from the position *x* to the position *x*<=+<=1. The dog is not allowed to move to the left, the dog runs only to the right with the constant speed 1 distance unit per second. When the dog reaches a bowl (say, the bowl *i*), the following cases are possible:
- the food had cooled down (i.e. it passed at least *t**i* seconds from the show start): the dog immediately eats the food and runs to the right without any stop, - the food is hot (i.e. it passed less than *t**i* seconds from the show start): the dog has two options: to wait for the *i*-th bowl, eat the food and continue to run at the moment *t**i* or to skip the *i*-th bowl and continue to run to the right without any stop.
After *T* seconds from the start the show ends. If the dog reaches a bowl of food at moment *T* the dog can not eat it. The show stops before *T* seconds if the dog had run to the right of the last bowl.
You need to help your dog create a strategy with which the maximum possible number of bowls of food will be eaten in *T* seconds.
Input Specification:
Two integer numbers are given in the first line - *n* and *T* (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*T*<=≤<=2·109) — the number of bowls of food and the time when the dog is stopped.
On the next line numbers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=109) are given, where *t**i* is the moment of time when the *i*-th bowl of food is ready for eating.
Output Specification:
Output a single integer — the maximum number of bowls of food the dog will be able to eat in *T* seconds.
Demo Input:
['3 5\n1 5 3\n', '1 2\n1\n', '1 1\n1\n']
Demo Output:
['2\n', '1\n', '0\n']
Note:
In the first example the dog should skip the second bowl to eat from the two bowls (the first and the third). | ```python
# using the min-heap
from heapq import heappush,heappop
bowels,Time = map(int,input().split())
myLine = [-int(b) for b in input().split()]
gulp = []; eat = 0
for i in range(1,min(bowels+1,Time)):
while gulp and -gulp[0] >= Time - i:
# remove the bowel with the highest time penalty
heappop(gulp)
# Check if the option is viable
if -myLine[i-1] < Time:
# Remove the step penalty and store the remaining
heappush(gulp,myLine[i-1] + i)
eat = max(len(gulp),eat)
print (eat)
``` |
938 | Erasing Substrings | Title: Erasing Substrings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s*, initially consisting of *n* lowercase Latin letters. After that, you perform *k* operations with it, where . During *i*-th operation you must erase some substring of length exactly 2*i*<=-<=1 from *s*.
Print the lexicographically minimal string you may obtain after performing *k* such operations.
Input Specification:
The only line contains one string *s* consisting of *n* lowercase Latin letters (1<=≤<=*n*<=≤<=5000).
Output Specification:
Print the lexicographically minimal string you may obtain after performing *k* operations.
Demo Input:
['adcbca\n', 'abacabadabacaba\n']
Demo Output:
['aba\n', 'aabacaba\n']
Note:
Possible operations in examples:
1. adcbca <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> adcba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aba; 1. abacabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> abcabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aabadabacaba <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/70a0795f45d32287dba0eb83fc4a3f470c6e5537.png" style="max-width: 100.0%;max-height: 100.0%;"/> aabacaba. | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
s = list(input().rstrip())
n = len(s)
pow2 = [1]
for _ in range(14):
pow2.append(2 * pow2[-1])
k = 0
while pow2[k + 1] <= n:
k += 1
m = pow2[k]
pow2 = pow2[:k]
l = n - m + 1
x = [[] for _ in range(26)]
for i in range(n):
x[s[i] - 97].append(i)
dp = [1] * m
ans = []
for i in range(l):
dp0 = [0] * m
for j in range(26):
ok = 0
for u in x[j]:
v = u - i
if v >= m:
break
if v >= 0 and dp[v]:
ok, dp0[v] = 1, 1
if ok:
ans.append(chr(j + 97))
break
for j in pow2:
for u in range(j, m):
if u & j:
dp0[u] |= dp0[u ^ j]
dp = dp0
sys.stdout.write("".join(ans))
``` |
632 | Magic Matrix | Title: Magic Matrix
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You're given a matrix *A* of size *n*<=×<=*n*.
Let's call the matrix with nonnegative elements magic if it is symmetric (so *a**ij*<==<=*a**ji*), *a**ii*<==<=0 and *a**ij*<=≤<=*max*(*a**ik*,<=*a**jk*) for all triples *i*,<=*j*,<=*k*. Note that *i*,<=*j*,<=*k* do not need to be distinct.
Determine if the matrix is magic.
As the input/output can reach very 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 integer *n* (1<=≤<=*n*<=≤<=2500) — the size of the matrix *A*.
Each of the next *n* lines contains *n* integers *a**ij* (0<=≤<=*a**ij*<=<<=109) — the elements of the matrix *A*.
Note that the given matrix not necessarily is symmetric and can be arbitrary.
Output Specification:
Print ''MAGIC" (without quotes) if the given matrix *A* is magic. Otherwise print ''NOT MAGIC".
Demo Input:
['3\n0 1 2\n1 0 2\n2 2 0\n', '2\n0 1\n2 3\n', '4\n0 1 2 3\n1 0 3 4\n2 3 0 5\n3 4 5 0\n']
Demo Output:
['MAGIC\n', 'NOT MAGIC\n', 'NOT MAGIC\n']
Note:
none | ```python
from collections import defaultdict, deque
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_root(s):
v = []
while not s == root[s]:
v.append(s)
s = root[s]
for i in v:
root[i] = s
return s
def unite(s, t):
rs, rt = get_root(s), get_root(t)
if not rs ^ rt:
return
if rank[s] == rank[t]:
rank[rs] += 1
if rank[s] >= rank[t]:
root[rt] = rs
size[rs] += size[rt]
else:
root[rs] = rt
size[rt] += size[rs]
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def bfs(s):
q = deque()
q.append(s)
dist = [-1] * n
dist[s] = 0
while q:
i = q.popleft()
di = dist[i]
for j, c in G[i]:
if dist[j] == -1:
dist[j] = max(di, c)
q.append(j)
return dist
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
d = defaultdict(lambda : [])
ok = 1
for i in range(n):
ai = a[i]
for j in range(i + 1, n):
if ai[j] ^ a[j][i]:
ok = 0
break
d[ai[j]].append(i * n + j)
if ai[i]:
ok = 0
if not ok:
break
if ok:
root = [i for i in range(n)]
rank = [1 for _ in range(n)]
size = [1 for _ in range(n)]
G = [[] for _ in range(n)]
c = 1
for i in sorted(d.keys()):
for x in d[i]:
u, v = x // n, x % n
if not same(u, v):
unite(u, v)
auv = a[u][v]
G[u].append((v, auv))
G[v].append((u, auv))
c += 1
if not c ^ n:
break
if not c ^ n:
break
for i in range(n):
dist = bfs(i)
ai = a[i]
for x, y in zip(dist, ai):
if x < y:
ok = 0
break
if not ok:
break
ans = "MAGIC" if ok else "NOT MAGIC"
print(ans)
``` |
817 | Choosing The Commander | Title: Choosing The Commander
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.
Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.
Each warrior is represented by his personality — an integer number *p**i*. Each commander has two characteristics — his personality *p**j* and leadership *l**j* (both are integer numbers). Warrior *i* respects commander *j* only if ( is the bitwise excluding OR of *x* and *y*).
Initially Vova's army is empty. There are three different types of events that can happen with the army:
- 1 *p**i* — one warrior with personality *p**i* joins Vova's army; - 2 *p**i* — one warrior with personality *p**i* leaves Vova's army; - 3 *p**i* *l**i* — Vova tries to hire a commander with personality *p**i* and leadership *l**i*.
For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
Input Specification:
The first line contains one integer *q* (1<=≤<=*q*<=≤<=100000) — the number of events.
Then *q* lines follow. Each line describes the event:
- 1 *p**i* (1<=≤<=*p**i*<=≤<=108) — one warrior with personality *p**i* joins Vova's army; - 2 *p**i* (1<=≤<=*p**i*<=≤<=108) — one warrior with personality *p**i* leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment); - 3 *p**i* *l**i* (1<=≤<=*p**i*,<=*l**i*<=≤<=108) — Vova tries to hire a commander with personality *p**i* and leadership *l**i*. There is at least one event of this type.
Output Specification:
For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.
Demo Input:
['5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3\n']
Demo Output:
['1\n0\n']
Note:
In the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him (<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3d8e4cd0a5c3c0cdc8b35097f3dc7317604240a6.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and 2 < 3, but <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4e3eeab99fa495ecdcd103c68de47dd72943016f.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him. | ```python
import sys
from collections import defaultdict
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
q = int(sys.stdin.readline())
root = Node(0)
# def search(node, bit, )
for _ in range(q):
l = list(map(int, sys.stdin.readline().split()))
if l[0] == 1:
# add
bit = 28
cur = root
num = l[1]
# print(num,'num')
while bit >= 0:
if ((1<<bit)&num) == (1<<bit):
if cur.right is None:
cur.right = Node(1)
# print(bit,'bit right')
else:
cur.right.val += 1
# print(bit,'bit add right')
cur = cur.right
else:
if cur.left is None:
cur.left = Node(1)
# print(bit,'bit left', cur.left.val)
else:
cur.left.val += 1
# print(bit,'bit add left', cur.left.val)
cur = cur.left
bit -= 1
if l[0] == 2:
num = l[1]
bit, cur = 28, root
# print(num,'num')
while bit >= 0:
if((1<<bit)&num) == (1<<bit):
cur.right.val -= 1
cur = cur.right
else:
cur.left.val -= 1
cur = cur.left
bit -= 1
# remove
if l[0] == 3:
# print
res, cur, bit = 0, root, 28
# print(res, cur, bit)
while bit >= 0:
num = (1<<bit)
# print(bit,'bit')
if (num&l[2]) and (num&l[1]):
# print("A")
if cur.right is not None:
res += cur.right.val
if cur.left is None:
break
cur = cur.left
bit -= 1
continue
if (num&l[2]) and not (num&l[1]):
# print("B")
if cur.left is not None:
res += cur.left.val
if cur.right is None:
break
cur = cur.right
bit -= 1
continue
if not (num&l[2]) and (num&l[1]):
# print("C")
if cur.right is None:
break
cur = cur.right
bit -= 1
continue
if not (num&l[2]) and not (num&l[1]):
# print("D")
if cur.left is None:
break
cur = cur.left
bit -= 1
continue
print(res)
``` |
245 | Game with Coins | Title: Game with Coins
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two pirates Polycarpus and Vasily play a very interesting game. They have *n* chests with coins, the chests are numbered with integers from 1 to *n*. Chest number *i* has *a**i* coins.
Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer *x* (2·*x*<=+<=1<=≤<=*n*) and take a coin from each chest with numbers *x*, 2·*x*, 2·*x*<=+<=1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.
Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of chests with coins. The second line contains a sequence of space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=1000), where *a**i* is the number of coins in the chest number *i* at the beginning of the game.
Output Specification:
Print a single integer — the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.
Demo Input:
['1\n1\n', '3\n1 2 3\n']
Demo Output:
['-1\n', '3\n']
Note:
In the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.
In the second sample there is only one possible move *x* = 1. This move should be repeated at least 3 times to empty the third chest. | ```python
n = int(input())
if n == 1 or n & 1 == 0: print(-1)
else:
t = list(map(int, input().split()))
s, k = 0, n // 2 - 1
for i in range(n - 1, 1, -2):
p = max(t[i], t[i - 1])
t[k] = max(0, t[k] - p)
s += p
k -= 1
print(s + t[0])
``` |
961 | k-substrings | Title: k-substrings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s* consisting of *n* lowercase Latin letters.
Let's denote *k*-substring of *s* as a string *subs**k*<==<=*s**k**s**k*<=+<=1..*s**n*<=+<=1<=-<=*k*. Obviously, *subs*1<==<=*s*, and there are exactly such substrings.
Let's call some string *t* an odd proper suprefix of a string *T* iff the following conditions are met:
- |*T*|<=><=|*t*|; - |*t*| is an odd number; - *t* is simultaneously a prefix and a suffix of *T*.
For evey *k*-substring () of *s* you have to calculate the maximum length of its odd proper suprefix.
Input Specification:
The first line contains one integer *n* (2<=≤<=*n*<=≤<=106) — the length *s*.
The second line contains the string *s* consisting of *n* lowercase Latin letters.
Output Specification:
Print integers. *i*-th of them should be equal to maximum length of an odd proper suprefix of *i*-substring of *s* (or <=-<=1, if there is no such string that is an odd proper suprefix of *i*-substring).
Demo Input:
['15\nbcabcabcabcabca\n', '24\nabaaabaaaabaaabaaaabaaab\n', '19\ncabcabbcabcabbcabca\n']
Demo Output:
['9 7 5 3 1 -1 -1 -1\n', '15 13 11 9 7 5 3 1 1 -1 -1 1\n', '5 3 1 -1 -1 1 1 -1 -1 -1\n']
Note:
The answer for first sample test is folowing:
- 1-substring: bcabcabcabcabca - 2-substring: cabcabcabcabc - 3-substring: abcabcabcab - 4-substring: bcabcabca - 5-substring: cabcabc - 6-substring: abcab - 7-substring: bca - 8-substring: c | ```python
import random
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def is_Prime(n):
if n == 1:
return False
for i in range(2, min(int(n ** (1 / 2)) + 2, n)):
if n % i == 0:
return False
return True
def random_mod():
mod = random.randint(5 * pow(10, 8), pow(10, 9))
if not mod % 2:
mod += 1
while not is_Prime(mod):
mod += 2
while not min(mod % 3, mod % 5):
mod += 2
return mod
def binary_search(c1, c2, u):
c = (c1 + c2 + 1) // 2
while abs(c1 - c2) > 1:
c = (c1 + c2 + 1) // 2
if ok(c, u):
c1 = c
else:
c2 = c
c += 2
while not ok(c, u):
c -= 1
return c
def ok(c, u):
if not c:
return True
if c > u:
return False
l1, r1 = u - c, u + c
l2, r2 = n - u - 1 - c, n - u - 1 + c
h1 = (h[r1 + 1] - h[l1]) % mod * x[l1] % mod
h2 = (h[r2 + 1] - h[l2]) % mod * x[l2] % mod
return False if h1 ^ h2 else True
n = int(input())
s = list(input().rstrip())
for i in range(n):
s[i] -= 96
mod = random_mod()
b, h = 1, [0, s[0]]
for j in range(1, n):
b = 29 * b % mod
h.append((b * s[j] % mod + h[-1]) % mod)
x = [pow(b, mod - 2, mod)]
for _ in range(n - 1):
x.append(29 * x[-1] % mod)
x.reverse()
ans = [-1] * (n // 2 + n % 2)
for i in range(n // 2):
if s[i] ^ s[-i - 1]:
continue
c = binary_search(0, i + 1, i)
ans[i - c] = max(ans[i - c], 2 * c + 1)
for i in range(1, n // 2 + n % 2):
ans[i] = max(ans[i], ans[i - 1] - 2, -1)
sys.stdout.write(" ".join(map(str, ans)))
``` |
774 | Composing Of String | Title: Composing Of String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan has a set of *n* strings. Also, he has a favorite string *s*.
Stepan wants to do the following. He will take some strings of his set and write them down one after another. It is possible that he will take some strings more than once, and will not take some of them at all.
Your task is to determine the minimum number of strings in the set which Stepan needs to take and write so that the string *s* appears as a subsequence in the resulting written down string.
For example, in the string "abcd" strings "ad", "acd", "abcd" appear as subsequences, and strings "ba", "abdc" don't appear as subsequences.
Input Specification:
The first line contains the integer *n* (1<=≤<=*n*<=≤<=50) — the number of strings in Stepan's set.
The next *n* lines contain *n* non-empty strings consisting of lowercase letters of the English alphabet. The length of each of these strings does not exceed 50 symbols. It is possible that some strings from Stepan's set are the same.
The next line contains the non-empty string *s*, consisting of lowercase letters of the English alphabet — Stepan's favorite string. The length of this string doesn't exceed 2500 symbols.
Output Specification:
Print the minimum number of strings which Stepan should take from the set and write them down one after another so that the string *s* appears as a subsequence in the resulting written down string. Each string from the set should be counted as many times as Stepan takes it from the set.
If the answer doesn't exsist, print -1.
Demo Input:
['3\na\naa\na\naaa\n', '4\nab\naab\naa\nbb\nbaaab\n', '2\naaa\nbbb\naaacbbb\n']
Demo Output:
['2\n', '3\n', '-1\n']
Note:
In the first test, Stepan can take, for example, the third and the second strings from the set, write them down, and get exactly his favorite string.
In the second example Stepan can take, for example, the second, the third and again the second strings from the set and write them down. Then he will get a string "aabaaaab", in which his favorite string "baaab" is a subsequence.
In the third test Stepan can not get his favorite string, because it contains the letter "c", which is not presented in any of the strings in the set. | ```python
import sys
import math
MAXN = 55
INF = 1e9
MOD = 1e9+7
L_INF = 4e18
EPS = 1e-10
n = int(input())
s = []
for i in range(n):
s.append(input())
t = input()
l = len(t)
dp = [INF] * (l + 1)
dp[0] = 0
for i in range(l):
for j in range(n):
_l, _r = i, 0
while _r < len(s[j]) and _l < l:
if s[j][_r] == t[_l]:
_l += 1
_r += 1
dp[_l] = min(dp[_l], dp[i] + 1)
if dp[l] >= INF / 2:
dp[l] = -1
print(dp[l])
``` |
598 | Cut Length | Title: Cut Length
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Given simple (without self-intersections) *n*-gon. It is not necessary convex. Also you are given *m* lines. For each line find the length of common part of the line and the *n*-gon.
The boundary of *n*-gon belongs to polygon. It is possible that *n*-gon contains 180-degree angles.
Input Specification:
The first line contains integers *n* and *m* (3<=≤<=*n*<=≤<=1000;1<=≤<=*m*<=≤<=100). The following *n* lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following *m* lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output Specification:
Print *m* lines, the *i*-th line should contain the length of common part of the given *n*-gon and the *i*-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
Demo Input:
['4 3\n0 0\n1 0\n1 1\n0 1\n0 0 1 1\n0 0 0 1\n0 0 1 -1\n']
Demo Output:
['1.41421356237309514547\n1.00000000000000000000\n0.00000000000000000000\n']
Note:
none | ```python
I = lambda: [float(x) for x in input().split()]
n, m = [int(i) for i in input().split()]
V = [I() for _ in range(n)]
cmp = lambda x: (x >= 0) - (x <= 0)
for _ in range(m):
x0, y0, x1, y1 = I()
p0, p1 = x1 - x0, y1 - y0
V3 = [((x - x0)*p0 + (y - y0)*p1, (y - y0)*p0 - (x - x0)*p1) for x, y in V]
res = []
for (v1x, v1y), (v2x, v2y) in zip(V3, V3[1:] + V3[:1]):
if cmp(v1y) != cmp(v2y):
res.append(((v2x * v1y - v1x * v2y)/(v1y - v2y), cmp(v2y) - cmp(v1y)))
res.sort()
t, w = 0, 0.
for i, (tmp, s) in enumerate(res, -1):
if t:
w += tmp - res[i][0]
t += s
print(w/(p0*p0 + p1*p1)**0.5)
``` |
690 | The Wall (hard) | Title: The Wall (hard)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
So many wall designs to choose from! Even modulo 106<=+<=3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow them down.
Heidi is quick to come up with criteria for a useful wall:
- In a useful wall, at least one segment is wider than *W* bricks. This should give the zombies something to hit their heads against. Or, - in a useful wall, at least one column is higher than *H* bricks. This provides a lookout from which zombies can be spotted at a distance.
This should rule out a fair amount of possibilities, right? Help Heidi compute the number of useless walls that do not confirm to either of these criteria. In other words, a wall is useless if every segment has width at most *W* and height at most *H*.
Parameter *C*, the total width of the wall, has the same meaning as in the easy version. However, note that the number of bricks is now unlimited.
Output the number of useless walls modulo 106<=+<=3.
Input Specification:
The first and the only line of the input contains three space-separated integers *C*, *W* and *H* (1<=≤<=*C*<=≤<=108, 1<=≤<=*W*,<=*H*<=≤<=100).
Output Specification:
Output the number of different walls, modulo 106<=+<=3, which are useless according to Heidi's criteria.
Demo Input:
['1 1 1\n', '1 2 2\n', '1 2 3\n', '3 2 2\n', '5 4 9\n', '40 37 65\n']
Demo Output:
['2\n', '3\n', '4\n', '19\n', '40951\n', '933869\n']
Note:
If there is no brick in any of the columns, the structure is considered as a useless wall. | ```python
mod = 10 ** 6 + 3
def prod(a, b):
return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % mod for j in range(len(b[0]))] for i in range(len(a))]
c, w, h = map(int, input().split())
a = [[0] * (w + 1) for _ in range(w + 1)]
for i in range(w):
a[i][i + 1] = 1
for cnt in range(0, w + 1):
a[-1][-1 - cnt] = h ** cnt
ans = [[0] for _ in range(w + 1)]
ans[-1][0] = 1
ans[-2][0] = 1
while c > 0:
if c % 2 == 1:
ans = prod(a, ans)
c = c // 2
if c > 0:
a = prod(a, a)
print(ans[-1][0])
``` |
884 | Anti-Palindromize | Title: Anti-Palindromize
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A string *a* of length *m* is called antipalindromic iff *m* is even, and for each *i* (1<=≤<=*i*<=≤<=*m*) *a**i*<=≠<=*a**m*<=-<=*i*<=+<=1.
Ivan has a string *s* consisting of *n* lowercase Latin letters; *n* is even. He wants to form some string *t* that will be an antipalindromic permutation of *s*. Also Ivan has denoted the beauty of index *i* as *b**i*, and the beauty of *t* as the sum of *b**i* among all indices *i* such that *s**i*<==<=*t**i*.
Help Ivan to determine maximum possible beauty of *t* he can get.
Input Specification:
The first line contains one integer *n* (2<=≤<=*n*<=≤<=100, *n* is even) — the number of characters in *s*.
The second line contains the string *s* itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string.
The third line contains *n* integer numbers *b*1, *b*2, ..., *b**n* (1<=≤<=*b**i*<=≤<=100), where *b**i* is the beauty of index *i*.
Output Specification:
Print one number — the maximum possible beauty of *t*.
Demo Input:
['8\nabacabac\n1 1 1 1 1 1 1 1\n', '8\nabaccaba\n1 2 3 4 5 6 7 8\n', '8\nabacabca\n1 2 3 4 4 3 2 1\n']
Demo Output:
['8\n', '26\n', '17\n']
Note:
none | ```python
import sys
from heapq import heappop, heappush
class Edge:
def __init__(self, u, v, cap, cost, rev):
self.u = u
self.v = v
self.cap = cap
self.flow = 0
self.cost = cost
self.rev = rev
def add_edge(adj, u, v, capv, costv):
adj[u].append(Edge(u, v, capv, costv, len(adj[v])))
adj[v].append(Edge(v, u, 0, -costv, len(adj[u])-1))
def bellman_ford(adj):
potential = [0] * len(adj)
for _ in range(len(adj)):
for u in range(len(adj)):
for e in adj[u]:
reduced_cost = potential[e.u] + e.cost - potential[e.v]
if e.cap > 0 and reduced_cost < 0:
potential[e.v] += reduced_cost
return potential
def dijkstra(adj, potential, s, t):
oo = float('inf')
dist, pi = [+oo] * len(adj), [None] * len(adj)
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 = potential[e.u] + e.cost - potential[e.v]
if e.cap - e.flow > 0 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
return dist, pi
def min_cost_max_flow(adj, s, t, flow_limit = float('inf')):
min_cost, max_flow = 0, 0
oo = float('inf')
potential = bellman_ford(adj)
while True:
dist, pi = dijkstra(adj, potential, s, t)
if dist[t] == +oo:
break
for u in range(len(adj)):
if dist[u] < dist[t]:
potential[u] += dist[u] - dist[t]
limit, v = +oo, t
while v:
e = pi[v]
limit = min(limit, e.cap - e.flow)
v = e.u
max_limit_reached = max_flow + limit >= flow_limit
limit = max_limit_reached and flow_limit - max_flow or limit
if max_limit_reached:
min_cost += limit * (potential[t] - potential[s])
max_flow += limit
return min_cost, max_flow
v = t
while v:
e = pi[v]
e.flow += limit
adj[v][e.rev].flow -= limit
v = e.u
min_cost += limit * (potential[t] - potential[s])
max_flow += limit
return min_cost, max_flow
n = int(sys.stdin.readline())
a = sys.stdin.readline().rstrip()
b = list(map(int, sys.stdin.readline().split()))
latin_alp = [chr(i) for i in range(97, 97 + 26)]
s, t = 0, n // 2 + 27
adj = [[] for _ in range(t + 1)]
max_beauty = sum(b) * 2
for i in range(26):
add_edge(adj, s, i + 1, a.count(latin_alp[i]), 0)
for j in range(n // 2):
add_edge(adj, j + 27, t, 2, 0)
for j in range(n // 2):
for i in range(26):
if a[j] == a[-(j+1)] == latin_alp[i]:
add_edge(adj, i + 1, j + 27, 1, min(b[j], b[-(j + 1)]))
elif a[j] == latin_alp[i]:
add_edge(adj, i + 1, j + 27, 1, b[-(j + 1)])
elif a[-(j + 1)] == latin_alp[i]:
add_edge(adj, i + 1, j + 27, 1, b[j])
else:
add_edge(adj, i + 1, j + 27, 1, b[j] + b[-(j + 1)])
cost, _ = min_cost_max_flow(adj, s, t)
print(max_beauty - cost)
``` |
802 | Heidi and Library (hard) | Title: Heidi and Library (hard)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The good times at Heidi's library are over. Marmots finally got their internet connections and stopped coming to the library altogether. Not only that, but the bookstore has begun charging extortionate prices for some books. Namely, whereas in the previous versions each book could be bought for 1 CHF, now the price of book *i* is *c**i* CHF.
Input Specification:
The first line of input will contain two integers *n* and *k* (). The second line will contain *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) – the sequence of book requests. The third line contains *n* integers *c*1,<=*c*2,<=...,<=*c**n* (0<=≤<=*c**i*<=≤<=106) – the costs of the books.
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\n1 1 1 1\n', '4 1\n1 2 2 1\n1 1 1 1\n', '4 2\n1 2 3 1\n1 1 1 1\n', '7 2\n1 2 3 1 1 1 2\n1 10 1 0 0 0 0\n']
Demo Output:
['2', '3', '3', '13']
Note:
The first three sample cases are repeated, but the fourth one is new.
In the fourth test case, when buying book 3, Heidi should discard either book 1 or 2. Even though book 2 will be requested later than book 1, she should keep it, because it is so expensive to buy again. | ```python
import sys
from heapq import heappop, heappush
class Edge:
def __init__(self, u, v, cap, cost, rev):
self.u = u
self.v = v
self.cap = cap
self.flow = 0
self.cost = cost
self.rev = rev
def add_edge(adj, u, v, capv, costv):
adj[u].append(Edge(u, v, capv, costv, len(adj[v])))
adj[v].append(Edge(v, u, 0, -costv, len(adj[u])-1))
def bellman_ford(adj):
potential = [0] * len(adj)
for _ in range(len(adj)):
for u in range(len(adj)):
for e in adj[u]:
reduced_cost = potential[e.u] + e.cost - potential[e.v]
if e.cap > 0 and reduced_cost < 0:
potential[e.v] += reduced_cost
return potential
def dijkstra(adj, potential, s, t):
oo = float('inf')
dist, pi = [+oo] * len(adj), [None] * len(adj)
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 = potential[e.u] + e.cost - potential[e.v]
if e.cap - e.flow > 0 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
return dist, pi
def min_cost_max_flow(adj, s, t, flow_limit = float('inf')):
min_cost, max_flow = 0, 0
oo = float('inf')
potential = bellman_ford(adj)
while True:
dist, pi = dijkstra(adj, potential, s, t)
if dist[t] == +oo:
break
for u in range(len(adj)):
if dist[u] < dist[t]:
potential[u] += dist[u] - dist[t]
limit, v = +oo, t
while v:
e = pi[v]
limit = min(limit, e.cap - e.flow)
v = e.u
max_limit_reached = max_flow + limit >= flow_limit
limit = max_limit_reached and flow_limit - max_flow or limit
if max_limit_reached:
min_cost += limit * (potential[t] - potential[s])
max_flow += limit
return min_cost, max_flow
v = t
while v:
e = pi[v]
e.flow += limit
adj[v][e.rev].flow -= limit
v = e.u
min_cost += limit * (potential[t] - potential[s])
max_flow += limit
return min_cost, max_flow
n, k = map(int, sys.stdin.readline().split())
# n, k = map(int, "7 2".split())
# n, k = map(int, "4 80".split())
pre = [None] * (n + 1)
s, t = 0, 2 * n + 1
adj = [[] for _ in range(t + 1)]
a = [None] + list(map(int, sys.stdin.readline().split()))
# a = [None] + list(map(int, "1 2 3 1 1 1 2".split()))
# a = [None] + list(map(int, "1 2 2 1".split()))
for i in range(1, n+1):
add_edge(adj, i, i+n, 1, 0)
add_edge(adj, i+n, t, 1, 0)
c = [None] + list(map(int, sys.stdin.readline().split()))
# c = [None] + list(map(int, "1 10 1 0 0 0 0".split()))
# c = [None] + list(map(int, "1 1 1 1".split()))
for i in range(1, n+1):
add_edge(adj, s, i, 1, c[a[i]])
if pre[a[i]]:
add_edge(adj, i-1, pre[a[i]] + n, 1, -c[a[i]])
# add_edge(adj, i, pre[a[i]] + n, 1, -c[a[i]])
pre[a[i]] = i
for i in range(1, n):
add_edge(adj, i, i+1, k-1, 0)
min_cost, _ = min_cost_max_flow(adj, s, t)
print(min_cost)
``` |
883 | Automatic Door | Title: Automatic Door
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is an automatic door at the entrance of a factory. The door works in the following way:
- when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, - when one or several people come to the door and it is open, all people immediately come inside, - opened door immediately closes in *d* seconds after its opening, - if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close.
For example, if *d*<==<=3 and four people are coming at four different moments of time *t*1<==<=4, *t*2<==<=7, *t*3<==<=9 and *t*4<==<=13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12.
It is known that *n* employees will enter at moments *a*,<=2·*a*,<=3·*a*,<=...,<=*n*·*a* (the value *a* is positive integer). Also *m* clients will enter at moments *t*1,<=*t*2,<=...,<=*t**m*.
Write program to find the number of times the automatic door will open. Assume that the door is initially closed.
Input Specification:
The first line contains four integers *n*, *m*, *a* and *d* (1<=≤<=*n*,<=*a*<=≤<=109, 1<=≤<=*m*<=≤<=105, 1<=≤<=*d*<=≤<=1018) — the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes.
The second line contains integer sequence *t*1,<=*t*2,<=...,<=*t**m* (1<=≤<=*t**i*<=≤<=1018) — moments of time when clients will come. The values *t**i* are given in non-decreasing order.
Output Specification:
Print the number of times the door will open.
Demo Input:
['1 1 3 4\n7\n', '4 3 4 2\n7 9 11\n']
Demo Output:
['1\n', '4\n']
Note:
In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time. | ```python
n1,m,a,d=list(map(int,input().split()))
t=list(map(int,input().split()))
from bisect import *
from math import *
insort(t,a*n1)
pred=0
k=0
kpred=0
n=0
step=d//a+1
sol=0
fl=0
for i in t:
if (i > pred):
if fl == 0:
n=(i-pred+(pred%a))//a
if n!=0:
k+=(n//step)*step - step*(n % step == 0) + 1
if k > n1:
k=n1
fl=1
#print(k)
if (k*a+d>=i) and (n!=0):
pred=k*a+d
else:
pred=i+d
k=floor(pred//a)
sol+=1
#if n==0:
k=min(floor(pred//a),n1)
sol+=n//step+(n%step!=0)
else:
sol+=1
pred=i+d
if i==a*n1:
fl=1
#print(i,pred,sol,n,step,k, fl)
print(sol)
``` |
845 | Guards In The Storehouse | Title: Guards In The Storehouse
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop.
The storehouse can be represented as a matrix with *n* rows and *m* columns. Each element of the matrix is either . (an empty space) or x (a wall).
Polycarp wants to hire some guards (possibly zero) to watch for the storehouse. Each guard will be in some cell of matrix and will protect every cell to the right of his own cell and every cell to the bottom of his own cell, until the nearest wall. More formally, if the guard is standing in the cell (*x*0,<=*y*0), then he protects cell (*x*1,<=*y*1) if all these conditions are met:
- (*x*1,<=*y*1) is an empty cell; - either *x*0<==<=*x*1 and *y*0<=≤<=*y*1, or *x*0<=≤<=*x*1 and *y*0<==<=*y*1; - there are no walls between cells (*x*0,<=*y*0) and (*x*1,<=*y*1). There can be a guard between these cells, guards can look through each other.
Guards can be placed only in empty cells (and can protect only empty cells). The plan of placing the guards is some set of cells where guards will be placed (of course, two plans are different if there exists at least one cell that is included in the first plan, but not included in the second plan, or vice versa). Polycarp calls a plan suitable if there is not more than one empty cell that is not protected.
Polycarp wants to know the number of suitable plans. Since it can be very large, you have to output it modulo 109<=+<=7.
Input Specification:
The first line contains two numbers *n* and *m* — the length and the width of the storehouse (1<=≤<=*n*,<=*m*<=≤<=250, 1<=≤<=*nm*<=≤<=250).
Then *n* lines follow, *i*th line contains a string consisting of *m* characters — *i*th row of the matrix representing the storehouse. Each character is either . or x.
Output Specification:
Output the number of suitable plans modulo 109<=+<=7.
Demo Input:
['1 3\n.x.\n', '2 2\nxx\nxx\n', '2 2\n..\n..\n', '3 1\nx\n.\nx\n']
Demo Output:
['3\n', '1\n', '10\n', '2\n']
Note:
In the first example you have to put at least one guard, so there are three possible arrangements: one guard in the cell (1, 1), one guard in the cell (1, 3), and two guards in both these cells. | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
mod = pow(10, 9) + 7
if n >= m:
s = [list(input().rstrip()) for _ in range(n)]
else:
s = [[] for _ in range(m)]
for _ in range(n):
s0 = list(input().rstrip())
for j in range(m):
s[j].append(s0[j])
n, m = m, n
pow2 = [1]
for _ in range(m):
pow2.append(2 * pow2[-1])
l = pow2[m]
dp0 = [[0] * (2 * l) for _ in range(2)]
dp0[0][0] = 1
for s0 in s:
for i in range(m):
pi = pow2[i]
dp1 = [[0] * (2 * l) for _ in range(2)]
if s0[i] & 2:
for j in range(2):
for k in range(l):
if not k & pi:
dp1[j][k ^ pi + l] += dp0[j][k] + dp0[j][k + l]
dp1[j][k ^ pi + l] %= mod
dp1[j][k + l] += dp0[j][k + l]
dp1[j][k + l] %= mod
else:
dp1[j][k + l] += dp0[j][k] + 2 * dp0[j][k + l]
dp1[j][k + l] %= mod
dp1[j][k] += dp0[j][k]
dp1[j][k] %= mod
for j in range(l):
if not j & pi:
dp1[1][j] += dp0[0][j]
dp1[1][j] %= mod
else:
u = (l - 1) ^ pi
for j in range(2):
for k in range(l):
dp1[j][k & u] += dp0[j][k] + dp0[j][k + l]
dp1[j][k & u] %= mod
dp0 = [dp1[0], dp1[1]]
for j in range(2):
for k in range(l):
dp0[j][k] += dp0[j][k + l]
dp0[j][k] %= mod
dp0[j][k + l] = 0
ans = 0
for dp in dp0:
for i in dp:
ans += i
ans %= mod
print(ans)
``` |
938 | Shortest Path Queries | Title: Shortest Path Queries
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times).
There are three types of queries you have to process:
- 1 *x* *y* *d* — add an edge connecting vertex *x* to vertex *y* with weight *d*. It is guaranteed that there is no edge connecting *x* to *y* before this query; - 2 *x* *y* — remove an edge connecting vertex *x* to vertex *y*. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; - 3 *x* *y* — calculate the length of the shortest path (possibly non-simple) from vertex *x* to vertex *y*.
Print the answers for all queries of type 3.
Input Specification:
The first line contains two numbers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200000) — the number of vertices and the number of edges in the graph, respectively.
Then *m* lines follow denoting the edges of the graph. Each line contains three integers *x*, *y* and *d* (1<=≤<=*x*<=<<=*y*<=≤<=*n*, 0<=≤<=*d*<=≤<=230<=-<=1). Each pair (*x*,<=*y*) is listed at most once. The initial graph is connected.
Then one line follows, containing an integer *q* (1<=≤<=*q*<=≤<=200000) — the number of queries you have to process.
Then *q* lines follow, denoting queries in the following form:
- 1 *x* *y* *d* (1<=≤<=*x*<=<<=*y*<=≤<=*n*, 0<=≤<=*d*<=≤<=230<=-<=1) — add an edge connecting vertex *x* to vertex *y* with weight *d*. It is guaranteed that there is no edge connecting *x* to *y* before this query; - 2 *x* *y* (1<=≤<=*x*<=<<=*y*<=≤<=*n*) — remove an edge connecting vertex *x* to vertex *y*. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; - 3 *x* *y* (1<=≤<=*x*<=<<=*y*<=≤<=*n*) — calculate the length of the shortest path (possibly non-simple) from vertex *x* to vertex *y*.
It is guaranteed that at least one query has type 3.
Output Specification:
Print the answers for all queries of type 3 in the order they appear in input.
Demo Input:
['5 5\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n1 5 1\n5\n3 1 5\n1 1 3 1\n3 1 5\n2 1 5\n3 1 5\n']
Demo Output:
['1\n1\n2\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v):
return u << 20 ^ v
def unite(s, t, w):
while s ^ root[s]:
w ^= d[s]
s = root[s]
while t ^ root[t]:
w ^= d[t]
t = root[t]
if s == t:
return 0
if rank[s] < rank[t]:
s, t = t, s
ra, ro = rank[s], root[t]
if rank[s] == rank[t]:
rank[s] += 1
root[t], d[t] = s, w
st1.append(f(s, t))
st2.append(f(ra, ro))
return 1
def dist(s, t, c0):
u = s
while u ^ root[u]:
color[u] = c0
u = root[u]
color[u] = c0
ans = 0
while color[t] ^ c0:
ans ^= d[t]
t = root[t]
while s ^ t:
ans ^= d[s]
s = root[s]
return ans
def undo(x, y):
s, t = x >> 20, x & z
ra, ro = y >> 20, y & z
rank[s], root[t], d[t] = ra, ro, 0
return
n, m = map(int, input().split())
u = dict()
for _ in range(m):
x, y, d = map(int, input().split())
u[f(x, y)] = f(d, 0)
q = int(input())
t = -1
a, b, c = [], [], []
q1 = []
z = 1048575
for _ in range(q):
q0 = list(map(int, input().split()))
x, y = q0[1], q0[2]
if q0[0] == 1:
d = q0[3]
u[f(x, y)] = f(d, t + 1)
elif q0[0] == 2:
if u[f(x, y)] & z <= t:
a.append(f(x, y))
b.append(f(u[f(x, y)] & z, t))
c.append(u[f(x, y)] >> 20)
u[f(x, y)] = -1
else:
t += 1
q1.append(f(x, y))
for i in u:
if u[i] & z <= t:
a.append(i)
b.append(f(u[i] & z, t))
c.append(u[i] >> 20)
m = t + 1
l1 = pow(2, (m + 1).bit_length())
l2 = 2 * l1
s0 = [0] * l2
for i in b:
l0 = (i >> 20) + l1
r0 = (i & z) + l1
while l0 <= r0:
if l0 & 1:
s0[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
s0[r0] += 1
r0 -= 1
r0 >>= 1
for i in range(1, l2):
s0[i] += s0[i - 1]
now = [0] + list(s0)
tree = [-1] * now[l2]
for i in range(len(b)):
l0 = (b[i] >> 20) + l1
r0 = (b[i] & z) + l1
while l0 <= r0:
if l0 & 1:
tree[now[l0]] = i
now[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
tree[now[r0]] = i
now[r0] += 1
r0 -= 1
r0 >>= 1
root = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
d = [0] * (n + 1)
s0 = [0] + s0
now = 1
visit = [0] * l2
cnt1, cnt2 = [0] * l2, [0] * l2
st1, st2 = [], []
color, c0 = [0] * (n + 1), 0
b = []
ans = []
while len(ans) ^ m:
if not visit[now]:
visit[now] = 1
for k in range(s0[now], s0[now + 1]):
i = tree[k]
u, v, w0 = a[i] >> 20, a[i] & z, c[i]
f0 = unite(u, v, w0)
if f0:
cnt1[now] += 1
continue
c0 += 1
w = dist(u, v, c0) ^ w0
for j in b:
w = min(w, w ^ j)
if w:
b.append(w)
cnt2[now] += 1
if now < l1:
now = now << 1
else:
u, v = q1[now ^ l1] >> 20, q1[now ^ l1] & z
c0 += 1
ans0 = dist(u, v, c0)
for j in b:
ans0 = min(ans0, ans0 ^ j)
ans.append(ans0)
elif now < l1 and not visit[now << 1 ^ 1]:
now = now << 1 ^ 1
else:
for _ in range(cnt1[now]):
undo(st1.pop(), st2.pop())
for _ in range(cnt2[now]):
b.pop()
now >>= 1
sys.stdout.write("\n".join(map(str, ans)))
``` |
76 | Tourist | Title: Tourist
Time Limit: 0 seconds
Memory Limit: 256 megabytes
Problem Description:
Tourist walks along the *X* axis. He can choose either of two directions and any speed not exceeding *V*. He can also stand without moving anywhere. He knows from newspapers that at time *t*1 in the point with coordinate *x*1 an interesting event will occur, at time *t*2 in the point with coordinate *x*2 — another one, and so on up to (*x**n*,<=*t**n*). Interesting events are short so we can assume they are immediate. Event *i* counts visited if at time *t**i* tourist was at point with coordinate *x**i*.
Write program tourist that will find maximum number of events tourist if:
- at the beginning (when time is equal to 0) tourist appears at point 0, - tourist can choose initial point for himself.
Yes, you should answer on two similar but different questions.
Input Specification:
The first line of input contains single integer number *N* (1<=≤<=*N*<=≤<=100000) — number of interesting events. The following *N* lines contain two integers *x**i* and *t**i* — coordinate and time of the *i*-th event. The last line of the input contains integer *V* — maximum speed of the tourist. All *x**i* will be within range <=-<=2·108<=≤<=*x**i*<=≤<=2·108, all *t**i* will be between 1 and 2·106 inclusive. *V* will be positive and will not exceed 1000. The input may contain events that happen at the same time or in the same place but not in the same place at the same time.
Output Specification:
The only line of the output should contain two space-sepatated integers — maximum number of events tourist can visit in he starts moving from point 0 at time 0, and maximum number of events tourist can visit if he chooses the initial point for himself.
Demo Input:
['3\n-1 1\n42 7\n40 8\n2\n']
Demo Output:
['1 2\n']
Note:
none | ```python
from sys import stdin
input = stdin.buffer.readline
from bisect import bisect
from itertools import zip_longest
def main():
n = int(input())
events = [tuple(map(int,input().split())) for _ in range(n)]
v = int(input())
tot, zero = [], []
for i, e in enumerate(events):
pos, time = e
zero.append(abs(pos) <= v * time)
tot.append((v * time + pos, v * time - pos))
order = sorted(range(n), key=lambda i:tot[i])
lis1, lis2 = [], []
for i in order:
x, y = tot[i]
if zero[i]:
i = bisect(lis1, y)
if i == len(lis1):
lis1.append(y)
else:
lis1[i] = y
i = bisect(lis2, y)
if i == len(lis2):
lis2.append(y)
else:
lis2[i] = y
print(len(lis1), len(lis2))
main()
``` |
1,005 | Berland and the Shortest Paths | Title: Berland and the Shortest Paths
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $1$ to $n$.
It is known that, from the capital (the city with the number $1$), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly $n-1$ roads. The President plans to choose a set of $n-1$ roads such that:
- it is possible to travel from the capital to any other city along the $n-1$ chosen roads, - if $d_i$ is the number of roads needed to travel from the capital to city $i$, moving only along the $n-1$ chosen roads, then $d_1 + d_2 + \dots + d_n$ is minimized (i.e. as minimal as possible).
In other words, the set of $n-1$ roads should preserve the connectivity of the country, and the sum of distances from city $1$ to all cities should be minimized (where you can only use the $n-1$ chosen roads).
The president instructed the ministry to prepare $k$ possible options to choose $n-1$ roads so that both conditions above are met.
Write a program that will find $k$ possible ways to choose roads for repair. If there are fewer than $k$ ways, then the program should output all possible valid ways to choose roads.
Input Specification:
The first line of the input contains integers $n$, $m$ and $k$ ($2 \le n \le 2\cdot10^5, n-1 \le m \le 2\cdot10^5, 1 \le k \le 2\cdot10^5$), where $n$ is the number of cities in the country, $m$ is the number of roads and $k$ is the number of options to choose a set of roads for repair. It is guaranteed that $m \cdot k \le 10^6$.
The following $m$ lines describe the roads, one road per line. Each line contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \ne b_i$) — the numbers of the cities that the $i$-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output Specification:
Print $t$ ($1 \le t \le k$) — the number of ways to choose a set of roads for repair. Recall that you need to find $k$ different options; if there are fewer than $k$ of them, then you need to find all possible different valid options.
In the following $t$ lines, print the options, one per line. Print an option as a string of $m$ characters where the $j$-th character is equal to '1' if the $j$-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the $t$ lines should be different.
Since it is guaranteed that $m \cdot k \le 10^6$, the total length of all the $t$ lines will not exceed $10^6$.
If there are several answers, output any of them.
Demo Input:
['4 4 3\n1 2\n2 3\n1 4\n4 3\n', '4 6 3\n1 2\n2 3\n1 4\n4 3\n2 4\n1 3\n', '5 6 2\n1 2\n1 3\n2 4\n2 5\n3 4\n3 5\n']
Demo Output:
['2\n1110\n1011\n', '1\n101001\n', '2\n111100\n110110\n']
Note:
none | ```python
from collections import deque
n,r,k=map(int,input().split())
edges=[[] for _ in range(n)]
edge=[]
for i in range(r):
temp=list(map(int,input().split()))
edge.append([temp[0]-1,temp[1]-1])
edges[temp[0]-1].append(temp[1]-1)
edges[temp[1]-1].append(temp[0]-1)
d=[float('inf')]*n
d[0]=0
q=deque([0])
while q:
temp=q.popleft()
for x in edges[temp]:
if d[x]==float('inf'):
d[x]=d[temp]+1
q.append(x)
prex=[[] for _ in range(n)]
for i in range(r):
if d[edge[i][0]]==d[edge[i][1]]+1:
prex[edge[i][0]].append(i)
elif d[edge[i][1]]==d[edge[i][0]]+1:
prex[edge[i][1]].append(i)
f=[0]*n
result=[]
for i in range(k):
temp=['0']*r
for j in range(1,n):
temp[prex[j][f[j]]]='1'
result.append(''.join(temp))
judge=0
for j in range(1,n):
if f[j]+1<len(prex[j]):
f[j]=f[j]+1
judge=1
break
else:
f[j]=0
if judge==0:
break
nr=len(result)
print(nr)
for i in range(nr):
print(result[i])
``` |
717 | Dexterina’s Lab | Title: Dexterina’s Lab
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim.
Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0,<=*x*]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game.
Womandark is coming up with a brand new and evil idea on how to thwart Dexterina’s plans, so she hasn’t got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above.
Input Specification:
The first line of the input contains two integers *n* (1<=≤<=*n*<=≤<=109) and *x* (1<=≤<=*x*<=≤<=100) — the number of heaps and the maximum number of objects in a heap, respectively. The second line contains *x*<=+<=1 real numbers, given with up to 6 decimal places each: *P*(0),<=*P*(1),<=... ,<=*P*(*X*). Here, *P*(*i*) is the probability of a heap having exactly *i* objects in start of a game. It's guaranteed that the sum of all *P*(*i*) is equal to 1.
Output Specification:
Output a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10<=-<=6.
Demo Input:
['2 2\n0.500000 0.250000 0.250000\n']
Demo Output:
['0.62500000\n']
Note:
none | ```python
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,x=map(int,input().split())
def mult(a,b):
# compute a*b
c=[0]*128
for i in range(128):
for j in range(128):
c[i^j]+=a[i]*b[j]
return c
def quickpow(a,b):
# compute a**b
if b==1:
return a
if b&1:
return mult(quickpow(mult(a,a),b//2),a)
return quickpow(mult(a,a),b//2)
prob=list(map(float,input().split()))
prob+=[0.0]*(128-len(prob))
print("%.9f"%(1-quickpow(prob,n)[0]))
``` |
632 | Thief in a Shop | Title: Thief in a Shop
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A thief made his way to a shop.
As usual he has his lucky knapsack with him. The knapsack can contain *k* objects. There are *n* kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind *i* is *a**i*.
The thief is greedy, so he will take exactly *k* products (it's possible for some kinds to take several products of that kind).
Find all the possible total costs of products the thief can nick into his knapsack.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=1000) — the number of kinds of products and the number of products the thief will take.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=1000) — the costs of products for kinds from 1 to *n*.
Output Specification:
Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order.
Demo Input:
['3 2\n1 2 3\n', '5 5\n1 1 1 1 1\n', '3 3\n3 5 11\n']
Demo Output:
['2 3 4 5 6\n', '5\n', '9 11 13 15 17 19 21 25 27 33\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
MOD = 998244353
IMAG = 911660635
IIMAG = 86583718
rate2 = (0, 911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 867605899, 0)
irate2 = (0, 86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960, 354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 103369235, 0)
rate3 = (0, 372528824, 337190230, 454590761, 816400692, 578227951, 180142363, 83780245, 6597683, 70046822, 623238099, 183021267, 402682409, 631680428, 344509872, 689220186, 365017329, 774342554, 729444058, 102986190, 128751033, 395565204, 0)
irate3 = (0, 509520358, 929031873, 170256584, 839780419, 282974284, 395914482, 444904435, 72135471, 638914820, 66769500, 771127074, 985925487, 262319669, 262341272, 625870173, 768022760, 859816005, 914661783, 430819711, 272774365, 530924681, 0)
def butterfly(a):
n = len(a)
h = (n - 1).bit_length()
le = 0
while le < h:
if h - le == 1:
p = 1 << (h - le - 1)
rot = 1
for s in range(1 << le):
offset = s << (h - le)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p] * rot
a[i + offset] = (l + r) % MOD
a[i + offset + p] = (l - r) % MOD
rot *= rate2[(~s & -~s).bit_length()]
rot %= MOD
le += 1
else:
p = 1 << (h - le - 2)
rot = 1
for s in range(1 << le):
rot2 = rot * rot % MOD
rot3 = rot2 * rot % MOD
offset = s << (h - le)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p] * rot
a2 = a[i + offset + p * 2] * rot2
a3 = a[i + offset + p * 3] * rot3
a1na3imag = (a1 - a3) % MOD * IMAG
a[i + offset] = (a0 + a2 + a1 + a3) % MOD
a[i + offset + p] = (a0 + a2 - a1 - a3) % MOD
a[i + offset + p * 2] = (a0 - a2 + a1na3imag) % MOD
a[i + offset + p * 3] = (a0 - a2 - a1na3imag) % MOD
rot *= rate3[(~s & -~s).bit_length()]
rot %= MOD
le += 2
def butterfly_inv(a):
n = len(a)
h = (n - 1).bit_length()
le = h
while le:
if le == 1:
p = 1 << (h - le)
irot = 1
for s in range(1 << (le - 1)):
offset = s << (h - le + 1)
for i in range(p):
l = a[i + offset]
r = a[i + offset + p]
a[i + offset] = (l + r) % MOD
a[i + offset + p] = (l - r) * irot % MOD
irot *= irate2[(~s & -~s).bit_length()]
irot %= MOD
le -= 1
else:
p = 1 << (h - le)
irot = 1
for s in range(1 << (le - 2)):
irot2 = irot * irot % MOD
irot3 = irot2 * irot % MOD
offset = s << (h - le + 2)
for i in range(p):
a0 = a[i + offset]
a1 = a[i + offset + p]
a2 = a[i + offset + p * 2]
a3 = a[i + offset + p * 3]
a2na3iimag = (a2 - a3) * IIMAG % MOD
a[i + offset] = (a0 + a1 + a2 + a3) % MOD
a[i + offset + p] = (a0 - a1 + a2na3iimag) * irot % MOD
a[i + offset + p * 2] = (a0 + a1 - a2 - a3) * irot2 % MOD
a[i + offset + p * 3] = (a0 - a1 - a2na3iimag) * irot3 % MOD
irot *= irate3[(~s & -~s).bit_length()]
irot %= MOD
le -= 2
def multiply(s, t):
n = len(s)
m = len(t)
if min(n, m) <= 60:
a = [0] * (n + m - 1)
for i in range(n):
if i % 8 == 0:
for j in range(m):
a[i + j] += s[i] * t[j]
a[i + j] %= MOD
else:
for j in range(m):
a[i + j] += s[i] * t[j]
return [x % MOD for x in a]
a = s.copy()
b = t.copy()
z = 1 << (n + m - 2).bit_length()
a += [0] * (z - n)
b += [0] * (z - m)
butterfly(a)
butterfly(b)
for i in range(z):
a[i] *= b[i]
a[i] %= MOD
butterfly_inv(a)
a = a[:n + m - 1]
iz = pow(z, MOD - 2, MOD)
return [v * iz % MOD for v in a]
def mul(a,b):
c=multiply(a,b)
return [i>=1 for i in c]
def doubling(x,k):
if k==1:
return x
if k%2==0:
y=doubling(x,k//2)
return mul(y,y)
return mul(doubling(x,k-1),x)
n,k=map(int,input().split())
a=list(map(int,input().split()))
mx=max(a)
c=[0]*(mx+1)
for i in a:
c[i]=1
d=doubling(c,k)
ans=[]
for i in range(len(d)):
if d[i]:
ans.append(i)
print(*ans)
``` |
409 | Feed the Golorp | Title: Feed the Golorp
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Golorps are mysterious creatures who feed on variables. Golorp's name is a program in some programming language. Some scientists believe that this language is Befunge; golorps are tantalizingly silent.
Variables consumed by golorps can take values from 0 to 9, inclusive. For each golorp its daily diet is defined by its name. Some golorps are so picky that they can't be fed at all. Besides, all golorps are very health-conscious and try to eat as little as possible. Given a choice of several valid sequences of variable values, each golorp will choose lexicographically smallest one.
For the purposes of this problem you can assume that a golorp consists of jaws and a stomach. The number of variables necessary to feed a golorp is defined by the shape of its jaws. Variables can get to the stomach only via the jaws.
A hungry golorp is visiting you. You know its name; feed it or figure out that it's impossible.
Input Specification:
The input is a single string (between 13 and 1024 characters long) — the name of the visiting golorp. All names are similar and will resemble the ones given in the samples. The name is guaranteed to be valid.
Output Specification:
Output lexicographically smallest sequence of variable values fit for feeding this golorp. Values should be listed in the order in which they get into the jaws. If the golorp is impossible to feed, output "false".
Demo Input:
['?(_-_/___*__):-___>__.\n', '?(__-_+_/_____):-__>__,_____<__.\n', '?(______________________/____+_______*__-_____*______-___):-__<___,___<____,____<_____,_____<______,______<_______.\n', '?(__+___+__-___):-___>__.\n']
Demo Output:
['0010\n', 'false\n', '0250341\n', '0101\n']
Note:
none | ```python
import re
line=input()
line = line.rstrip('.')
a, b, c = line.partition("):-")
rels = c.split(',')
relations = set()
for rel in rels:
if "<" in rel:
x, _, y = rel.partition("<")
relations.add((len(x), len(y)))
else:
x, _, y = rel.partition(">")
relations.add((len(y), len(x)))
a = a.lstrip("?(")
args = re.split(r"(\+|-|\*|/)", a)
args = [len(args[i]) for i in range(0, len(args), 2)]
# print(args)
# print(relations)
edges = {k:[] for k in args}
for j, i in relations:
edges[i].append(j)
seen = {k:0 for k in args}
q = []
def topsort(k):
if seen[k] == 1:
print("false")
quit()
seen[k] = 1
for other in edges[k]:
topsort(other)
q.append(k)
seen[k] = 2
return True
for k in args:
if seen[k] == 0:
topsort(k)
vals = {}
for k in q:
others = edges[k]
maxval = -1
for other in others:
maxval = max(maxval, vals.get(other, -1))
vals[k] = maxval+1
if(vals[k]>9):
print("false")
quit()
for k in args:
print(vals[k], end='')
print()
``` |
813 | Army Creation | Title: Army Creation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.
In the game Vova can hire *n* different warriors; *i*th warrior has the type *a**i*. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than *k* warriors of this type in the army. Of course, Vova wants his army to be as large as possible.
To make things more complicated, Vova has to consider *q* different plans of creating his army. *i*th plan allows him to hire only warriors whose numbers are not less than *l**i* and not greater than *r**i*.
Help Vova to determine the largest size of a balanced army for each plan.
Be aware that the plans are given in a modified way. See input section for details.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100000).
The second line contains *n* integers *a*1, *a*2, ... *a**n* (1<=≤<=*a**i*<=≤<=100000).
The third line contains one integer *q* (1<=≤<=*q*<=≤<=100000).
Then *q* lines follow. *i*th line contains two numbers *x**i* and *y**i* which represent *i*th plan (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*).
You have to keep track of the answer to the last plan (let's call it *last*). In the beginning *last*<==<=0. Then to restore values of *l**i* and *r**i* for the *i*th plan, you have to do the following:
1. *l**i*<==<=((*x**i*<=+<=*last*) *mod* *n*)<=+<=1; 1. *r**i*<==<=((*y**i*<=+<=*last*) *mod* *n*)<=+<=1; 1. If *l**i*<=><=*r**i*, swap *l**i* and *r**i*.
Output Specification:
Print *q* numbers. *i*th number must be equal to the maximum size of a balanced army when considering *i*th plan.
Demo Input:
['6 2\n1 1 1 2 2 2\n5\n1 6\n4 3\n1 1\n2 6\n2 6\n']
Demo Output:
['2\n4\n1\n3\n2\n']
Note:
In the first example the real plans are:
1. 1 2 1. 1 6 1. 6 6 1. 2 4 1. 4 6 | ```python
class segtree():
def __init__(self,init,func,ide):
self.n=len(init)
self.func=func
self.ide=ide
self.size=1<<(self.n-1).bit_length()
self.tree=[self.ide for i in range(2*self.size)]
for i in range(self.n):
self.tree[self.size+i]=init[i]
for i in range(self.size-1,0,-1):
self.tree[i]=self.func(self.tree[2*i], self.tree[2*i|1])
def update(self,k,x):
k+=self.size
self.tree[k]=x
k>>=1
while k:
self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1])
k>>=1
def get(self,i):
return self.tree[i+self.size]
def query(self,l,r):
L=l
l+=self.size
r+=self.size
ans=0
while l<r:
if l&1:
ans+=count(self.tree[l],L)
l+=1
if r&1:
r-=1
ans+=count(self.tree[r],L)
l>>=1
r>>=1
return ans
def debug(self,s=10):
print([self.get(i) for i in range(min(self.n,s))])
def op(x,y):
return sorted(x+y)
import bisect
def count(arr,x):
return bisect.bisect_left(arr,x)
from sys import stdin
input=lambda :stdin.readline()[:-1]
n,k=map(int,input().split())
a=list(map(lambda x:int(x)-1,input().split()))
idx=[[] for i in range(10**5)]
b=[0]*n
for i in range(n):
if len(idx[a[i]])<k:
b[i]=-1
else:
b[i]=idx[a[i]][-k]
idx[a[i]].append(i)
seg=segtree([[i] for i in b],op,[])
lst=0
q=int(input())
for _ in range(q):
x,y=map(int,input().split())
l=(x+lst)%n
r=(y+lst)%n
if l>r:
l,r=r,l
ans=seg.query(l,r+1)
print(ans)
lst=ans
``` |
652 | Pursuit For Artifacts | Title: Pursuit For Artifacts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience.
In that country there are *n* islands and *m* bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful artifacts. Johnny is not interested in artifacts, but he can get some money by selling some artifact.
At the start Johnny is in the island *a* and the artifact-dealer is in the island *b* (possibly they are on the same island). Johnny wants to find some artifact, come to the dealer and sell it. The only difficulty is that bridges are too old and destroying right after passing over them. Johnnie's character can't swim, fly and teleport, so the problem became too difficult.
Note that Johnny can't pass the half of the bridge, collect the artifact and return to the same island.
Determine if Johnny can find some artifact and sell it.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=3·105, 0<=≤<=*m*<=≤<=3·105) — the number of islands and bridges in the game.
Each of the next *m* lines contains the description of the bridge — three integers *x**i*, *y**i*, *z**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, *x**i*<=≠<=*y**i*, 0<=≤<=*z**i*<=≤<=1), where *x**i* and *y**i* are the islands connected by the *i*-th bridge, *z**i* equals to one if that bridge contains an artifact and to zero otherwise. There are no more than one bridge between any pair of islands. It is guaranteed that it's possible to travel between any pair of islands.
The last line contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*) — the islands where are Johnny and the artifact-dealer respectively.
Output Specification:
If Johnny can find some artifact and sell it print the only word "YES" (without quotes). Otherwise print the word "NO" (without quotes).
Demo Input:
['6 7\n1 2 0\n2 3 0\n3 1 0\n3 4 1\n4 5 0\n5 6 0\n6 4 0\n1 6\n', '5 4\n1 2 0\n2 3 0\n3 4 0\n2 5 1\n1 4\n', '5 6\n1 2 0\n2 3 0\n3 1 0\n3 4 0\n4 5 1\n5 3 0\n1 2\n']
Demo Output:
['YES\n', 'NO\n', 'YES\n']
Note:
none | ```python
if True:
from io import BytesIO, IOBase
import math
import random
import sys
import os
import bisect
import typing
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations, count
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase, ascii_letters
from typing import *
BUFSIZE = 4096
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 = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def LFI():
return list(map(float, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')
dfs, hashing = True, True
if dfs:
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
if hashing:
RANDOM = random.getrandbits(20)
class Wrapper(int):
def __init__(self, x):
int.__init__(x)
def __hash__(self):
return super(Wrapper, self).__hash__() ^ RANDOM
n, m = MII()
path = [[] for _ in range(n)]
edges = []
for _ in range(m):
u, v, t = MII()
u -= 1
v -= 1
edges.append((u, v, t))
path[u].append(v)
path[v].append(u)
dfn = [0] * n
low = [0] * n
col = [0] * n
color = tmstamp = 0
stack = []
@bootstrap
def tarjan(u, f):
global color, tmstamp
tmstamp += 1
dfn[u] = low[u] = tmstamp
stack.append(u)
for v in path[u]:
if dfn[v] == 0:
yield tarjan(v, u)
low[u] = min(low[u], low[v])
elif v != f: low[u] = min(low[u], dfn[v])
if low[u] == dfn[u]:
while True:
col[stack[-1]] = color
tmp = stack.pop()
if tmp == u: break
color += 1
yield
tarjan(0, -1)
u, v = GMI()
start, end = col[u], col[v]
vals = [0] * color
new_graph = [[] for _ in range(color)]
for u, v, t in edges:
if col[u] == col[v]:
if t: vals[col[u]] = 1
else:
new_graph[col[u]].append((col[v], t))
new_graph[col[v]].append((col[u], t))
calc = [-1] * color
calc[start] = vals[start]
stack = [start]
while stack:
u = stack.pop()
for v, t in new_graph[u]:
if calc[v] == -1:
calc[v] = max(calc[u], t, vals[v])
stack.append(v)
print('YES' if calc[end] else 'NO')
``` |
802 | Marmots (easy) | Title: Marmots (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of *V* (1<=≤<=*V*<=≤<=100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.
Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants *P* (10<=≤<=*P*<=≤<=1000) of the village, they respond with a random non-negative integer *k*, drawn from one of two types of probability distributions:
- Poisson (d'avril) distribution: the probability of getting an answer *k* is for *k*<==<=0,<=1,<=2,<=3,<=..., - Uniform distribution: the probability of getting an answer *k* is for *k*<==<=0,<=1,<=2,<=...,<=2*P*.
Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.
Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?
Input Specification:
The first line of input will contain the number of villages *V* (1<=≤<=*V*<=≤<=100). The following *V* lines each describe one village. The description of each village consists of 250 space-separated integers *k*, drawn from one of the above distributions.
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 answer came from a uniform distribution.
Demo Input:
['2\n92 100 99 109 93 105 103 106 101 99 ... (input is truncated)\n28 180 147 53 84 80 180 85 8 16 ... (input is truncated)']
Demo Output:
['poisson\nuniform\n']
Note:
The full example input is visually represented below, along with the probability distribution function it was drawn from (the *y*-axis is labeled by its values multiplied by 250).
<img class="tex-graphics" src="https://espresso.codeforces.com/77563a6378b39d03eb21012c835c6e96df776b81.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
for i in range(int(input())):
t = list(map(int, input().split()))
d = 212 * sum(q ** 2 for q in t) > sum(t) ** 2
print(['poisson', 'uniform'][d])
``` |
946 | Largest Beautiful Number | Title: Largest Beautiful Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Yes, that's another problem with definition of "beautiful" numbers.
Let's call a positive integer *x* beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since it contains 4 digits, and there exists a palindromic permutation 2442.
Given a positive integer *s*, find the largest beautiful number which is less than *s*.
Input Specification:
The first line contains one integer *t* (1<=≤<=*t*<=≤<=105) — the number of testcases you have to solve.
Then *t* lines follow, each representing one testcase and containing one string which is the decimal representation of number *s*. It is guaranteed that this string has even length, contains no leading zeroes, and there exists at least one beautiful number less than *s*.
The sum of lengths of *s* over all testcases doesn't exceed 2·105.
Output Specification:
For each testcase print one line containing the largest beautiful number which is less than *s* (it is guaranteed that the answer exists).
Demo Input:
['4\n89\n88\n1000\n28923845\n']
Demo Output:
['88\n77\n99\n28923839\n']
Note:
none | ```python
import sys
t = int(sys.stdin.buffer.readline().decode('utf-8'))
ans = ['']*t
for _ in range(t):
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').rstrip()))
n = len(a)
parity = [0]*10
for x in a:
parity[x] ^= 1
psum = sum(parity)
for i, free in zip(range(n-1, -1, -1), range(n)):
psum += -1 if parity[a[i]] else 1
parity[a[i]] ^= 1
for j in range(a[i]-1, -1, -1):
if psum + (-1 if parity[j] else 1) - free <= 0:
if i == 0 and j == 0:
ans[_] = '9'*(n-2)
break
parity[j] ^= 1
a[i] = j
for k in range(n-1, i, -1):
for l in range(10):
if parity[l]:
a[k] = l
parity[l] = 0
break
else:
a[k] = 9
ans[_] = ''.join(map(str, a))
break
else:
continue
break
sys.stdout.buffer.write('\n'.join(ans).encode('utf-8'))
``` |
774 | Amusement Park | Title: Amusement Park
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pupils decided to go to amusement park. Some of them were with parents. In total, *n* people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.
Tickets for group of *x* people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is *c*1<=+<=*c*2·(*x*<=-<=1)2 (in particular, if the group consists of one person, then the price is *c*1).
All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group.
Input Specification:
The first line contains three integers *n*, *c*1 and *c*2 (1<=≤<=*n*<=≤<=200<=000, 1<=≤<=*c*1,<=*c*2<=≤<=107) — the number of visitors and parameters for determining the ticket prices for a group.
The second line contains the string of length *n*, which consists of zeros and ones. If the *i*-th symbol of the string is zero, then the *i*-th visitor is a pupil, otherwise the *i*-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.
Output Specification:
Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.
Demo Input:
['3 4 1\n011\n', '4 7 2\n1101\n']
Demo Output:
['8\n', '18\n']
Note:
In the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)<sup class="upper-index">2</sup> = 8.
In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)<sup class="upper-index">2</sup> = 9. Thus, the total price for two groups is 18. | ```python
n, c1, c2 = [int(x) for x in input().split(' ')]
s = input()
cnt = s.count('1')
def price(x):
return c1 + c2 * (x - 1) ** 2
prices = []
for i in range(1, cnt + 1):
bigGroupsPeople = n // i + 1
numBigGroups = n % i
smallGroupsPeople = n // i
numSmallGroups = i - n % i
totalPrice = numBigGroups * price(bigGroupsPeople) + numSmallGroups * price(smallGroupsPeople)
prices.append(totalPrice)
print(min(prices))
``` |
730 | Toda 2 | Title: Toda 2
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*.
The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all *n* friends. So the friends are faced with the problem: how to make all their ratings equal.
One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than *n*) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so *r**i*<==<=0 doesn't change after losing.
The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).
The friends want to make their ratings equal but as high as possible.
Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.
Input Specification:
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=100) — the number of friends.
The second line contains *n* non-negative integers *r*1,<=*r*2,<=...,<=*r**n* (0<=≤<=*r**i*<=≤<=100), where *r**i* is the initial rating of the *i*-th friend.
Output Specification:
In the first line, print a single integer *R* — the final rating of each of the friends.
In the second line, print integer *t* — the number of matches the friends have to play. Each of the following *t* lines should contain *n* characters '0' or '1', where the *j*-th character of the *i*-th line is equal to:
- '0', if friend *j* should not play in match *i*, - '1', if friend *j* should play in match *i*.
Each line should contain between two and five characters '1', inclusive.
The value *t* should not exceed 104, it is guaranteed that such solution exists.
Remember that you shouldn't minimize the value *t*, but you should maximize *R*. If there are multiple solutions, print any of them.
Demo Input:
['5\n4 5 1 7 4\n', '2\n1 2\n', '3\n1 1 1\n']
Demo Output:
['1\n8\n01010\n00011\n01010\n10010\n00011\n11000\n00011\n11000\n', '0\n2\n11\n11\n', '1\n0\n']
Note:
none | ```python
# https://codeforces.com/problemset/problem/730/A
#
import heapq
def solve_for_0(d, max_, ans):
pos_M = list(d[max_])[0]
pos_m = list(d[0])[0]
for _ in range(max_):
ans.append([pos_M, pos_m])
def solve_one_seg(d, max_, min_, ans):
seg = list(d[max_])
n = len(seg)
if n <= 5:
for _ in range(max_ - min_):
ans.append(seg)
else:
ori = []
for i in range(0, n, 2):
if i == n-1:
ori[-1].append(seg[i])
else:
ori.append([seg[i], seg[i+1]])
for _ in range(max_ - min_):
ans.extend(ori)
def push(d, x, val, i):
if x not in d:
d[x] = set()
if val == 1:
d[x].add(i)
else:
d[x].remove(i)
if len(d[x]) == 0:
del d[x]
def check(d):
if len(d) != 2:
return 'none', None
max_ = max(list(d.keys()))
min_ = min(list(d.keys()))
if len(d[max_]) >= 2:
return 'seg', [max_, min_]
elif min_ == 0:
return '0', [max_]
return 'none', None
def pr(ans, n):
print(len(ans))
arr = [[0]*n for _ in range(len(ans))]
for i, val in enumerate(ans):
for ind in val:
arr[i][ind] = 1
S = ''
for s in arr:
S += ''.join([str(x) for x in s])
S += '\n'
print(S)
#5
#4 5 1 7 4
n = int(input())#len(arr)
arr = list(map(int, input().split()))#[1,3,1,3,2,3,2,3,2,3,2,3,2,3]
ans = []
Q = []
d = {}
for i, x in enumerate(arr):
push(d, x, 1, i)
heapq.heappush(Q, (-x, x, i))
if len(d) == 1:
print(list(d.keys())[0])
print(0)
else:
while True:
type_, arg = check(d)
if type_ == 'none':
val1, num1, i1 = heapq.heappop(Q)
val2, num2, i2 = heapq.heappop(Q)
push(d, num1, -1, i1)
push(d, num2, -1, i2)
ans.append([i1, i2])
new1 = max(0, num1-1)
new2 = max(0, num2-1)
heapq.heappush(Q, (-new1, new1, i1))
heapq.heappush(Q, (-new2, new2, i2))
push(d, new1, 1, i1)
push(d, new2, 1, i2)
elif type_ == 'seg':
max_, min_ = arg[0], arg[1]
solve_one_seg(d, max_, min_, ans)
print(min_)
pr(ans, n)
break
else:
max_ = arg[0]
solve_for_0(d, max_, ans)
print(0)
pr(ans, n)
break
``` |
954 | Runner's Problem | Title: Runner's Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are running through a rectangular field. This field can be represented as a matrix with 3 rows and *m* columns. (*i*,<=*j*) denotes a cell belonging to *i*-th row and *j*-th column.
You start in (2,<=1) and have to end your path in (2,<=*m*). From the cell (*i*,<=*j*) you may advance to:
- (*i*<=-<=1,<=*j*<=+<=1) — only if *i*<=><=1, - (*i*,<=*j*<=+<=1), or - (*i*<=+<=1,<=*j*<=+<=1) — only if *i*<=<<=3.
However, there are *n* obstacles blocking your path. *k*-th obstacle is denoted by three integers *a**k*, *l**k* and *r**k*, and it forbids entering any cell (*a**k*,<=*j*) such that *l**k*<=≤<=*j*<=≤<=*r**k*.
You have to calculate the number of different paths from (2,<=1) to (2,<=*m*), and print it modulo 109<=+<=7.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=104, 3<=≤<=*m*<=≤<=1018) — the number of obstacles and the number of columns in the matrix, respectively.
Then *n* lines follow, each containing three integers *a**k*, *l**k* and *r**k* (1<=≤<=*a**k*<=≤<=3, 2<=≤<=*l**k*<=≤<=*r**k*<=≤<=*m*<=-<=1) denoting an obstacle blocking every cell (*a**k*,<=*j*) such that *l**k*<=≤<=*j*<=≤<=*r**k*. Some cells may be blocked by multiple obstacles.
Output Specification:
Print the number of different paths from (2,<=1) to (2,<=*m*), taken modulo 109<=+<=7. If it is impossible to get from (2,<=1) to (2,<=*m*), then the number of paths is 0.
Demo Input:
['2 5\n1 3 4\n2 2 3\n']
Demo Output:
['2\n']
Note:
none | ```python
L = 3
M = 10**9 + 7
iden = [[0] * L for _ in range(L)]
for i in range(L):
iden[i][i] = 1
def mat_multiply(a, b):
n = len(a)
ret = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
ret[i][j] = (ret[i][j] + a[i][k] * b[k][j]) % M
return ret
def vector_matrix_multiply(a, b):
n = len(a)
ret = [0] * n
for j in range(n):
for i in range(n):
ret[j] = (ret[j] + a[i] * b[i][j]) % M
return ret
def mat_pow(mt, p):
if p == 0:
return iden
ret = mat_pow(mt, p >> 1)
ret = mat_multiply(ret, ret)
if p & 1:
ret = mat_multiply(ret, mt)
return ret
def make_cur_mat(cnt):
ret = [[0] * L for _ in range(L)]
for i in range(L):
for j in range(L):
if not cnt[i] and abs(i - j) <= 1:
ret[i][j] = 1
return ret
def main():
n, m = map(int, input().split())
events = {}
for _ in range(n):
a, l, r = map(int, input().split())
a -= 1
if l in events:
events[l].append((0, a))
else:
events[l] = [(0, a)]
if r + 1 in events:
events[r + 1].append((1, a))
else:
events[r + 1] = [(1, a)]
prev = 1
dp = [0] * L
dp[1] = 1
cnt = [0] * L
for time, event_list in sorted(events.items()):
cur = time
cur_mt = make_cur_mat(cnt)
cur_mt = mat_pow(cur_mt, cur - prev)
dp = vector_matrix_multiply(dp, cur_mt)
for event in event_list:
open_event, a = event
if open_event:
cnt[a] += 1
else:
cnt[a] -= 1
prev = cur
cur_mt = make_cur_mat(cnt)
cur_mt = mat_pow(cur_mt, m - prev)
dp = vector_matrix_multiply(dp, cur_mt)
print(dp[1])
if __name__ == "__main__":
main()# 1692026702.165854
``` |
630 | Pyramids | Title: Pyramids
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.
The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.
Input Specification:
The only line of the input contains three integers *l*3,<=*l*4,<=*l*5 (1<=≤<=*l*3,<=*l*4,<=*l*5<=≤<=1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.
Output Specification:
Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10<=-<=9.
Demo Input:
['2 5 3\n']
Demo Output:
['38.546168065709']
Note:
none | ```python
from sys import stdin, stdout
def solve():
l3, l4, l5 = (int(s) for s in stdin.readline().split())
v1 = l3*l3*l3*(2**0.5)*2
v2 = l4*l4*l4*(2**0.5)*4
v3 = l5*l5*l5*(2**0.5)*((15+5*(5**0.5))**0.5)
ans = (v1+v2+v3)/24
print(ans)
if __name__ == '__main__':
solve()
``` |
852 | Property | Title: Property
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2*n*-sided polygon *A*0 *A*1... *A*2*n*<=-<=1 *A*2*n*,<= *A*2*n*<==<= *A*0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
- Split every edge *A**k* *A**k*<=+<=1,<= *k*<==<=0... 2*n*<=-<=1 in *n* equal parts of size 1<=/<=*n* with points *P*0,<=*P*1,<=...,<=*P**n*<=-<=1 - On every edge *A*2*k* *A*2*k*<=+<=1,<= *k*<==<=0... *n*<=-<=1 court will choose one point *B*2*k*<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - On every edge *A*2*k*<=+<=1*A*2*k*<=+<=2,<= *k*<==<=0...*n*<=-<=1 Bill will choose one point *B*2*k*<=+<=1<==<= *P**i* for some *i*<==<=0,<=...,<= *n*<=-<=1 such that - Bill gets to keep property inside of 2*n*-sided polygon *B*0 *B*1... *B*2*n*<=-<=1
Luckily, Bill found out which *B*2*k* points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input Specification:
The first line contains one integer number *n* (2<=≤<=*n*<=≤<=50000), representing number of edges of 2*n*-sided polygon.
The second line contains *n* distinct integer numbers *B*2*k* (0<=≤<=*B*2*k*<=≤<=*n*<=-<=1,<= *k*<==<=0... *n*<=-<=1) separated by a single space, representing points the court chose. If *B*2*k*<==<=*i*, the court chose point *P**i* on side *A*2*k* *A*2*k*<=+<=1.
Output Specification:
Output contains *n* distinct integers separated by a single space representing points *B*1,<=*B*3,<=...,<=*B*2*n*<=-<=1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
Demo Input:
['3\n0 1 2\n']
Demo Output:
['0 2 1\n']
Note:
To maximize area Bill should choose points: *B*<sub class="lower-index">1</sub> = *P*<sub class="lower-index">0</sub>, *B*<sub class="lower-index">3</sub> = *P*<sub class="lower-index">2</sub>, *B*<sub class="lower-index">5</sub> = *P*<sub class="lower-index">1</sub>
<img class="tex-graphics" src="https://espresso.codeforces.com/03c7bbc496053c0ca19cfcf073d88965c4c90895.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
n = int(input())
a = input().split()
for i in range(n):
a[i] = int(a[i])
b = []
for i in range(0, n-1):
b.append((a[i]-(n-a[i+1]), i))
b.append((a[n-1]-(n-a[0]), n-1))
b = sorted(b)
ans = n*[0]
for i in range(n):
# the line segment at index b[i][1]
ans[b[i][1]] = i
for i in range(n):
print(ans[i], end = ' ')
``` |
774 | Significant Cups | Title: Significant Cups
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan is a very experienced olympiad participant. He has *n* cups for Physics olympiads and *m* cups for Informatics olympiads. Each cup is characterized by two parameters — its significance *c**i* and width *w**i*.
Stepan decided to expose some of his cups on a shelf with width *d* in such a way, that:
- there is at least one Physics cup and at least one Informatics cup on the shelf, - the total width of the exposed cups does not exceed *d*, - from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance *x* is exposed, then all the cups for this subject with significance greater than *x* must be exposed too).
Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width *d*, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.
Input Specification:
The first line contains three integers *n*, *m* and *d* (1<=≤<=*n*,<=*m*<=≤<=100<=000, 1<=≤<=*d*<=≤<=109) — the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf.
Each of the following *n* lines contains two integers *c**i* and *w**i* (1<=≤<=*c**i*,<=*w**i*<=≤<=109) — significance and width of the *i*-th cup for Physics olympiads.
Each of the following *m* lines contains two integers *c**j* and *w**j* (1<=≤<=*c**j*,<=*w**j*<=≤<=109) — significance and width of the *j*-th cup for Informatics olympiads.
Output Specification:
Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width *d*, considering all the rules described in the statement.
If there is no way to expose cups on the shelf, then print 0.
Demo Input:
['3 1 8\n4 2\n5 5\n4 2\n3 2\n', '4 3 12\n3 4\n2 4\n3 5\n3 4\n3 5\n5 2\n3 4\n', '2 2 2\n5 3\n6 3\n4 2\n8 1\n']
Demo Output:
['8\n', '11\n', '0\n']
Note:
In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. | ```python
from functools import cmp_to_key
def comparator(a, b) :
if a[0] > b[0] :
return -1
if a[0] < b[0] :
return 1
if a[1] < b[1] :
return -1
if a[1] > b[1] :
return 1
return 0
n, m, d = list(map(int, input().split()))
a = []
b = []
for i in range(n):
a.append(list(map(int, input().split())))
for i in range(m):
b.append(list(map(int, input().split())))
a = sorted(a, key = cmp_to_key(comparator))
b = sorted(b, key = cmp_to_key(comparator))
pref = []
s = []
pref.append(0)
s.append(0)
for e in b :
pref.append(pref[len(pref) - 1] + e[1])
s.append(s[len(s) - 1] + e[0])
cur = 0
ruc = 0
ans = 0
for e in a :
cur += e[1]
ruc += e[0]
l = 1
r = m
j = -1
while l <= r :
mid = (l + r) // 2
if cur + pref[mid] <= d :
j = mid
l = mid + 1
else :
r = mid - 1
if j != -1 :
ans = max(ans, ruc + s[j])
print(ans)
``` |
620 | New Year Tree | Title: New Year Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with *n* vertices and root in the vertex 1.
You should process the queries of the two types:
1. Change the colours of all vertices in the subtree of the vertex *v* to the colour *c*. 1. Find the number of different colours in the subtree of the vertex *v*.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=4·105) — the number of vertices in the tree and the number of the queries.
The second line contains *n* integers *c**i* (1<=≤<=*c**i*<=≤<=60) — 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 vertices of the *j*-th edge. It is guaranteed that you are given correct undirected tree.
The last *m* lines contains the description of the queries. Each description starts with the integer *t**k* (1<=≤<=*t**k*<=≤<=2) — the type of the *k*-th query. For the queries of the first type then follows two integers *v**k*,<=*c**k* (1<=≤<=*v**k*<=≤<=*n*,<=1<=≤<=*c**k*<=≤<=60) — the number of the vertex whose subtree will be recoloured with the colour *c**k*. For the queries of the second type then follows integer *v**k* (1<=≤<=*v**k*<=≤<=*n*) — the number of the vertex for which subtree you should find the number of different colours.
Output Specification:
For each query of the second type print the integer *a* — the number of different colours in the subtree of the vertex given in the query.
Each of the numbers should be printed on a separate line in order of query appearing in the input.
Demo Input:
['7 10\n1 1 1 1 1 1 1\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n1 3 2\n2 1\n1 4 3\n2 1\n1 2 5\n2 1\n1 6 4\n2 1\n2 2\n2 3\n', '23 30\n1 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n4 9\n4 10\n4 11\n6 12\n6 13\n7 14\n7 15\n7 16\n8 17\n8 18\n10 19\n10 20\n10 21\n11 22\n11 23\n2 1\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n2 11\n2 4\n1 12 1\n1 13 1\n1 14 1\n1 15 1\n1 16 1\n1 17 1\n1 18 1\n1 19 1\n1 20 1\n1 21 1\n1 22 1\n1 23 1\n2 1\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n2 11\n2 4\n']
Demo Output:
['2\n3\n4\n5\n1\n2\n', '6\n1\n3\n3\n2\n1\n2\n3\n5\n5\n1\n2\n2\n1\n1\n1\n2\n3\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
def popcount(n):
c=(n&0x5555555555555555)+((n>>1)&0x5555555555555555)
c=(c&0x3333333333333333)+((c>>2)&0x3333333333333333)
c=(c&0x0f0f0f0f0f0f0f0f)+((c>>4)&0x0f0f0f0f0f0f0f0f)
c=(c&0x00ff00ff00ff00ff)+((c>>8)&0x00ff00ff00ff00ff)
c=(c&0x0000ffff0000ffff)+((c>>16)&0x0000ffff0000ffff)
c=(c&0x00000000ffffffff)+((c>>32)&0x00000000ffffffff)
return c
class lazy_segtree():
def update(self,k):self.d[k]=self.op(self.d[2*k],self.d[2*k+1])
def all_apply(self,k,f):
self.d[k]=self.mapping(f,self.d[k])
if (k<self.size):self.lz[k]=self.composition(f,self.lz[k])
def push(self,k):
self.all_apply(2*k,self.lz[k])
self.all_apply(2*k+1,self.lz[k])
self.lz[k]=self.identity
def __init__(self,V,OP,E,MAPPING,COMPOSITION,ID):
self.n=len(V)
self.log=(self.n-1).bit_length()
self.size=1<<self.log
self.d=[E for i in range(2*self.size)]
self.lz=[ID for i in range(self.size)]
self.e=E
self.op=OP
self.mapping=MAPPING
self.composition=COMPOSITION
self.identity=ID
for i in range(self.n):self.d[self.size+i]=V[i]
for i in range(self.size-1,0,-1):self.update(i)
def set(self,p,x):
assert 0<=p and p<self.n
p+=self.size
for i in range(self.log,0,-1):self.push(p>>i)
self.d[p]=x
for i in range(1,self.log+1):self.update(p>>i)
def get(self,p):
assert 0<=p and p<self.n
p+=self.size
for i in range(self.log,0,-1):self.push(p>>i)
return self.d[p]
def prod(self,l,r):
assert 0<=l and l<=r and r<=self.n
if l==r:return self.e
l+=self.size
r+=self.size
for i in range(self.log,0,-1):
if (((l>>i)<<i)!=l):self.push(l>>i)
if (((r>>i)<<i)!=r):self.push(r>>i)
sml,smr=self.e,self.e
while(l<r):
if l&1:
sml=self.op(sml,self.d[l])
l+=1
if r&1:
r-=1
smr=self.op(self.d[r],smr)
l>>=1
r>>=1
return self.op(sml,smr)
def all_prod(self):return self.d[1]
def apply_point(self,p,f):
assert 0<=p and p<self.n
p+=self.size
for i in range(self.log,0,-1):self.push(p>>i)
self.d[p]=self.mapping(f,self.d[p])
for i in range(1,self.log+1):self.update(p>>i)
def apply(self,l,r,f):
assert 0<=l and l<=r and r<=self.n
if l==r:return
l+=self.size
r+=self.size
for i in range(self.log,0,-1):
if (((l>>i)<<i)!=l):self.push(l>>i)
if (((r>>i)<<i)!=r):self.push((r-1)>>i)
l2,r2=l,r
while(l<r):
if (l&1):
self.all_apply(l,f)
l+=1
if (r&1):
r-=1
self.all_apply(r,f)
l>>=1
r>>=1
l,r=l2,r2
for i in range(1,self.log+1):
if (((l>>i)<<i)!=l):self.update(l>>i)
if (((r>>i)<<i)!=r):self.update((r-1)>>i)
def max_right(self,l,g):
assert 0<=l and l<=self.n
assert g(self.e)
if l==self.n:return self.n
l+=self.size
for i in range(self.log,0,-1):self.push(l>>i)
sm=self.e
while(1):
while(l%2==0):l>>=1
if not(g(self.op(sm,self.d[l]))):
while(l<self.size):
self.push(l)
l=(2*l)
if (g(self.op(sm,self.d[l]))):
sm=self.op(sm,self.d[l])
l+=1
return l-self.size
sm=self.op(sm,self.d[l])
l+=1
if (l&-l)==l:break
return self.n
def min_left(self,r,g):
assert (0<=r and r<=self.n)
assert g(self.e)
if r==0:return 0
r+=self.size
for i in range(self.log,0,-1):self.push((r-1)>>i)
sm=self.e
while(1):
r-=1
while(r>1 and (r%2)):r>>=1
if not(g(self.op(self.d[r],sm))):
while(r<self.size):
self.push(r)
r=(2*r+1)
if g(self.op(self.d[r],sm)):
sm=self.op(self.d[r],sm)
r-=1
return r+1-self.size
sm=self.op(self.d[r],sm)
if (r&-r)==r:break
return 0
def operate(a,b):
return a|b
def mapping(f,x):
if f==-1:
return x
return f
def composition(f,g):
if f==-1:
return g
return f
n,q=map(int,input().split())
c=list(map(lambda x:int(x)-1,input().split()))
edge=[[] for i in range(n)]
for _ in range(n-1):
a,b=map(lambda x:int(x)-1,input().split())
edge[a].append(b)
edge[b].append(a)
L=[0]*n
R=[0]*n
todo=[(1,0,-1),(0,0,-1)]
tmp=0
while todo:
t,v,p=todo.pop()
if t==0:
L[v]=tmp
tmp+=1
for u in edge[v]:
if u!=p:
todo.append((1,u,v))
todo.append((0,u,v))
else:
R[v]=tmp
seg=lazy_segtree([0]*n,operate,0,mapping,composition,-1)
for i in range(n):
seg.set(L[i],1<<c[i])
for _ in range(q):
query=list(map(int,input().split()))
if query[0]==1:
v,c=query[1:]
v-=1
c-=1
seg.apply(L[v],R[v],1<<c)
else:
v=query[1]-1
bit=seg.prod(L[v],R[v])
print(popcount(bit))
``` |
234 | Champions' League | Title: Champions' League
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world — the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups.
The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose *n* teams will take part in the group stage (*n* is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as *m* (). Each team has a rating — an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating).
After that four "baskets" are formed, each of which will contain *m* teams: the first *m* teams with the highest rating go to the first basket, the following *m* teams go to the second one, and so on.
Then the following procedure repeats *m*<=-<=1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets.
The four teams remaining in the baskets after (*m*<=-<=1) such procedures are performed, form the last group.
In the real draw the random selection of teams from the basket is performed by people — as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers *x*,<=*a*,<=*b*,<=*c*. Every time there is a call to the random number generator, it produces the following actions:
- calculates ; - replaces parameter *x* by value *y* (assigns ); - returns *x* as another random number.
Operation means taking the remainder after division: , .
A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number *k*. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to *s*<=-<=1, in the order of decreasing rating, where *s* is the current size of the basket. Then a team number is taken from the basket.
Given a list of teams and the parameters of the random number generator, determine the result of the draw.
Input Specification:
The first input line contains integer *n* (4<=≤<=*n*<=≤<=64, *n* is divisible by four) — the number of teams that take part in the sorting. The second line contains four space-separated integers *x*,<=*a*,<=*b*,<=*c* (1<=≤<=*x*,<=*a*,<=*b*,<=*c*<=≤<=1000) — the parameters of the random number generator. Each of the following *n* lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct.
Output Specification:
Print the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format.
Demo Input:
['8\n1 3 1 7\nBarcelona 158\nMilan 90\nSpartak 46\nAnderlecht 48\nCeltic 32\nBenfica 87\nZenit 79\nMalaga 16\n']
Demo Output:
['Group A:\nBarcelona\nBenfica\nSpartak\nCeltic\nGroup B:\nMilan\nZenit\nAnderlecht\nMalaga\n']
Note:
In the given sample the random number generator will be executed four times:
- <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2d76d911e7446d6db4b0be2679ce6e5ab930ab92.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cc339c0d810046d7adb9ef4339e48f5554842ae2.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/74fb01e5b91f6c73ead806139c45f3e73fa1232d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f8a9ac4805dfae22b7d7a65c5daa8f4cc5a21a5a.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
import sys
sys.stdin = open("input.txt")
sys.stdout = open("output.txt",'w')
n = int(input())
m = n//4
x, a, b, c = map(int, input().split())
g = sorted([(int(j), i) for i, j in [input().split() for _ in range(n)]], reverse=1)
w1, w2, w3, w4 = g[:m].copy(), g[m:2*m].copy(), g[2*m:3*m].copy(), g[3*m:].copy()
k = [w1, w2, w3, w4]
d = []
while m:
f = []
for w in range(4):
y = (x*a+b)%c
x = y
y %= m
f.append(k[w][y])
k[w] = k[w][:y] + k[w][y+1:]
d.append(f.copy())
m -= 1
for i in range(n//4):
print(f'Group {chr(i+65)}:')
for j in d[i]:
print(j[1])
``` |
802 | Heidi and Library (medium) | Title: Heidi and Library (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.
Input Specification:
Same as the easy version, but the limits have changed: 1<=≤<=*n*,<=*k*<=≤<=400<=000.
Output Specification:
Same as the easy version.
Demo Input:
['4 100\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:
none | ```python
# https://codeforces.com/problemset/problem/802/B
import heapq
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pos = {}
Q = []
cnt = 0
for i, x in enumerate(a):
if x not in pos:
pos[x] = []
pos[x].append(i)
for i, x in enumerate(a):
if x not in d:
cnt += 1
if len(d) == k:
pos_, x_ = heapq.heappop(Q)
del d[x_]
d[x] = 1
pos[x].pop(0)
if len(pos[x]) > 0:
heapq.heappush(Q, (-pos[x][0], x))
else:
heapq.heappush(Q, (-float('inf'), x))
print(cnt)
``` |
903 | Clear The Matrix | Title: Clear The Matrix
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a matrix *f* with 4 rows and *n* columns. Each element of the matrix is either an asterisk (*) or a dot (.).
You may perform the following operation arbitrary number of times: choose a square submatrix of *f* with size *k*<=×<=*k* (where 1<=≤<=*k*<=≤<=4) and replace each element of the chosen submatrix with a dot. Choosing a submatrix of size *k*<=×<=*k* costs *a**k* coins.
What is the minimum number of coins you have to pay to replace all asterisks with dots?
Input Specification:
The first line contains one integer *n* (4<=≤<=*n*<=≤<=1000) — the number of columns in *f*.
The second line contains 4 integers *a*1, *a*2, *a*3, *a*4 (1<=≤<=*a**i*<=≤<=1000) — the cost to replace the square submatrix of size 1<=×<=1, 2<=×<=2, 3<=×<=3 or 4<=×<=4, respectively.
Then four lines follow, each containing *n* characters and denoting a row of matrix *f*. Each character is either a dot or an asterisk.
Output Specification:
Print one integer — the minimum number of coins to replace all asterisks with dots.
Demo Input:
['4\n1 10 8 20\n***.\n***.\n***.\n...*\n', '7\n2 1 8 2\n.***...\n.***..*\n.***...\n....*..\n', '4\n10 10 1 10\n***.\n*..*\n*..*\n.***\n']
Demo Output:
['9\n', '3\n', '2\n']
Note:
In the first example you can spend 8 coins to replace the submatrix 3 × 3 in the top-left corner, and 1 coin to replace the 1 × 1 submatrix in the bottom-right corner.
In the second example the best option is to replace the 4 × 4 submatrix containing columns 2 – 5, and the 2 × 2 submatrix consisting of rows 2 – 3 and columns 6 – 7.
In the third example you can select submatrix 3 × 3 in the top-left corner and then submatrix 3 × 3 consisting of rows 2 – 4 and columns 2 – 4. | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int, input().split()))
b = [0] * (4 * n)
for i in range(4):
f = list(input().rstrip())
for j in range(n):
b[i + 4 * j] = (46 - f[j]) // 4
for _ in range(4):
b.append(0)
pow2 = [1]
for _ in range(12):
pow2.append(2 * pow2[-1])
m = pow2[12]
m0 = m - 1
x = [[pow2[4 * i + j] for i in range(3)] for j in range(4)]
y = []
for k in range(3):
ak = a[k]
for i in range(4 - k):
for j in range(3 - k):
z = m0
for u in range(k + 1):
for v in range(k + 1):
z ^= x[i + u][j + v]
y.append((z, ak))
z = []
c = 0
for i in range(m):
z0 = []
for j, k in y:
if (j ^ m0) & i:
z0.append((i & j, k))
c += 1
z.append(z0)
inf = pow(10, 9) + 1
dp0 = [inf] * m
x = 0
for i in range(12):
if b[i]:
x ^= pow2[i]
dp0[x] = 0
for i in range(n - 2):
for j in range(m0, -1, -1):
if not dp0[j] ^ inf:
continue
dp0j = dp0[j]
for k, l in z[j]:
dp0[k] = min(dp0[k], dp0j + l)
dp = [inf] * m
dp[0] = min(dp0) + a[3]
x, k = 0, 8
for j in range(12 + 4 * i, 16 + 4 * i):
if b[j]:
x ^= pow2[k]
k += 1
for j in range(0, m, 16):
dp[j // 16 + x] = dp0[j]
dp0 = dp
ans = dp[0]
print(ans)
``` |
245 | Log Stream Analysis | Title: Log Stream Analysis
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got a list of program warning logs. Each record of a log stream is a string in this format:
String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.
The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).
Your task is to print the first moment of time, when the number of warnings for the last *n* seconds was not less than *m*.
Input Specification:
The first line of the input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=10000).
The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.
It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.
Output Specification:
If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last *n* seconds got no less than *m*.
Demo Input:
['60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected\n', '1 2\n2012-03-16 23:59:59:Disk size\n2012-03-17 00:00:00: Network\n2012-03-17 00:00:01:Cant write varlog\n', '2 2\n2012-03-16 23:59:59:Disk size is too sm\n2012-03-17 00:00:00:Network failute dete\n2012-03-17 00:00:01:Cant write varlogmysq\n']
Demo Output:
['2012-03-16 16:16:43\n', '-1\n', '2012-03-17 00:00:00\n']
Note:
none | ```python
# import atexit
# import io
# import sys
#
# _INPUT_LINES = sys.stdin.read().splitlines()
# input = iter(_INPUT_LINES).__next__
# _OUTPUT_BUFFER = io.StringIO()
# sys.stdout = _OUTPUT_BUFFER
#
#
# @atexit.register
# def write():
# sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
import bisect
from datetime import datetime
def main():
n, m = map(int, input().split())
n -= 1
timestamps = []
raw = []
while True:
s = ""
try:
s = input()
except:
print(-1)
exit(0)
d = datetime.strptime(s[0:19], "%Y-%m-%d %H:%M:%S")
timestamps.append(int(d.timestamp()))
raw.append(s[0:19])
idx = bisect.bisect_left(timestamps, timestamps[-1] - n)
if len(timestamps) - idx == m:
print(raw[-1])
exit(0)
if __name__ == "__main__":
main()
``` |
888 | Xor-MST | Title: Xor-MST
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a complete undirected graph with *n* vertices. A number *a**i* is assigned to each vertex, and the weight of an edge between vertices *i* and *j* is equal to *a**i*<=*xor*<=*a**j*.
Calculate the weight of the minimum spanning tree in this graph.
Input Specification:
The first line contains *n* (1<=≤<=*n*<=≤<=200000) — the number of vertices in the graph.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (0<=≤<=*a**i*<=<<=230) — the numbers assigned to the vertices.
Output Specification:
Print one number — the weight of the minimum spanning tree in the graph.
Demo Input:
['5\n1 2 3 4 5\n', '4\n1 2 3 4\n']
Demo Output:
['8\n', '8\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def insert(x, la):
j = 0
for i in p:
if x & i:
if not G[j] >> 25:
la += 1
G[j] ^= la << 25
j = la
else:
j = G[j] >> 25
else:
if not G[j] & 33554431:
la += 1
G[j] ^= la
j = la
else:
j = G[j] & 33554431
cnt[j] += 1
return la
def xor_min(x, s):
j, ans = s, 0
for i in range(30 - len(st), -1, -1):
if x & pow2[i]:
if G[j] >> 25:
j = G[j] >> 25
else:
ans ^= pow2[i]
j = G[j] & 33554431
else:
if G[j] & 33554431:
j = G[j] & 33554431
else:
ans ^= pow2[i]
j = G[j] >> 25
return ans
n = int(input())
a = list(map(int, input().split()))
a = list(set(a))
a.sort()
pow2 = [1]
l = 30
for _ in range(l):
pow2.append(2 * pow2[-1])
p = pow2[::-1]
n = len(a)
G, cnt, la = [0] * 5000000, [0] * 5000000, 0
for i in a:
la = insert(i, la)
h = l
l0 = [-1] * (la + 1)
l0[0] = 0
st = [0]
ans = 0
while st:
i = st[-1]
j, k = G[i] & 33554431, G[i] >> 25
if l0[j] == -1 and l0[k] == -1 and min(cnt[j], cnt[k]):
l = l0[i]
m = l + cnt[j]
r = m + cnt[k]
ans0 = pow2[30]
if (m - l) * (r - m) <= 5000:
for u in range(l, m):
au = a[u]
for v in range(m, r):
ans0 = min(ans0, au ^ a[v])
elif m - l <= r - m:
for u in range(l, m):
ans0 = min(ans0, xor_min(a[u], k))
else:
for u in range(m, r):
ans0 = min(ans0, xor_min(a[u], j))
ans0 |= pow2[h]
ans += ans0
if l0[j] == -1:
if cnt[j] > 1:
st.append(j)
h -= 1
l0[j] = l0[i]
elif l0[k] == -1:
if cnt[k] > 1:
st.append(k)
h -= 1
l0[k] = l0[i] + cnt[j]
else:
st.pop()
h += 1
print(ans)
``` |
665 | Four Divisors | Title: Four Divisors
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
If an integer *a* is divisible by another integer *b*, then *b* is called the divisor of *a*.
For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12.
Let’s define a function *D*(*n*) — number of integers between 1 and *n* (inclusive) which has exactly four positive divisors.
Between 1 and 10 only the integers 6, 8 and 10 has exactly four positive divisors. So, *D*(10)<==<=3.
You are given an integer *n*. You have to calculate *D*(*n*).
Input Specification:
The only line contains integer *n* (1<=≤<=*n*<=≤<=1011) — the parameter from the problem statement.
Output Specification:
Print the only integer *c* — the number of integers between 1 and *n* with exactly four divisors.
Demo Input:
['10\n', '20\n']
Demo Output:
['3\n', '5\n']
Note:
none | ```python
def prime_pi(n):
if n <= 1:
return 0
elif n <= 3:
return 2
v = int(n ** 0.5) - 1
while v ** 2 <= n:
v += 1
v -= 1
smalls = [(i + 1) // 2 for i in range(v + 1)]
s = (v + 1) // 2
roughs = [2 * i + 1 for i in range(s)]
larges = [(n // (2 * i + 1) + 1) // 2 for i in range(s)]
skip = [False] * (v + 1)
pc = 0
for p in range(3, v + 1, 2):
if skip[p]:
continue
q = p * p
pc += 1
if q * q > n:
break
skip[p] = True
for i in range(q, v + 1, 2 * p):
skip[i] = True
ns = 0
for k in range(s):
i = roughs[k]
if skip[i]:
continue
d = i * p
if d <= v:
x = larges[smalls[d] - pc]
else:
x = smalls[n // d]
larges[ns] = larges[k] + pc - x
roughs[ns] = i
ns += 1
s = ns
i = v
for j in range(v // p, p - 1, -1):
c = smalls[j] - pc
e = j * p
while i >= e:
smalls[i] -= c
i -= 1
ret = larges[0] + (s + 2 * (pc - 1)) * (s - 1) // 2 - sum(larges[1:s])
for l in range(1, s):
q = roughs[l]
m = n // q
e = smalls[m // q] - pc
if e <= l:
break
t = 0
for r in roughs[l + 1:e + 1]:
t += smalls[m // r]
ret += t - (e - l) * (pc + l - 1)
return ret
n=int(input())
m=4*10**5
seive=[1]*m
seive[0],seive[1]=0,0
primes=[]
for p in range(2,m):
if seive[p]:
primes.append(p)
for i in range(2*p,m,p):
seive[i]=0
ans=0
s=len(primes)
now=s-1
for i in range(s):
p=primes[i]
x=n//p
res=prime_pi(x)
ans+=max(0,res-i-1)
for p in primes:
if p**3<=n:
ans+=1
print(ans)
``` |
702 | Analysis of Pathes in Functional Graph | Title: Analysis of Pathes in Functional Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to *n*<=-<=1.
Graph is given as the array *f*0,<=*f*1,<=...,<=*f**n*<=-<=1, where *f**i* — the number of vertex to which goes the only arc from the vertex *i*. Besides you are given array with weights of the arcs *w*0,<=*w*1,<=...,<=*w**n*<=-<=1, where *w**i* — the arc weight from *i* to *f**i*.
Also you are given the integer *k* (the length of the path) and you need to find for each vertex two numbers *s**i* and *m**i*, where:
- *s**i* — the sum of the weights of all arcs of the path with length equals to *k* which starts from the vertex *i*; - *m**i* — the minimal weight from all arcs on the path with length *k* which starts from the vertex *i*.
The length of the path is the number of arcs on this path.
Input Specification:
The first line contains two integers *n*,<=*k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=1010). The second line contains the sequence *f*0,<=*f*1,<=...,<=*f**n*<=-<=1 (0<=≤<=*f**i*<=<<=*n*) and the third — the sequence *w*0,<=*w*1,<=...,<=*w**n*<=-<=1 (0<=≤<=*w**i*<=≤<=108).
Output Specification:
Print *n* lines, the pair of integers *s**i*, *m**i* in each line.
Demo Input:
['7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3\n', '4 4\n0 1 2 3\n0 1 2 3\n', '5 3\n1 2 3 4 0\n4 1 2 14 3\n']
Demo Output:
['10 1\n8 1\n7 1\n10 2\n8 2\n7 1\n9 3\n', '0 0\n4 1\n8 2\n12 3\n', '7 1\n17 1\n19 2\n21 3\n8 1\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n,k = map(int, input().split())
a = list(map(int, input().split()))
w = list(map(int, input().split()))
pow_pos = a[:]
pow_mi = w[:]
pow_s = w[:]
pos = list(range(n))
mi = [10 ** 18] * n
s = [0] * n
for i in range(35):
if k & (1 << i):
s = [s[pow_pos[i]] + pow_s[i] for i in range(n)]
mi = [min(pow_mi[i],mi[pow_pos[i]]) for i in range(n)]
pos = [pos[j] for j in pow_pos]
pow_s = [pow_s[pow_pos[i]] + pow_s[i] for i in range(n)]
pow_mi = [min(pow_mi[i],pow_mi[pow_pos[i]]) for i in range(n)]
pow_pos = [pow_pos[j] for j in pow_pos]
for i in range(n):
print(s[i],mi[i])
``` |
883 | Road Widening | Title: Road Widening
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!
The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.
The street is split into *n* equal length parts from left to right, the *i*-th part is characterized by two integers: width of road *s**i* and width of lawn *g**i*.
For each of *n* parts the Mayor should decide the size of lawn to demolish. For the *i*-th part he can reduce lawn width by integer *x**i* (0<=≤<=*x**i*<=≤<=*g**i*). After it new road width of the *i*-th part will be equal to *s*'*i*<==<=*s**i*<=+<=*x**i* and new lawn width will be equal to *g*'*i*<==<=*g**i*<=-<=*x**i*.
On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each *i* (1<=≤<=*i*<=<<=*n*) the inequation |*s*'*i*<=+<=1<=-<=*s*'*i*|<=≤<=1 should hold. Initially this condition might not be true.
You need to find the the total width of lawns the Mayor will destroy according to his plan.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2·105) — number of parts of the street.
Each of the following *n* lines contains two integers *s**i*,<=*g**i* (1<=≤<=*s**i*<=≤<=106, 0<=≤<=*g**i*<=≤<=106) — current width of road and width of the lawn on the *i*-th part of the street.
Output Specification:
In the first line print the total width of lawns which will be removed.
In the second line print *n* integers *s*'1,<=*s*'2,<=...,<=*s*'*n* (*s**i*<=≤<=*s*'*i*<=≤<=*s**i*<=+<=*g**i*) — new widths of the road starting from the first part and to the last.
If there is no solution, print the only integer -1 in the first line.
Demo Input:
['3\n4 5\n4 5\n4 10\n', '4\n1 100\n100 1\n1 100\n100 1\n', '3\n1 1\n100 100\n1 1\n']
Demo Output:
['16\n9 9 10 \n', '202\n101 101 101 101 \n', '-1\n']
Note:
none | ```python
n = int(input())
s = [0]*n
g = [0]*n
for i in range(n):
a,b = map(int,input().split())
s[i] = a
g[i] = a+b
for i in range(1,n):
g[i] = min(g[i],g[i-1]+1)
for i in range(n-2,-1,-1):
g[i] = min(g[i],g[i+1]+1)
ans = 0
for i in range(n):
if s[i] <= g[i]:
ans += g[i] - s[i]
else:
print(-1)
break
else:
print(ans)
print(*g)
``` |
852 | Neural Network country | Title: Neural Network country
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Due to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. They also have one entry, and one exit point.
There are exactly *L* layers, each having *N* cities. Let us look at the two adjacent layers *L*1 and *L*2. Each city from the layer *L*1 is connected to each city from the layer *L*2 with the traveling cost *c**ij* for , and each pair of adjacent layers has the same cost in between their cities as any other pair (they just stacked the same layers, as usual). Also, the traveling costs to each city from the layer *L*2 are same for all cities in the *L*1, that is *c**ij* is the same for , and fixed *j*.
Doctor G. needs to speed up his computations for this country so he asks you to find the number of paths he can take from entry to exit point such that his traveling cost is divisible by given number *M*.
Input Specification:
The first line of input contains *N* (1<=≤<=*N*<=≤<=106), *L* (2<=≤<=*L*<=≤<=105) and *M* (2<=≤<=*M*<=≤<=100), the number of cities in each layer, the number of layers and the number that travelling cost should be divisible by, respectively.
Second, third and fourth line contain *N* integers each denoting costs 0<=≤<=*cost*<=≤<=*M* from entry point to the first layer, costs between adjacent layers as described above, and costs from the last layer to the exit point.
Output Specification:
Output a single integer, the number of paths Doctor G. can take which have total cost divisible by *M*, modulo 109<=+<=7.
Demo Input:
['2 3 13\n4 6\n2 1\n3 4\n']
Demo Output:
['2']
Note:
<img class="tex-graphics" src="https://espresso.codeforces.com/959c8bea1eef9daad659ecab34d36a2f692c5e88.png" style="max-width: 100.0%;max-height: 100.0%;"/>
This is a country with 3 layers, each layer having 2 cities. Paths <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ea33f7ca0560180dc03b2657e6a1f9fd874e5adc.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4b3fe7f211ecca3ab05c72cd3b995d28d037ab45.png" style="max-width: 100.0%;max-height: 100.0%;"/> are the only paths having total cost divisible by 13. Notice that input edges for layer cities have the same cost, and that they are same for all layers. | ```python
import sys
from array import array
class Matrix:
def __init__(self, r, c, mat=None, id=None):
self.r, self.c = r, c
if mat != None:
self.mat = [[mat[i][j] for j in range(c)] for i in range(r)]
else:
self.mat = [[0 for i in range(c)] for j in range(r)]
if id != None:
for i in range(r):
self.mat[i][i] = 1
def __add__(self, other):
mat0 = Matrix(self.r, self.c)
for i in range(self.r):
for j in range(self.c):
mat0[i][j] = self[i][j] + other[i][j]
return mat0
def __mul__(self, other):
mat0 = Matrix(self.r, other.c)
for i in range(self.r):
for j in range(other.c):
for k in range(self.c):
mat0[i][j] += self[i][k] * other[k][j]
mat0[i][j] %= 10 ** 9 + 7
return mat0
def dot_mul(self, other):
res = 0
for i in range(self.r):
for j in range(self.c):
res += self.mat[i][j] * other.mat[j][i]
return res
def trace(self):
res = 0
for i in range(self.r):
res += self.mat[i][i]
return res
def __pow__(self, p, modulo=None):
sq, mat = Matrix(self.r, self.r, id=1), self
while p:
if p & 1:
p -= 1
sq = sq * mat
p //= 2
mat *= mat
return sq
def __getitem__(self, item):
return self.mat[item]
input = lambda: sys.stdin.buffer.readline().decode().strip()
city, layer, m = map(int, input().split())
be, mid, en = [array('i', [int(x) for x in input().split()]) for _ in range(3)]
mem, coff, dp_ = [0] * m, [], [[0] for _ in range(m)]
for i in range(city):
mem[mid[i] % m] += 1
for i in range(m):
coff.append([])
for j in range(m):
coff[-1].append(mem[(i - j) % m])
for i in range(city):
dp_[be[i] % m][0] += 1
dp = (Matrix(m, m, coff) ** (layer - 2)) * Matrix(m, 1, dp_)
res = 0
for i in range(city):
res += dp[(-mid[i] - en[i]) % m][0]
print(res % (10 ** 9 + 7))
``` |
946 | Almost Increasing Array | Title: Almost Increasing Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it).
You are given an array *a* consisting of *n* elements. You are allowed to replace any element with any integer number (and you may do so any number of times you need). What is the minimum number of replacements you have to perform in order to make the array almost increasing?
Input Specification:
The first line contains one integer *n* (2<=≤<=*n*<=≤<=200000) — the number of elements in *a*.
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109) — the array *a*.
Output Specification:
Print the minimum number of replaces you have to perform so that *a* is almost increasing.
Demo Input:
['5\n5 4 3 2 1\n', '5\n1 2 8 9 5\n']
Demo Output:
['3\n', '0\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def segment_tree(n):
tree = [0] * pow(2, n.bit_length() + 1)
return tree
def update(i, x, tree):
i += len(tree) // 2
tree[i] = x
i //= 2
while True:
if i == 0:
break
tree[i] = max(tree[2 * i], tree[2 * i + 1])
i //= 2
return
def get_max(s, t, tree):
s += len(tree) // 2
t += len(tree) // 2
ans = 0
while s <= t:
if s % 2 == 0:
s //= 2
else:
ans = max(ans, tree[s])
s = (s + 1) // 2
if t % 2 == 1:
t //= 2
else:
ans = max(ans, tree[t])
t = (t - 1) // 2
return ans
n = int(input())
a = list(map(int, input().split()))
b = [a[i] - i for i in range(n)]
c = [a[i] - i + 1 for i in range(n)]
s = list(set(b + c))
s.sort()
d = dict()
l = len(s)
for i in range(l):
d[s[i]] = i + 1
tree1 = segment_tree(l + 5)
tree2 = segment_tree(l + 5)
for i in range(n - 1):
u = d[c[i + 1]]
ma = max(get_max(1, u, tree1), get_max(1, u, tree2))
update(u, ma + 1, tree2)
v = d[b[i]]
ma = get_max(1, v, tree1)
update(v, ma + 1, tree1)
ans = n - max(tree1[1], tree2[1]) - 1
print(ans)
``` |
609 | Gadgets for dollars and pounds | Title: Gadgets for dollars and pounds
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Nura wants to buy *k* gadgets. She has only *s* burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for *n* days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to *n*) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during *n* days.
Help Nura to find the minimum day index when she will have *k* gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to *m* in order of their appearing in input.
Input Specification:
First line contains four integers *n*,<=*m*,<=*k*,<=*s* (1<=≤<=*n*<=≤<=2·105,<=1<=≤<=*k*<=≤<=*m*<=≤<=2·105,<=1<=≤<=*s*<=≤<=109) — number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the cost of one dollar in burles on *i*-th day.
Third line contains *n* integers *b**i* (1<=≤<=*b**i*<=≤<=106) — the cost of one pound in burles on *i*-th day.
Each of the next *m* lines contains two integers *t**i*,<=*c**i* (1<=≤<=*t**i*<=≤<=2,<=1<=≤<=*c**i*<=≤<=106) — type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
Output Specification:
If Nura can't buy *k* gadgets print the only line with the number -1.
Otherwise the first line should contain integer *d* — the minimum day index, when Nura will have *k* gadgets. On each of the next *k* lines print two integers *q**i*,<=*d**i* — the number of gadget and the day gadget should be bought. All values *q**i* should be different, but the values *d**i* can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to *n*.
In case there are multiple possible solutions, print any of them.
Demo Input:
['5 4 2 2\n1 2 3 2 1\n3 2 1 2 3\n1 1\n2 1\n1 2\n2 2\n', '4 3 2 200\n69 70 71 72\n104 105 106 107\n1 1\n2 2\n1 2\n', '4 3 1 1000000000\n900000 910000 940000 990000\n990000 999000 999900 999990\n1 87654\n2 76543\n1 65432\n']
Demo Output:
['3\n1 1\n2 3\n', '-1\n', '-1\n']
Note:
none | ```python
'''
Auther: ghoshashis545 Ashis Ghosh
College: Jalpaiguri Govt Enggineering College
'''
from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('0')
file = 1
def ceil(a,b):
return (a+b-1)//b
def solve():
# for _ in range(1,ii()+1):
n,m,k,s = mi()
a = li()
b = li()
gadgets = [[] for i in range(2)]
for i in range(m):
x,y = mi()
gadgets[x-1].append([y,i+1])
gadgets[0].sort()
gadgets[1].sort()
sz = [len(gadgets[0]),len(gadgets[1])]
def check(idx):
mnx1 = inf
mnx2 = inf
for i in range(idx+1):
mnx1 = min(mnx1,a[i])
mnx2 = min(mnx2,b[i])
l1,l2,res = 0,0,0
if k > sz[0] + sz[1]:
return 0
for i in range(k):
if l1 == sz[0]:
res += gadgets[1][l2][0]*mnx2
l2 += 1
elif l2 == sz[1]:
res += gadgets[0][l1][0]*mnx1
l1 += 1
elif gadgets[0][l1][0]*mnx1 <= gadgets[1][l2][0]*mnx2:
res += gadgets[0][l1][0]*mnx1
l1 += 1
else:
res += gadgets[1][l2][0]*mnx2
l2 += 1
return res <= s
l = 0
r = n-1
ans = -1
while l<=r:
mid = (l+r)>>1
if check(mid):
ans = mid+1
r = mid-1
else:
l=mid+1
print(ans)
if ans == -1:
return
mnx1 = inf
mnx2 = inf
idx1,idx2 = -1,-1
for i in range(ans):
if a[i] < mnx1:
mnx1 = a[i]
idx1 = i
if b[i] < mnx2:
mnx2 = b[i]
idx2 = i
l1,l2,res = 0,0,[]
for i in range(k):
if l1 == sz[0]:
res.append([gadgets[1][l2][1],idx2+1])
l2 += 1
elif l2==sz[1]:
res.append([gadgets[0][l1][1],idx1+1])
l1 += 1
elif gadgets[0][l1][0]*mnx1 <= gadgets[1][l2][0]*mnx2:
res.append([gadgets[0][l1][1],idx1+1])
l1 += 1
else:
res.append([gadgets[1][l2][1],idx2+1])
l2 += 1
for i in res:
print(*i)
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
solve()
``` |
600 | Area of Two Circles' Intersection | Title: Area of Two Circles' Intersection
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two circles. Find the area of their intersection.
Input Specification:
The first line contains three integers *x*1,<=*y*1,<=*r*1 (<=-<=109<=≤<=*x*1,<=*y*1<=≤<=109,<=1<=≤<=*r*1<=≤<=109) — the position of the center and the radius of the first circle.
The second line contains three integers *x*2,<=*y*2,<=*r*2 (<=-<=109<=≤<=*x*2,<=*y*2<=≤<=109,<=1<=≤<=*r*2<=≤<=109) — the position of the center and the radius of the second circle.
Output Specification:
Print the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
Demo Input:
['0 0 4\n6 0 4\n', '0 0 5\n11 0 5\n']
Demo Output:
['7.25298806364175601379\n', '0.00000000000000000000\n']
Note:
none | ```python
from math import pi, sqrt
from decimal import *
getcontext().prec = 100
def cos(x):
getcontext().prec += 2
i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
getcontext().prec -= 2
return +s
def acos(x):
mn, mx = Decimal(0), Decimal(pi)
for i in range(1000):
md = (mn+mx)/2
if cos(md) <= x:
mx = md
else:
mn = md
return mx
def dis(x1,y1,x2,y2):
return sqrt((x1-x2)**2+(y1-y2)**2)
def calculate_angle(x1,y1,x2,y2,x3,y3):
v1 = (x1 - x2, y1 - y2)
v2 = (x3 - x2, y3 - y2)
dot_product = v1[0] * v2[0] + v1[1] * v2[1]
magnitude_v1 = sqrt(v1[0] ** 2 + v1[1] ** 2)
magnitude_v2 = sqrt(v2[0] ** 2 + v2[1] ** 2)
# Calculate the angle in radians
angle_radians = acos(dot_product / (magnitude_v1 * magnitude_v2))
return angle_radians
def herons(x1,y1,x2,y2,x3,y3):
side1 = dis(x1,y1,x2,y2)
side2 = dis(x1,y1,x3,y3)
side3 = dis(x3,y3,x2,y2)
semip = (side1+side2+side3) / 2
area = sqrt(semip*(semip-side1)*(semip-side2)*(semip-side3))
return area
def solve():
x1, y1, r1 = map(int, input().split())
x2, y2, r2 = map(int, input().split())
x1, y1, r1 = Decimal(x1), Decimal(y1), Decimal(r1)
x2, y2, r2 = Decimal(x2), Decimal(y2), Decimal(r2)
dcx, dcy = x2-x1, y2-y1
d = dcx**2 + dcy**2
if d >= (r1+r2)**2:
print("0")
return
if d <= (r2-r1)**2:
print("%.7f"%(Decimal(pi)*r1.min(r2)**2))
return
d = d.sqrt()
ans = r1*r1*acos((d*d+r1*r1-r2*r2)/(2*d*r1)) + r2*r2*acos((d*d+r2*r2-r1*r1)/(2*d*r2))
ans = ans - Decimal((d + r1 + r2) * (-d + r1 + r2) * (d + r1 - r2) * (d + r2 - r1)).sqrt()/2
print("%.20f"%(ans))
solve()
``` |
690 | Brain Network (hard) | Title: Brain Network (hard)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input Specification:
The first line of the input contains one number *n* – the number of brains in the final nervous system (2<=≤<=*n*<=≤<=200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1,<=2,<=...,<=*n* in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2,<=3,<=...,<=*n* are added). The second line contains *n*<=-<=1 space-separated numbers *p*2,<=*p*3,<=...,<=*p**n*, meaning that after a new brain *k* is added to the system, it gets connected to a parent-brain .
Output Specification:
Output *n*<=-<=1 space-separated numbers – the brain latencies after the brain number *k* is added, for *k*<==<=2,<=3,<=...,<=*n*.
Demo Input:
['6\n1\n2\n2\n1\n5\n']
Demo Output:
['1 2 2 3 4 ']
Note:
none | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write 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")
from collections import defaultdict
class SparseTable:
def __init__(self, A, F):
self.A = A
self.F = F
self.buildLG()
self.buildST()
def buildLG(self):
self.LG = []
lg, V = 0, 1
for e in range(len(self.A) + 1):
if V * 2 <= e:
V *= 2
lg += 1
self.LG.append(lg)
def buildST(self):
n = len(self.A)
self.ST = []
length = 1
while length <= n:
if length == 1:
self.ST.append(self.A)
else:
self.ST.append([self.F(self.ST[-1][s], self.ST[-1][s + length//2]) for s in range(n - length + 1)])
length <<= 1
def query(self, l, r):
if l == r:
return self.ST[0][l]
if l > r:
l, r = r, l
e = self.LG[r - l + 1]
return self.F(self.ST[e][l], self.ST[e][r - 2**e + 1])
def dfs(G, root, dst, H):
Q = [(root, root, 0)]
while Q:
e, parent, h = Q.pop()
if e not in H:
H[e] = h
dst.append(e)
dst.append(parent)
for x in G[e]:
if x != parent:
Q.append((x, e, h + 1))
n = int(input())
G = defaultdict(set)
for i in range(2, n + 1):
e = int(input())
G[e].add(i)
H = {}
lcaDfs = []
dfs(G, 1, lcaDfs, H)
lcaFirst = [-1] * (n + 1)
for i in range(len(lcaDfs)):
if lcaFirst[lcaDfs[i]] == -1:
lcaFirst[lcaDfs[i]] = i
ST = SparseTable([(H[e], e) for e in lcaDfs], min)
latency, u, v = 1, 1, 2
L = [latency]
for e in range(3, n + 1):
h1, v1 = ST.query(lcaFirst[u], lcaFirst[e])
latency1 = H[e] + H[u] - 2*h1
if latency1 > latency:
latency = latency1
u, v = u, e
else:
h2, v2 = ST.query(lcaFirst[v], lcaFirst[e])
latency2 = H[e] + H[v] - 2*h2
if latency2 > latency:
latency = latency2
u, v = e, v
L.append(latency)
print(" ".join(str(l) for l in L))
``` |
665 | Beautiful Subarrays | Title: Beautiful Subarrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day, ZS the Coder wrote down an array of integers *a*<=with elements *a*1,<=<=*a*2,<=<=...,<=<=*a**n*.
A subarray of the array *a* is a sequence *a**l*,<=<=*a**l*<=<=+<=<=1,<=<=...,<=<=*a**r* for some integers (*l*,<=<=*r*) such that 1<=<=≤<=<=*l*<=<=≤<=<=*r*<=<=≤<=<=*n*. ZS the Coder thinks that a subarray of *a* is beautiful if the bitwise xor of all the elements in the subarray is at least *k*.
Help ZS the Coder find the number of beautiful subarrays of *a*!
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=106,<=1<=≤<=*k*<=≤<=109) — the number of elements in the array *a* and the value of the parameter *k*.
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=109) — the elements of the array *a*.
Output Specification:
Print the only integer *c* — the number of beautiful subarrays of the array *a*.
Demo Input:
['3 1\n1 2 3\n', '3 2\n1 2 3\n', '3 3\n1 2 3\n']
Demo Output:
['5\n', '3\n', '2\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def insert(x, la):
j = 0
for i in p:
if x & i:
if not G[j] >> 25:
la += 1
G[j] ^= la << 25
j = la
else:
j = G[j] >> 25
else:
if not G[j] & 33554431:
la += 1
G[j] ^= la
j = la
else:
j = G[j] & 33554431
cnt[j] += 1
return la
def cnt_xor_max(x, k):
ans, j = 0, 0
for i in p:
if x & i:
if not k & i:
ans += cnt[G[j] & 33554431]
j = G[j] >> 25
else:
j = G[j] & 33554431
else:
if not k & i:
ans += cnt[G[j] >> 25]
j = G[j] & 33554431
else:
j = G[j] >> 25
if not j:
return ans
return ans
n, k = map(int, input().split())
a = list(map(int, input().split()))
G, cnt = [0] * 30000000, [0] * 30000000
l, la = 30, 0
pow2 = [1]
for _ in range(l):
pow2.append(2 * pow2[-1])
p = pow2[::-1]
la = insert(0, la)
ans, u = 0, 0
for i in a:
u ^= i
ans += cnt_xor_max(u, k - 1)
la = insert(u, la)
print(ans)
``` |
802 | Marmots (medium) | Title: Marmots (medium)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.
Can you help Heidi estimate each village's population?
Input Specification:
Same as the easy version.
Output Specification:
Output one line per village, in the same order as provided in the input, containing your (integer) population estimate.
Your answer is considered correct if it is an integer that falls into the interval , where *P* is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.
Note:
none | ```python
def sampleVariance(V):
X = sum(V) / len(V)
S = 0.0
for x in V:
S += (X-x)**2
S /= (len(V))
return (X, S)
#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
V = list(map(int, input().split()))
X, S = sampleVariance(V)
v1 = X
v2 = (2*X) ** 2 / 12
if abs(v1-S) < abs(v2-S):
print(int(X))
else:
print((max(V)+min(V)) // 2)
``` |
873 | Forbidden Indices | Title: Forbidden Indices
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s* consisting of *n* lowercase Latin letters. Some indices in this string are marked as forbidden.
You want to find a string *a* such that the value of |*a*|·*f*(*a*) is maximum possible, where *f*(*a*) is the number of occurences of *a* in *s* such that these occurences end in non-forbidden indices. So, for example, if *s* is aaaa, *a* is aa and index 3 is forbidden, then *f*(*a*)<==<=2 because there are three occurences of *a* in *s* (starting in indices 1, 2 and 3), but one of them (starting in index 2) ends in a forbidden index.
Calculate the maximum possible value of |*a*|·*f*(*a*) you can get.
Input Specification:
The first line contains an integer number *n* (1<=≤<=*n*<=≤<=200000) — the length of *s*.
The second line contains a string *s*, consisting of *n* lowercase Latin letters.
The third line contains a string *t*, consisting of *n* characters 0 and 1. If *i*-th character in *t* is 1, then *i* is a forbidden index (otherwise *i* is not forbidden).
Output Specification:
Print the maximum possible value of |*a*|·*f*(*a*).
Demo Input:
['5\nababa\n00100\n', '5\nababa\n00000\n', '5\nababa\n11111\n']
Demo Output:
['5\n', '6\n', '0\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def suffix_array(s):
l = len(s)
x = [[] for _ in range(222)]
for i in range(l):
x[s[i]].append(i)
y = []
z = [0]
for x0 in x:
for i in x0:
y.append(i)
z.append(len(y))
u = list(z)
p = 1
for _ in range((l - 1).bit_length()):
y0, s0, z0 = [0] * l, [0] * l, [0]
for i in range(len(z) - 1):
z1, z2 = z[i], z[i + 1]
k = z1
for j in range(z1, z2):
if y[j] - p >= 0:
k = j
break
for _ in range(z2 - z1):
j = s[(y[k] - p) % l]
y0[u[j]] = (y[k] - p) % l
u[j] += 1
k += 1
if k == z2:
k = z1
i, u, v, c = 0, s[y0[0]], s[(y0[0] + p) % l], 0
for j in y0:
if u ^ s[j] or v ^ s[(j + p) % l]:
i += 1
u, v = s[j], s[(j + p) % l]
z0.append(c)
c += 1
s0[j] = i
z0.append(l)
u = list(z0)
p *= 2
y, s, z = y0, s0, z0
if len(z) > l:
break
return y, s
def lcp_array(s, sa):
l = len(s)
lcp, rank = [0] * l, [0] * l
for i in range(l):
rank[sa[i]] = i
v = 0
for i in range(l):
if not rank[i]:
continue
j = sa[rank[i] - 1]
u = min(i, j)
while u + v < l and s[i + v] == s[j + v]:
v += 1
lcp[rank[i]] = v
v = max(v - 1, 0)
return lcp
def largest_rectangle(a, n):
ans = 0
st = []
l = []
for i in range(n):
ai = a[i]
if not st or st[-1] ^ ai:
j = i
while st and st[-1] > ai:
k = st.pop()
j = l.pop()
ans = max(ans, (i - j + 1) * k)
if not st or st[-1] ^ ai:
st.append(ai)
l.append(j)
for i in range(len(st)):
ans = max(ans, (n - l[i] + 1) * st[i])
return ans
n = int(input())
s = list(input().rstrip())
s.reverse()
s.append(0)
t = list(input().rstrip())
t.reverse()
if min(t) & 1:
ans = 0
print(ans)
exit()
sa, p = suffix_array(list(s))
lcp = lcp_array(s, sa)
u = [1] * n
for i in range(1, n + 1):
if t[sa[i]] & 1:
u[i - 1] = 0
ans = n
for i in t:
if not i & 1:
break
ans -= 1
c = n
v = []
for i, j in zip(lcp[1:], u):
c = min(c, i)
if j:
v.append(c)
c = n
ans = max(ans, largest_rectangle(v, len(v)))
print(ans)
``` |
620 | Xors on Segments | Title: Xors on Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array with *n* integers *a**i* and *m* queries. Each query is described by two integers (*l**j*,<=*r**j*).
Let's define the function . The function is defined for only *u*<=≤<=*v*.
For each query print the maximal value of the function *f*(*a**x*,<=*a**y*) over all *l**j*<=≤<=*x*,<=*y*<=≤<=*r**j*,<= *a**x*<=≤<=*a**y*.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=5·104,<= 1<=≤<=*m*<=≤<=5·103) — the size of the array and the number of the queries.
The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array *a*.
Each of the next *m* lines contains two integers *l**j*,<=*r**j* (1<=≤<=*l**j*<=≤<=*r**j*<=≤<=*n*) – the parameters of the *j*-th query.
Output Specification:
For each query print the value *a**j* on a separate line — the maximal value of the function *f*(*a**x*,<=*a**y*) over all *l**j*<=≤<=*x*,<=*y*<=≤<=*r**j*,<= *a**x*<=≤<=*a**y*.
Demo Input:
['6 3\n1 2 3 4 5 6\n1 6\n2 5\n3 4\n', '1 1\n1\n1 1\n', '6 20\n10 21312 2314 214 1 322\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n2 2\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 4\n4 5\n4 6\n5 5\n5 6\n6 6\n']
Demo Output:
['7\n7\n7\n', '1\n', '10\n21313\n21313\n21313\n21313\n21313\n21312\n21313\n21313\n21313\n21313\n2314\n2315\n2315\n214\n215\n323\n1\n323\n322\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v, w):
return (u * z + v) * z + w
def update1(x, c):
i = x ^ l1
tree1[i], color1[i] = x, c
i >>= 1
for _ in range(w):
j, k = i << 1, i << 1 ^ 1
if color1[j] ^ c:
tree1[i] = tree1[k]
elif color1[k] ^ c:
tree1[i] = tree1[j]
else:
tree1[i] = min(tree1[j], tree1[k])
color1[i] = c
i >>= 1
return
def update2(x, c):
i = x ^ l1
tree2[i], color2[i] = x, c
i >>= 1
for _ in range(w):
j, k = i << 1, i << 1 ^ 1
if color2[j] ^ c:
tree2[i] = tree2[k]
elif color2[k] ^ c:
tree2[i] = tree2[j]
else:
tree2[i] = max(tree2[j], tree2[k])
color2[i] = c
i >>= 1
return
def xor_max1(x, r, c):
i = 1
if color1[i] ^ c or not tree1[i] < r:
return 0
for _ in range(w):
j, k = i << 1, i << 1 ^ 1
if color1[j] ^ c:
f0 = 1
elif color1[k] ^ c:
f0 = 0
elif tree1[k] < r and x ^ x0[tree1[j]] < x ^ x0[tree1[k]]:
f0 = 1
else:
f0 = 0
i = i << 1 ^ f0
return x ^ x0[i ^ l1]
def xor_max2(x, l, c):
i = 1
if color2[i] ^ c or not tree2[i] > l:
return 0
for _ in range(w):
j, k = i << 1, i << 1 ^ 1
if color2[j] ^ c:
f0 = 1
elif color2[k] ^ c:
f0 = 0
elif tree2[j] > l and x ^ x0[tree2[k]] < x ^ x0[tree2[j]]:
f0 = 0
else:
f0 = 1
i = i << 1 ^ f0
return x ^ x0[i ^ l1]
n, m = map(int, input().split())
a = list(map(int, input().split()))
x0 = [0] * (max(a) + 5)
for i in range(1, len(x0)):
x0[i] = x0[i - 1] ^ i
l0, r0 = [0] * m, [0] * m
m1 = 432
m2 = n // m1 + 3
q = []
s0 = [0] * (m2 + 1)
ans = [0] * m
z = max(m, n) + 5
for i in range(m):
l, r = map(int, input().split())
l, r = l - 1, r - 1
if l // m1 == r // m1:
ans0 = 0
for j in range(l, r + 1):
u = a[j]
for k in range(j, r + 1):
v = a[k]
ans1 = x0[u - 1] ^ x0[v] if u <= v else x0[u] ^ x0[v - 1]
ans0 = max(ans0, ans1)
ans[i] = ans0
continue
l0[i], r0[i] = l, r
x = l // m1
q.append(f(x, r, i))
s0[x + 1] += 1
ma = [0] * n
for i in range(n):
mai, u = 0, a[i]
for j in range(i, min(i // m1 * m1 + m1, n)):
v = a[j]
maj = x0[u - 1] ^ x0[v] if u <= v else x0[u] ^ x0[v - 1]
mai = max(mai, maj)
ma[i] = mai
for i in range(n - 2, -1, -1):
if (i + 1) % m1:
ma[i] = max(ma[i], ma[i + 1])
for i in range(1, m2 + 1):
s0[i] += s0[i - 1]
w = (max(a) + 1).bit_length()
l1 = pow(2, w)
l2 = 2 * l1
inf = pow(10, 9) + 1
tree1, color1 = [inf] * l2, [-1] * l2
tree2, color2 = [-inf] * l2, [-1] * l2
q.sort()
for c in range(m2):
if s0[c] == s0[c + 1]:
continue
r = (c + 1) * m1
c10, c11, c20, c21 = inf, inf, -inf, -inf
ans0 = 0
for i in range(s0[c], s0[c + 1]):
j = q[i] % z
ll, rr = l0[j], r0[j]
while r <= rr:
ar = a[r]
x1, x2 = x0[ar], x0[ar - 1]
if x1 > 1:
update2(ar, c)
elif x1 == 0:
c20 = max(c20, ar)
elif x1 == 1:
c21 = max(c21, ar)
if x2 > 1:
update1(ar - 1, c)
elif x2 == 0:
c10 = min(c10, ar - 1)
elif x2 == 1:
c11 = min(c11, ar - 1)
ans0 = max(ans0, xor_max1(x1, ar, c), xor_max2(x2, ar - 1, c))
if c10 < ar:
ans0 = max(ans0, x1)
if c11 < ar:
ans0 = max(ans0, x1 ^ 1)
if ar - 1 < c20:
ans0 = max(ans0, x2)
if ar - 1 < c21:
ans0 = max(ans0, x2 ^ 1)
r += 1
ans1 = max(ma[ll], ans0)
for l in range(ll, (c + 1) * m1):
al = a[l]
x1, x2 = x0[al], x0[al - 1]
ans1 = max(ans1, xor_max1(x1, al, c), xor_max2(x2, al - 1, c))
if c10 < al:
ans1 = max(ans1, x1)
if c11 < al:
ans1 = max(ans1, x1 ^ 1)
if al - 1 < c20:
ans1 = max(ans1, x2)
if al - 1 < c21:
ans1 = max(ans1, x2 ^ 1)
ans[j] = ans1
sys.stdout.write("\n".join(map(str, ans)))
``` |
883 | Orientation of Edges | Title: Orientation of Edges
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex *s* from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex *s*; 1. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex *s*.
In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.
Help Vasya find the plans.
Input Specification:
The first line contains three integers *n*, *m* and *s* (2<=≤<=*n*<=≤<=3·105, 1<=≤<=*m*<=≤<=3·105, 1<=≤<=*s*<=≤<=*n*) — number of vertices and edges in the graph, and the vertex Vasya has picked.
The following *m* lines contain information about the graph edges. Each line contains three integers *t**i*, *u**i* and *v**i* (1<=≤<=*t**i*<=≤<=2, 1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*) — edge type and vertices connected by the edge. If *t**i*<==<=1 then the edge is directed and goes from the vertex *u**i* to the vertex *v**i*. If *t**i*<==<=2 then the edge is undirected and it connects the vertices *u**i* and *v**i*.
It is guaranteed that there is at least one undirected edge in the graph.
Output Specification:
The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices.
A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of *f* symbols '+' and '-', where *f* is the number of undirected edges in the initial graph. Print '+' as the *j*-th symbol of the string if the *j*-th undirected edge (*u*,<=*v*) from the input should be oriented from *u* to *v*. Print '-' to signify the opposite direction (from *v* to *u*). Consider undirected edges to be numbered in the same order they are given in the input.
If there are multiple solutions, print any of them.
Demo Input:
['2 2 1\n1 1 2\n2 2 1\n', '6 6 3\n2 2 6\n1 4 5\n2 3 4\n1 4 1\n1 3 1\n2 2 3\n']
Demo Output:
['2\n-\n2\n+\n', '6\n++-\n2\n+-+\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
def put():
return map(int, input().split())
def dfs0(x):
s = [x]
vis = [0] * n
ans = ['+'] * m
vis[x] = 1
while s:
i = s.pop()
for j, k in graph[i]:
if (vis[j] == 0):
if (k < 0):
ans[-k - 1] = '-'
elif (k > 0):
ans[k - 1] = '+'
s.append(j)
vis[j] = 1
return ''.join(ans), sum(vis)
def dfs1(x):
s = [x]
vis = [0] * n
ans = ['+'] * m
vis[x] = 1
while s:
i = s.pop()
for j, k in graph[i]:
if (vis[j] == 0):
if (k < 0):
ans[-k - 1] = '+'
elif (k > 0):
ans[k - 1] = '-'
if (k == 0):
s.append(j)
vis[j] = 1
return ''.join(ans), sum(vis)
n,m,s = put()
graph = [[] for i in range(n)]
k = 1
for _ in range(m):
z,x,y = put()
x,y = x - 1, y - 1
if (z == 1):
graph[x].append((y, 0))
else:
graph[x].append((y, k))
graph[y].append((x, -k))
k += 1
m = k - 1
x, y = dfs0(s - 1)
print(y)
print(x)
x, y = dfs1(s - 1)
print(y)
print(x)
``` |
808 | Anthem of Berland | Title: Anthem of Berland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.
Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.
He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.
The anthem is the string *s* of no more than 105 small Latin letters and question marks. The most glorious victory is the string *t* of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string *t* in string *s* is maximal.
Note that the occurrences of string *t* in *s* can overlap. Check the third example for clarification.
Input Specification:
The first line contains string of small Latin letters and question marks *s* (1<=≤<=|*s*|<=≤<=105).
The second line contains string of small Latin letters *t* (1<=≤<=|*t*|<=≤<=105).
Product of lengths of strings |*s*|·|*t*| won't exceed 107.
Output Specification:
Output the maximum number of occurrences of string *t* you can achieve by replacing all the question marks in string *s* with small Latin letters.
Demo Input:
['winlose???winl???w??\nwin\n', 'glo?yto?e??an?\nor\n', '??c?????\nabcab\n']
Demo Output:
['5\n', '3\n', '2\n']
Note:
In the first example the resulting string *s* is "winlosewinwinlwinwin"
In the second example the resulting string *s* is "glorytoreorand". The last letter of the string can be arbitrary.
In the third example occurrences of string *t* are overlapping. String *s* with maximal number of occurrences of *t* is "abcabcab". | ```python
import sys
input = sys.stdin.readline
def z_algorithm(w):
m = len(w)
z = [0] * m
z[0] = m
i, j = 1, 0
while i < m:
while i + j < m and w[j] == w[i + j]:
j += 1
z[i] = j
if not j:
i += 1
continue
l = 1
while l < j and l + z[l] < j:
z[i + l] = z[l]
l += 1
i += l
j -= l
return z
s = list(input().rstrip())
t = list(input().rstrip())
ls, lt = len(s), len(t)
if ls < lt:
ans = 0
print(ans)
exit()
z = z_algorithm(t)
x = []
for i in range(lt):
if i + z[i] == lt:
x.append(i)
n = ls - lt + 1
dp = [0] * n
mdp = [0] * n
for i in range(n):
ok = 1
for j in range(lt):
if not s[i + j] == "?" and not s[i + j] == t[j]:
ok = 0
break
if ok:
dpi = 1 if i - lt < 0 else mdp[i - lt] + 1
for j in x:
if i - j >= 0:
dpi = max(dpi, dp[i - j] + 1)
dp[i] = dpi
if i:
mdp[i] = max(mdp[i - 1], dp[i])
else:
mdp[i] = dp[i]
ans = max(dp)
print(ans)
``` |
509 | Sums of Digits | Title: Sums of Digits
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya had a strictly increasing sequence of positive integers *a*1, ..., *a**n*. Vasya used it to build a new sequence *b*1, ..., *b**n*, where *b**i* is the sum of digits of *a**i*'s decimal representation. Then sequence *a**i* got lost and all that remained is sequence *b**i*.
Vasya wonders what the numbers *a**i* could be like. Of all the possible options he likes the one sequence with the minimum possible last number *a**n*. Help Vasya restore the initial sequence.
It is guaranteed that such a sequence always exists.
Input Specification:
The first line contains a single integer number *n* (1<=≤<=*n*<=≤<=300).
Next *n* lines contain integer numbers *b*1, ..., *b**n* — the required sums of digits. All *b**i* belong to the range 1<=≤<=*b**i*<=≤<=300.
Output Specification:
Print *n* integer numbers, one per line — the correct option for numbers *a**i*, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the *i*-th number should be equal to *b**i*.
If there are multiple sequences with least possible number *a**n*, print any of them. Print the numbers without leading zeroes.
Demo Input:
['3\n1\n2\n3\n', '3\n3\n2\n1\n']
Demo Output:
['1\n2\n3\n', '3\n11\n100\n']
Note:
none | ```python
import sys
def get_max(su, le):
div, mod = divmod(su, 9)
ret = ['9'] * div
if mod:
ret = [str(mod)] + ret
if le - len(ret) > 0:
x = str(int(ret.pop(0)) - 1)
ret = ['1', x] + ret
if le - len(ret) > 0:
ret = [ret[0]] + ['0'] * (le - len(ret)) + ret[1:]
return ret
def get_max2(su, le):
div, mod = divmod(su, 9)
ret = ['9'] * div
if mod:
ret = [str(mod)] + ret
return ['0'] * (le - len(ret)) + ret
input = lambda: sys.stdin.buffer.readline().decode().strip()
lst = ['0']
for _ in range(int(input())):
su = int(input())
le = su // 9 + bool(su % 9)
if le > len(lst):
lst = get_max(su, le)
else:
rem, ix = su, -1
for i in range(len(lst)):
if int(lst[i]) > rem:
break
if lst[i] != '9' and rem > int(lst[i]) and 9 * (len(lst) - i) >= rem:
ix = i
rem -= int(lst[i])
if ix == -1:
lst = get_max(su, len(lst) + 1)
else:
rem = su - sum([int(lst[i]) for i in range(ix + 1)])
cur = 1
for i in range(int(lst[ix]) + 1, 10):
rem -= 1
if (len(lst) - ix - 1) * 9 >= rem:
break
cur += 1
lst = lst[:ix] + [str(int(lst[ix]) + cur)] + get_max2(rem, len(lst) - ix - 1)
print(''.join(lst))
``` |
691 | Xor-sequences | Title: Xor-sequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n*.
A sequence of integers *x*1,<=<=*x*2,<=<=...,<=<=*x**k* is called a "xor-sequence" if for every 1<=<=≤<=<=*i*<=<=≤<=<=*k*<=-<=1 the number of ones in the binary representation of the number *x**i* *x**i*<=<=+<=<=1's is a multiple of 3 and for all 1<=≤<=*i*<=≤<=*k*. The symbol is used for the binary exclusive or operation.
How many "xor-sequences" of length *k* exist? Output the answer modulo 109<=+<=7.
Note if *a*<==<=[1,<=1] and *k*<==<=1 then the answer is 2, because you should consider the ones from *a* as different.
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=1018) — the number of given integers and the length of the "xor-sequences".
The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=1018).
Output Specification:
Print the only integer *c* — the number of "xor-sequences" of length *k* modulo 109<=+<=7.
Demo Input:
['5 2\n15 1 2 4 8\n', '5 1\n15 1 2 4 8\n']
Demo Output:
['13\n', '5\n']
Note:
none | ```python
mod=10**9+7
def popcount(n):
c=(n&0x5555555555555555)+((n>>1)&0x5555555555555555)
c=(c&0x3333333333333333)+((c>>2)&0x3333333333333333)
c=(c&0x0f0f0f0f0f0f0f0f)+((c>>4)&0x0f0f0f0f0f0f0f0f)
c=(c&0x00ff00ff00ff00ff)+((c>>8)&0x00ff00ff00ff00ff)
c=(c&0x0000ffff0000ffff)+((c>>16)&0x0000ffff0000ffff)
c=(c&0x00000000ffffffff)+((c>>32)&0x00000000ffffffff)
return c
def matmul(A,B):
res = [[0]*len(B[0]) for _ in [None]*len(A)]
for i, resi in enumerate(res):
for k, aik in enumerate(A[i]):
for j,bkj in enumerate(B[k]):
resi[j] += aik*bkj
resi[j] %= mod
return res
def matpow(A,p):
if p%2:
return matmul(A, matpow(A,p-1))
elif p > 0:
b = matpow(A,p//2)
return matmul(b,b)
else:
return [[int(i==j) for j in range(len(A))] for i in range(len(A))]
n,k=map(int,input().split())
a=list(map(int,input().split()))
mat=[[0]*n for i in range(n)]
for i in range(n):
for j in range(n):
if popcount(a[i]^a[j])%3==0:
mat[i][j]=1
matp=matpow(mat,k-1)
ansmat=matmul(matp,[[1] for i in range(n)])
ans=0
for i in range(n):
ans+=ansmat[i][0]
print(ans%mod)
``` |
630 | Area of a Star | Title: Area of a Star
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.
A "star" figure having *n*<=≥<=5 corners where *n* is a prime number is constructed the following way. On the circle of radius *r* *n* points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.
Input Specification:
The only line of the input contains two integers *n* (5<=≤<=*n*<=<<=109, *n* is prime) and *r* (1<=≤<=*r*<=≤<=109) — the number of the star corners and the radius of the circumcircle correspondingly.
Output Specification:
Output one number — the star area. The relative error of your answer should not be greater than 10<=-<=7.
Demo Input:
['7 10\n']
Demo Output:
['108.395919545675']
Note:
none | ```python
from math import *
n,r = map(int,input().split())
print(n*r*r/(1/tan(pi/(2*n))+1/tan(pi/n)))
``` |
245 | Queries for Number of Palindromes | Title: Queries for Number of Palindromes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got a string *s*<==<=*s*1*s*2... *s*|*s*| of length |*s*|, consisting of lowercase English letters. There also are *q* queries, each query is described by two integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|). The answer to the query is the number of substrings of string *s*[*l**i*... *r**i*], which are palindromes.
String *s*[*l*... *r*]<==<=*s**l**s**l*<=+<=1... *s**r* (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) is a substring of string *s*<==<=*s*1*s*2... *s*|*s*|.
String *t* is called a palindrome, if it reads the same from left to right and from right to left. Formally, if *t*<==<=*t*1*t*2... *t*|*t*|<==<=*t*|*t*|*t*|*t*|<=-<=1... *t*1.
Input Specification:
The first line contains string *s* (1<=≤<=|*s*|<=≤<=5000). The second line contains a single integer *q* (1<=≤<=*q*<=≤<=106) — the number of queries. Next *q* lines contain the queries. The *i*-th of these lines contains two space-separated integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=|*s*|) — the description of the *i*-th query.
It is guaranteed that the given string consists only of lowercase English letters.
Output Specification:
Print *q* integers — the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.
Demo Input:
['caaaba\n5\n1 1\n1 4\n2 3\n4 6\n4 5\n']
Demo Output:
['1\n7\n3\n4\n2\n']
Note:
Consider the fourth query in the first test case. String *s*[4... 6] = «aba». Its palindrome substrings are: «a», «b», «a», «aba». | ```python
import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
s, out = input(), array('i')
n = len(s)
dp = [array('i', [1] * n) for _ in range(n)]
pre = array('i', [1] * n)
for i in range(2, n + 1):
for j in range(n - i + 1):
l, r = j, i + j - 1
dp[l][r] = dp[l + 1][r - 1] * (s[l] == s[r])
pre[r] += dp[l][r]
for i in range(n):
for j in range(i + 1, n):
cur = dp[i][j]
dp[i][j] = dp[i][j - 1] + pre[j]
pre[j] -= cur
for _ in range(int(input())):
l, r = map(int, input().split())
out.append(dp[l - 1][r - 1])
print('\n'.join(map(str, out)))
``` |
954 | Path Counting | Title: Path Counting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a rooted tree. Let's denote *d*(*x*) as depth of node *x*: depth of the root is 1, depth of any other node *x* is *d*(*y*)<=+<=1, where *y* is a parent of *x*.
The tree has the following property: every node *x* with *d*(*x*)<==<=*i* has exactly *a**i* children. Maximum possible depth of a node is *n*, and *a**n*<==<=0.
We define *f**k* as the number of unordered pairs of vertices in the tree such that the number of edges on the simple path between them is equal to *k*.
Calculate *f**k* modulo 109<=+<=7 for every 1<=≤<=*k*<=≤<=2*n*<=-<=2.
Input Specification:
The first line of input contains an integer *n* (2<=<=≤<=<=*n*<=<=≤<=<=5<=000) — the maximum depth of a node.
The second line of input contains *n*<=-<=1 integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n*<=-<=1 (2<=≤<=<=*a**i*<=<=≤<=109), where *a**i* is the number of children of every node *x* such that *d*(*x*)<==<=*i*. Since *a**n*<==<=0, it is not given in the input.
Output Specification:
Print 2*n*<=-<=2 numbers. The *k*-th of these numbers must be equal to *f**k* modulo 109<=+<=7.
Demo Input:
['4\n2 2 2\n', '3\n2 3\n']
Demo Output:
['14 19 20 20 16 16 ', '8 13 6 9 ']
Note:
This the tree from the first sample: | ```python
mod=10**9+7
n=int(input())
a=[1]+list(map(int,input().split()))+[1]
ans=[0]*(2*n)
cnt=[1]
for i in a[1:]:
cnt.append(cnt[-1]*i%mod)
dp=[0]*2*n
for i in range(n):
for j in range(1,2*n):
ans[j]+=cnt[i]*dp[j]
ans[j]%=mod
ndp=[0]*2*n
for j in range(2*n-1):
ndp[j+1]=dp[j]
res=1
c=(a[i+1]-1)*pow(a[i+1],mod-2,mod)%mod
for j in range(i+1,n):
res*=a[j]
res%=mod
ndp[j-i+1]+=res*c
ndp[j-i+1]%=mod
ans[j-i]+=cnt[i]*res
ans[j-i]%=mod
ndp[1]=1
dp=ndp
inv2=pow(2,mod-2,mod)
ans=[i*inv2%mod for i in ans[1:-1]]
print(*ans)
``` |
241 | Challenging Balloons | Title: Challenging Balloons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement:
Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready!
There are *n* balloons (initially empty) that are tied to a straight line on certain positions *x*1,<=*x*2,<=...,<=*x**n*. Bardia inflates the balloons from left to right. As a result, *i*-th balloon gets bigger and bigger until its radius reaches the pressure endurance *p**i* or it touches another previously-inflated balloon.
While Bardia was busy with the balloons, he wondered "What will be the sum of radius of balloons after all of the balloons are inflated?". Being a nerdy type of guy, he is now thinking about the problem instead of preparing his sister's birthday. Calculate the answer to Bardia's problem so that Nadia's birthday won't be balloon-less.
Artha — Martha's student — claimed his solution got accepted. Martha (being his teacher for a long time!) knew he couldn't have solved the problem for real and thus thinks there is something wrong with the testcases. Artha isn't anyhow logical, which means there is no way for Martha to explain the wrong point in his algorithm. So, the only way is to find a testcase to prove him wrong!
Artha's pseudo-code is shown below:
You should output a small testcase for the problem such that Artha's algorithm is incorrect. The algorithm's output is considered correct if it differs from the correct value by no more than 1.
Input Specification:
Please pay attention! No input will be given to your program for this problem. So you do not have to read from the input anything.
Output Specification:
You should output the generated small testcase (which Artha's solution doesn't get it right). It should be in the following format:
- First line must contain the only number *n* (1<=≤<=*n*<=≤<=500). - The *i*-th of the next *n* lines should contain the description of the *i*-th balloon — two space-separated integers *x**i*,<=*p**i* (1<=≤<=*p**i*<=≤<=106, 0<=≤<=*x*1<=<<=*x*2<=<<=...<=<<=*x**n*<=≤<=106).
Note:
The testcase depicted in the figure above (just showing how output should be formatted): | ```python
n = 402
print (n)
print (0, 1000000)
for i in range(1, n-1):
print (i * 1000, n-i)
print (1000000, 1000000)
``` |
730 | Award Ceremony | Title: Award Ceremony
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
All-Berland programming contest comes to an end. In total, *n* teams participated in it. Like in ACM-ICPC, current results stopped refreshing one hour before the contest ends. So at the Award Ceremony, results are partially known. For each team the value *a**i* is given — the number of points the *i*-th team has earned before the last hour of the contest. Besides that, the Jury has evaluated all submissions sent during the last hour and knows values *d**i* — the number of points earned by the *i*-th team during the last hour (these values can be negative, which means that a team can lose points).
Before the contest, each team got unique id from 1 to *n*. According to the contest rules, a team with more points takes a higher place. If two or more teams have equal number of points, the team with lower id will take the higher place. So no two teams can share the same place.
The Award Ceremony proceeds in the following way. At the beginning of the ceremony, a large screen shows the results for the time moment "one hour before the end", which means that the *i*-th team has *a**i* points. Then the Jury unfreezes results of the teams one by one in some order. When result of the *j*-th team is unfrozen, its score changes from *a**j* to *a**j*<=+<=*d**j*. At this time the table of results is modified and the place of the team can change. The unfreezing of the *j*-th team is followed by the applause from the audience with duration of |*x**j*<=-<=*y**j*| seconds, where *x**j* is the place of the *j*-th team before unfreezing and *y**j* is the place right after the unfreezing. For example, if the team does not change the place, there is no applause from the audience. As you can see, during the Award Ceremony, each team will be unfrozen exactly once.
Your task is to find such an order to unfreeze all the teams that the total duration of applause is maximum possible.
Input Specification:
The first line of the input file contains a single integer *n* (1<=≤<=*n*<=≤<=100) — the number of teams.
Each of the next *n* lines contains two integers *a**i* and *d**i* (1<=≤<=*a**i*<=≤<=100, <=-<=100<=≤<=*d**i*<=≤<=100) — the number of points the *i*-th team has earned before the last hour of the contest and the number of points earned by this team during the last hour. It is possible that after unfreezing a team will have a negative score.
Output Specification:
Print the only integer — maximal total applause duration in seconds if the Jury can choose any order of the teams to unfreeze.
Demo Input:
['4\n17 -14\n52 -5\n1 52\n6 0\n', '5\n4 5\n3 2\n5 -3\n6 -2\n4 3\n']
Demo Output:
['4\n', '14\n']
Note:
In the first example the initial standings are:
1. Team 2, 52 points 1. Team 1, 17 points 1. Team 4, 6 points 1. Team 3, 1 point
Here any order of unfreezing the teams leads to 4 seconds of applause in total. For example, let's unfreeze teams in their order from the Team 1 to the Team 4.
After the Team 1 became unfrozen the standings are:
1. Team 2, 52 points 1. Team 4, 6 points 1. Team 1, 3 points 1. Team 3, 1 point
So there is 1 second of applause, because the difference between old and new places |2 - 3| = 1.
After the Team 2 became unfrozen the standings are:
1. Team 2, 47 points 1. Team 4, 6 points 1. Team 1, 3 points 1. Team 3, 1 point
The place of the Team 2 has not changed, so no applause during unfreezing.
After the Team 3 became unfrozen the standings are:
1. Team 3, 53 point 1. Team 2, 47 points 1. Team 4, 6 points 1. Team 1, 3 points
The place of the Team 3 has changed from 4 to 1, so the duration of applause is |4 - 1| = 3.
The unfreezing of the Team 4 has not changed any place because *d*<sub class="lower-index">4</sub> = 0.
Therefore, the total duration of applause is 1 + 0 + 3 + 0 = 4 seconds. | ```python
n = int(input())
a = []
d = []
p = []
for i in range(n):
ai, di = map(int, input().split())
a.append(ai)
d.append(di)
p.append((ai, -i))
p.append((ai + di, -i))
p.sort()
s = []
for i in range(n):
s.append((p.index((a[i], -i)), p.index((a[i] + d[i], -i))))
ans = 0
for i in range(n):
for j in range(i):
x = []
x.append((s[i][0], 0))
x.append((s[i][1], 1))
x.append((s[j][0], 2))
x.append((s[j][1], 3))
x.sort()
c = [x[k][1] for k in range(4)]
if c[0] >= 2:
for k in range(4):
c[k] ^= 2
if c[0] + c[1] == 1:
continue
ans += 1
if c == [0, 2, 1, 3] or c == [1, 3, 0, 2]:
ans += 1
print(ans)# 1698868566.077163
``` |
845 | Shortest Path Problem? | Title: Shortest Path Problem?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex 1 and vertex *n*.
Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.
Input Specification:
The first line contains two numbers *n* and *m* (1<=≤<=*n*<=≤<=100000, *n*<=-<=1<=≤<=*m*<=≤<=100000) — the number of vertices and the number of edges, respectively.
Then *m* lines follow, each line containing three integer numbers *x*, *y* and *w* (1<=≤<=*x*,<=*y*<=≤<=*n*, 0<=≤<=*w*<=≤<=108). These numbers denote an edge that connects vertices *x* and *y* and has weight *w*.
Output Specification:
Print one number — the minimum length of path between vertices 1 and *n*.
Demo Input:
['3 3\n1 2 3\n1 3 2\n3 2 0\n', '2 2\n1 1 3\n1 2 3\n']
Demo Output:
['2\n', '0\n']
Note:
none | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
from collections import defaultdict
class UnionFind():
def __init__(self,n):
self.n=n
self.parents=[-1]*n
def find(self,x):
if self.parents[x]<0:
return x
else:
self.parents[x]=self.find(self.parents[x])
return self.parents[x]
def union(self,x,y):
x=self.find(x)
y=self.find(y)
if x==y:
return
if self.parents[x]>self.parents[y]:
x,y=y,x
self.parents[x]+=self.parents[y]
self.parents[y]=x
def size(self,x):
return -self.parents[self.find(x)]
def same(self,x,y):
return self.find(x)==self.find(y)
def members(self,x):
root=self.find(x)
return [i for i in range(self.n) if self.find(i)==root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x< 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
group_members=defaultdict(list)
for member in range(self.n):
group_members[self.find(member)].append(member)
return group_members
n,m=map(int,input().split())
tree_edge=[[] for i in range(n)]
non_tree_edge=[]
uf=UnionFind(n)
for _ in range(m):
a,b,c=map(int,input().split())
a,b=a-1,b-1
if uf.same(a,b):
non_tree_edge.append((a,b,c))
else:
uf.union(a,b)
tree_edge[a].append((b,c))
tree_edge[b].append((a,c))
dist=[0]*n
todo=[(0,-1)]
while todo:
v,p=todo.pop()
for u,w in tree_edge[v]:
if u!=p:
todo.append((u,v))
dist[u]=dist[v]^w
S=[]
def add(v):
for i in S:
v=min(v,v^i)
if v!=0:
S.append(v)
for a,b,c in non_tree_edge:
add(dist[a]^dist[b]^c)
res=dist[n-1]
for i in sorted(S,reverse=True):
res=min(res,res^i)
print(res)
``` |
774 | Pens And Days Of Week | Title: Pens And Days Of Week
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan has *n* pens. Every day he uses them, and on the *i*-th day he uses the pen number *i*. On the (*n*<=+<=1)-th day again he uses the pen number 1, on the (*n*<=+<=2)-th — he uses the pen number 2 and so on.
On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day.
Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.
Input Specification:
The first line contains the integer *n* (1<=≤<=*n*<=≤<=50<=000) — the number of pens Stepan has.
The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is equal to the number of milliliters of ink which the pen number *i* currently has.
Output Specification:
Print the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above.
Pens are numbered in the order they are given in input data. The numeration begins from one.
Note that the answer is always unambiguous, since several pens can not end at the same time.
Demo Input:
['3\n3 3 3\n', '5\n5 4 5 4 4\n']
Demo Output:
['2\n', '5\n']
Note:
In the first test Stepan uses ink of pens as follows:
1. on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it; 1. on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it; 1. on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it; 1. on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1 milliliters of ink in it; 1. on the day number 5 (Friday) Stepan will use the pen number 2, after that there will be 1 milliliters of ink in it; 1. on the day number 6 (Saturday) Stepan will use the pen number 3, after that there will be 1 milliliters of ink in it; 1. on the day number 7 (Sunday) Stepan will use the pen number 1, but it is a day of rest so he will not waste ink of this pen in it; 1. on the day number 8 (Monday) Stepan will use the pen number 2, after that this pen will run out of ink.
So, the first pen which will not have ink is the pen number 2. | ```python
import sys
def Min(x, y):
if x > y:
return y
else:
return x
def Gcd(x, y):
if x == 0:
return y
else:
return Gcd(y % x, x)
def Lcm(x, y):
return x * y // Gcd(x, y)
n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]
ok = 0
cur = 0
len = Lcm(7, n)
for i in range(0, 7 * n):
if a[i % n] == 0 :
print(i % n + 1)
ok = 1
break
if cur != 6:
a[i % n] -= 1
d[i % n] += 1
cur = (cur + 1) % 7
if ok == 0:
k = 10**20
for i in range(0, n):
a[i] += d[i]
if d[i] == 0: continue
if a[i] % d[i] > 0:
k = Min(k, a[i] // d[i])
else:
k = Min(k, a[i] // d[i] - 1)
if k == 10**20:
k = 0
for i in range(0, n):
a[i] -= k * d[i]
iter = 0
cur = 0
while True:
if a[iter] == 0:
print(iter % n + 1)
break
else:
if cur != 6:
a[iter] -= 1
cur = (cur + 1) % 7
iter = (iter + 1) % n
``` |
954 | Castle Defense | Title: Castle Defense
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into *n* sections. At this moment there are exactly *a**i* archers located at the *i*-th section of this wall. You know that archer who stands at section *i* can shoot orcs that attack section located at distance not exceeding *r*, that is all such sections *j* that |*i*<=-<=*j*|<=≤<=*r*. In particular, *r*<==<=0 means that archers are only capable of shooting at orcs who attack section *i*.
Denote as defense level of section *i* the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of *k* archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input Specification:
The first line of the input contains three integers *n*, *r* and *k* (1<=≤<=*n*<=≤<=500<=000, 0<=≤<=*r*<=≤<=*n*, 0<=≤<=*k*<=≤<=1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109) — the current number of archers at each section.
Output Specification:
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute *k* additional archers optimally.
Demo Input:
['5 0 6\n5 4 3 4 9\n', '4 2 0\n1 2 3 4\n', '5 1 1\n2 1 2 1 2\n']
Demo Output:
['5\n', '6\n', '3\n']
Note:
none | ```python
import sys
from array import array
from collections import deque
input = lambda: sys.stdin.buffer.readline().decode().strip()
n, dist, k = map(int, input().split())
a = array('i', [int(x) for x in input().split()])
cum = [0] * (n + 1)
for i in range(n):
cum[i + 1] = cum[i] + a[i]
be, en = 0, 10 ** 18 + 10 ** 15
while be < en:
md = (be + en + 1) >> 1
su, rem = 0, k
sums, ix = [0] * n, 0
for i in range(n):
l, r = max(0, i - dist), min(i + dist, n - 1)
while ix < l:
su -= sums[ix]
ix += 1
val = cum[r + 1] - cum[l] + su
if val + rem < md:
en = md - 1
break
tem = max(md - val, 0)
sums[r] += tem
rem -= tem
su += tem
else:
be = md
print(be)
``` |
290 | HQ | Title: HQ
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...
Input Specification:
The only line of the input is a string between 1 and 106 characters long.
Output Specification:
Output "Yes" or "No".
Demo Input:
['HHHH\n', 'HQHQH\n', 'HHQHHQH\n', 'HHQQHHQQHH\n']
Demo Output:
['Yes\n', 'No\n', 'No\n', 'Yes\n']
Note:
The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. | ```python
a = input()
b = []
h = ''
c = 0
for i in a:
if i == 'Q':
c += 1
if c == 0:
print('Yes')
exit(0)
r = -1
for i in range(1001):
if i*i == c:
r = i
break
if r == -1:
print('No')
exit(0)
h = [a.split('Q')[0], a.split('Q')[-1]]
c = [len(h[0]), len(h[1])]
if c[0] % 2 != 0 or c[1] % 2 != 0:
print('No')
exit(0)
c[0] //= 2
c[1] //= 2
resp = ''
i = c[0]
while True:
if i >= len(a):
break
if r == 0 and a[i] == 'Q':
break
resp += a[i]
if r == 0 and a[i] == 'H':
c[1] -= 1
if c[1] == 0 and r == 0:
break
if a[i] == 'Q':
r -= 1
if r == -1:
print('No')
exit(0)
i += 1
def hq(a):
resp = ''
for i in a:
if i == 'H':
resp += 'H'
else:
resp += a
return resp
if a == hq(resp):
print('Yes')
else:
print('No')
``` |
903 | Yet Another Maxflow Problem | Title: Yet Another Maxflow Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In this problem you will have to deal with a very special network.
The network consists of two parts: part *A* and part *B*. Each part consists of *n* vertices; *i*-th vertex of part *A* is denoted as *A**i*, and *i*-th vertex of part *B* is denoted as *B**i*.
For each index *i* (1<=≤<=*i*<=<<=*n*) there is a directed edge from vertex *A**i* to vertex *A**i*<=+<=1, and from *B**i* to *B**i*<=+<=1, respectively. Capacities of these edges are given in the input. Also there might be several directed edges going from part *A* to part *B* (but never from *B* to *A*).
You have to calculate the [maximum flow value](https://en.wikipedia.org/wiki/Maximum_flow_problem) from *A*1 to *B**n* in this network. Capacities of edges connecting *A**i* to *A**i*<=+<=1 might sometimes change, and you also have to maintain the maximum flow value after these changes. Apart from that, the network is fixed (there are no changes in part *B*, no changes of edges going from *A* to *B*, and no edge insertions or deletions).
Take a look at the example and the notes to understand the structure of the network better.
Input Specification:
The first line contains three integer numbers *n*, *m* and *q* (2<=≤<=*n*,<=*m*<=≤<=2·105, 0<=≤<=*q*<=≤<=2·105) — the number of vertices in each part, the number of edges going from *A* to *B* and the number of changes, respectively.
Then *n*<=-<=1 lines follow, *i*-th line contains two integers *x**i* and *y**i* denoting that the edge from *A**i* to *A**i*<=+<=1 has capacity *x**i* and the edge from *B**i* to *B**i*<=+<=1 has capacity *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=109).
Then *m* lines follow, describing the edges from *A* to *B*. Each line contains three integers *x*, *y* and *z* denoting an edge from *A**x* to *B**y* with capacity *z* (1<=≤<=*x*,<=*y*<=≤<=*n*, 1<=≤<=*z*<=≤<=109). There might be multiple edges from *A**x* to *B**y*.
And then *q* lines follow, describing a sequence of changes to the network. *i*-th line contains two integers *v**i* and *w**i*, denoting that the capacity of the edge from *A**v**i* to *A**v**i*<=+<=1 is set to *w**i* (1<=≤<=*v**i*<=<<=*n*, 1<=≤<=*w**i*<=≤<=109).
Output Specification:
Firstly, print the maximum flow value in the original network. Then print *q* integers, *i*-th of them must be equal to the maximum flow value after *i*-th change.
Demo Input:
['4 3 2\n1 2\n3 4\n5 6\n2 2 7\n1 4 8\n4 3 9\n1 100\n2 100\n']
Demo Output:
['9\n14\n14\n']
Note:
This is the original network in the example: | ```python
import heapq
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def make_graph(n, m):
x, y, s = [0] * (2 * m), [0] * m, [0] * (n + 3)
for i in range(0, 2 * m, 2):
u, v, w = map(int, input().split())
s[u + 2] += 1
x[i], x[i + 1] = u, v
y[i >> 1] = w
for i in range(3, n + 3):
s[i] += s[i - 1]
G, W = [0] * m, [0] * m
for i in range(0, 2 * m, 2):
j = x[i] + 1
G[s[j]] = x[i ^ 1]
W[s[j]] = y[i >> 1]
s[j] += 1
return G, W, s
def f(i):
if not lazy[i]:
return
tree[i] += lazy[i]
if i < l1:
lazy[i << 1] += lazy[i]
lazy[i << 1 ^ 1] += lazy[i]
lazy[i] = 0
return
def update(l, r, s):
q, ll, rr, i = [1], [0], [l1 - 1], 0
while len(q) ^ i:
j = q[i]
l0, r0 = ll[i], rr[i]
if l <= l0 and r0 <= r:
if s:
lazy[j] += s
f(j)
i += 1
continue
f(j)
m0 = (l0 + r0) >> 1
if l <= m0 and l0 <= r:
q.append(j << 1)
ll.append(l0)
rr.append(m0)
if l <= r0 and m0 + 1 <= r:
q.append(j << 1 ^ 1)
ll.append(m0 + 1)
rr.append(r0)
i += 1
for i in q[::-1]:
if i < l1:
j, k = i << 1, i << 1 ^ 1
f(j)
f(k)
tree[i] = min(tree[j], tree[k])
return
def get_min(s, t):
update(s, t, 0)
s += l1
t += l1
ans = inf
while s <= t:
if s % 2:
ans = min(ans, tree[s])
s += 1
s >>= 1
if not t % 2:
ans = min(ans, tree[t])
t -= 1
t >>= 1
return ans
n, m, q = map(int, input().split())
a, b = [0] * (n + 1), [0] * n
for i in range(1, n):
x, y = map(int, input().split())
a[i], b[i] = x, y
G, W, s0 = make_graph(n, m)
l1 = pow(2, (n + 1).bit_length())
l2 = 2 * l1
inf = pow(10, 15) + 1
tree, lazy = [inf] * l2, [0] * l2
mi = inf
for i in range(n - 1, -1, -1):
mi = min(mi, b[i])
tree[i + l1] = mi
for i in range(l1 - 1, 0, -1):
tree[i] = min(tree[2 * i], tree[2 * i + 1])
c = [0] * (n + 1)
for i in range(1, n + 1):
for j in range(s0[i], s0[i + 1]):
update(0, G[j] - 1, W[j])
c[i] = tree[1]
h = []
for i in range(1, n + 1):
heapq.heappush(h, (a[i] + c[i], i))
ans = [h[0][0]]
for _ in range(q):
v, w = map(int, input().split())
heapq.heappush(h, (w + c[v], v))
a[v] = w
while (a[h[0][1]] + c[h[0][1]]) ^ h[0][0]:
heapq.heappop(h)
ans0 = h[0][0]
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans)))
``` |
985 | Isomorphic Strings | Title: Isomorphic Strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s* of length *n* consisting of lowercase English letters.
For two given strings *s* and *t*, say *S* is the set of distinct characters of *s* and *T* is the set of distinct characters of *t*. The strings *s* and *t* are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) *f* between *S* and *T* for which *f*(*s**i*)<==<=*t**i*. Formally:
1. *f*(*s**i*)<==<=*t**i* for any index *i*, 1. for any character there is exactly one character that *f*(*x*)<==<=*y*, 1. for any character there is exactly one character that *f*(*x*)<==<=*y*.
For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best".
You have to handle *m* queries characterized by three integers *x*,<=*y*,<=*len* (1<=≤<=*x*,<=*y*<=≤<=*n*<=-<=*len*<=+<=1). For each query check if two substrings *s*[*x*... *x*<=+<=*len*<=-<=1] and *s*[*y*... *y*<=+<=*len*<=-<=1] are isomorphic.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*m*<=≤<=2·105) — the length of the string *s* and the number of queries.
The second line contains string *s* consisting of *n* lowercase English letters.
The following *m* lines contain a single query on each line: *x**i*, *y**i* and *len**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, 1<=≤<=*len**i*<=≤<=*n*<=-<=*max*(*x**i*,<=*y**i*)<=+<=1) — the description of the pair of the substrings to check.
Output Specification:
For each query in a separate line print "YES" if substrings *s*[*x**i*... *x**i*<=+<=*len**i*<=-<=1] and *s*[*y**i*... *y**i*<=+<=*len**i*<=-<=1] are isomorphic and "NO" otherwise.
Demo Input:
['7 4\nabacaba\n1 1 1\n1 4 2\n2 1 3\n2 4 3\n']
Demo Output:
['YES\nYES\nNO\nYES\n']
Note:
The queries in the example are following:
1. substrings "a" and "a" are isomorphic: *f*(*a*) = *a*; 1. substrings "ab" and "ca" are isomorphic: *f*(*a*) = *c*, *f*(*b*) = *a*; 1. substrings "bac" and "aba" are not isomorphic since *f*(*b*) and *f*(*c*) must be equal to *a* at same time; 1. substrings "bac" and "cab" are isomorphic: *f*(*b*) = *c*, *f*(*a*) = *a*, *f*(*c*) = *b*. | ```python
from sys import stdin
input=lambda :stdin.readline()[:-1]
mod=10**9+7
n,q=map(int,input().split())
base=103
s=[ord(i)-97 for i in input()]
a=[]
for i in range(26):
b=[0]
tmp=0
res=1
for j in range(n):
res*=base
res%=mod
if s[j]==i:
tmp+=res
tmp%=mod
b.append(tmp)
a.append(b)
inv=pow(base,mod-2,mod)
pow_inv=[1]
for i in range(n):
pow_inv.append(pow_inv[-1]*inv%mod)
for _ in range(q):
x,y,L=map(int,input().split())
h1=[]
l,r=x-1,x+L-1
for i in range(26):
h=(a[i][r]-a[i][l])*pow_inv[x-1]%mod
h1.append(h)
h2=[]
l,r=y-1,y+L-1
for i in range(26):
h=(a[i][r]-a[i][l])*pow_inv[y-1]%mod
h2.append(h)
h1.sort()
h2.sort()
if h1==h2:
print('YES')
else:
print('NO')
``` |
792 | Mages and Monsters | Title: Mages and Monsters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.
Vova's character can learn new spells during the game. Every spell is characterized by two values *x**i* and *y**i* — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage *x* and mana cost *y* for *z* seconds, then he will deal *x*·*z* damage and spend *y*·*z* mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.
Also Vova can fight monsters. Every monster is characterized by two values *t**j* and *h**j* — monster kills Vova's character in *t**j* seconds and has *h**j* health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.
Vova's character kills a monster, if he deals *h**j* damage to it in no more than *t**j* seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in *t**j* seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.
You have to write a program which can answer two types of queries:
- 1 *x* *y* — Vova's character learns new spell which deals *x* damage per second and costs *y* mana per second. - 2 *t* *h* — Vova fights the monster which kills his character in *t* seconds and has *h* health points.
Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.
For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
Input Specification:
The first line contains two integer numbers *q* and *m* (2<=≤<=*q*<=≤<=105,<=1<=≤<=*m*<=≤<=1012) — the number of queries and the amount of mana at the beginning of every fight.
*i*-th of each next *q* lines contains three numbers *k**i*, *a**i* and *b**i* (1<=≤<=*k**i*<=≤<=2,<=1<=≤<=*a**i*,<=*b**i*<=≤<=106).
Using them you can restore queries this way: let *j* be the index of the last query of second type with positive answer (*j*<==<=0 if there were none of these).
- If *k**i*<==<=1, then character learns spell with *x*<==<=(*a**i*<=+<=*j*) *mod* 106<=+<=1, *y*<==<=(*b**i*<=+<=*j*) *mod* 106<=+<=1. - If *k**i*<==<=2, then you have to determine if Vova is able to win the fight against monster with *t*<==<=(*a**i*<=+<=*j*) *mod* 106<=+<=1, *h*<==<=(*b**i*<=+<=*j*) *mod* 106<=+<=1.
Output Specification:
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
Demo Input:
['3 100\n1 4 9\n2 19 49\n2 19 49\n']
Demo Output:
['YES\nNO\n']
Note:
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana. | ```python
#!/usr/bin/env python3
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _/
def is_right(xy0, xy1, xy):
(x0, y0) = xy0
(x1, y1) = xy1
(x, y) = xy
return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)
def in_chull(x, y):
i = 0
if x > spell_chull[-1][0]:
return False
while spell_chull[i][0] < x:
i += 1
if spell_chull[i][0] == x:
return spell_chull[i][1] <= y
else:
return is_right(spell_chull[i - 1], spell_chull[i], (x, y))
def add_spell(x, y):
global spell_chull
if in_chull(x, y):
return
i_left = 0
while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
i_left += 1
i_right = i_left + 1
while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
i_right += 1
if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
i_right += 1
spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]
for i, qi in enumerate(qis):
(k, a, b) = qi
x = (a + j) % mod + 1
y = (b + j) % mod + 1
if k == 1:
add_spell(x, y)
else: #2
if in_chull(y / x, m / x):
print ('YES')
j = i + 1
else:
print ('NO')
``` |
920 | Tanks | Title: Tanks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly *V* ml of water.
Petya has got *N* tanks, *i*-th of them initially containing *a**i* ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is).
Also Petya has got a scoop that can contain up to *K* ml of water (initially the scoop is empty). This scoop can be used to get some water from some tank, and after that pour it all into some tank (it is impossible to get water from multiple tanks without pouring it, or leave some water in the scoop when pouring it). When Petya tries to get some water from a tank, he gets *min*(*v*,<=*K*) water, where *v* is the current volume of water in the tank.
Is it possible to obtain a tank with exactly *V* ml of water using these operations? If it is possible, print a sequence of operations that allows to do it. If there are multiple ways to obtain needed amount of water in some tank, print any of them.
Input Specification:
The first line contains 3 integers: *N* (2<=≤<=*N*<=≤<=5000), *K* (1<=≤<=*K*<=≤<=5000), and *V* (0<=≤<=*V*<=≤<=109) — the number of tanks, the maximum volume of water the scoop can contain, and the required amount of water in some tank, respectively.
The second line contains *N* integers *a**i* (0<=≤<=*a**i*<=≤<=105), where *a**i* is initial volume of water in *i*-th tank.
Output Specification:
If it is impossible to obtain a tank with exactly *V* ml of water, print NO.
Otherwise print YES in the first line, and beginning from the second line, print the sequence of operations in the following format:
Each line has to contain 3 numbers denoting a compressed operation: "*cnt* *x* *y*" (1<=≤<=*cnt*<=≤<=109,<=1<=≤<=*x*,<=*y*<=≤<=*N*), where *x* is the index of the tank where we get water, *y* is the index of the tank where we pour water, and *cnt* is the number of times we transfer water from tank *x* to tank *y*.
The number of these lines must not exceed *N*<=+<=5.
Demo Input:
['2 3 5\n2 3\n', '2 3 4\n2 3\n', '5 2 0\n1 3 5 7 9\n']
Demo Output:
['YES\n1 2 1\n', 'NO\n', 'YES\n2 2 1\n3 3 1\n4 4 1\n5 5 1\n']
Note:
none | ```python
n,k,v=map(int,input().split())
a=list(map(int,input().split()))
s=sum(a)
if s<v:
print('NO')
exit()
def ceil(a,b):
return (a+b-1)//b
if (s-v)%k==0:
print('YES')
ans=[]
for i in range(1,n):
ans.append((ceil(a[i],k),i,0))
ans.append((ceil(s-v,k),0,1))
for x,y,z in ans:
if x!=0:
print(x,y+1,z+1)
exit()
dp=[[False]*k for i in range(n+1)]
dp[0][0]=True
for i in range(n):
x=(a[i]//k)*k
y=a[i]
for j in range(k):
dp[i+1][(j+x)%k]|=dp[i][j]
dp[i+1][(j+y)%k]|=dp[i][j]
if not dp[n][v%k]:
print('NO')
exit()
tmp=(s-v)%k
x=[]
y=[]
for i in range(n-1,-1,-1):
if tmp==0:
y.append(i)
continue
if dp[i][(tmp-a[i])%k]:
tmp-=a[i]
tmp%=k
x.append(i)
else:
y.append(i)
x.reverse()
x0=x[0]
if x0!=0:
z=0
else:
z=1
ans=[]
for i in x[1:]:
ans.append((ceil(a[i],k),i,x0))
a[x0]+=a[i]
a[i]=0
ans.append((a[x0]//k,x0,z))
a[z]+=a[x0]//k*k
a[x0]-=a[x0]//k*k
for i in range(n):
if i!=z and i!=x0:
ans.append((ceil(a[i],k),i,z))
a[z]+=a[i]
a[i]=0
ans.append(((a[z]-v)//k,z,x0))
a[x0]+=a[z]-v
a[z]-=a[z]-v
print('YES')
for x,y,z in ans:
if x!=0:
print(x,y+1,z+1)
# print(a)
``` |
813 | Bipartite Checking | Title: Bipartite Checking
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph consisting of *n* vertices. Initially there are no edges in the graph. Also you are given *q* queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).
Input Specification:
The first line contains two integers *n* and *q* (2<=≤<=*n*,<=*q*<=≤<=100000).
Then *q* lines follow. *i*th line contains two numbers *x**i* and *y**i* (1<=≤<=*x**i*<=<<=*y**i*<=≤<=*n*). These numbers describe *i*th query: if there is an edge between vertices *x**i* and *y**i*, then remove it, otherwise add it.
Output Specification:
Print *q* lines. *i*th line must contain YES if the graph is bipartite after *i*th query, and NO otherwise.
Demo Input:
['3 5\n2 3\n1 3\n1 2\n1 2\n1 2\n']
Demo Output:
['YES\nYES\nNO\nYES\nNO\n']
Note:
none | ```python
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v, w):
return (u * n2 + v) * n2 + w
def g(u, v):
return u * n2 + v
def get_root(s):
while s ^ root[s]:
s = root[s]
return s
def unite(s, t, i):
s, t = get_root(s), get_root(t)
if s == t:
return
if rank[s] < rank[t]:
s, t = t, s
c1, c2, c3, c4 = s, t, 0, root[t]
if rank[s] == rank[t]:
rank[s] += 1
c3 = 1
root[t] = s
st1.append(f(c1, c2, c3))
st2.append(g(i, c4))
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def undo(x, y):
s, z = divmod(x, n2 * n2)
t, c = divmod(z, n2)
rt = y % n2
rank[s] -= c
root[t] = rt
return
n, q = map(int, input().split())
d = defaultdict(lambda : -1)
u, v = [], []
x, y = [0] * q, [0] * q
for i in range(q):
x0, y0 = map(int, input().split())
if x0 > y0:
x0, y0 = y0, x0
x[i], y[i] = x0, y0
if d[(x0, y0)] == -1:
d[(x0, y0)] = i
else:
u.append(d[(x0, y0)])
v.append(i - 1)
d[(x0, y0)] = -1
for i in d.values():
if i ^ -1:
u.append(i)
v.append(q - 1)
l1 = pow(2, (q + 1).bit_length())
l2 = 2 * l1
s0 = [0] * l2
for u0, v0 in zip(u, v):
l0 = u0 + l1
r0 = v0 + l1
while l0 <= r0:
if l0 & 1:
s0[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
s0[r0] += 1
r0 -= 1
r0 >>= 1
for i in range(1, l2):
s0[i] += s0[i - 1]
now = [0] + list(s0)
tree = [-1] * now[l2]
m = len(u)
for i in range(m):
l0 = u[i] + l1
r0 = v[i] + l1
while l0 <= r0:
if l0 & 1:
tree[now[l0]] = u[i]
now[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
tree[now[r0]] = u[i]
now[r0] += 1
r0 -= 1
r0 >>= 1
n += 5
n2 = 2 * n
root = [i for i in range(n2)]
rank = [1 for _ in range(n2)]
s0 = [0] + s0
st1, st2 = [], []
now = 1
ng = 0
for i in range(s0[1], s0[2]):
j = tree[i]
u0, v0 = get_root(x[j]), get_root(y[j])
u1, v1 = get_root(x[j] + n), get_root(y[j] + n)
if u0 == v0 and u0 == v1:
continue
if u0 == u1:
ng -= 1
if v0 == v1:
ng -= 1
unite(u0, v1, 1)
unite(u1, v0, 1)
if same(u0, u1):
ng += 1
visit = [0] * l2
cnt = [0] * l2
cnt[1] = ng
ans = []
while len(ans) ^ q:
if now >= l1:
ans.append("YES" if not ng else "NO")
if now >= l1 or visit[now << 1 ^ 1]:
visit[now] = 1
while st1 and st2[-1] // n2 == now:
undo(st1.pop(), st2.pop())
now >>= 1
ng = cnt[now]
continue
now = now << 1 if not visit[now << 1] else now << 1 ^ 1
for i in range(s0[now], s0[now + 1]):
j = tree[i]
u0, v0 = get_root(x[j]), get_root(y[j])
u1, v1 = get_root(x[j] + n), get_root(y[j] + n)
if u0 == v0 and u0 == v1:
continue
if u0 == u1:
ng -= 1
if v0 == v1:
ng -= 1
unite(u0, v1, now)
unite(u1, v0, now)
if same(u0, u1):
ng += 1
cnt[now] = ng
sys.stdout.write("\n".join(map(str, ans)))
``` |
1,009 | Allowed Letters | Title: Allowed Letters
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup!
Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent.
In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there.
Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?)
More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible).
What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters?
If Polycarp can't produce any valid name then print "Impossible".
Input Specification:
The first line is the string $s$ ($1 \le |s| \le 10^5$) — the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f".
The second line contains a single integer $m$ ($0 \le m \le |s|$) — the number of investors.
The $i$-th of the next $m$ lines contain an integer number $pos_i$ and a non-empty string of allowed characters for $pos_i$ ($1 \le pos_i \le |s|$). Each string contains pairwise distinct letters from "a" to "f". $pos_1, pos_2, \dots, pos_m$ are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position.
Output Specification:
If Polycarp can't produce any valid name then print "Impossible".
Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string $s$ such that the letter at every position is among the allowed ones.
Demo Input:
['bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef\n', 'abacaba\n0\n', 'fc\n2\n1 cfab\n2 f\n']
Demo Output:
['deadbeef\n', 'aaaabbc\n', 'cf\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
s = list(input().rstrip())
pow2 = [1]
for _ in range(6):
pow2.append(2 * pow2[-1])
p = pow2[6]
cnt = [0] * p
for i in s:
cnt[pow2[i - 97]] += 1
sp = set(pow2)
u = [[pow2[i]] for i in range(6)]
for i in range(1, p):
if i in sp:
continue
for j in range(6):
pj = pow2[j]
if i & pj:
cnt[i] += cnt[pj]
u[j].append(i)
n = len(s)
y = [p - 1] * n
m = int(input())
for _ in range(m):
pos, s = input().rstrip().split()
x = 0
for i in s:
x ^= pow2[i - 97]
y[int(pos) - 1] = x
c = [0] * p
for i in y:
c[i] += 1
v = [[i] for i in range(p)]
for i in range(p - 1, -1, -1):
ci = c[i]
for j in range(i + 1, p):
if i & j == i:
c[j] += ci
v[i].append(j)
ans = []
for i in y:
for j in v[i]:
c[j] -= 1
ok = 0
for j in range(6):
pj = pow2[j]
if not i & pj or not cnt[pj]:
continue
f = 1
for k in range(1, p):
if c[k] > cnt[k] - min(1, k & pj):
f = 0
break
if f:
ok = 1
ans.append(chr(97 + j))
for k in u[j]:
cnt[k] -= 1
break
if not ok:
ans = ["Impossible"]
break
sys.stdout.write("".join(ans))
``` |
813 | Two Melodies | Title: Two Melodies
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!
Alice has a sheet with *n* notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.
You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.
Input Specification:
The first line contains one integer number *n* (2<=≤<=*n*<=≤<=5000).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — notes written on a sheet.
Output Specification:
Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.
Demo Input:
['4\n1 2 4 5\n', '6\n62 22 60 61 48 49\n']
Demo Output:
['4\n', '5\n']
Note:
In the first example subsequences [1, 2] and [4, 5] give length 4 in total.
In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal. | ```python
import sys
def solve():
n = int(sys.stdin.readline())
a = [0] + [int(i) for i in sys.stdin.readline().split()]
dp = [[0]*(n + 1) for i in range(n + 1)]
ans = 0
maxnum = [0] * (10**5 + 2)
maxmod = [0] * 7
for y in range(n + 1):
maxmod = [0] * 7
for ai in a:
maxnum[ai] = 0
for i in range(y):
maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y])
maxnum[a[i]] = max(maxnum[a[i]], dp[i][y])
for x in range(y + 1, n + 1):
dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1
dp[y][x] = dp[x][y]
maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y])
maxnum[a[x]] = max(maxnum[a[x]], dp[x][y])
ans = max(ans, dp[x][y])
print(ans)
if __name__ == '__main__':
solve()
``` |
946 | Fibonacci String Subsequences | Title: Fibonacci String Subsequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a binary string *s* (each character of this string is either 0 or 1).
Let's denote the cost of string *t* as the number of occurences of *s* in *t*. For example, if *s* is 11 and *t* is 111011, then the cost of *t* is 3.
Let's also denote the Fibonacci strings sequence as follows:
- *F*(0) is 0;- *F*(1) is 1;- *F*(*i*)<==<=*F*(*i*<=-<=1)<=+<=*F*(*i*<=-<=2) if *i*<=><=1, where <=+<= means the concatenation of two strings.
Your task is to calculate the sum of costs of all subsequences of the string *F*(*x*). Since answer may be large, calculate it modulo 109<=+<=7.
Input Specification:
The first line contains two integers *n* and *x* (1<=≤<=*n*<=≤<=100, 0<=≤<=*x*<=≤<=100) — the length of *s* and the index of a Fibonacci string you are interested in, respectively.
The second line contains *s* — a string consisting of *n* characters. Each of these characters is either 0 or 1.
Output Specification:
Print the only integer — the sum of costs of all subsequences of the string *F*(*x*), taken modulo 109<=+<=7.
Demo Input:
['2 4\n11\n', '10 100\n1010101010\n']
Demo Output:
['14\n', '553403224\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v):
return u * n + v
n, x = map(int, input().split())
mod = pow(10, 9) + 7
s = list(input().rstrip())
m = 105
inv2 = pow(2, mod - 2, mod)
fib = [1, 1]
p = [2, 2]
ip = [inv2, inv2]
for _ in range(m):
fib.append((fib[-1] + fib[-2]) % mod)
p.append(p[-1] * p[-2] % mod)
ip.append(ip[-1] * ip[-2] % mod)
if n == 1:
dp1, dp2 = [0] * (m + 1), [0] * (m + 1)
dp1[0], dp2[1] = 1, 1
for i in range(2, m + 1):
dp1[i] = (dp1[i - 1] + dp1[i - 2]) % mod
dp2[i] = (dp2[i - 1] + dp2[i - 2]) % mod
u = dp1[x] if not s[0] & 1 else dp2[x]
ans = u * p[x] % mod * inv2 % mod
print(ans)
exit()
elif fib[x] < n:
ans = 0
print(ans)
exit()
dp1, dp2 = [0] * (n * n), [0] * (n * n)
dpp1, dpp2 = [0] * n, [0] * n
dps1, dps2 = [0] * n, [0] * n
for i in range(n):
if not s[i] & 1:
dp1[f(i, i)] = 1
else:
dp2[f(i, i)] = 1
if not s[0] & 1:
dpp1[0] = inv2
else:
dpp2[0] = inv2
if not s[-1] & 1:
dps1[-1] = inv2
else:
dps2[-1] = inv2
ans = 0
for u in range(2, x + 1):
dp3 = [i + j for i, j in zip(dp1, dp2)]
for i in range(n):
for j in range(i, n):
for k in range(j + 1, n):
dp3[f(i, k)] += dp2[f(i, j)] * dp1[f(j + 1, k)] % mod
c = fib[x - u]
for i in range(n - 1):
ans += dpp2[i] * dps1[i + 1] % mod * c % mod
dpp3, dps3 = list(dpp2), list(dps1)
for i in range(1, n):
for j in range(i, n):
dpp3[j] += dp1[f(i, j)] * dpp2[i - 1] % mod
for i in range(n - 1):
for j in range(i, n - 1):
dps3[i] += dp2[f(i, j)] * dps1[j + 1] % mod
dpp3 = [(dpp3[i] % mod * ip[u - 2] + dpp1[i]) % mod for i in range(n)]
dps3 = [(dps3[i] % mod * ip[u - 1] + dps2[i]) % mod for i in range(n)]
dp1 = dp2
dp2 = [i % mod for i in dp3]
dpp1, dps1 = dpp2, dps2
dpp2, dps2 = dpp3, dps3
ans = ans % mod * p[x] % mod
print(ans)
``` |
837 | Functions On The Segments | Title: Functions On The Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have an array *f* of *n* functions.The function *f**i*(*x*) (1<=≤<=*i*<=≤<=*n*) is characterized by parameters: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 and take values:
- *y*1, if *x*<=≤<=*x*1. - *a*·*x*<=+<=*b*, if *x*1<=<<=*x*<=≤<=*x*2. - *y*2, if *x*<=><=*x*2.
There are *m* queries. Each query is determined by numbers *l*, *r* and *x*. For a query with number *i* (1<=≤<=*i*<=≤<=*m*), you need to calculate the sum of all *f**j*(*x**i*) where *l*<=≤<=*j*<=≤<=*r*. The value of *x**i* is calculated as follows: *x**i*<==<=(*x*<=+<=*last*) mod 109, where *last* is the answer to the query with number *i*<=-<=1. The value of *last* equals 0 if *i*<==<=1.
Input Specification:
First line contains one integer number *n* (1<=≤<=*n*<=≤<=75000).
Each of the next *n* lines contains six integer numbers: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 (0<=≤<=*x*1<=<<=*x*2<=≤<=2·105, 0<=≤<=*y*1,<=*y*2<=≤<=109, 0<=≤<=*a*,<=*b*<=≤<=104).
Next line contains one integer number *m* (1<=≤<=*m*<=≤<=500000).
Each of the next *m* lines contains three integer numbers: *l*, *r* and *x* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, 0<=≤<=*x*<=≤<=109).
Output Specification:
none
Demo Input:
['1\n1 2 1 4 5 10\n1\n1 1 2\n', '3\n2 5 1 1 1 4\n3 6 8 2 5 7\n1 3 5 1 4 10\n3\n1 3 3\n2 3 2\n1 2 5\n']
Demo Output:
['13\n', '19\n17\n11\n']
Note:
none | ```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_segment(s, t):
s, t = s + l1, t + l1
ans = []
while s <= t:
if s & 1:
ans.append(s)
s += 1
s >>= 1
if not t & 1:
ans.append(t)
t -= 1
t >>= 1
return ans
n = int(input())
l1 = pow(2, (n + 1).bit_length())
l2 = 2 * l1
s0 = [0] * (l2 + 1)
s0[1], s0[2] = 0, 3 * l1
for i in range(2, l2):
u = (s0[(i >> 1) + 1] - s0[i >> 1]) >> 1
s0[i + 1] = s0[i] + u
z = s0[l2]
inf = pow(10, 9) + 1
a, b, s = [0] * z, [0] * z, [inf] * z
for i in range(1, n + 1):
x1, x2, y1, a0, b0, y2 = map(int, input().split())
j = s0[i + l1]
a[j + 1] = a0
b[j], b[j + 1], b[j + 2] = y1, b0, y2
s[j], s[j + 1] = x1, x2
for i in range(l1 - 1, 0, -1):
u, v, w = s0[2 * i], s0[2 * i + 1], s0[i]
ru, rv = s0[2 * i + 1], s0[2 * i + 2]
while u < ru or v < rv:
a[w], b[w] = a[u] + a[v], b[u] + b[v]
k = min(s[u], s[v])
if s[u] == k:
u += 1
if s[v] == k:
v += 1
s[w] = k
if k == inf:
break
w += 1
pow2 = [1]
for _ in range(20):
pow2.append(2 * pow2[-1])
m = int(input())
ans = [0] * m
last, mod = 0, pow(10, 9)
for i in range(m):
l, r, x = map(int, input().split())
x = (x + last) % mod
seg = get_segment(l, r)
ans0 = 0
for j in seg:
k, r0 = s0[j], s0[j + 1]
c = (k - r0).bit_length()
for u in range(c, -1, -1):
if k + pow2[u] < r0 and s[k + pow2[u]] < x:
k += pow2[u]
if s[k] < x and k < r0:
k += 1
ans0 += a[k] * x + b[k]
ans[i] = ans0
last = ans0
sys.stdout.write("\n".join(map(str, ans)))
``` |