contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
|---|---|---|---|
875
|
Royal Questions
|
Title: Royal Questions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his *n* sons-princes marry the brides with as big dowry as possible.
In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with *m* unmarried princesses. Receiving guests, Karl learned that the dowry of the *i* th princess is *w**i* of golden coins.
Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.
Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.
Help the king to organize the marriage of his sons in the most profitable way for the treasury.
Input Specification:
The first line contains two integers *n*, *m* (2<=≤<=*n*<=≤<=200<=000, 1<=≤<=*m*<=≤<=200<=000) — number of princes and princesses respectively.
Each of following *m* lines contains three integers *a**i*, *b**i*, *w**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*, 1<=≤<=*w**i*<=≤<=10<=000) — number of princes, which *i*-th princess is ready to marry and the value of her dowry.
Output Specification:
Print the only integer — the maximum number of gold coins that a king can get by playing the right weddings.
Demo Input:
['2 3\n1 2 5\n1 2 1\n2 1 10\n', '3 2\n1 2 10\n3 2 20\n']
Demo Output:
['15', '30']
Note:
none
|
```python
import io, os, sys
from heapq import heappush, heappop
from operator import itemgetter
class UnionSet:
def __init__(self, n: int):
self.parent = [*range(n)]
self.rank = [1] * n
self.is_circle = [False] * n
def __len__(self):
return sum([x == self.parent[x] for x in range(len(self.parent))])
def find(self, x):
while x != self.parent[x]:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def check(self, x: int, y: int) -> bool:
return self.find(x) == self.find(y)
def check_circle(self, x: int) -> bool:
return self.is_circle[self.find(x)]
def union(self, x, y):
x_0 = self.find(x)
y_0 = self.find(y)
if self.is_circle[x_0] and self.is_circle[y_0]:
return False
if x_0 != y_0:
if self.rank[x_0] < self.rank[y_0]:
self.parent[x_0] = y_0
elif self.rank[x_0] > self.rank[y_0]:
self.parent[y_0] = x_0
else:
self.rank[x_0] += 1
self.parent[y_0] = x_0
self.is_circle[x_0] = self.is_circle[y_0] = self.is_circle[x_0] or self.is_circle[y_0]
else:
self.is_circle[x_0] = True
return True
def main():
n, m = read_int_tuple()
edges = [read_int_tuple() for _ in range(m)]
us = UnionSet(n + 1)
edges.sort(key=itemgetter(2), reverse=True)
res = 0
for u, v, w in edges:
if us.union(u, v):
res += w
print(res)
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = io.BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# def input(): return stdin.readline().strip()
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())
if __name__ == '__main__':
main()
```
|
508
|
Arthur and Brackets
|
Title: Arthur and Brackets
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2*n*. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.
All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the *i*-th opening bracket he remembers the segment [*l**i*,<=*r**i*], containing the distance to the corresponding closing bracket.
Formally speaking, for the *i*-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [*l**i*,<=*r**i*].
Help Arthur restore his favorite correct bracket sequence!
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=600), the number of opening brackets in Arthur's favorite correct bracket sequence.
Next *n* lines contain numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=<<=2*n*), representing the segment where lies the distance from the *i*-th opening bracket and the corresponding closing one.
The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.
Output Specification:
If it is possible to restore the correct bracket sequence by the given data, print any possible choice.
If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).
Demo Input:
['4\n1 1\n1 1\n1 1\n1 1\n', '3\n5 5\n3 3\n1 1\n', '3\n5 5\n3 3\n2 2\n', '3\n2 3\n1 4\n1 4\n']
Demo Output:
['()()()()\n', '((()))\n', 'IMPOSSIBLE\n', '(())()\n']
Note:
none
|
```python
n = int(input())
L = [tuple(map(int, input().split(' '))) for i in range(n)]
ans = []
try :
for l,r in reversed(L) :
d,a=1,"("
while d < l :
d += len(ans[-1])
a += ans.pop()
if d > r : raise IndexError
a += ")"
ans.append(a)
except IndexError :
print("IMPOSSIBLE")
exit()
print("".join(reversed(ans)))
```
|
615
|
Hexagons
|
Title: Hexagons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined:
Ayrat is searching through the field. He started at point (0,<=0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after *n* moves.
Input Specification:
The only line of the input contains integer *n* (0<=≤<=*n*<=≤<=1018) — the number of Ayrat's moves.
Output Specification:
Print two integers *x* and *y* — current coordinates of Ayrat coordinates.
Demo Input:
['3\n', '7\n']
Demo Output:
['-2 0\n', '3 2\n']
Note:
none
|
```python
#!/usr/bin/python3
import math
def solve(n):
if n == 0:
return (0, 0)
k = int(0.5 * (-1 + math.sqrt(1 + 4 * n / 3.0))) + 10
while 3 * k * (k + 1) >= n:
k -= 1
n -= 3 * k * (k + 1) + 1
x = 1 + 2 * k
y = 2
lim = [k] + [k + 1] * 5
dx = [-1, -2, -1, 1, 2, 1]
dy = [2, 0, -2, -2, 0, 2]
i = 0
while n > 0:
t = min(n, lim[i])
x += t * dx[i]
y += t * dy[i]
n -= t
i += 1
return (x, y)
x, y = solve(int(input()))
print(x, y)
# for i in range(21):
# print(i, solve(i))
```
|
534
|
Berland Local Positioning System
|
Title: Berland Local Positioning System
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are *n* bus stops located along the street, the *i*-th of them is located at the distance *a**i* from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, *a**i*<=<<=*a**i*<=+<=1 for all *i* from 1 to *n*<=-<=1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number *n*, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop *n*. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: , then the request about this segment of the path will have form: 3,<=4,<=5,<=5,<=6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1,<=2,<=2,<=3,<=3,<=4,<=5,<=5,<=6.
You will have to repeat the Berland programmers achievement and implement this function.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of stops.
The second line contains *n* integers (1<=≤<=*a**i*<=≤<=109) — the distance from the *i*-th stop to the central square. The numbers in the second line go in the increasing order.
The third line contains integer *m* (1<=≤<=*m*<=≤<=4·105) — the number of stops the bus visited on some segment of the path.
The fourth line contains *m* integers (1<=≤<=*b**i*<=≤<=*n*) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.
It is guaranteed that the query corresponds to some segment of the path.
Output Specification:
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print <=-<=1.
Demo Input:
['6\n2 3 5 7 11 13\n5\n3 4 5 5 6\n', '6\n2 3 5 7 11 13\n9\n1 2 2 3 3 4 5 5 6\n', '3\n10 200 300\n4\n1 2 2 3\n', '3\n1 2 3\n4\n1 2 2 3\n']
Demo Output:
['10\n', '16\n', '-1\n', '3\n']
Note:
The first test from the statement demonstrates the first example shown in the statement of the problem.
The second test from the statement demonstrates the second example shown in the statement of the problem.
In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.
In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
|
```python
r = lambda: list(map(int, input().split()))
ri = lambda: int(input())
n, a, m, b = ri(), r(), ri(), r()
c = [0] * n
for e in b: c[e - 1] += 1
c[0] *= 2; c[-1] *= 2
d = 0
df= 0
r = max(e // 2 for e in c)
c = [e - r * 2 for e in c]
if any(c):
for i in range(n - 1):
de = a[i+1] - a[i]
d += min(c[i], c[i+1]) * de
df += de
print(d + r * 2 * df)
else:
de = a[1] - a[0]
for i in range(1, n - 1):
if a[i + 1] - a[i] != de: print(-1); break
else: print(r * de * 2 * (n - 1) - de)
```
|
135
|
Weak Subsequence
|
Title: Weak Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to *k*. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string *s* if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals *w*.
String *a* with the length of *n* is considered the weak subsequence of the string *s* with the length of *m*, if there exists such a set of indexes 1<=≤<=*i*1<=<<=*i*2<=<<=...<=<<=*i**n*<=≤<=*m*, that has the following two properties:
- *a**k*<==<=*s**i**k* for all *k* from 1 to *n*; - there exists at least one such *k* (1<=≤<=*k*<=<<=*n*), for which *i**k*<=+<=1<=–<=*i**k*<=><=1.
Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1".
Input Specification:
The first line contains two integers *k* (1<=≤<=*k*<=≤<=106) and *w* (2<=≤<=*w*<=≤<=109) — the alphabet size and the required length of the maximum substring that also is the weak subsequence, correspondingly.
Output Specification:
Print a single number — the number of strings Petya can buy using the voucher, modulo 1000000007 (109<=+<=7). If there are infinitely many such strings, print "-1" (without the quotes).
Demo Input:
['2 2\n', '3 5\n', '2 139\n']
Demo Output:
['10\n', '1593\n', '717248223\n']
Note:
In the first sample Petya can buy the following strings: aaa, aab, abab, abb, abba, baa, baab, baba, bba, bbb.
|
```python
from sys import stdin #Bibliotecas para optimizar la entrada/salida
from sys import stdout
MOD = 1000000007 #Modulo
def qp(a,p): #Exponenciacion binaria O(log p)
a = int(a)
p = int(p)
if p == 0:
return 1
x = qp(a,p//2)
x = (x*x)%MOD
if p%2 == 1:
x = (x*a)%MOD
return x
def inv(a): #inverso multiplicativo, ya que el modulo es primo usamos el pequeño teorema de fermat para hallarlo
return qp(a,MOD-2)
inputs = list(map(int,stdin.readline().split())) #lee la entrada
k,w = inputs[0],inputs[1]
fact = [0 for i in range(k+1)] #Lista que va a mantener para cada valor entre 0 y k el factorial de ese numero (modulado)
ifact = [0 for i in range(k+1)] #Lista que va a mantener para cada valor entre 0 y k el inverso multiplicativo del factorial de ese numero.
#Computamos el factorial recursivamente
fact[0] = 1
for i in range(1,k+1):
fact[i] = (fact[i-1]*i)%MOD
#Computamos el inverso multiplicativo del factorial recursivamente teniendo en cuenta que (k!)^(-1) = ((k+1)!^(-1))*k+1
ifact[k] = inv(fact[k])
for i in range(2,k+2):
ifact[k + 1 - i] = (ifact[k + 2 - i]*(k + 2 - i))%MOD
invk = inv(k) #variable que guarda el inverso multiplicativo de k
#Lista que almacena en la posicion i el valor (k^(w-i))%MOD
qpk = [0 for i in range(k+1)]
qpk[0] = qp(k,w)
for i in range(k):
qpk[i+1] = (qpk[i]*invk) %MOD
ans = 0 #Variable para la respuesta
for i in range(1,k+1):
subans = 1
#Calculamos la cantidad de palabras cuyos sufijos de tamaño w son subcadenas buenas máximas
if i < w:
subans*=fact[k]
subans%=MOD
subans*=fact[k-1]
subans%=MOD
subans*=qpk[i]
subans%=MOD
subans*=i
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
ans += subans
subans = 1
else:
subans*=fact[k]
subans%=MOD
subans*=fact[k-1-i+w]
subans%=MOD
subans*=w
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
ans += subans
subans = 1
ans%=MOD
#Calculamos la cantidad de palabras cuyos prefijos de tamaño w son subcadenas buenas máximas
if i < k:
if i+1 < w:
subans*=fact[k]
subans%=MOD
subans*=fact[k-1]
subans%=MOD
subans*= qpk[i+1]
subans%=MOD
subans*=i
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
subans*=ifact[k-i-1]
subans%=MOD
ans += subans
subans = 1
else:
subans*=fact[k]
subans%=MOD
subans*=fact[k-2-i+w]
subans%=MOD
subans*=(w-1)
subans%=MOD
subans*=ifact[k-i]
subans%=MOD
subans*=ifact[k-i-1]
subans%=MOD
ans += subans
subans = 1
ans%=MOD
print(int(ans))
```
|
749
|
Inversions After Shuffle
|
Title: Inversions After Shuffle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a permutation of integers from 1 to *n*. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:
1. Pick a random segment (continuous subsequence) from *l* to *r*. All segments are equiprobable. 1. Let *k*<==<=*r*<=-<=*l*<=+<=1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to *k*, *p*1,<=*p*2,<=...,<=*p**k*. All *k*! permutation are equiprobable. 1. This permutation is applied to elements of the chosen segment, i.e. permutation *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*<=-<=1,<=*a**r*,<=*a**r*<=+<=1,<=...,<=*a**n* is transformed to *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*<=-<=1<=+<=*p*1,<=*a**l*<=-<=1<=+<=*p*2,<=...,<=*a**l*<=-<=1<=+<=*p**k*<=-<=1,<=*a**l*<=-<=1<=+<=*p**k*,<=*a**r*<=+<=1,<=...,<=*a**n*.
Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (*i*,<=*j*) such that *i*<=<<=*j* and *a**i*<=><=*a**j*. Find the expected number of inversions after we apply exactly one operation mentioned above.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the length of the permutation.
The second line contains *n* distinct integers from 1 to *n* — elements of the permutation.
Output Specification:
Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=9.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
Demo Input:
['3\n2 3 1\n']
Demo Output:
['1.916666666666666666666666666667\n']
Note:
none
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def fenwick_tree(n):
tree = [0] * (n + 1)
return tree
def get_sum(i):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
def add(i, x):
while i < len(tree):
tree[i] += x
i += i & -i
n = int(input())
a = list(map(int, input().split()))
p = [0] * (n + 1)
for i in range(n):
p[a[i]] = i + 1
tree = fenwick_tree(n + 5)
s1 = 0
for i in range(1, n + 1):
pi = p[i]
s1 += (n - pi + 1) * get_sum(pi)
add(pi, pi)
tree = fenwick_tree(n + 5)
s2 = 0
for i in range(n, 0, -1):
pi = p[i]
s2 += (n - pi + 1) * get_sum(pi)
add(pi, pi)
tree = fenwick_tree(n + 5)
s3 = 0
for i in range(n, 0, -1):
pi = p[i]
s3 += get_sum(pi)
add(pi, 1)
m = n * (n + 1)
ans = (s1 + m * s3 - s2) / m
print(ans)
```
|
626
|
Group Projects
|
Title: Group Projects
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the *i*-th student *a**i* minutes to finish his/her independent piece.
If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum *a**i* in the group minus the minimum *a**i* in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most *k*?
Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.
Input Specification:
The first line contains two space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=200, 0<=≤<=*k*<=≤<=1000) — the number of students and the maximum total imbalance allowed, respectively.
The second line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=500) — the time it takes the *i*-th student to complete his/her independent piece of work.
Output Specification:
Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109<=+<=7.
Demo Input:
['3 2\n2 4 5\n', '4 3\n7 8 9 10\n', '4 0\n5 10 20 21\n']
Demo Output:
['3\n', '13\n', '1\n']
Note:
In the first sample, we have three options:
- The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2. - The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1. - All three students form their own groups. Total imbalance is 0.
In the third sample, the total imbalance must be 0, so each student must work individually.
|
```python
# Problem: F. Group Projects
# Contest: Codeforces - 8VC Venture Cup 2016 - Elimination Round
# URL: https://codeforces.com/contest/626/problem/F
# Memory Limit: 256 MB
# Time Limit: 2000 ms
import sys
import random
from types import GeneratorType
import bisect
import io, os
from bisect import *
from collections import *
from contextlib import redirect_stdout
from itertools import *
from array import *
from functools import lru_cache, reduce
from heapq import *
from math import sqrt, gcd, inf
if sys.version >= '3.8': # ACW没有comb
from math import comb
RI = lambda: map(int, sys.stdin.buffer.readline().split())
RS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())
RILST = lambda: list(RI())
DEBUG = lambda *x: sys.stderr.write(f'{str(x)}\n')
# print = lambda d: sys.stdout.write(str(d) + "\n") # 打开可以快写,但是无法使用print(*ans,sep=' ')这种语法,需要print(' '.join(map(str, p))),确实会快。
DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 右下左上
DIRS8 = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0),
(-1, 1)] # →↘↓↙←↖↑↗
RANDOM = random.randrange(2 ** 62)
MOD = 10 ** 9 + 7
# MOD = 998244353
PROBLEM = """https://codeforces.com/contest/626/problem/F
输入 n(1≤n≤200) k(0≤k≤1000) 和长为 n 的数组 a(1≤a[i]≤500)。
有 n 个人,第 i 个人的能力值为 a[i]。
把这 n 个人分成若干组,一个组的不平衡度定义为组内最大值减最小值。
特别地,如果组内只有一个人,那么不平衡度为 0。
要求所有组的不平衡度之和不超过 k。
有多少种分组方案?模 1e9+7。
注:一个组是 a 的子序列,不要求连续。
输入
3 2
2 4 5
输出 3
输入
4 3
7 8 9 10
输出 13
输入
4 0
5 10 20 21
输出 1
"""
"""先排序。
提示 1:把作为最小值的数看成左括号,作为最大值的数看成右括号。由于作为最小值的个数不能低于作为最大值的个数,所以这和括号问题是相似的,可以用解决括号问题的技巧来思考。
提示 2:如何优雅地计算不平衡度呢?假设从小到大有 a b c d 四个数,选了 a c d,那么 d-a = (d-c) + (c-b) + (b-a)。注意这里算上了没有选的 b。
这意味着我们只需要考虑相邻两个数对不平衡度的影响。
提示 3:记忆化搜索,我的实现是从 n-1 开始,递归到 -1。先选最大值,再选最小值。
定义 dfs(i, groups, leftK) 表示前 i 个数中,有最大值但是尚未确定最小值的组有 groups 个,剩余不平衡度为 leftK。
需要考虑四种情况:
1. a[i] 作为一个新的组的最大值(创建一个新的组)。
2. a[i] 作为某个组的最小值(有 groups 种选择方案)。
3. a[i] 单独形成一个组(这个组只有一个数)。
4. a[i] 添加到某个组中(有 groups 种选择方案)。
具体见代码 https://codeforces.com/contest/626/submission/211471819
注:这题用到的思路和我在【1681. 最小不兼容性】这题评论区发的代码是类似的
https://leetcode.cn/problems/minimum-incompatibility/discussion/comments/2051770"""
# ms
def solve():
n, m = RI()
a = RILST()
a.sort()
a = [0] + a
f = [[0] * (m + 1) for _ in range(n + 1)] # f[i][j][k]表示前i个数,有j个段尚未闭合,不平衡度为k时的方案数
f[0][0] = 1
for i in range(1, n + 1):
g = [[0] * (m + 1) for _ in range(n + 1)]
d = a[i] - a[i - 1]
for j in range(n + 1):
for k in range(m + 1):
if j != 0 and k - (j - 1) * d>=0:
g[j][k] += f[j - 1][k - (j - 1) * d]
if j!=n and k - (j + 1) * d>=0:
g[j][k] += f[j + 1][k - (j + 1) * d] * (j + 1)
if k-j*d >= 0:
g[j][k] +=f[j][k-j * d] * (j + 1)
g[j][k] %= MOD
f = g
print(sum(f[0][:m + 1]) % MOD)
if __name__ == '__main__':
t = 0
if t:
t, = RI()
for _ in range(t):
solve()
else:
solve()
```
|
755
|
PolandBall and White-Red graph
|
Title: PolandBall and White-Red graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
PolandBall has an undirected simple graph consisting of *n* vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red.
Colorfulness of the graph is a value *min*(*d**r*,<=*d**w*), where *d**r* is the diameter of the red subgraph and *d**w* is the diameter of white subgraph. The diameter of a graph is a largest value *d* such that shortest path between some pair of vertices in it is equal to *d*. If the graph is not connected, we consider its diameter to be -1.
PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to *k*. Can you help him and find any graph which satisfies PolandBall's requests?
Input Specification:
The only one input line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*k*<=≤<=1000), representing graph's size and sought colorfulness.
Output Specification:
If it's impossible to find a suitable graph, print -1.
Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output *m* — the number of red edges in your graph. Then, you should output *m* lines, each containing two integers *a**i* and *b**i*, (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*) which means that there is an undirected red edge between vertices *a**i* and *b**i*. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order.
Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed.
Demo Input:
['4 1\n', '5 2\n']
Demo Output:
['-1\n', '4\n1 2\n2 3\n3 4\n4 5\n']
Note:
In the first sample case, no graph can fulfill PolandBall's requirements.
In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5.
|
```python
def PolandBall(n, k):
# condiciones que no cumplen con los requisitos
if n < 4 or k > 3 or k == 1 or (k == 2 and n == 4):
print('-1')
return
# si k=2
if k == 2:
print(n-1)
for i in range(1, n):
print(str(i)+' '+str(i+1))
return
# si k=3 y n=4
if n == 4:
print(n-1)
print('1 2')
print('2 3')
print('3 4')
return
# si k=3 y n>4
print(n)
print('1 2')
print('2 3')
print('1 4')
print('3 5')
for i in range(5, n+1):
print('1 '+str(i))
n, k = map(int, input().split())
PolandBall(n, k)
# Casos de prueba:
# 4 1 ##respuesta -1
# 5 2 ##respuesta 4
# 2 1 ##respuesta -1
# 2 3 ##respuesta -1
# 3 3 ##respuesta -1
# 4 2 ##respuesta -1
# 7 2 ##respuesta 6
# 100 2 ##respuesta 99
# 500 2 ##respuesta 499
# 1000 2 ##respuesta 999
# 4 3 ##respuesta 3
# 7 3 ##respuesta 7
# 100 3 ##respuesta 100
# 500 3 ##respuesta 500
# 1000 3 ##respuesta 1000
# 1000 1000 ##respuesta -1
```
|
891
|
Lust
|
Title: Lust
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A false witness that speaketh lies!
You are given a sequence containing *n* integers. There is a variable *res* that is equal to 0 initially. The following process repeats *k* times.
Choose an index from 1 to *n* uniformly at random. Name it *x*. Add to *res* the multiply of all *a**i*'s such that 1<=≤<=*i*<=≤<=*n*, but *i*<=≠<=*x*. Then, subtract *a**x* by 1.
You have to find expected value of *res* at the end of the process. It can be proved that the expected value of *res* can be represented as an irreducible fraction . You have to find .
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=5000, 1<=≤<=*k*<=≤<=109) — the number of elements and parameter *k* that is specified in the statement.
The second line contains *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109).
Output Specification:
Output a single integer — the value .
Demo Input:
['2 1\n5 5\n', '1 10\n80\n', '2 2\n0 0\n', '9 4\n0 11 12 9 20 7 8 18 2\n']
Demo Output:
['5', '10', '500000003', '169316356']
Note:
none
|
```python
mod=1000000007
def powmod(a, b, mod):
res = 1
a %= mod
assert b >= 0
while b:
if b & 1:
res = res * a % mod
a = a * a % mod
b >>= 1
return res
N = 10100
n, k = map(int, input().split())
poly = [0] * N
q = [0] * N
ret = [0] * N
a = list(map(int, input().split()))
ans = 0
poly[0] = 1
for i in range(n):
for j in range(i, -1, -1):
poly[j + 1] = (poly[j] + poly[j + 1]) % mod
poly[j] = poly[j] * (mod - a[i]) % mod
for i in range(n):
for j in range(n + 1):
q[j] = poly[j]
for j in range(n, 0, -1):
ret[j - 1] = (ret[j - 1] + q[j]) % mod
q[j - 1] = (q[j - 1] + q[j] * a[i]) % mod
coef = 1
for i in range(n):
coef = coef * (k - i) % mod
ans = (ans + powmod(n, mod - 2 - i, mod) * coef % mod * powmod(i + 1, mod - 2, mod) % mod * ret[i]) % mod
ans = ans * powmod(mod - 1, n + 1, mod) % mod
print(ans)# 1693218474.6046677
```
|
540
|
Infinite Inversions
|
Title: Infinite Inversions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is an infinite sequence consisting of all positive integers in the increasing order: *p*<==<={1,<=2,<=3,<=...}. We performed *n* swap operations with this sequence. A *swap*(*a*,<=*b*) is an operation of swapping the elements of the sequence on positions *a* and *b*. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (*i*,<=*j*), that *i*<=<<=*j* and *p**i*<=><=*p**j*.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of swap operations applied to the sequence.
Each of the next *n* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=109, *a**i*<=≠<=*b**i*) — the arguments of the swap operation.
Output Specification:
Print a single integer — the number of inversions in the resulting sequence.
Demo Input:
['2\n4 2\n1 4\n', '3\n1 6\n3 4\n2 5\n']
Demo Output:
['4\n', '15\n']
Note:
In the first sample the sequence is being modified as follows: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/014a32f190673020641bf266b205f41f0a704f2d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. It has 4 inversions formed by index pairs (1, 4), (2, 3), (2, 4) and (3, 4).
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_sum(i):
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
def add(i, x):
while i < len(tree):
tree[i] += x
i += i & -i
n = int(input())
ab = [tuple(map(int, input().split())) for _ in range(n)]
s = [0]
for a, b in ab:
s.append(a)
s.append(b)
s = list(set(sorted(s)))
s.sort()
d = dict()
l = len(s)
for i in range(l):
d[s[i]] = i
x = [i for i in range(l)]
for a, b in ab:
u, v = d[a], d[b]
x[u], x[v] = x[v], x[u]
tree = [0] * (l + 5)
ans = 0
for i in x[::-1][:-1]:
ans += get_sum(i)
add(i, 1)
for i in range(1, l):
j = x[i]
ans += abs(s[i] - s[j])
ans -= abs(i - j)
print(ans)
```
|
723
|
One-Way Reform
|
Title: One-Way Reform
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* cities and *m* two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.
The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.
Input Specification:
The first line contains a positive integer *t* (1<=≤<=*t*<=≤<=200) — the number of testsets in the input.
Each of the testsets is given in the following way. The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=200, 0<=≤<=*m*<=≤<=*n*·(*n*<=-<=1)<=/<=2) — the number of cities and the number of roads in Berland.
The next *m* lines contain the description of roads in Berland. Each line contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) — the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities.
It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200.
Pay attention that for hacks, you can only use tests consisting of one testset, so *t* should be equal to one.
Output Specification:
For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it.
In the next *m* lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once.
Demo Input:
['2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2\n']
Demo Output:
['3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7\n']
Note:
none
|
```python
import sys
input = sys.stdin.buffer.readline
line = lambda : [int(x) for x in input().split()]
def ecyc(graph: list[list[int]], edges: list[int]) -> list[list[int]]:
"""Finds euler cycles of `graph`
Can only be used if all degrees of nodes in `graph` are even. If the
graph is disconnected, returns a LIST of cycles. Otherwise returns a
LIST with the single cycle.
Constructs euler cycle from graph in adj-list format (undirected, v
in adj[u] and u in adj[v] for every edge (u, v)). The graph can take
multiple edges. It MAY work with self-loops. Or we may pop the wrong
number of 'x' from adj[x].
Also takes an edge counter: edge[code(u, v)] is the number of copies of edge
(u, v) that have not been walked on.
OVERWRITES both `graph` and `edges`.
"""
res = []
for x in range(n):
if not adj[x]: continue
cyc = [x]
#breakpoint()
while True:
neighs = graph[x]
while neighs and edges[code(x, neighs[-1])] == 0:
neighs.pop()
if not neighs:
res.append(cyc)
break # Nowhere left to go. Should only happen when
# no edges left.
assert neighs
y = neighs.pop()
edges[code(x, y)] -= 1
cyc.append(y)
x = y
#breakpoint()
return res
def code(u, v):
if u < v: u, v = v, u
return u*n+v
for _ in range(int(input())):
n, m = line()
deg = [0]*n
orig = [0]*(n**2)
adj : list[list[int]] = [[] for _ in range(n)]
for _ in range(m):
u, v = [int(x) -1 for x in input().split()]
orig[code(u, v)] += 1
deg[u] += 1
deg[v] += 1
adj[u].append(v)
adj[v].append(u)
odd = [i for (i, v) in enumerate(deg) if v%2 == 1]
print(n-len(odd))
full = orig[:]
while odd:
assert len(odd) >= 2
u, v = odd.pop(), odd.pop()
adj[u].append(v)
adj[v].append(u)
full[code(u, v)] += 1
cycs = ecyc(adj, full)
assert all(x==0 for x in full)
for u, *cyc in cycs:
for v in cyc:
c = code(u, v)
if orig[c] > 0:
orig[c] -= 1
print(u+1, v+1)
u = v
```
|
629
|
Famil Door and Roads
|
Title: Famil Door and Roads
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are *n* intersections in the city connected by *n*<=-<=1 bidirectional roads.
There are *m* friends of Famil Door living in the city. The *i*-th friend lives at the intersection *u**i* and works at the intersection *v**i*. Everyone in the city is unhappy because there is exactly one simple path between their home and work.
Famil Door plans to construct exactly one new road and he will randomly choose one among *n*·(*n*<=-<=1)<=/<=2 possibilities. Note, that he may even build a new road between two cities that are already connected by one.
He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both *u**i* and *v**i*.
Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both *u**i* and *v**i* if we consider only cases when such a cycle exists.
Input Specification:
The first line of the input contains integers *n* and *m* (2<=≤<=*n*,<= *m*<=≤<=100<=000) — the number of the intersections in the Treeland and the number of Famil Door's friends.
Then follow *n*<=-<=1 lines describing bidirectional roads. Each of them contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) — the indices of intersections connected by the *i*-th road.
Last *m* lines of the input describe Famil Door's friends. The *i*-th of these lines contain two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=*u**i*<=≠<=*v**i*) — indices of intersections where the *i*-th friend lives and works.
Output Specification:
For each friend you should print the expected value of pleasure if he will be happy. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
Demo Input:
['4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1\n', '3 3\n1 2\n1 3\n1 2\n1 3\n2 3\n']
Demo Output:
['4.00000000\n3.00000000\n3.00000000\n', '2.50000000\n2.50000000\n3.00000000\n']
Note:
Consider the second sample.
1. Both roads (1, 2) and (2, 3) work, so the expected length if <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ec563337e40cadafa8449c9571eb5b8c7199e10c.png" style="max-width: 100.0%;max-height: 100.0%;"/> 1. Roads (1, 3) and (2, 3) make the second friend happy. Same as for friend 1 the answer is 2.5 1. The only way to make the third friend happy is to add road (2, 3), so the answer is 3
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def bfs(s):
q = [s]
dist = [-1] * (n + 1)
dist[s] = 0
parent = [-1] * (n + 1)
for k in range(n):
i = q[k]
di = dist[i]
for j in G[i]:
if dist[j] == -1:
dist[j] = di + 1
q.append(j)
parent[j] = i
return q, dist, parent
n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
p, dist, parent = bfs(1)
dp = []
dp0 = parent
dp.append(dp0)
while True:
dp1 = [-1] * (n + 1)
for i in range(1, n + 1):
if dp0[i] == -1:
continue
dp1[i] = dp0[dp0[i]]
if max(dp1) < 0:
break
dp0 = dp1
dp.append(dp0)
l = len(dp)
pow2 = [1]
for _ in range(l):
pow2.append(2 * pow2[-1])
cnt1 = [1] * (n + 1)
dp1 = [0] * (n + 1)
for i in p[::-1][:-1]:
j = parent[i]
cnt1[j] += cnt1[i]
dp1[j] += cnt1[i] + dp1[i]
cnt2 = [n - i for i in cnt1]
dp2 = [0] * (n + 1)
for i in p:
c = []
for j in G[i]:
if j ^ parent[i]:
c.append(j)
if not c:
continue
s = dp1[i] + dp2[i] + cnt2[i]
for j in c:
dp2[j] = s - (cnt1[j] + dp1[j])
ans = []
for _ in range(m):
u, v = map(int, input().split())
if dist[u] > dist[v]:
u, v = v, u
d = dist[v] - dist[u]
w = v
for i in range(l):
if not d:
break
if d & pow2[i]:
d ^= pow2[i]
w = dp[i][w]
if u == w:
d = dist[v] - dist[u] - 1
d0 = d + 1
u = v
for i in range(l):
if not d:
break
if d & pow2[i]:
d ^= pow2[i]
u = dp[i][u]
ans0 = (cnt1[v] * dp2[u] + cnt2[u] * dp1[v]) / (cnt2[u] * cnt1[v]) + d0 + 1
else:
x = u
for i in range(l - 1, -1, -1):
if dp[i][x] ^ dp[i][w]:
x, w = dp[i][x], dp[i][w]
d0 = dist[u] + dist[v] - 2 * (dist[w] - 1)
ans0 = (cnt1[v] * dp1[u] + cnt1[u] * dp1[v]) / (cnt1[u] * cnt1[v]) + d0 + 1
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans)))
```
|
292
|
Copying Data
|
Title: Copying Data
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.
More formally, you've got two arrays of integers *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n* of length *n*. Also, you've got *m* queries of two types:
1. Copy the subsegment of array *a* of length *k*, starting from position *x*, into array *b*, starting from position *y*, that is, execute *b**y*<=+<=*q*<==<=*a**x*<=+<=*q* for all integer *q* (0<=≤<=*q*<=<<=*k*). The given operation is correct — both subsegments do not touch unexistent elements. 1. Determine the value in position *x* of array *b*, that is, find value *b**x*.
For each query of the second type print the result — the value of the corresponding element of array *b*.
Input Specification:
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers *a*1,<=*a*2,<=...,<=*a**n* (|*a**i*|<=≤<=109). The third line contains an array of integers *b*1,<=*b*2,<=...,<=*b**n* (|*b**i*|<=≤<=109).
Next *m* lines contain the descriptions of the queries. The *i*-th line first contains integer *t**i* — the type of the *i*-th query (1<=≤<=*t**i*<=≤<=2). If *t**i*<==<=1, then the *i*-th query means the copying operation. If *t**i*<==<=2, then the *i*-th query means taking the value in array *b*. If *t**i*<==<=1, then the query type is followed by three integers *x**i*,<=*y**i*,<=*k**i* (1<=≤<=*x**i*,<=*y**i*,<=*k**i*<=≤<=*n*) — the parameters of the copying query. If *t**i*<==<=2, then the query type is followed by integer *x**i* (1<=≤<=*x**i*<=≤<=*n*) — the position in array *b*.
All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays *a* and *b*.
Output Specification:
For each second type query print the result on a single line.
Demo Input:
['5 10\n1 2 0 -1 3\n3 1 5 -2 0\n2 5\n1 3 3 3\n2 5\n2 4\n2 1\n1 2 1 4\n2 1\n2 4\n1 4 2 1\n2 2\n']
Demo Output:
['0\n3\n-1\n3\n2\n3\n-1\n']
Note:
none
|
```python
import sys
'''
SEGMENT TREE
Assign
'''
class SegmTree():
'''
- modify elements on interval
- get single element
'''
def __init__(self, size):
N = 1
while N < size:
N <<= 1
self.N = N
self.tree = [0] * (2*N)
def modify_range(self, l, r, value):
l += self.N
r += self.N
while l < r:
if l & 1:
self.tree[l] = value
l += 1
if r & 1:
r -= 1
self.tree[r] = value
l >>= 1
r >>= 1
def query(self, i):
i += self.N
latest_change = self.tree[i]
p = i
while p > 1:
p >>= 1
latest_change = max(latest_change, self.tree[p])
return latest_change
# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (map(int, line.split()) for line in sys.stdin)
input = reader.__next__
n, m = input()
a = list(input())
b = list(input())
st = SegmTree(n)
request = [None] * (m + 1)
for i in range(1, m+1):
t, *arg = input()
if t == 1:
x, y, k = request[i] = arg
st.modify_range(y-1, y-1+k, i)
else:
pos = arg[0] - 1
req_id = st.query(pos)
if req_id > 0:
x, y, k = request[req_id]
ans = a[x+(pos-y)]
else:
ans = b[pos]
sys.stdout.write(f'{ans}\n')
# inf.close()
```
|
228
|
The Road to Berland is Paved With Good Intentions
|
Title: The Road to Berland is Paved With Good Intentions
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Berland has *n* cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.
The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.
Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.
Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most *n* days. Help the king.
Input Specification:
The first line contains two space-separated integers *n*,<=*m* — the number of cities and roads in Berland, correspondingly. Next *m* lines contain the descriptions of roads in Berland: the *i*-th line contains three space-separated integers *a**i*,<=*b**i*,<=*c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*; 0<=≤<=*c**i*<=≤<=1). The first two integers (*a**i*,<=*b**i*) are indexes of the cities that are connected by the *i*-th road, the third integer (*c**i*) equals 1, if the road was initially asphalted, and 0 otherwise.
Consider the cities in Berland indexed from 1 to *n*, and the roads indexed from 1 to *m*. It is guaranteed that between two Berlandian cities there is not more than one road.
Output Specification:
In the first line print a single integer *x* (0<=≤<=*x*<=≤<=*n*) — the number of days needed to asphalt all roads. In the second line print *x* space-separated integers — the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them.
If there's no way to asphalt all roads, print "Impossible" (without the quotes).
Demo Input:
['4 4\n1 2 1\n2 4 0\n4 3 1\n3 2 0\n', '3 3\n1 2 0\n2 3 0\n3 1 0\n']
Demo Output:
['4\n3 2 1 3\n', 'Impossible\n']
Note:
none
|
```python
import sys
readline=sys.stdin.readline
def SCC(N,edges):
start = [0] * (N + 1)
elist = [0] * len(edges)
for e in edges:
start[e[0] + 1] += 1
for i in range(1, N + 1):
start[i] += start[i - 1]
counter = start[:]
for e in edges:
elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
N = N
now_ord = group_num = 0
visited = []
low = [0] * N
order = [-1] * N
ids = [0] * N
parent = [-1] * N
stack = []
for i in range(N):
if order[i] == -1:
stack.append(i)
stack.append(i)
while stack:
v = stack.pop()
if order[v] == -1:
low[v] = order[v] = now_ord
now_ord += 1
visited.append(v)
for i in range(start[v], start[v + 1]):
to = elist[i]
if order[to] == -1:
stack.append(to)
stack.append(to)
parent[to] = v
else:
low[v] = min(low[v], order[to])
else:
if low[v] == order[v]:
while True:
u = visited.pop()
order[u] = N
ids[u] = group_num
if u == v:
break
group_num += 1
if parent[v] != -1:
low[parent[v]] = min(low[parent[v]], low[v])
for i, x in enumerate(ids):
ids[i] = group_num - 1 - x
groups = [[] for _ in range(group_num)]
for i, x in enumerate(ids):
groups[x].append(i)
return groups
class TwoSAT:
def __init__(self,N):
self.N=N
self.edges=[]
def Add_Clause(self,i,f,j,g):
assert 0<=i<self.N
assert 0<=j<self.N
self.edges.append((2*i+(0 if f else 1),2*j+(1 if g else 0)))
self.edges.append((2*j+(0 if g else 1),2*i+(1 if f else 0)))
def Satisfiable(self):
scc=SCC(2*self.N,self.edges)
idx=[None]*2*self.N
for i,lst in enumerate(scc):
for x in lst:
idx[x]=i
retu=[None]*self.N
for i in range(self.N):
if idx[2*i]==idx[2*i+1]:
return None
retu[i]=idx[2*i]<idx[2*i+1]
return retu
N,M=map(int,readline().split())
TSAT=TwoSAT(N)
for m in range(M):
a,b,c=map(int,readline().split())
a-=1;b-=1
TSAT.Add_Clause(a,0,b,c)
TSAT.Add_Clause(a,1,b,c^1)
lst=TSAT.Satisfiable()
if lst==None:
print("Impossible")
else:
ans_lst=[n+1 for n in range(N) if not lst[n]]
print(len(ans_lst))
print(*ans_lst)
```
|
960
|
Pathwalks
|
Title: Pathwalks
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a directed graph with *n* nodes and *m* edges, with all edges having a certain weight.
There might be multiple edges and self loops, and the graph can also be disconnected.
You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value.
Please note that the edges picked don't have to be consecutive in the input.
Input Specification:
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=100000,1<=≤<=*m*<=≤<=100000) — the number of vertices and edges in the graph, respectively.
*m* lines follows.
The *i*-th of these lines contains three space separated integers *a**i*, *b**i* and *w**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, 0<=≤<=*w**i*<=≤<=100000), denoting an edge from vertex *a**i* to vertex *b**i* having weight *w**i*
Output Specification:
Print one integer in a single line — the maximum number of edges in the path.
Demo Input:
['3 3\n3 1 3\n1 2 1\n2 3 2\n', '5 5\n1 3 2\n3 2 3\n3 4 5\n5 4 0\n4 5 8\n']
Demo Output:
['2', '3']
Note:
The answer for the first sample input is 2: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/609340f155794c4e9eebcd9cdfa23c73cf982f28.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Note that you cannot traverse <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9b1d1f66686c43090329870c208942499764a73b.png" style="max-width: 100.0%;max-height: 100.0%;"/> because edge <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/030fc9181b578c2d906254d38dc56da5554323eb.png" style="max-width: 100.0%;max-height: 100.0%;"/> appears earlier in the input than the other two edges and hence cannot be picked/traversed after either of the other two edges.
In the second sample, it's optimal to pick 1-st, 3-rd and 5-th edges to get the optimal answer: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bd608e0d11c1e7d39405f62afde4e5a2d18cecf6.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
|
```python
import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v):
return u * z + v
def update(i, x):
i += l1
tree[i] = x
i //= 2
while i:
tree[i] = max(tree[2 * i], tree[2 * i + 1])
i //= 2
return
def get_max(s, t):
s, t = s + l1, t + l1
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, m = map(int, input().split())
abw = [tuple(map(int, input().split())) for _ in range(m)]
z = pow(10, 5) + 5
s = []
for a, b, w in abw:
s.append(f(b, w))
s = list(set(sorted(s)))
s.sort()
l = len(s)
d = dict()
for i in range(l):
d[s[i]] = i
l1 = pow(2, (l + 1).bit_length())
l2 = 2 * l1
tree = [0] * l2
for a, b, w in abw:
l0 = bisect.bisect_left(s, f(a, 0))
r0 = bisect.bisect_left(s, f(a, w)) - 1
update(d[f(b, w)], max(get_max(l0, r0) + 1, tree[d[f(b, w)] + l1]))
ans = tree[1]
print(ans)
```
|
567
|
Mausoleum
|
Title: Mausoleum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2*n* blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1<=×<=1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of *n* meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
- [1,<=2,<=2,<=3,<=4,<=4,<=3,<=1]; - [1,<=1]; - [2,<=2,<=1,<=1]; - [1,<=2,<=3,<=3,<=2,<=1].
Suddenly, *k* more requirements appeared. Each of the requirements has the form: "*h*[*x**i*] sign*i* *h*[*y**i*]", where *h*[*t*] is the height of the *t*-th block, and a sign*i* is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the *k* additional requirements is given by a pair of indexes *x**i*, *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=2*n*) and sign sign*i*.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the *k* additional requirements were met.
Input Specification:
The first line of the input contains integers *n* and *k* (1<=≤<=*n*<=≤<=35, 0<=≤<=*k*<=≤<=100) — the number of pairs of blocks and the number of additional requirements.
Next *k* lines contain listed additional requirements, one per line in the format "*x**i* sign*i* *y**i*" (1<=≤<=*x**i*,<=*y**i*<=≤<=2*n*), and the sign is on of the list of the five possible signs.
Output Specification:
Print the sought number of ways.
Demo Input:
['3 0\n', '3 1\n2 > 3\n', '4 1\n3 = 6\n']
Demo Output:
['9\n', '1\n', '3\n']
Note:
none
|
```python
N, K = map(int, input().split())
rel = [[0] * 75 for _ in range(75)]
dp = [[-1] * 40 for _ in range(75)]
sign = ["=", "<", ">", "<=", ">="]
rev = [0, 2, 1, 4, 3]
rs = [[] for _ in range(75)]
def solve(st, pos):
if pos >= N:
if rel[st][st + 1] == 1 or rel[st][st + 1] == 2:
return 0
return 1
if dp[st][pos] != -1:
return dp[st][pos]
res = 0
en = 2 * N - (2 * pos - st - 1)
fl = 1
p, s = 0, 0
for i in range(len(rs[st])):
p = rs[st][i]
s = rel[st][p]
if p == en or p == st:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
for i in range(len(rs[en])):
p = rs[en][i]
s = rel[en][p]
if p == st or p == en:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
if fl:
res += solve(st + 1, pos + 1)
fl = 1
for i in range(len(rs[st])):
p = rs[st][i]
s = rel[st][p]
if p == st + 1 or p == st:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
for i in range(len(rs[st + 1])):
p = rs[st + 1][i]
s = rel[st + 1][p]
if p == st or p == st + 1:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
if fl:
res += solve(st + 2, pos + 1)
fl = 1
for i in range(len(rs[en - 1])):
p = rs[en - 1][i]
s = rel[en - 1][p]
if p == en or p == en - 1:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
for i in range(len(rs[en])):
p = rs[en][i]
s = rel[en][p]
if p == en - 1 or p == en:
if s == 2 or s == 1:
fl = 0
elif p < st or p > en:
if s != 2 and s != 4:
fl = 0
elif s != 1 and s != 3:
fl = 0
if fl:
res += solve(st, pos + 1)
dp[st][pos] = res
return res
for _ in range(K):
a, s, b = map(str, input().split())
a, b = int(a), int(b)
x = sign.index(s)
rs[a].append(b)
rs[b].append(a)
rel[a][b] = x
rel[b][a] = rev[x]
print(solve(1, 1))# 1693600427.7071342
```
|
159
|
Zebra Tower
|
Title: Zebra Tower
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color *c**i* and size *s**i*. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.
A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
Input Specification:
The first line contains an integer *n* (2<=≤<=*n*<=≤<=105) — the number of cubes. Next *n* lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers *c**i* and *s**i* (1<=≤<=*c**i*,<=*s**i*<=≤<=109) — the *i*-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
Output Specification:
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to *n* in the order in which they were given in the input.
If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Demo Input:
['4\n1 2\n1 3\n2 4\n3 3\n', '2\n1 1\n2 1\n']
Demo Output:
['9\n3\n2 3 1 \n', '2\n2\n2 1 \n']
Note:
none
|
```python
from collections import defaultdict
n=int(input())
g=defaultdict(list)
for i in range(n):
c,s=map(int,input().strip().split())
g[c].append((s,i+1))
pref=defaultdict(list)
for i in g:
g[i].sort(key=lambda s:s[0],reverse=True)
pre=g[i][0][0]
sz=1
pref[sz].append((pre,i))
for id in range(1,len(g[i])):
sz+=1
pre+=g[i][id][0]
pref[sz].append((pre,i))
ans=0
pair=None
# print(pref)
[pref[i].sort(reverse=True) for i in pref]
for i in pref:
if len(pref[i])>=2:
if pref[i][0][0]+pref[i][1][0]>ans:
ans=pref[i][0][0]+pref[i][1][0]
pair=((pref[i][0][1],i),(pref[i][1][1],i)) #id, size of pref taken
if i==1:
continue
i2=i-1
if pref[i2][0][1]==pref[i][0][1]:
if len(pref[i2])>=2:
if pref[i2][1][0]+pref[i][0][0]>ans:
ans=pref[i2][1][0]+pref[i][0][0]
pair=((pref[i2][1][1],i2),(pref[i][0][1],i))
if len(pref[i])>=2:
if pref[i2][0][0] + pref[i][1][0] > ans:
ans = pref[i2][0][0] + pref[i][1][0]
pair = ((pref[i2][0][1], i2), (pref[i][1][1], i))
else:
if pref[i2][0][0] + pref[i][0][0] > ans:
ans = pref[i2][0][0] + pref[i][0][0]
pair = ((pref[i2][0][1], i2), (pref[i][0][1], i))
print(ans)
gen=[]
for col,sz in pair:
gen1=[id for wt,id in g[col][:sz]]
gen.append(gen1)
a,b=sorted(gen,key=len,reverse=True)
print(len(a)+len(b))
while a :
print(a.pop(0),end=" ")
if b:
print(b.pop(0),end=" ")
```
|
288
|
Polo the Penguin and Lucky Numbers
|
Title: Polo the Penguin and Lucky Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Polo the Penguin have two positive integers *l* and *r* (*l*<=<<=*r*), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.
Let's assume that *n* is the number of distinct lucky numbers, each of them cannot be greater than *r* or less than *l*, and *a**i* is the *i*-th (in increasing order) number of them. Find *a*1·*a*2<=+<=*a*2·*a*3<=+<=...<=+<=*a**n*<=-<=1·*a**n*. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109<=+<=7).
Input Specification:
The first line contains a positive integer *l*, and the second line contains a positive integer *r* (1<=≤<=*l*<=<<=*r*<=≤<=10100000). The numbers are given without any leading zeroes.
It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.
Output Specification:
In the single line print a single integer — the answer to the problem modulo 1000000007 (109<=+<=7).
Demo Input:
['4\n7\n', '474\n777\n']
Demo Output:
['28\n', '2316330\n']
Note:
none
|
```python
mod = 1000000007
N = 100000
two = [0] * (N + 1)
ten = [0] * (N + 1)
four = [0] * (N + 1)
seven = [0] * (N + 1)
prod = [0] * (N + 1)
sum_val = [0] * (N + 1)
Prod = [0] * (N + 1)
lar = [0] * (N + 1)
dp = [[False, False] for _ in range(N + 1)]
pa = [[-1, -1] for _ in range(N + 1)]
def init():
two[0] = ten[0] = 1
for i in range(1, N + 1):
two[i] = 2 * two[i - 1] % mod
ten[i] = 10 * ten[i - 1] % mod
for i in range(1, N + 1):
four[i] = (10 * four[i - 1] + 4) % mod
seven[i] = (10 * seven[i - 1] + 7) % mod
prod[1] = Prod[1] = 28
sum_val[1] = 11
for i in range(2, N + 1):
prod[i] = (prod[i - 1] + 4 * ten[i - 1] % mod * (2 * sum_val[i - 1] - four[i - 1] - seven[i - 1]) % mod + 4 * ten[i - 1] % mod * 4 * ten[i - 1] % mod * (two[i - 1] - 1) + prod[i - 1] + 7 * ten[i - 1] % mod * (2 * sum_val[i - 1] - four[i - 1] - seven[i - 1]) % mod + 7 * ten[i - 1] % mod * 7 * ten[i - 1] % mod * (two[i - 1] - 1) + (4 * ten[i - 1] + seven[i - 1]) % mod * (7 * ten[i - 1] + four[i - 1]) % mod) % mod
sum_val[i] = (2 * sum_val[i - 1] + 11 * ten[i - 1] % mod * two[i - 1] % mod) % mod
Prod[i] = (Prod[i - 1] + prod[i] + seven[i - 1] * four[i] % mod) % mod
def sol(n, s):
global pa, dp, lar
pa = [[-1, -1] for _ in range(N + 1)]
dp = [[False, False] for _ in range(N + 1)]
if s[n - 1] >= '4':
dp[n - 1][0] = True
if s[n - 1] >= '7':
dp[n - 1][1] = True
for i in range(n - 2, -1, -1):
if s[i] >= '4':
if dp[i + 1][1]:
dp[i][0] = True
pa[i][0] = 1
elif dp[i + 1][0]:
dp[i][0] = True
pa[i][0] = 0
if s[i] >= '7':
if dp[i + 1][1]:
dp[i][1] = True
pa[i][1] = 1
elif dp[i + 1][0]:
dp[i][1] = True
pa[i][1] = 0
now = 1 if dp[0][1] else 0 if dp[0][0] else -1
lar[0] = now
for i in range(1, n):
now = pa[i - 1][now]
lar[i] = now
ans = Prod[n - 1]
if now == -1:
return ans
now = 0
las = 0
if n > 1:
las = seven[n - 2]
for i in range(n):
head = (10 * now + 4) % mod * ten[n - i - 1] % mod
if lar[i] == 1:
ans = (ans + las * (head + four[n - i - 1]) % mod + prod[n - i - 1] + head * (2 * sum_val[n - i - 1] - four[n - i - 1] - seven[n - i - 1]) % mod + head * head % mod * (two[n - i - 1] - 1) % mod) % mod
las = (head + seven[n - i - 1]) % mod
now = (10 * now + (4 if lar[i] == 0 else 7)) % mod
ans = (ans + las * now) % mod
return ans
def main():
init()
a = input()
b = input()
na = len(a)
nb = len(b)
result = ((sol(nb, b) - sol(na, a)) % mod + mod) % mod
print(result)
if __name__ == "__main__":
main()
```
|
811
|
Vladik and Entertaining Flags
|
Title: Vladik and Entertaining Flags
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In his spare time Vladik estimates beauty of the flags.
Every flag could be represented as the matrix *n*<=×<=*m* which consists of positive integers.
Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components:
But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1,<=*l*) and (*n*,<=*r*), where conditions 1<=≤<=*l*<=≤<=*r*<=≤<=*m* are satisfied.
Help Vladik to calculate the beauty for some segments of the given flag.
Input Specification:
First line contains three space-separated integers *n*, *m*, *q* (1<=≤<=*n*<=≤<=10, 1<=≤<=*m*,<=*q*<=≤<=105) — dimensions of flag matrix and number of segments respectively.
Each of next *n* lines contains *m* space-separated integers — description of flag matrix. All elements of flag matrix is positive integers not exceeding 106.
Each of next *q* lines contains two space-separated integers *l*, *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*m*) — borders of segment which beauty Vladik wants to know.
Output Specification:
For each segment print the result on the corresponding line.
Demo Input:
['4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5\n']
Demo Output:
['6\n7\n3\n4\n']
Note:
Partitioning on components for every segment from first test case:
<img class="tex-graphics" src="https://espresso.codeforces.com/5c89ff7036ddb39d2997c8f594d4a0729e524ab0.png" style="max-width: 100.0%;max-height: 100.0%;"/>
|
```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
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):
s, t = get_root(s), get_root(t)
if s == t:
return
if rank[s] < rank[t]:
s, t = t, s
if rank[s] == rank[t]:
rank[s] += 1
root[t] = s
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def get_segment(s, t):
s, t = s + l1, t + l1
u, v = [], []
while s <= t:
if s & 1:
u.append(s)
s += 1
s >>= 1
if not t & 1:
v.append(t)
t -= 1
t >>= 1
return u + v[::-1]
n, m, q = map(int, input().split())
l1 = pow(2, (m + 1).bit_length())
l2 = 2 * l1
a = [0] * (n * l2)
for i in range(n):
a0 = list(map(int, input().split()))
for j in range(m):
a[f(j, i)] = a0[j]
root = [i for i in range(n * l1)]
rank = [1 for _ in range(n * l1)]
l0, r0 = [0] * l2, [0] * l2
ll, rr = [0] * (n * l2), [0] * (n * l2)
cnt = [0] * l2
for i in range(l1):
c = n
for j in range(n - 1):
u, v = f(i, j), f(i, j + 1)
if a[u] == a[v] and not same(u, v):
unite(u, v)
c -= 1
for j in range(n):
u, v = f(i + l1, j), get_root(f(i, j))
ll[u], rr[u] = v, v
l0[i + l1], r0[i + l1] = i, i
cnt[i + l1] = c
for i in range(l1 - 1, 0, -1):
c = cnt[2 * i] + cnt[2 * i + 1]
l, r = r0[2 * i], l0[2 * i + 1]
for j in range(n):
u, v = f(l, j), f(r, j)
if a[u] == a[v] and not same(u, v):
unite(u, v)
c -= 1
l, r = l0[2 * i], r0[2 * i + 1]
for j in range(n):
u = f(i, j)
ll[u], rr[u] = get_root(f(l, j)), get_root(f(r, j))
l0[i], r0[i] = l, r
cnt[i] = c
ans = [0] * q
root = [i for i in range(n * l1)]
rank = [1 for _ in range(n * l1)]
for q0 in range(q):
l, r = map(int, input().split())
x = get_segment(l - 1, r - 1)
ans0 = cnt[x[0]]
for i in range(len(x) - 1):
l, r = x[i], x[i + 1]
ans0 += cnt[r]
for j in range(n):
u, v = rr[f(l, j)], ll[f(r, j)]
if a[u] == a[v] and not same(u, v):
unite(u, v)
ans0 -= 1
ans[q0] = ans0
for i in x:
for j in range(n):
u, v = ll[f(i, j)], rr[f(i, j)]
root[u], root[v] = u, v
rank[u], rank[v] = 1, 1
sys.stdout.write("\n".join(map(str, ans)))
```
|
869
|
The Untended Antiquity
|
Title: The Untended Antiquity
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Adieu l'ami.
Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.
The space is represented by a rectangular grid of *n*<=×<=*m* cells, arranged into *n* rows and *m* columns. The *c*-th cell in the *r*-th row is denoted by (*r*,<=*c*).
Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by "1 *r*1 *c*1 *r*2 *c*2" means Oshino's placing barriers around a rectangle with two corners being (*r*1,<=*c*1) and (*r*2,<=*c*2) and sides parallel to squares sides. Similarly, "2 *r*1 *c*1 *r*2 *c*2" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the *n*<=×<=*m* area.
Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "3 *r*1 *c*1 *r*2 *c*2" means that Koyomi tries to walk from (*r*1,<=*c*1) to (*r*2,<=*c*2) without crossing barriers.
And you're here to tell Koyomi the feasibility of each of his attempts.
Input Specification:
The first line of input contains three space-separated integers *n*, *m* and *q* (1<=≤<=*n*,<=*m*<=≤<=2<=500, 1<=≤<=*q*<=≤<=100<=000) — the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively.
The following *q* lines each describes an action, containing five space-separated integers *t*, *r*1, *c*1, *r*2, *c*2 (1<=≤<=*t*<=≤<=3, 1<=≤<=*r*1,<=*r*2<=≤<=*n*, 1<=≤<=*c*1,<=*c*2<=≤<=*m*) — the type and two coordinates of an action. Additionally, the following holds depending on the value of *t*:
- If *t*<==<=1: 2<=≤<=*r*1<=≤<=*r*2<=≤<=*n*<=-<=1, 2<=≤<=*c*1<=≤<=*c*2<=≤<=*m*<=-<=1; - If *t*<==<=2: 2<=≤<=*r*1<=≤<=*r*2<=≤<=*n*<=-<=1, 2<=≤<=*c*1<=≤<=*c*2<=≤<=*m*<=-<=1, the specified group of barriers exist on the ground before the removal. - If *t*<==<=3: no extra restrictions.
Output Specification:
For each of Koyomi's attempts (actions with *t*<==<=3), output one line — containing "Yes" (without quotes) if it's feasible, and "No" (without quotes) otherwise.
Demo Input:
['5 6 5\n1 2 2 4 5\n1 3 3 3 3\n3 4 4 1 1\n2 2 2 4 5\n3 1 1 4 4\n', '2500 2500 8\n1 549 1279 1263 2189\n1 303 795 1888 2432\n1 2227 622 2418 1161\n3 771 2492 1335 1433\n1 2017 2100 2408 2160\n3 48 60 798 729\n1 347 708 1868 792\n3 1940 2080 377 1546\n']
Demo Output:
['No\nYes\n', 'No\nYes\nNo\n']
Note:
For the first example, the situations of Koyomi's actions are illustrated below.
|
```python
import random
g = {}
n, m, q = map(int, input().split())
c = [[0] * 2520 for _ in range(2520)]
def R(x, y, z):
i = x
while i <= n:
j = y
while j <= m:
c[i][j] += z
j += j & -j
i += i & -i
def G(x, y):
re = 0
i = x
while i > 0:
j = y
while j > 0:
re += c[i][j]
j -= j & -j
i -= i & -i
return re
def rd():
return random.randint(0, (1 << 30) - 1)
for _ in range(11):
random.seed(rd())
for _ in range(q):
o, xa, ya, xb, yb = map(int, input().split())
if o == 1:
u = rd()
g[((xa, ya), (xb, yb))] = u
R(xa, ya, u)
R(xa, yb + 1, -u)
R(xb + 1, ya, -u)
R(xb + 1, yb + 1, u)
elif o == 2:
u = g.get(((xa, ya), (xb, yb)), 0)
R(xa, ya, -u)
R(xa, yb + 1, u)
R(xb + 1, ya, u)
R(xb + 1, yb + 1, -u)
else:
va = G(xa, ya)
vb = G(xb, yb)
if va == vb:
print("Yes")
else:
print("No")# 1693743640.2748132
```
|
492
|
Vanya and Field
|
Title: Vanya and Field
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya decided to walk in the field of size *n*<=×<=*n* cells. The field contains *m* apple trees, the *i*-th apple tree is at the cell with coordinates (*x**i*,<=*y**i*). Vanya moves towards vector (*dx*,<=*dy*). That means that if Vanya is now at the cell (*x*,<=*y*), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both *a* and *b*. Vanya ends his path when he reaches the square he has already visited.
Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
Input Specification:
The first line contains integers *n*,<=*m*,<=*dx*,<=*dy*(1<=≤<=*n*<=≤<=106, 1<=≤<=*m*<=≤<=105, 1<=≤<=*dx*,<=*dy*<=≤<=*n*) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next *m* lines contain integers *x**i*,<=*y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=*n*<=-<=1) — the coordinates of apples. One cell may contain multiple apple trees.
Output Specification:
Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
Demo Input:
['5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1\n', '2 3 1 1\n0 0\n0 1\n1 1\n']
Demo Output:
['1 3\n', '0 0\n']
Note:
In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)
In the second sample: (0, 0) - (1, 1) - (0, 0)
|
```python
f = lambda: map(int, input().split())
n, m, dx, dy = f()
p = [0] * n
for i in range(n): p[dx * i % n] = i
s = [0] * n
for j in range(m):
x, y = f()
s[(y - dy * p[x]) % n] += 1
print(0, s.index(max(s)))
```
|
631
|
Product Sum
|
Title: Product Sum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.
You are given an array *a* of length *n*. The characteristic of this array is the value — the sum of the products of the values *a**i* by *i*. One may perform the following operation exactly once: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.
Input Specification:
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=200<=000) — the size of the array *a*.
The second line contains *n* integers *a**i* (1<=≤<=*i*<=≤<=*n*, |*a**i*|<=≤<=1<=000<=000) — the elements of the array *a*.
Output Specification:
Print a single integer — the maximum possible value of characteristic of *a* that can be obtained by performing no more than one move.
Demo Input:
['4\n4 3 2 5\n', '5\n1 1 2 7 1\n', '3\n1 1 2\n']
Demo Output:
['39', '49', '9']
Note:
In the first sample, one may pick the first element and place it before the third (before 5). Thus, the answer will be 3·1 + 2·2 + 4·3 + 5·4 = 39.
In the second sample, one may pick the fifth element of the array and place it before the third. The answer will be 1·1 + 1·2 + 1·3 + 2·4 + 7·5 = 49.
|
```python
from sys import stdin, stdout
def calculate(m0,c0,m1,c1):
return (c0-c1)/(m1-m0)
n = int(stdin.readline())
A = [int(x) for x in stdin.readline().split()]
sigma = [0]
for i in range(n-1):
sigma.append(sigma[-1]+A[i])
running_sum = sum([A[i]*(i+1) for i in range(n)])
answer = 0
line_stack = [(0,0)]
segment_lefts = [-1000000]
pointer = 0
for i in range(1,n-1):
answer = max(answer, line_stack[pointer][0]*A[i]+line_stack[pointer][1]-A[i]*i+sigma[i])
while len(line_stack) > 0 and calculate(line_stack[-1][0], line_stack[-1][1], i, -sigma[i]) <= segment_lefts[-1]:
line_stack.pop()
segment_lefts.pop()
if len(line_stack) == 0:
segment_lefts.append(-1000000)
else:
segment_lefts.append(calculate(line_stack[-1][0], line_stack[-1][1], i, -sigma[i]))
line_stack.append((i, -sigma[i]))
lower = 0
upper = len(line_stack)
while upper - lower > 1:
candidate = (upper + lower)//2
if segment_lefts[candidate] > A[i+1]:
upper = candidate
else:
lower = candidate
pointer = lower
answer = max(answer, line_stack[pointer][0]*A[n-1]+line_stack[pointer][1]-A[n-1]*(n-1)+sigma[n-1])
sigma = [0]
for i in range(n-1,0,-1):
sigma.append(sigma[-1]+A[i])
line_stack = [(-(n-1),0)]
segment_lefts = [-1000000]
pointer = 0
for i in range(n-2,0,-1):
answer = max(answer, line_stack[pointer][0]*(-A[i])+line_stack[pointer][1]-A[i]*i-sigma[n-1-i])
while len(line_stack) > 0 and calculate(line_stack[-1][0], line_stack[-1][1], -i, sigma[n-1-i]) <= segment_lefts[-1]:
line_stack.pop()
segment_lefts.pop()
if len(line_stack) == 0:
segment_lefts.append(-1000000)
else:
segment_lefts.append(calculate(line_stack[-1][0], line_stack[-1][1], -i, sigma[n-1-i]))
line_stack.append((-i, sigma[n-1-i]))
lower = 0
upper = len(line_stack)
while upper - lower > 1:
candidate = (upper + lower)//2
if segment_lefts[candidate] > -A[i-1]:
upper = candidate
else:
lower = candidate
pointer = lower
answer = max(answer, line_stack[pointer][0]*(-A[0])+line_stack[pointer][1]-sigma[n-1])
true_answer = answer + running_sum
stdout.write('{}\n'.format(true_answer))
```
|
765
|
Tree Folding
|
Title: Tree Folding
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex *v*, and two disjoint (except for *v*) paths of equal length *a*0<==<=*v*, *a*1, ..., *a**k*, and *b*0<==<=*v*, *b*1, ..., *b**k*. Additionally, vertices *a*1, ..., *a**k*, *b*1, ..., *b**k* must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices *b*1, ..., *b**k* can be effectively erased:
Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.
Input Specification:
The first line of input contains the number of vertices *n* (2<=≤<=*n*<=≤<=2·105).
Next *n*<=-<=1 lines describe edges of the tree. Each of these lines contains two space-separated integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.
Output Specification:
If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.
Demo Input:
['6\n1 2\n2 3\n2 4\n4 5\n1 6\n', '7\n1 2\n1 3\n3 4\n1 5\n5 6\n6 7\n']
Demo Output:
['3\n', '-1\n']
Note:
In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.
It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
G = [set() for _ in range(n + 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
G[u].add(v)
G[v].add(u)
q = []
x = [set() for _ in range(n + 1)]
cnt = [len(g) for g in G]
for i in range(1, n + 1):
if cnt[i] == 1:
q.append(i)
x[i].add(0)
k = 0
ans = n - 1
while len(q) ^ k and k < n - 1:
i = q[k]
u = x[i].pop()
j = G[i].pop()
G[j].remove(i)
if u + 1 in x[j] or not len(x[j]):
cnt[j] -= 1
if u + 1 in x[j]:
ans -= u + 1
x[j].add(u + 1)
if len(x[j]) == 1 and cnt[j] == 1:
q.append(j)
k += 1
c = 0
for y in x:
if len(y) >= 3:
ans = -1
elif len(y):
c += 1
if c ^ 1:
ans = -1
while not ans % 2:
ans //= 2
print(ans)
```
|
325
|
The Red Button
|
Title: The Red Button
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of *n* nodes, numbered from 0 to *n* - 1. In order to deactivate the button, the *n* nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node *i*, the next node to be disarmed must be either node (2·*i*) modulo *n* or node (2·*i*)<=+<=1 modulo *n*. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input Specification:
Input consists of a single integer *n* (2<=≤<=*n*<=≤<=105).
Output Specification:
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Demo Input:
['2\n', '3\n', '4\n', '16\n']
Demo Output:
['0 1 0\n', '-1', '0 1 3 2 0\n', '0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0\n']
Note:
none
|
```python
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
```
|
580
|
Kefa and Watch
|
Title: Kefa and Watch
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money.
The pawnbroker said that each watch contains a serial number represented by a string of digits from 0 to 9, and the more quality checks this number passes, the higher is the value of the watch. The check is defined by three positive integers *l*, *r* and *d*. The watches pass a check if a substring of the serial number from *l* to *r* has period *d*. Sometimes the pawnbroker gets distracted and Kefa changes in some substring of the serial number all digits to *c* in order to increase profit from the watch.
The seller has a lot of things to do to begin with and with Kefa messing about, he gave you a task: to write a program that determines the value of the watch.
Let us remind you that number *x* is called a period of string *s* (1<=≤<=*x*<=≤<=|*s*|), if *s**i*<=<==<=<=*s**i*<=+<=*x* for all *i* from 1 to |*s*|<=<=-<=<=*x*.
Input Specification:
The first line of the input contains three positive integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=+<=*k*<=≤<=105) — the length of the serial number, the number of change made by Kefa and the number of quality checks.
The second line contains a serial number consisting of *n* digits.
Then *m*<=+<=*k* lines follow, containing either checks or changes.
The changes are given as 1 *l* *r* *c* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, 0<=≤<=*c*<=≤<=9). That means that Kefa changed all the digits from the *l*-th to the *r*-th to be *c*.
The checks are given as 2 *l* *r* *d* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*, 1<=≤<=*d*<=≤<=*r*<=-<=*l*<=+<=1).
Output Specification:
For each check on a single line print "YES" if the watch passed it, otherwise print "NO".
Demo Input:
['3 1 2\n112\n2 2 3 1\n1 1 3 8\n2 1 2 1\n', '6 2 3\n334934\n2 2 5 2\n1 4 4 3\n2 1 6 3\n1 2 3 8\n2 3 6 1\n']
Demo Output:
['NO\nYES\n', 'NO\nYES\nNO\n']
Note:
In the first sample test two checks will be made. In the first one substring "12" is checked on whether or not it has period 1, so the answer is "NO". In the second one substring "88", is checked on whether or not it has period 1, and it has this period, so the answer is "YES".
In the second statement test three checks will be made. The first check processes substring "3493", which doesn't have period 2. Before the second check the string looks as "334334", so the answer to it is "YES". And finally, the third check processes substring "8334", which does not have period 1.
|
```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, False
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
class LazySegTree:
def __init__(
self,
op: typing.Callable[[typing.Any, typing.Any], typing.Any],
e: typing.Any,
mapping: typing.Callable[[typing.Any, typing.Any], typing.Any],
composition: typing.Callable[[typing.Any, typing.Any], typing.Any],
id_: typing.Any,
v: typing.Union[int, typing.List[typing.Any]]) -> None:
self._op = op
self._e = e
self._mapping = mapping
self._composition = composition
self._id = id_
if isinstance(v, int):
v = [e] * v
self._n = len(v)
self._log = (self._n - 1).bit_length()
self._size = 1 << self._log
self._d = [e] * (2 * self._size)
self._lz = [self._id] * self._size
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: int, x: typing.Any) -> None:
assert 0 <= 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: int) -> typing.Any:
assert 0 <= 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, left: int, right: int) -> typing.Any:
assert 0 <= left <= right <= self._n
if left == right:
return self._e
left += self._size
right += self._size
for i in range(self._log, 0, -1):
if ((left >> i) << i) != left:
self._push(left >> i)
if ((right >> i) << i) != right:
self._push(right >> i)
sml = self._e
smr = self._e
while left < right:
if left & 1:
sml = self._op(sml, self._d[left])
left += 1
if right & 1:
right -= 1
smr = self._op(self._d[right], smr)
left >>= 1
right >>= 1
return self._op(sml, smr)
def all_prod(self) -> typing.Any:
return self._d[1]
def apply(self, left: int, right: typing.Optional[int] = None,
f: typing.Optional[typing.Any] = None) -> None:
assert f is not None
if right is None:
p = left
assert 0 <= left < 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)
else:
assert 0 <= left <= right <= self._n
if left == right:
return
left += self._size
right += self._size
for i in range(self._log, 0, -1):
if ((left >> i) << i) != left:
self._push(left >> i)
if ((right >> i) << i) != right:
self._push((right - 1) >> i)
l2 = left
r2 = right
while left < right:
if left & 1:
self._all_apply(left, f)
left += 1
if right & 1:
right -= 1
self._all_apply(right, f)
left >>= 1
right >>= 1
left = l2
right = r2
for i in range(1, self._log + 1):
if ((left >> i) << i) != left:
self._update(left >> i)
if ((right >> i) << i) != right:
self._update((right - 1) >> i)
def max_right(
self, left: int, g: typing.Callable[[typing.Any], bool]) -> int:
assert 0 <= left <= self._n
assert g(self._e)
if left == self._n:
return self._n
left += self._size
for i in range(self._log, 0, -1):
self._push(left >> i)
sm = self._e
first = True
while first or (left & -left) != left:
first = False
while left % 2 == 0:
left >>= 1
if not g(self._op(sm, self._d[left])):
while left < self._size:
self._push(left)
left *= 2
if g(self._op(sm, self._d[left])):
sm = self._op(sm, self._d[left])
left += 1
return left - self._size
sm = self._op(sm, self._d[left])
left += 1
return self._n
def min_left(self, right: int, g: typing.Any) -> int:
assert 0 <= right <= self._n
assert g(self._e)
if right == 0:
return 0
right += self._size
for i in range(self._log, 0, -1):
self._push((right - 1) >> i)
sm = self._e
first = True
while first or (right & -right) != right:
first = False
right -= 1
while right > 1 and right % 2:
right >>= 1
if not g(self._op(self._d[right], sm)):
while right < self._size:
self._push(right)
right = 2 * right + 1
if g(self._op(self._d[right], sm)):
sm = self._op(self._d[right], sm)
right -= 1
return right + 1 - self._size
sm = self._op(self._d[right], sm)
return 0
def _update(self, k: int) -> None:
self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])
def _all_apply(self, k: int, f: typing.Any) -> None:
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: int) -> None:
self._all_apply(2 * k, self._lz[k])
self._all_apply(2 * k + 1, self._lz[k])
self._lz[k] = self._id
n, m, k = MII()
q = m + k
mod = random.getrandbits(32)
pow10 = [1] * (n + 1)
for i in range(1, n + 1):
pow10[i] = pow10[i-1] * 10 % mod
pow10_acc = list(accumulate(pow10, initial=0))
for i in range(n + 1):
pow10_acc[i] %= mod
mask = (1 << 32) - 1
def op(x, y):
l1, v1 = x >> 32, x & mask
l2, v2 = y >> 32, y & mask
l = l1 + l2
v = (v1 * pow10[l2] + v2) % mod
return l << 32 | v
def mapping(f, x):
if f == -1: return x
l = x >> 32
return l << 32 | (pow10_acc[l] * f % mod)
def composition(f1, f2):
return f2 if f1 == -1 else f1
seg = LazySegTree(op, 0, mapping, composition, -1, [int(x) + mask + 1 for x in I()])
for _ in range(q):
t, l, r, x = GMI()
x += 1
if t: print('YES' if seg.prod(l, r-x+1) == seg.prod(l+x, r+1) else 'NO')
else: seg.apply(l, r + 1, x)
```
|
313
|
Ilya and Roads
|
Title: Ilya and Roads
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as *n* holes in a row. We will consider the holes numbered from 1 to *n*, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least *k* holes (perharps he can fix more) on a single ZooVille road.
The city has *m* building companies, the *i*-th company needs *c**i* money units to fix a road segment containing holes with numbers of at least *l**i* and at most *r**i*. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.
Determine the minimum money Ilya will need to fix at least *k* holes.
Input Specification:
The first line contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*<=≤<=300,<=1<=≤<=*m*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*). The next *m* lines contain the companies' description. The *i*-th line contains three integers *l**i*,<=*r**i*,<=*c**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*,<=1<=≤<=*c**i*<=≤<=109).
Output Specification:
Print a single integer — the minimum money Ilya needs to fix at least *k* holes.
If it is impossible to fix at least *k* holes, print -1.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['10 4 6\n7 9 11\n6 9 13\n7 7 7\n3 5 6\n', '10 7 1\n3 4 15\n8 9 8\n5 6 8\n9 10 6\n1 4 2\n1 4 10\n8 10 13\n', '10 1 9\n5 10 14\n']
Demo Output:
['17\n', '2\n', '-1\n']
Note:
none
|
```python
INF = 10**18
n, m, k = map(int, input().split())
cost = [[INF]*(n+1) for i in range(n+1)]
dp = [[INF]*(n+1) for i in range(n+1)]
for i in range(m):
l, r, c = map(int, input().split())
for j in range(l, r+1):
cost[j][r] = min(cost[j][r], c)
dp[0][0] = 0
for i in range(n):
for j in range(k+1):
dp[i+1][j] = min(dp[i+1][j], dp[i][j])
for len in range(n+1):
if i+len <= n and j+len <= k:
dp[i+len][j+len] = min(dp[i+len][j+len], dp[i][j] + cost[i+1][i+len])
if dp[n][k] == INF : print(-1)
else : print(dp[n][k])
```
|
919
|
A Game With Numbers
|
Title: A Game With Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Imagine that Alice is playing a card game with her friend Bob. They both have exactly $8$ cards and there is an integer on each card, ranging from $0$ to $4$. In each round, Alice or Bob in turns choose two cards from different players, let them be $a$ and $b$, where $a$ is the number on the player's card, and $b$ is the number on the opponent's card. It is necessary that $a \cdot b \ne 0$. Then they calculate $c = (a + b) \bmod 5$ and replace the number $a$ with $c$. The player who ends up with numbers on all $8$ cards being $0$, wins.
Now Alice wants to know who wins in some situations. She will give you her cards' numbers, Bob's cards' numbers and the person playing the first round. Your task is to determine who wins if both of them choose the best operation in their rounds.
Input Specification:
The first line contains one positive integer $T$ ($1 \leq T \leq 100\,000$), denoting the number of situations you need to consider.
The following lines describe those $T$ situations. For each situation:
- The first line contains a non-negative integer $f$ ($0 \leq f \leq 1$), where $f = 0$ means that Alice plays first and $f = 1$ means Bob plays first. - The second line contains $8$ non-negative integers $a_1, a_2, \ldots, a_8$ ($0 \leq a_i \leq 4$), describing Alice's cards. - The third line contains $8$ non-negative integers $b_1, b_2, \ldots, b_8$ ($0 \leq b_i \leq 4$), describing Bob's cards.
We guarantee that if $f=0$, we have $\sum_{i=1}^{8}a_i \ne 0$. Also when $f=1$, $\sum_{i=1}^{8}b_i \ne 0$ holds.
Output Specification:
Output $T$ lines. For each situation, determine who wins. Output
- "Alice" (without quotes) if Alice wins. - "Bob" (without quotes) if Bob wins. - "Deal" (without quotes) if it gets into a deal, i.e. no one wins.
Demo Input:
['4\n1\n0 0 0 0 0 0 0 0\n1 2 3 4 1 2 3 4\n1\n0 0 0 1 0 0 0 0\n0 0 0 0 4 0 0 0\n0\n1 0 0 0 0 0 0 0\n0 0 0 4 0 0 2 0\n1\n1 1 1 1 1 1 1 1\n1 1 1 1 1 1 1 1\n']
Demo Output:
['Alice\nBob\nAlice\nDeal\n']
Note:
In the first situation, Alice has all her numbers $0$. So she wins immediately.
In the second situation, Bob picks the numbers $4$ and $1$. Because we have $(4 + 1) \bmod 5 = 0$, Bob wins after this operation.
In the third situation, Alice picks the numbers $1$ and $4$. She wins after this operation.
In the fourth situation, we can prove that it falls into a loop.
|
```python
# My Solution for CF 919/F.
import sys
import itertools
from collections import deque
t = int(input())
hand_size = 8
num_values = 5
res = 1
for x in range(hand_size + 1, hand_size + num_values):
res *= x
for x in range(1, num_values):
res //= x
# res = (handsize + numvalues - 1) choose (handsize)
counts = [0] * res * 5
# Precompute the possible winning/losing locations.
# First, generate the possible hand values, and turn them into integers.
m = {}
for i, v in enumerate(itertools.combinations(range(hand_size + num_values - 1), num_values - 1)):
prev = -1
ind = 0
for x in v:
counts[i * 5 + ind] = x - prev - 1
prev = x
ind += 1
counts[i * 5 + ind] = hand_size + num_values - prev - 2
m[tuple(counts[i*5:i*5+5])] = i
# 0 = DEAL
# 1 = WIN
# -1 = LOSE
CURRENT_STATUS = [0] * (res * res)
DEG = [0] * (res * res)
# Now, any vertex is just two numbers, ranging from 0 to res-1.
# We assume for a particular node that it is my turn.
# Then in the recursion we simply invert at each opportunity.
decided_queue = deque()
win_index = m[(hand_size, 0, 0, 0, 0)]
for i in range(res):
if i != win_index:
decided_queue.append(win_index * res + i)
CURRENT_STATUS[win_index * res + i] = 1
decided_queue.append(i * res + win_index)
CURRENT_STATUS[i * res + win_index] = -1
for i in range(res * res):
id1 = i // res
id2 = i % res
# What choices can I make as id1?
n_options_l = 0
for x in range(1, 5):
if counts[id1 * 5 + x] > 0:
n_options_l += 1
n_options_r = 0
for x in range(1, 5):
if counts[id2 * 5 + x] > 0:
n_options_r += 1
DEG[i] = n_options_l * n_options_r
p = [False] * (res * res)
parent = [-1] * (res * res)
while len(decided_queue) > 0:
index = decided_queue.pop()
if p[index]:
raise ValueError("Cycle bad.")
p[index] = True
# Check all possible inroads to this state.
# Which of the cards could've p2 just made?
id1 = index // res
id2 = index % res
for x in range(5):
if counts[id2 * 5 + x] > 0:
# We could've made this card.
# But what would the card have been / what of my cards should they have picked?
for y in range(1, 5):
if counts[id1 * 5 + y] > 0:
# They could've picked this card.
# x = y + z mod 5. So z = x - y mod 5.
z = (x - y) % 5
if z == 0:
continue
n_count = [counts[id2 * 5 + i] for i in range(5)]
n_count[x] -= 1
n_count[z] += 1
old_id2 = m[tuple(n_count)]
# Remember to flip
old_index = old_id2 * res + id1
if CURRENT_STATUS[old_index] == 0:
DEG[old_index] -= 1
if CURRENT_STATUS[index] == -1:
# If the other player is winning here, they can move here to win.
CURRENT_STATUS[old_index] = 1
decided_queue.append(old_index)
parent[old_index] = index
else:
if DEG[old_index] == 0:
# We've tried every edge and all of them are winning for me, so losing for the person above.
CURRENT_STATUS[old_index] = -1
decided_queue.append(old_index)
parent[old_index] = index
for case in range(t):
f = int(input())
alice_hand = tuple(map(int, input().split()))
c = [0] * num_values
for h in alice_hand:
c[h] += 1
alice = m[tuple(c)]
bob_hand = tuple(map(int, input().split()))
c = [0] * num_values
for h in bob_hand:
c[h] += 1
bob = m[tuple(c)]
if f == 0:
index = alice * res + bob
if CURRENT_STATUS[index] == 0:
print("Deal")
elif CURRENT_STATUS[index] == 1:
print("Alice")
else:
print("Bob")
else:
index = bob * res + alice
if CURRENT_STATUS[index] == 0:
print("Deal")
elif CURRENT_STATUS[index] == 1:
print("Bob")
else:
print("Alice")
```
|
489
|
Special Matrices
|
Title: Special Matrices
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
An *n*<=×<=*n* square matrix is special, if:
- it is binary, that is, each cell contains either a 0, or a 1; - the number of ones in each row and column equals 2.
You are given *n* and the first *m* rows of the matrix. Print the number of special *n*<=×<=*n* matrices, such that the first *m* rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number *mod*.
Input Specification:
The first line of the input contains three integers *n*, *m*, *mod* (2<=≤<=*n*<=≤<=500, 0<=≤<=*m*<=≤<=*n*, 2<=≤<=*mod*<=≤<=109). Then *m* lines follow, each of them contains *n* characters — the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given *m*<=×<=*n* table contains at most two numbers one.
Output Specification:
Print the remainder after dividing the required value by number *mod*.
Demo Input:
['3 1 1000\n011\n', '4 4 100500\n0110\n1010\n0101\n1001\n']
Demo Output:
['2\n', '1\n']
Note:
For the first test the required matrices are:
In the second test the required matrix is already fully given, so the answer is 1.
|
```python
n,m,M=[int(e) for e in input().split()]
c=[2]*n
for i in range(m):
a=[int(e) for e in input()]
for j in range(n):
c[j]-=a[j]
def C(n,k):
if k>n or n<0 or k<0:
return 0
res=1
for i in range(n-k+1, n+1):
res*=i
for i in range(1, k+1):
res//=i
return res
F={}
def f(k1, k2):
if k1==0 and k2==0:
return 1
if (k1,k2) in F.keys():
return F[(k1,k2)]
F[(k1,k2)]=( (C(k1,2)*f(k1-2,k2) if k1>=2 else 0) + (k1*k2*f(k1,k2-1) if k1>=1 and k2>=1 else 0) + (C(k2,2)*f(k1+2,k2-2) if k2>=2 else 0) )%M
return F[(k1,k2)]
print(f(c.count(1),c.count(2)))
```
|
413
|
Maze 2D
|
Title: Maze 2D
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a 2<=×<=*n* maze.
Imagine a maze that looks like a 2<=×<=*n* rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other.
Unfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a 2<=×<=*n* maze.
Input Specification:
The first line contains two integers, *n* and *m* (1<=≤<=*n*<=≤<=2·105; 1<=≤<=*m*<=≤<=2·105) — the width of the maze and the number of queries, correspondingly. Next two lines contain the maze. Each line contains *n* characters, each character equals either '.' (empty cell), or 'X' (obstacle).
Each of the next *m* lines contains two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=2*n*) — the description of the *i*-th request. Numbers *v**i*, *u**i* mean that you need to print the value of the shortest path from the cell of the maze number *v**i* to the cell number *u**i*. We assume that the cells of the first line of the maze are numbered from 1 to *n*, from left to right, and the cells of the second line are numbered from *n*<=+<=1 to 2*n* from left to right. It is guaranteed that both given cells are empty.
Output Specification:
Print *m* lines. In the *i*-th line print the answer to the *i*-th request — either the size of the shortest path or -1, if we can't reach the second cell from the first one.
Demo Input:
['4 7\n.X..\n...X\n5 1\n1 3\n7 7\n1 4\n6 1\n4 7\n5 7\n', '10 3\nX...X..X..\n..X...X..X\n11 7\n7 18\n18 10\n']
Demo Output:
['1\n4\n0\n5\n2\n2\n2\n', '9\n-1\n3\n']
Note:
none
|
```python
import sys
input = sys.stdin.readline
infinity = 10**6
def convert(c):
if c == '.':
return True
else:
return False
def find_next_dist_helper(i, b, c, shift, dist, maze):
if shift == 1:
if (not maze[b][i]) or (not maze[c][i + 1]):
return infinity
if b == c:
return 1
if maze[c][i] or maze[b][i + 1]:
return 2
return infinity
i = 2*i
return min(dist[-1][i][b][0] + dist[-1][i + 1][0][c], dist[-1][i][b][1] + dist[-1][i + 1][1][c])
def find_next_dist(i, shift, dist, maze):
return ((find_next_dist_helper(i, 0, 0, shift, dist, maze), find_next_dist_helper(i, 0, 1, shift, dist, maze)), (find_next_dist_helper(i, 1, 0, shift, dist, maze), find_next_dist_helper(i, 1, 1, shift, dist, maze)))
def preprocess(maze, n):
dist = []
shift = 1
while shift < n:
i = 0
new_dist = []
while shift*i + shift < n:
new_dist.append(find_next_dist(i, shift, dist, maze))
i += 1
shift *= 2
dist.append(new_dist)
return dist
def get_dist(u, b, v, c, dist, maze):
shift = 1
i = 0
pos = u
total = 0
while u + shift <= v:
if pos % 2 != 0:
if dist[i][pos][b][0] < dist[i][pos][b][1]:
pos, u, b, total = pos + 1, u + shift, 0, total + dist[i][pos][b][0]
else:
pos, u, b, total = pos + 1, u + shift, 1, total + dist[i][pos][b][1]
shift, i, pos = shift*2, i + 1, pos//2
while u < v:
shift, i, pos = shift//2, i - 1, pos*2
if u + shift <= v:
if dist[i][pos][b][0] < dist[i][pos][b][1]:
pos, u, b, total = pos + 1, u + shift, 0, total + dist[i][pos][b][0]
else:
pos, u, b, total = pos + 1, u + shift, 1, total + dist[i][pos][b][1]
if b != c:
if maze[b][u] and maze[c][v]:
return total + 1
else:
return infinity
else:
return total
n, m = map(int, input().split())
maze = [list(map(convert, input().strip())), list(map(convert, input().strip()))]
dist = preprocess(maze, n)
for _ in range(m):
u, v = map(int, input().split())
u, b, v, c = (u - 1) % n, (u - 1)//n, (v - 1) % n, (v - 1)//n
if v < u:
u, b, v, c = v, c, u, b
if u == v and b == c:
print(0)
elif u == v and b != c:
print(1)
else:
d = get_dist(u, b, v, c, dist, maze)
if d >= infinity:
print(-1)
else:
print(d)
```
|
727
|
Games on a CD
|
Title: Games on a CD
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Several years ago Tolya had *n* computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to *k*. The names didn't overlap.
Thus, there is a cyclic string of length *n*·*k* written on the CD.
Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were *g* popular games that days. All of the games he burned were among these *g* games, and no game was burned more than once.
You have to restore any valid list of games Tolya could burn to the CD several years ago.
Input Specification:
The first line of the input contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=105, 1<=≤<=*k*<=≤<=105) — the amount of games Tolya burned to the CD, and the length of each of the names.
The second line of the input contains one string consisting of lowercase English letters — the string Tolya wrote on the CD, split in arbitrary place. The length of the string is *n*·*k*. It is guaranteed that the length is not greater than 106.
The third line of the input contains one positive integer *g* (*n*<=≤<=*g*<=≤<=105) — the amount of popular games that could be written on the CD. It is guaranteed that the total length of names of all popular games is not greater than 2·106.
Each of the next *g* lines contains a single string — the name of some popular game. Each name consists of lowercase English letters and has length *k*. It is guaranteed that the names are distinct.
Output Specification:
If there is no answer, print "NO" (without quotes).
Otherwise, print two lines. In the first line print "YES" (without quotes). In the second line, print *n* integers — the games which names were written on the CD. You should print games in the order they could have been written on the CD, it means, in clockwise order. You can print games starting from any position. Remember, that no game was burned to the CD more than once. If there are several possible answers, print any of them.
Demo Input:
['3 1\nabc\n4\nb\na\nc\nd\n', '4 2\naabbccdd\n4\ndd\nab\nbc\ncd\n']
Demo Output:
['YES\n2 1 3 \n', 'NO\n']
Note:
none
|
```python
import sys
input = sys.stdin.buffer.readline
p = 24738041398529
def process(n, k, S, G):
g = len(G)
matrix = [[0 for j in range(k)] for i in range(g)]
sums = [0 for i in range(k)]
word_dict = {}
for i in range(g):
word = 0
for j in range(k):
si = ord(G[i][j])-ord('a')
word = (26*word+si) % p
word_dict[word] = i
word = 0
for i in range(k):
si = ord(S[i])-ord('a')
word = (26*word+si) % p
for i in range(k, n*k+k):
i2 = i % k
if word in word_dict:
i1 = word_dict[word]
if matrix[i1][i2]==0:
matrix[i1][i2] = i
if sums[i2] != -1:
sums[i2]+=1
else:
sums[i2] = -1
else:
sums[i2] = -1
s1 = S[(i-k) % (n*k)]
s2 = S[i % (n*k)]
s1 = ord(s1)-ord('a')
s2 = ord(s2)-ord('a')
word = (word-pow(26, k-1, p)*s1) % p
word = (26*word+s2) % p
for i in range(k):
if sums[i]==n:
answer = []
for j in range(g):
j2 = matrix[j][i]
"""
j = index of the game in my list
j2 = index of the game on the board.
"""
if j2 != 0:
answer.append([j2, j+1])
answer = sorted(answer)
answer = [x[1] for x in answer]
print("YES")
answer = ' '.join(map(str, answer))
sys.stdout.write(f'{answer}\n')
return
print('NO')
n, k = [int(x) for x in input().split()]
S = input().decode().strip()
g = int(input())
G = []
for i in range(g):
word = input().decode().strip()
G.append(word)
process(n, k, S, G)
```
|
545
|
Paths and Trees
|
Title: Paths and Trees
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a connected weighted undirected graph *G*<==<=(*V*,<=*E*) (here *V* is the set of vertices, *E* is the set of edges). The shortest-path tree from vertex *u* is such graph *G*1<==<=(*V*,<=*E*1) that is a tree with the set of edges *E*1 that is the subset of the set of edges of the initial graph *E*, and the lengths of the shortest paths from *u* to any vertex to *G* and to *G*1 are the same.
You are given a connected weighted undirected graph *G* and vertex *u*. Your task is to find the shortest-path tree of the given graph from vertex *u*, the total weight of whose edges is minimum possible.
Input Specification:
The first line contains two numbers, *n* and *m* (1<=≤<=*n*<=≤<=3·105, 0<=≤<=*m*<=≤<=3·105) — the number of vertices and edges of the graph, respectively.
Next *m* lines contain three integers each, representing an edge — *u**i*,<=*v**i*,<=*w**i* — the numbers of vertices connected by an edge and the weight of the edge (*u**i*<=≠<=*v**i*,<=1<=≤<=*w**i*<=≤<=109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.
The last line of the input contains integer *u* (1<=≤<=*u*<=≤<=*n*) — the number of the start vertex.
Output Specification:
In the first line print the minimum total weight of the edges of the tree.
In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.
If there are multiple answers, print any of them.
Demo Input:
['3 3\n1 2 1\n2 3 1\n1 3 2\n3\n', '4 4\n1 2 1\n2 3 1\n3 4 1\n4 1 2\n4\n']
Demo Output:
['2\n1 2 \n', '4\n2 3 4 \n']
Note:
In the first sample there are two possible shortest path trees:
- with edges 1 – 3 and 2 – 3 (the total weight is 3); - with edges 1 – 2 and 2 – 3 (the total weight is 2);
And, for example, a tree with edges 1 – 2 and 1 – 3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1.
|
```python
import heapq
n, m = map(int, input().split())
g = [[] for _ in range(n + 1)]
for i in range(1, m + 1):
u, v, w = map(int, input().split())
g[u].append((i, v, w))
g[v].append((i, u, w))
src = int(input())
pq = [(0, 0, src, -1)]
mk = [0] * (n + 1)
t = []
s = 0
while pq:
d, w, u, e = heapq.heappop(pq)
if mk[u]:
continue
mk[u] = 1
s += w
t.append(e)
for e, v, w in g[u]:
if not mk[v]:
heapq.heappush(pq, (d + w, w, v, e))
print(s)
print(*t[1:])
```
|
858
|
Tests Renumeration
|
Title: Tests Renumeration
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "*n*', where *n* is the total number of tests.
Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.
The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.
Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run:
- all examples are the first several tests having filenames "1", "2", ..., "*e*", where *e* is the total number of examples; - all other files contain regular tests with filenames "*e*<=+<=1", "*e*<=+<=2", ..., "*n*", where *n* is the total number of all tests.
Input Specification:
The first line contains single integer *n* (1<=≤<=*n*<=≤<=105) — the number of files with tests.
*n* lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the *i*-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of digits and small English letters with length from 1 to 6 characters. The filenames are guaranteed to be distinct.
Output Specification:
In the first line print the minimum number of lines in Vladimir's script file.
After that print the script file, each line should be "move file_1 file_2", where "file_1" is an existing at the moment of this line being run filename, and "file_2" — is a string of digits and small English letters with length from 1 to 6.
Demo Input:
['5\n01 0\n2 1\n2extra 0\n3 1\n99 0\n', '2\n1 0\n2 1\n', '5\n1 0\n11 1\n111 0\n1111 1\n11111 0\n']
Demo Output:
['4\nmove 3 1\nmove 01 5\nmove 2extra 4\nmove 99 3\n', '3\nmove 1 3\nmove 2 1\nmove 3 2', '5\nmove 1 5\nmove 11 1\nmove 1111 2\nmove 111 4\nmove 11111 3\n']
Note:
none
|
```python
n = int(input())
t = [1] + [0] * n
b, a = d = [], []
h, s = [], []
for i in range(n):
f, k = input().split()
d[int(k)].append(f)
m = len(a)
for i in a:
if i.isdigit() and i[0] != '0':
j = int(i)
if 0 < j <= m:
t[j] = 1
elif m < j <= n:
t[j] = -1
else:
s.append(i)
else:
s.append(i)
for i in b:
if i.isdigit() and i[0] != '0':
j = int(i)
if m < j <= n:
t[j] = 1
elif 0 < j <= m:
t[j] = -1
else:
s.append(i)
else:
s.append(i)
x = [j for j in range(1, m + 1) if t[j] < 0]
y = [j for j in range(m + 1, n + 1) if t[j] < 0]
u = [j for j in range(1, m + 1) if not t[j]]
v = [j for j in range(m + 1, n + 1) if not t[j]]
if not s and (x or y):
s = ['0']
if y:
i = y.pop()
v.append(i)
else:
i = x.pop()
u.append(i)
h.append(str(i) + ' 0')
t[i] = 0
while x or y:
if v and x:
i = x.pop()
j = v.pop()
t[j] = 1
h.append(str(i) + ' ' + str(j))
u.append(i)
else:
u, v, x, y = v, u, y, x
k = 1
for j in s:
while t[k] == 1: k += 1
h.append(j + ' ' + str(k))
k += 1
d = '\nmove '
print(str(len(h)) + d + d.join(h) if h else 0)
```
|
912
|
Prime Gift
|
Title: Prime Gift
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of *n* distinct prime numbers alongside with a simple task: Oleg is to find the *k*-th smallest integer, such that all its prime divisors are in this set.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=16).
The next line lists *n* distinct prime numbers *p*1,<=*p*2,<=...,<=*p**n* (2<=≤<=*p**i*<=≤<=100) in ascending order.
The last line gives a single integer *k* (1<=≤<=*k*). It is guaranteed that the *k*-th smallest integer such that all its prime divisors are in this set does not exceed 1018.
Output Specification:
Print a single line featuring the *k*-th smallest integer. It's guaranteed that the answer doesn't exceed 1018.
Demo Input:
['3\n2 3 5\n7\n', '5\n3 7 11 13 31\n17\n']
Demo Output:
['8\n', '93\n']
Note:
The list of numbers with all prime divisors inside {2, 3, 5} begins as follows:
(1, 2, 3, 4, 5, 6, 8, ...)
The seventh number in this list (1-indexed) is eight.
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(x):
a = [1]
for i in range(1, pow2[len(x)]):
y = []
u = 1
for j in range(len(x)):
if i & pow2[j]:
y.append(x[j])
u *= x[j]
s, q, k = set(), [u], 0
s.add(u)
while len(q) ^ k:
u = q[k]
a.append(u)
for j in y:
if not u * j in s and u * j < inf:
s.add(u * j)
q.append(u * j)
k += 1
a.sort()
return a
def binary_search(c1, c2, k):
m = (c1 + c2 + 1) // 2
while abs(c1 - c2) > 1:
m = (c1 + c2 + 1) // 2
if ok(m, k):
c2 = m
else:
c1 = m
m = max(1, m - 2)
while not ok(m, k):
m += 1
return m
def ok(m, k):
l = len(b) - 1
cnt = 0
for i in a:
while l >= 0 and i * b[l] > m:
l -= 1
cnt += l + 1
return True if cnt >= k else False
n = int(input())
p = list(map(int, input().split()))
p.sort()
pow2 = [1]
for _ in range(n):
pow2.append(2 * pow2[-1])
u, v = [], []
for i in range(n):
if not i % 2:
u.append(p[i])
else:
v.append(p[i])
inf = pow(10, 18) + 1
a, b = f(u), f(v)
k = int(input())
ans = binary_search(0, inf, k)
print(ans)
```
|
928
|
Autocompletion
|
Title: Autocompletion
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.
Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».
With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?
A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».
Input Specification:
The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty.
Output Specification:
Print a single integer — the minimum number of clicks.
Demo Input:
['snow affects sports such as skiing, snowboarding, and snowmachine travel.\nsnowboarding is a recreational activity and olympic and paralympic sport.\n', "'co-co-co, codeforces?!'\n", 'thun-thun-thunder, thunder, thunder\nthunder, thun-, thunder\nthun-thun-thunder, thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, feel the thunder\nlightning then the thunder\nthunder, thunder\n']
Demo Output:
['141\n', '25\n', '183\n']
Note:
In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.
In sample case two it doesn't matter whether to use autocompletion or not.
|
```python
# python3
# utf-8
class Trie:
def __init__(self):
self.letter___node = {}
self.words_nr = 0
def add_word(self, word):
word = word + '$'
curr_node = self
for letter in word:
if letter not in curr_node.letter___node:
curr_node.letter___node[letter] = Trie()
curr_node.words_nr += 1
curr_node = curr_node.letter___node[letter]
def check_word(self, word):
word = word + '$'
curr_node = self
for letter in word:
if letter not in curr_node.letter___node:
return False
curr_node = curr_node.letter___node[letter]
return True
def count_word(self, word):
word = word + '$'
curr_node = self
curr_state = 0
presses_saved = 0
for letter in word:
if letter not in curr_node.letter___node:
if curr_state == 1:
# print(presses_saved)
if '$' in curr_node.letter___node:
return min(len(word) - 1,
len(word) - 1 - presses_saved + 1
)
else:
return len(word) - 1
if curr_state == 0:
return len(word) - 1
if curr_node.words_nr > 1:
curr_node = curr_node.letter___node[letter]
elif curr_node.words_nr == 1:
# print(letter, presses_saved)
if curr_state == 0:
curr_state = 1
presses_saved += 1
curr_node = curr_node.letter___node[letter]
elif curr_node.words_nr == 0:
if curr_state == 1:
return min(len(word) - 1,
len(word) - 1 - presses_saved + 1
)
elif curr_state == 0:
return len(word) - 1
if curr_node.words_nr == 0:
presses_saved -= 1
if curr_state == 1:
return min(len(word) - 1,
len(word) - 1 - presses_saved + 1
)
elif curr_state == 0:
return len(word) - 1
text = ''
while(1):
try:
line = input()
if line == '':
raise Exception('e')
text += line + '\n'
except:
break
# print(text)
ans = 0
syms = ['\n', '.', ',', '?', '!', "'", '-']
for sym in syms:
text = text.replace(sym, ' ')
ans += text.count(' ')
idx___word = text.split(' ')
root = Trie()
root.add_word('$')
root.add_word('$$')
for word in idx___word:
if word == '':
continue
count = root.count_word(word)
check = root.check_word(word)
# print(word, check, count)
ans += count
if not check:
root.add_word(word)
print(ans)
```
|
725
|
Contest Balloons
|
Title: Contest Balloons
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.
You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.
A contest has just finished. There are *n* teams, numbered 1 through *n*. The *i*-th team has *t**i* balloons and weight *w**i*. It's guaranteed that *t**i* doesn't exceed *w**i* so nobody floats initially.
Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.
What is the best place Limak can get?
Input Specification:
The first line of the standard input contains one integer *n* (2<=≤<=*n*<=≤<=300<=000) — the number of teams.
The *i*-th of *n* following lines contains two integers *t**i* and *w**i* (0<=≤<=*t**i*<=≤<=*w**i*<=≤<=1018) — respectively the number of balloons and the weight of the *i*-th team. Limak is a member of the first team.
Output Specification:
Print one integer denoting the best place Limak can get.
Demo Input:
['8\n20 1000\n32 37\n40 1000\n45 50\n16 16\n16 16\n14 1000\n2 1000\n', '7\n4 4\n4 4\n4 4\n4 4\n4 4\n4 4\n5 5\n', '7\n14000000003 1000000000000000000\n81000000000 88000000000\n5000000000 7000000000\n15000000000 39000000000\n46000000000 51000000000\n0 1000000000\n0 0\n']
Demo Output:
['3\n', '2\n', '2\n']
Note:
In the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is:
1. Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place.1. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified.1. Limak gives 1 balloon to each of two teams with 16 balloons initially.1. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons.1. There are three other teams left and their numbers of balloons are 40, 14 and 2.1. Limak gets the third place because there are two teams with more balloons.
In the second sample, Limak has the second place and he can't improve it.
In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7).
|
```python
#!/usr/bin/env python3
from sys import stdin,stdout
from bisect import *
from heapq import *
def ri():
return map(int, input().split())
n = int(input())
abw = [list(ri()) for i in range(n)]
a1 = abw[0][0]
a = [abw[i][0] for i in range(1,n)]
a.sort()
abw = abw[1:]
abw.sort(key=lambda e: e[0])
for j in range(len(abw)):
if abw[j][0] > a1:
break
else:
j += 1
f = 0
mins = n - j
pq = [abw[i][1]-abw[i][0] for i in range(j, n-1)]
heapify(pq)
iiprv = j
while len(pq) and a1 > 0:
g = heappop(pq)
if a1 > g:
f += 1
a1 -= g+1
ii = bisect(a,a1)
for k in range(ii, iiprv):
heappush(pq, abw[k][1]-abw[k][0])
iiprv = ii
mins = min(mins, n-ii-f)
print(mins)
```
|
785
|
Anton and School - 2
|
Title: Anton and School - 2
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence *s* of length *n* is an RSBS if the following conditions are met:
- It is not empty (that is *n*<=≠<=0). - The length of the sequence is even. - First charactes of the sequence are equal to "(". - Last charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence *s*. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of *s* is a string that can be obtained from *s* by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109<=+<=7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input Specification:
The only line of the input contains a string *s* — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200<=000.
Output Specification:
Output one number — the answer for the task modulo 109<=+<=7.
Demo Input:
[')(()()\n', '()()()\n', ')))\n']
Demo Output:
['6\n', '7\n', '0\n']
Note:
In the first sample the following subsequences are possible:
- If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())". - If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()". - If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()". - If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()". - If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()". - If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
|
```python
t = input()
n, m = len(t) + 1, 1000000007
a, b = 0, t.count(')') - 1
f = [1] * n
for i in range(2, n): f[i] = i * f[i - 1] % m
g = [pow(q, m - 2, m) for q in f]
s = 0
for q in t:
if b < 0: break
if q == '(':
a += 1
s += f[a + b] * g[a] * g[b]
else: b -= 1
print(s % m)
```
|
755
|
PolandBall and Polygon
|
Title: PolandBall and Polygon
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
PolandBall has such a convex polygon with *n* veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments.
He chose a number *k* such that *gcd*(*n*,<=*k*)<==<=1. Vertices of the polygon are numbered from 1 to *n* in a clockwise way. PolandBall repeats the following process *n* times, starting from the vertex 1:
Assume you've ended last operation in vertex *x* (consider *x*<==<=1 if it is the first operation). Draw a new segment from vertex *x* to *k*-th next vertex in clockwise direction. This is a vertex *x*<=+<=*k* or *x*<=+<=*k*<=-<=*n* depending on which of these is a valid index of polygon's vertex.
Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.
Input Specification:
There are only two numbers in the input: *n* and *k* (5<=≤<=*n*<=≤<=106, 2<=≤<=*k*<=≤<=*n*<=-<=2, *gcd*(*n*,<=*k*)<==<=1).
Output Specification:
You should print *n* values separated by spaces. The *i*-th value should represent number of polygon's sections after drawing first *i* lines.
Demo Input:
['5 2\n', '10 3\n']
Demo Output:
['2 3 5 8 11 ', '2 3 4 6 9 12 16 21 26 31 ']
Note:
The greatest common divisor (gcd) of two integers *a* and *b* is the largest positive integer that divides both *a* and *b* without a remainder.
For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines.
|
```python
n, k = map(int, input().split())
if k << 1 > n: k = n - k
s = 1
for i in range(n):
s += 1 + i * k // n + (i * k + k - 1) // n
print(s)
```
|
835
|
The penguin's game
|
Title: The penguin's game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Pay attention: this problem is interactive.
Penguin Xoriy came up with a new game recently. He has *n* icicles numbered from 1 to *n*. Each icicle has a temperature — an integer from 1 to 109. Exactly two of these icicles are special: their temperature is *y*, while a temperature of all the others is *x*<=≠<=*y*. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than 19 questions.
You are to find the special icicles.
Input Specification:
The first line contains three integers *n*, *x*, *y* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*x*,<=*y*<=≤<=109, *x*<=≠<=*y*) — the number of icicles, the temperature of non-special icicles and the temperature of the special icicles.
Output Specification:
To give your answer to the penguin you have to print character "!" (without quotes), then print two integers *p*1, *p*2 (*p*1<=<<=*p*2) — the indexes of the special icicles in ascending order. Note that "!" and *p*1 should be separated by a space; the indexes should be separated by a space too. After you gave the answer your program should terminate immediately.
Demo Input:
['4 2 1\n2\n1\n1']
Demo Output:
['? 3 1 2 3\n? 1 1\n? 1 3\n! 1 3']
Note:
The answer for the first question is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b32d8d96beb0d2be8d8a600f458c8cf2e2e28c54.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
The answer for the second and the third questions is 1, therefore, special icicles are indexes 1 and 3.
You can read more about bitwise XOR operation here: [https://en.wikipedia.org/wiki/Bitwise_operation#XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
|
```python
import sys
n, x, y = (int(x) for x in input().split())
ys = [y, x ^ y]
def ask(*bits):
arr = [x for x in range(1, n + 1) if all(x & i == i for i in bits)]
if len(arr) == 0:
return 0
print('?', len(arr), *arr)
sys.stdout.flush()
return int(input())
diffs = []
i = 1
while i <= n:
x = ask(i)
if x in ys:
diffs.append(i)
i <<= 1
i = diffs[-1]
j = 1
ans2 = i
while j <= n:
if j != i:
x = ask(i, j)
if x in ys:
ans2 |= j
j <<= 1
ans1 = sum(diffs) ^ ans2
print('!', ans1, ans2)
```
|
542
|
Playing on Graph
|
Title: Playing on Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.
Vova has a non-directed graph consisting of *n* vertices and *m* edges without loops and multiple edges. Let's define the operation of contraction two vertices *a* and *b* that are not connected by an edge. As a result of this operation vertices *a* and *b* are deleted and instead of them a new vertex *x* is added into the graph, and also edges are drawn from it to all vertices that were connected with *a* or with *b* (specifically, if the vertex was connected with both *a* and *b*, then also exactly one edge is added from *x* to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (*n*<=-<=1) vertices.
Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length *k* (*k*<=≥<=0) is a connected graph whose vertices can be numbered with integers from 1 to *k*<=+<=1 so that the edges of the graph connect all pairs of vertices (*i*,<=*i*<=+<=1) (1<=≤<=*i*<=≤<=*k*) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.
Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.
Input Specification:
The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=1000, 0<=≤<=*m*<=≤<=100<=000) — the number of vertices and the number of edges in the original graph.
Next *m* lines contain the descriptions of edges in the format *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), which means that there is an edge between vertices *a**i* and *b**i*. It is guaranteed that there is at most one edge between each pair of vertexes.
Output Specification:
If it is impossible to obtain a chain from the given graph, print <=-<=1. Otherwise, print the maximum possible number of edges in the resulting chain.
Demo Input:
['5 4\n1 2\n2 3\n3 4\n3 5\n', '4 6\n1 2\n2 3\n1 3\n3 4\n2 4\n1 4\n', '4 2\n1 3\n2 4\n']
Demo Output:
['3\n', '-1\n', '2\n']
Note:
In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.
In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.
In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.
|
```python
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for i in range(m):
p, q = map(int, input().split())
g[p - 1].append(q - 1)
g[q - 1].append(p - 1)
comp = [-1] * n
def shortest(root):
dist = [-1] * n
q = [0] * n
left, right = 0, 1
q[left] = root
dist[root] = 0
good = True
while left < right:
x = q[left]
left = left + 1
for i in g[x]:
if dist[i] is -1:
dist[i] = 1 + dist[x]
q[right] = i
right = right + 1
elif dist[i] == dist[x]:
good = False
far = 0
for i in dist:
if far < i:
far = i
return good, far, dist
arr = [0] * n
good = True
for i in range(n):
_, opt, dist = shortest(i)
if _ is False: good = False
if comp[i] is -1:
for j in range(n):
if dist[j] is not -1: comp[j] = i
if arr[comp[i]] < opt:
arr[comp[i]] = opt
if good is False: print('-1')
else: print(sum(arr))
```
|
662
|
Binary Table
|
Title: Binary Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa.
What is the minimum number of cells with value 1 you can get after applying some number of operations?
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=20, 1<=≤<=*m*<=≤<=100<=000) — the number of rows and the number of columns, respectively.
Then *n* lines follows with the descriptions of the rows. Each line has length *m* and contains only digits '0' and '1'.
Output Specification:
Output a single integer — the minimum possible number of ones you can get after applying some sequence of operations.
Demo Input:
['3 4\n0110\n1010\n0111\n']
Demo Output:
['2\n']
Note:
none
|
```python
from functools import reduce
n, m = map(int, input().split())
a = [input() for _ in range(n)]
a = list(map(lambda x: reduce(lambda x, y: x * 2 + int(y), x, 0), zip(*a)))
S = 1 << n
f, g = [0] * S, [0] * S
for x in a:
g[x] += 1
for mask in range(S):
k = bin(mask).count('1')
f[mask] = min(k, n - k)
def walsh_hadamard_transform(a, inverse = False):
n = len(a)
assert((n & (n - 1)) == 0)
step = 1;
while step < n:
for i in range(n):
if (i & step) == 0:
a[i], a[i + step] = a[i] + a[i + step], a[i] - a[i + step]
step <<= 1
if inverse:
for i in range(n):
a[i] //= n
# print(a)
# print(f)
# print(g)
walsh_hadamard_transform(f)
walsh_hadamard_transform(g)
for i in range(S):
f[i] *= g[i]
walsh_hadamard_transform(f, True)
ans = min(f)
print(ans)
```
|
512
|
Fox And Travelling
|
Title: Fox And Travelling
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Fox Ciel is going to travel to New Foxland during this summer.
New Foxland has *n* attractions that are linked by *m* undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has *k* days to visit this city and each day she will visit exactly one attraction.
There is one important rule in New Foxland: you can't visit an attraction if it has more than one adjacent attraction that you haven't visited yet.
At the beginning Fox Ciel haven't visited any attraction. During her travelling she may move aribtrarly between attraction. After visiting attraction *a*, she may travel to any attraction *b* satisfying conditions above that hasn't been visited yet, even if it is not reachable from *a* by using the roads (Ciel uses boat for travelling between attractions, so it is possible).
She wants to know how many different travelling plans she can make. Calculate this number modulo 109<=+<=9 for every *k* from 0 to *n* since she hasn't decided for how many days she is visiting New Foxland.
Input Specification:
First line contains two integers: *n*, *m* (1<=≤<=*n*<=≤<=100, ), the number of attractions and number of undirected roads.
Then next *m* lines each contain two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n* and *a**i*<=≠<=*b**i*), describing a road. There is no more than one road connecting each pair of attractions.
Output Specification:
Output *n*<=+<=1 integer: the number of possible travelling plans modulo 109<=+<=9 for all *k* from 0 to *n*.
Demo Input:
['3 2\n1 2\n2 3\n', '4 4\n1 2\n2 3\n3 4\n4 1\n', '12 11\n2 3\n4 7\n4 5\n5 6\n4 6\n6 12\n5 12\n5 8\n8 9\n10 8\n11 9\n', '13 0\n']
Demo Output:
['1\n2\n4\n4\n', '1\n0\n0\n0\n0\n', '1\n6\n31\n135\n483\n1380\n3060\n5040\n5040\n0\n0\n0\n0\n', '1\n13\n156\n1716\n17160\n154440\n1235520\n8648640\n51891840\n259459200\n37836791\n113510373\n227020746\n227020746\n']
Note:
In the first sample test for *k* = 3 there are 4 travelling plans: {1, 2, 3}, {1, 3, 2}, {3, 1, 2}, {3, 2, 1}.
In the second sample test Ciel can't visit any attraction in the first day, so for *k* > 0 the answer is 0.
In the third sample test Foxlands look like this:
|
```python
from collections import deque
# Find all the vertices inside a connected component.
def DFS(v):
index = len(cc) - 1 # Obtain the index of this connected component.
cc[index].append(v) # Add this vertex to the list of this connected component.
visited[v] = True # Mark this vertex as visited.
# For each adjacent of this vertex, if it has not been visited, we call recursive
# on it to visit its subtree.
for w in G[v]:
if not visited[w] and visitable[w]:
DFS(w)
# Computes the dp matrix values.
def DFS_DP(v, father, dp):
size = 1 # Size of the tree rooted at v (until the child visited at this time).
# DP base cases.
dp[v][0] = 1
dp[v][1] = 0
# For each w child of v.
for w in G[v]:
# If w is not the father of v.
if w != father and visitable[w]:
# Then, make a recursive call on w, to compute the dp tensor values
# corresponding to w, and the size of the subtree rooted at w.
w_size = DFS_DP(w, v, dp)
# Clean this dp section for incoming calculations.
# TODO: explain this.
for i in range(w_size + 1):
dp[v][i + size] = 0
# As a new child has visited, update the size of the subtree rooted at v.
size += w_size
# For every possible number of vertices that can be removed between the first k children.
for i in range(size, 0, -1):
# Of these, for every possible number of vertices that can be removed in the k-th child.
for j in range(1, min(i, w_size) + 1):
# The number of ways to remove i vertices from the tree rooted at v
# removing them from its first k children at most, is the number of
# ways to remove j of them from the subtree rooted at the k-th child,
# in any way, multiplied by the number of ways to remove the remaining
# i-j in the first k-1 children, for every possible j.
# TODO: comment why C[i][j] is necessary to count the ways of merging
# TODO: the order of deleting the j first vertices with the order of
# TODO: deleting the remaining i-j.
dp[v][i] = (dp[v][i] + (C[i][j] * (dp[v][i - j] * dp[w][j] % mod) % mod)) % mod
# The number of ways to remove all vertices from the tree rooted at v
# removing them from any of the children, is the number of ways to remove
# al vertices except this one from any of the children, and then remove this one.
dp[v][size] = dp[v][size - 1]
# Return the size of the tree rooted at v.
return size
# Calculate the solutions for one connected component, starting at a given root.
def root_calculate(root, dp, accum):
# Calculate the dp solution for this component starting from the root.
size = DFS_DP(root, -1, dp)
# For each of the possible sizes i, increase accum[i] with the number of ways
# to remove i vertices from the graph, starting from the root.
for i in range(size + 1):
accum[i] = (accum[i] + dp[root][i]) % mod
# Calculate the solutions for one connected component.
def calculate(index):
size = len(cc[index]) # Amount of vertices in this connected component.
root = cc[index][0] # Root of this connected component.
accum = [0] * (n + 1) # Array of dp accumulated solutions.
# DP three-dimensional tensor.
# DP[v][i][k] is the number of ways to remove i vertices from the tree rooted at v,
# removing them at most in the first k children of v.
dp = [[0] * (n + 1) for _ in range(n + 1)]
# If the root vertex is special (adjoins a cycle), it is obligatory root.
if special[root]:
root_calculate(root, dp, accum)
# If the vertex x is not special, and therefore is not obligatory root,
# calculate the solution for all possible roots.
else:
for v in cc[index]:
root_calculate(v, dp, accum)
# Divide f[i] by max(1, size - i) to eliminate repetitions in the count.
for i in range(size):
accum[i] = accum[i] * inv[size - i] % mod
return accum
# Auxiliary method of preparation for subsequent calculations.
def prepare():
# Calculate all combinations for al pairs (i, j), 0 <= i <= j <= n.
# C(i 0) is 1, for all i.
for i in range(n + 1):
C[i][0] = 1
# C(i j) = C(i-1 j-1) + C(i-1 j)
for i in range(1, n + 1):
for j in range(1, n + 1):
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod
# Calculate all modular inverses from 1 to n.
inv[1] = 1
for i in range(2, n + 1):
inv[i] = (mod - mod // i) * inv[mod % i] % mod
# Use the topological sort algorithm, to identify the vertices v that do not belong to any cycle
# (visitable[v] = true), those that belong (visitable[v] = false) and, of the latter, those that
# are adjacent to vertices that belong to a cycle (degree[v] == 1).
q = deque() # Topological sort queue.
degree = [0] * n # Degrees of the vertices.
# For each vertex of the graph.
for v in range(n):
degree[v] = len(G[v]) # Calculate the degree of this vertex.
if degree[v] < 2:
q.append(v) # If the degree is one or lower, add this vertex to the order.
# As long as there are vertices in the topological order.
while len(q) > 0:
v = q.popleft() # Take the first vertex and remove it from graph.
visitable[v] = True # Mark this vertex as one that does not belong to cycle.
# To simulate the removal of this vertex from the graph, decrease by one the degree
# of all its adjacent.
for w in G[v]:
degree[w] -= 1
# If the degree becomes one or lower, add this vertex to the order.
if degree[w] < 2 and not visitable[w]:
q.append(w)
# All vertices that maintain degree one, after all the removable vertices in topological order
# were eliminated, are vertices adjacent to vertices belonging to cycle.
for i in range(n):
special[i] = (degree[i] == 1)
# Now, calculate the connected components of the graph, resulting from removing from the graph
# all vertices belonging to cycle.
# For convenience, iterate first over the special vertices, because these are the ideal roots
# for the subsequent algorithm.
for v in range(n):
if special[v]:
cc.append([])
DFS(v)
# Once all the connected components of the vertices adjacent to cycles have been found,
# proceed to find all the components to which the rest of the vertices belong.
for v in range(n):
if not visited[v] and visitable[v]:
cc.append([])
DFS(v)
# Calculate the solutions for all i, 0 <= i <= n.
def solve():
c = len(cc) # Amount of connected components.
size = 0 # Amount of visited vertices.
# Array of solutions for all i, 0 <= i <= n.
# sol[i][k] is the number of ways to remove i vertices from the graph,
# removing them at most in the first k connected components.
sol = [0] * (n + 1) # List of solutions for all i, 0 <= i <= n;
sol[0] = 1 # DP base case.
# For each component, calculate the solution.
for k in range(1, c + 1):
if len(cc[k - 1]) > 0:
accum = calculate(k - 1) # Array of dp accumulated solutions.
# Increase the number of visited vertices by the number of vertices of this connected component.
c_size = len(cc[k - 1])
size += c_size
# The calculation of the dp2 applies the same logic as the dp.
# TODO: comment why C[i][j] is necessary to count the ways of merging
# TODO: the order of deleting the j first vertices with the order of
# TODO: deleting the remaining i-j.
for i in range(size, 0, -1):
for j in range(1, min(i, c_size) + 1):
sol[i] = (sol[i] + (C[i][j] * (sol[i - j] * accum[j] % mod) % mod)) % mod
# Return the solution.
return sol
# Read the amount of vertices and edges of the graph from input.
n, m = [int(data) for data in input().split()[0: 2]]
# Graph.
G = [[] for _ in range(n)]
# List of connected components.
cc = []
C = [[0] * (n + 1) for _ in range(n + 1)] # Matrix of combinations: C[i][j] = C(i j).
inv = [0] * (n + 1) # Modular inverses from 1 to n.
visited = [0] * n # Array of DFS visited vertices.
visitable = [0] * n # Determine whether a vertex belongs to a cycle.
special = [0] * n # Determine if a vertex that doesn't belong to a cycle is adjacent to another that if it is.
mod = 1000000009 # Modulo of the solution.
# Read the graph from input.
for _ in range(m):
x, y = [int(data) - 1 for data in input().split()[0: 2]] # Read an edge.
G[x].append(y), G[y].append(x) # Add the edge to the graph.
prepare() # Prepare the conditions for subsequent calculations.
ans = solve() # Calculate the solutions for all i, 0 <= i <= n.
# Print all solutions.
print("\n".join([str(data) for data in ans]))
```
|
778
|
Parquet Re-laying
|
Title: Parquet Re-laying
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Peter decided to lay a parquet in the room of size *n*<=×<=*m*, the parquet consists of tiles of size 1<=×<=2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it.
The workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a 2<=×<=2 square, rotate them 90 degrees and put them back on the same place.
They have no idea how to obtain the desired configuration using these operations, and whether it is possible at all.
Help Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most 100<=000 commands.
Input Specification:
The first line contains integer *n* and *m*, size of the room (1<=≤<=*n*,<=*m*<=≤<=50). At least one of them is even number.
The following *n* lines contain *m* characters each, the description of the current configuration of the parquet tiles. Each character represents the position of the half-tile. Characters 'L', 'R', 'U' and 'D' correspond to the left, right, upper and lower halves, respectively.
The following *n* lines contain *m* characters each, describing the desired configuration in the same format.
Output Specification:
In the first line output integer *k*, the number of operations. In the next *k* lines output description of operations. The operation is specified by coordinates (row and column) of the left upper half-tile on which the operation is performed.
If there is no solution, output -1 in the first line.
Demo Input:
['2 3\nULR\nDLR\nLRU\nLRD\n', '4 3\nULR\nDLR\nLRU\nLRD\nULR\nDUU\nUDD\nDLR']
Demo Output:
['2\n1 2\n1 1\n', '3\n3 1\n3 2\n2 2']
Note:
In the first sample test first operation is to rotate two rightmost tiles, after this all tiles lie vertically. Second operation is to rotate two leftmost tiles, after this we will get desired configuration.
|
```python
#!/usr/bin/env python3
board = []
n, m = 0, 0
def rotate(x, y):
if board[x][y] == 'L':
board[x][y] = board[x][y+1] = 'U'
board[x+1][y] = board[x+1][y+1] = 'D'
else:
board[x][y] = board[x+1][y] = 'L'
board[x][y+1] = board[x+1][y+1] = 'R'
def fix(x, y, moves):
if board[x+1][y] == 'U':
if board[x+1][y+1] == 'L':
fix(x+1, y+1, moves)
rotate(x+1, y)
moves.append((x+2, y+1))
rotate(x, y)
moves.append((x+1, y+1))
def solve_board(moves):
global board, n, m
board = []
for _ in range(n):
board.append(list(input()))
for i in range(n-1):
for j in range(m):
if board[i][j] == 'L':
fix(i, j, moves)
def main():
global n, m
n, m = map(int, input().split())
moves1 = []; moves2 = []
solve_board(moves1)
solve_board(moves2)
print(len(moves1) + len(moves2))
for move in moves1:
print(str(move[0]) + ' ' + str(move[1]))
for move in reversed(moves2):
print(str(move[0]) + ' ' + str(move[1]))
if __name__ == '__main__':
main()
```
|
712
|
Memory and Scores
|
Title: Memory and Scores
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score *a* and Lexa starts with score *b*. In a single turn, both Memory and Lexa get some integer in the range [<=-<=*k*;*k*] (i.e. one integer among <=-<=*k*,<=<=-<=*k*<=+<=1,<=<=-<=*k*<=+<=2,<=...,<=<=-<=2,<=<=-<=1,<=0,<=1,<=2,<=...,<=*k*<=-<=1,<=*k*) and add them to their current scores. The game has exactly *t* turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn.
Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are (2*k*<=+<=1)2*t* games in total. Since the answer can be very large, you should print it modulo 109<=+<=7. Please solve this problem for Memory.
Input Specification:
The first and only line of input contains the four integers *a*, *b*, *k*, and *t* (1<=≤<=*a*,<=*b*<=≤<=100, 1<=≤<=*k*<=≤<=1000, 1<=≤<=*t*<=≤<=100) — the amount Memory and Lexa start with, the number *k*, and the number of turns respectively.
Output Specification:
Print the number of possible games satisfying the conditions modulo 1<=000<=000<=007 (109<=+<=7) in one line.
Demo Input:
['1 2 2 1\n', '1 1 1 2\n', '2 12 3 1\n']
Demo Output:
['6\n', '31\n', '0\n']
Note:
In the first sample test, Memory starts with 1 and Lexa starts with 2. If Lexa picks - 2, Memory can pick 0, 1, or 2 to win. If Lexa picks - 1, Memory can pick 1 or 2 to win. If Lexa picks 0, Memory can pick 2 to win. If Lexa picks 1 or 2, Memory cannot win. Thus, there are 3 + 2 + 1 = 6 possible games in which Memory wins.
|
```python
def c(n, k):
if k > n:
return 0
a = b = 1
for i in range(n - k + 1, n + 1):
a *= i
for i in range(1, k + 1):
b *= i
return a // b
a, b, k, t = map(int, input().split())
n, m, s = 2 * k + 1, 2 * t, 2 * k * t + b - a
ans, mod = 0, 1000000007
for i in range(m + 1):
ans = (ans + [1, -1][i & 1] * c(m, i) * c(m + s - n * i, m)) % mod
print((pow(n, m, mod) - ans) % mod)
```
|
558
|
Guess Your Way Out! II
|
Title: Guess Your Way Out! II
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height *h*. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
- The root is number 1 - Each internal node *i* (*i*<=≤<=2*h*<=-<=1<=-<=1) will have a left child with index = 2*i* and a right child with index = 2*i*<=+<=1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level *h* are called leaves. The exit to the maze is located at some leaf node *n*, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the *ancestor*(*exit*,<=*i*) node number belong to the range [*L*,<=*R*]?". Here *ancestor*(*v*,<=*i*) is the ancestor of a node *v* that located in the level *i*. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input Specification:
The first line contains two integers *h*,<=*q* (1<=≤<=*h*<=≤<=50, 0<=≤<=*q*<=≤<=105), the height of the tree and the number of questions respectively.
The next *q* lines will contain four integers each *i*,<=*L*,<=*R*,<=*ans* (1<=≤<=*i*<=≤<=*h*, 2*i*<=-<=1<=≤<=*L*<=≤<=*R*<=≤<=2*i*<=-<=1, ), representing a question as described in the statement with its answer (*ans*<==<=1 if the answer is "Yes" and *ans*<==<=0 if the answer is "No").
Output Specification:
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Demo Input:
['3 1\n3 4 6 0\n', '4 3\n4 10 14 1\n3 6 6 0\n2 3 3 1\n', '4 2\n3 4 6 1\n4 12 15 1\n', '4 2\n3 4 5 1\n2 3 3 1\n']
Demo Output:
['7', '14', 'Data not sufficient!', 'Game cheated!']
Note:
Node *u* is an ancestor of node *v* if and only if
- *u* is the same node as *v*, - *u* is the parent of node *v*, - or *u* is an ancestor of the parent of node *v*.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<img class="tex-graphics" src="https://espresso.codeforces.com/18ab34534095660d59fe39e53e385d64d0346d2a.png" style="max-width: 100.0%;max-height: 100.0%;"/>
|
```python
import sys
input = sys.stdin.buffer.readline
def process(h, Q):
L1, R1 = 2**(h-1), 2**h-1
Q1 = []
n = 0
for i, L, R, ans in Q:
L2, R2 = 2**(h-i)*L, 2**(h-i)*R+2**(h-i)-1
if ans==0:
Q1.append([L2, 0, n])
Q1.append([R2, 1, n])
n+=1
else:
L1 = max(L1, L2)
R1 = min(R1, R2)
if L1 > R1:
sys.stdout.write('Game cheated!\n')
return
good = []
seen = 0
Q1.sort()
curr = 2**(h-1)
for x, t, i in Q1:
if t==0:
if seen==0 and x-1 >= curr:
l2 = max(curr, L1)
r2 = min(x-1, R1)
if l2 <= r2:
good.append([l2, r2])
seen+=1
curr = None
else:
seen-=1
if seen==0:
curr = x+1
if curr <= 2**h-1:
l2 = max(curr, L1)
r2= min(2**h-1, R1)
if l2 <= r2:
good.append([l2, r2])
if len(good)==0:
sys.stdout.write('Game cheated!\n')
return
if len(good) > 1:
sys.stdout.write('Data not sufficient!\n')
return
l, r = good[0]
if l != r:
sys.stdout.write('Data not sufficient!\n')
return
sys.stdout.write(f'{l}\n')
return
h, q = [int(x) for x in input().split()]
Q = []
for I in range(q):
i, L, R, ans = [int(x) for x in input().split()]
Q.append([i, L, R, ans])
process(h, Q)
```
|
512
|
Fox And Polygon
|
Title: Fox And Polygon
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Fox Ciel just designed a puzzle game called "Polygon"! It is played using triangulations of a regular *n*-edge polygon. The goal is to transform one triangulation to another by some tricky rules.
Triangulation of an *n*-edge poylgon is a set of *n*<=-<=3 diagonals satisfying the condition that no two diagonals share a common internal point.
For example, the initial state of the game may look like (a) in above figure. And your goal may look like (c). In each step you can choose a diagonal inside the polygon (but not the one of edges of the polygon) and flip this diagonal.
Suppose you are going to flip a diagonal *a*<=–<=*b*. There always exist two triangles sharing *a*<=–<=*b* as a side, let's denote them as *a*<=–<=*b*<=–<=*c* and *a*<=–<=*b*<=–<=*d*. As a result of this operation, the diagonal *a*<=–<=*b* is replaced by a diagonal *c*<=–<=*d*. It can be easily proven that after flip operation resulting set of diagonals is still a triangulation of the polygon.
So in order to solve above case, you may first flip diagonal 6<=–<=3, it will be replaced by diagonal 2<=–<=4. Then you flip diagonal 6<=–<=4 and get figure (c) as result.
Ciel just proved that for any starting and destination triangulations this game has a solution. She wants you to solve it in no more than 20<=000 steps for any puzzle satisfying *n*<=≤<=1000.
Input Specification:
The first line contain an integer *n* (4<=≤<=*n*<=≤<=1000), number of edges of the regular polygon.
Then follows two groups of (*n*<=-<=3) lines describing the original triangulation and goal triangulation.
Description of each triangulation consists of (*n*<=-<=3) lines. Each line contains 2 integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), describing a diagonal *a**i*<=–<=*b**i*.
It is guaranteed that both original and goal triangulations are correct (i. e. no two diagonals share a common internal point in both of these triangulations).
Output Specification:
First, output an integer *k* (0<=≤<=*k*<=≤<=20,<=000): number of steps.
Then output *k* lines, each containing 2 integers *a**i* and *b**i*: the endpoints of a diagonal you are going to flip at step *i*. You may output *a**i* and *b**i* in any order.
If there are several possible solutions, output any of them.
Demo Input:
['4\n1 3\n2 4\n', '6\n2 6\n3 6\n4 6\n6 2\n5 2\n4 2\n', '8\n7 1\n2 7\n7 3\n6 3\n4 6\n6 1\n6 2\n6 3\n6 4\n6 8\n']
Demo Output:
['1\n1 3\n', '2\n6 3\n6 4\n', '3\n7 3\n7 2\n7 1']
Note:
Sample test 2 is discussed above and shown on the picture.
|
```python
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n = int(input())
def adjacent(i,j):
return (j-i)%n == 1 or (i-j)%n == 1
res = []
A = [[False]*n for i in range(n)]
for _ in range(n-3):
a,b = mi()
a,b = a-1,b-1
A[a][b] = A[b][a] = True
while True:
idx = [1] + [i for i in range(n) if A[0][i]] + [n-1]
if len(idx) == n-1:
break
for a,b in zip(idx,idx[1:]):
if b!=a+1:
assert A[a][b]
res.append((a,b))
for c in range(1,n):
if (A[a][c] or adjacent(a,c)) and (A[c][b] or adjacent(b,c)):
A[0][c] = A[c][0] = True
A[a][b] = A[b][a] = False
break
back = []
B = [[False]*n for i in range(n)]
for _ in range(n-3):
c,d = mi()
c,d = c-1,d-1
B[c][d] = B[d][c] = True
while True:
idx = [1] + [i for i in range(n) if B[0][i]] + [n-1]
if len(idx) == n-1:
break
for a,b in zip(idx,idx[1:]):
if b!=a+1:
assert B[a][b]
for c in range(1,n):
if (B[a][c] or adjacent(a,c)) and (B[c][b] or adjacent(b,c)):
back.append((0,c))
B[0][c] = B[c][0] = True
B[a][b] = B[b][a] = False
break
ans = res + back[::-1]
print(len(ans))
for a,b in ans:
print(a+1,b+1)
```
|
877
|
Danil and a Part-time Job
|
Title: Danil and a Part-time Job
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.
Danil works in a rooted tree (undirected connected acyclic graph) with *n* vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.
Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.
There are two types of tasks:
1. pow v describes a task to switch lights in the subtree of vertex *v*.1. get v describes a task to count the number of rooms in the subtree of *v*, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.
A subtree of vertex *v* is a set of vertices for which the shortest path from them to the root passes through *v*. In particular, the vertex *v* is in the subtree of *v*.
Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the number of vertices in the tree.
The second line contains *n*<=-<=1 space-separated integers *p*2,<=*p*3,<=...,<=*p**n* (1<=≤<=*p**i*<=<<=*i*), where *p**i* is the ancestor of vertex *i*.
The third line contains *n* space-separated integers *t*1,<=*t*2,<=...,<=*t**n* (0<=≤<=*t**i*<=≤<=1), where *t**i* is 1, if the light is turned on in vertex *i* and 0 otherwise.
The fourth line contains a single integer *q* (1<=≤<=*q*<=≤<=200<=000) — the number of tasks.
The next *q* lines are get v or pow v (1<=≤<=*v*<=≤<=*n*) — the tasks described above.
Output Specification:
For each task get v print the number of rooms in the subtree of *v*, in which the light is turned on.
Demo Input:
['4\n1 1 1\n1 0 0 1\n9\nget 1\nget 2\nget 3\nget 4\npow 1\nget 1\nget 2\nget 3\nget 4\n']
Demo Output:
['2\n0\n0\n1\n2\n1\n1\n0\n']
Note:
<img class="tex-graphics" src="https://espresso.codeforces.com/839c4a0a06cc547ffb8d937bfe52730b51c842b4.png" style="max-width: 100.0%;max-height: 100.0%;"/> The tree after the task pow 1.
|
```python
import math
import sys
from bisect import *
from collections import *
from functools import *
from heapq import *
from itertools import *
from random import *
from string import *
from types import GeneratorType
# region fastio
input = lambda: sys.stdin.readline().rstrip()
sint = lambda: int(input())
mint = lambda: map(int, input().split())
ints = lambda: list(map(int, input().split()))
# print = lambda d: sys.stdout.write(str(d) + "\n")
# endregion fastio
# # region interactive
# def printQry(a, b) -> None:
# sa = str(a)
# sb = str(b)
# print(f"? {sa} {sb}", flush = True)
# def printAns(ans) -> None:
# s = str(ans)
# print(f"! {s}", flush = True)
# # endregion interactive
# # region dfsconvert
# 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
# # endregion dfsconvert
# MOD = 998244353
# MOD = 10 ** 9 + 7
# DIR = ((-1, 0), (0, 1), (1, 0), (0, -1))
def dfs(graph, start=0):
n = len(graph)
dfn = [-1] * n
sz = [1] * n
visited, finished = [False] * n, [False] * n
time = n - 1
stack = [start]
while stack:
start = stack[-1]
# push unvisited children into stack
if not visited[start]:
visited[start] = True
for child in graph[start]:
if not visited[child]:
stack.append(child)
else:
stack.pop()
dfn[start] = time
time -= 1
# update with finished children
for child in graph[start]:
if finished[child]:
sz[start] += sz[child]
finished[start] = True
return dfn, sz
class SegTree:
def __init__(self, nums: list) -> None:
n = len(nums)
self.n = n
self.tree = [0] * (4 * n)
self.lazy = [0] * (4 * n)
self.build(nums, 1, 1, n)
def build(self, nums: list, o: int, l: int, r: int) -> None:
if l == r:
self.tree[o] = nums[l - 1]
return
m = (l + r) >> 1
self.build(nums, o * 2, l, m)
self.build(nums, o * 2 + 1, m + 1, r)
self.pushUp(o)
def xor(self, o: int, l: int, r: int) -> None:
self.tree[o] = r - l + 1 - self.tree[o] # 异或反转
self.lazy[o] ^= 1
def do(self, o: int, l: int, r: int, val: int) -> None:
self.tree[o] = r - l + 1 - self.tree[o] # 异或反转
self.lazy[o] ^= 1
def op(self, a: int, b: int) -> int:
# + - * / max min
return a + b
def maintain(self, o: int, l: int, r: int) -> None:
self.tree[o] = self.op(self.tree[l], self.tree[r])
self.lazy[o] ^= 1
def pushUp(self, o: int) -> None:
self.tree[o] = self.tree[o * 2] + self.tree[o * 2 + 1]
def pushDown(self, o: int, l: int, r: int) -> None:
m = (l + r) >> 1
self.do(o * 2, l, m, self.lazy[o]) # 调用相应的更新操作方法
self.do(o * 2 + 1, m + 1, r, self.lazy[o])
self.lazy[o] = 0
def update(self, o: int, l: int, r: int, L: int, R: int, val: int) -> None:
if L <= l and r <= R: # 当前区间已完全包含在更新区间,不需要继续往下更新,存在lazy
self.xor(o, l, r)
return
if self.lazy[o]: # 当前lazyd存在更新,往下传递
self.pushDown(o, l, r)
m = (l + r) >> 1
if m >= L: # 左节点在更新区间
self.update(o * 2, l, m, L, R, val)
if m < R: # 右节点在更新区间
self.update(o * 2 + 1, m + 1, r, L, R, val)
self.pushUp(o) # 从左右节点更新当前节点值
def query(self, o: int, l: int, r: int, L: int, R: int) -> int:
if R < l or L > r:
return 0
if L <= l and r <= R:
return self.tree[o]
if self.lazy[o]: # 当前lazyd存在更新,往下传递
self.pushDown(o, l, r)
m = (l + r) >> 1
res = 0
if m >= L: # 左节点在查询区间
res += self.query(o * 2, l, m, L, R)
if m < R: # 右节点在查询区间
res += self.query(o * 2 + 1, m + 1, r, L, R)
return res
def solve() -> None:
n = sint()
p = ints()
# 建图
g = [[] for _ in range(n)]
for i, u in enumerate(p, 1):
g[u - 1].append(i)
# DFN序
dfn, sz = dfs(g)
# print(dfn)
# print(sz)
t = ints()
nums = [0] * n
for i, v in enumerate(t):
nums[dfn[i]] = v
# print(nums)
st = SegTree(nums)
for _ in range(sint()):
qry = input().split()
u = int(qry[1]) - 1
if qry[0] == "get":
print(st.query(1, 1, n, dfn[u] + 1, dfn[u] + sz[u]))
else:
st.update(1, 1, n, dfn[u] + 1, dfn[u] + sz[u], 1)
# for _ in range(int(input())):
solve()
```
|
776
|
The Holmes Children
|
Title: The Holmes Children
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Holmes children are fighting over who amongst them is the cleverest.
Mycroft asked Sherlock and Eurus to find value of *f*(*n*), where *f*(1)<==<=1 and for *n*<=≥<=2, *f*(*n*) is the number of distinct ordered positive integer pairs (*x*,<=*y*) that satisfy *x*<=+<=*y*<==<=*n* and *gcd*(*x*,<=*y*)<==<=1. The integer *gcd*(*a*,<=*b*) is the greatest common divisor of *a* and *b*.
Sherlock said that solving this was child's play and asked Mycroft to instead get the value of . Summation is done over all positive integers *d* that divide *n*.
Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.
She defined a *k*-composite function *F**k*(*n*) recursively as follows:
She wants them to tell the value of *F**k*(*n*) modulo 1000000007.
Input Specification:
A single line of input contains two space separated integers *n* (1<=≤<=*n*<=≤<=1012) and *k* (1<=≤<=*k*<=≤<=1012) indicating that Eurus asks Sherlock and Mycroft to find the value of *F**k*(*n*) modulo 1000000007.
Output Specification:
Output a single integer — the value of *F**k*(*n*) modulo 1000000007.
Demo Input:
['7 1\n', '10 2\n']
Demo Output:
['6', '4']
Note:
In the first case, there are 6 distinct ordered pairs (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1) satisfying *x* + *y* = 7 and *gcd*(*x*, *y*) = 1. Hence, *f*(7) = 6. So, *F*<sub class="lower-index">1</sub>(7) = *f*(*g*(7)) = *f*(*f*(7) + *f*(1)) = *f*(6 + 1) = *f*(7) = 6.
|
```python
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def prime_factorize(n):
ans = []
for i in range(2, int(n ** (1 / 2)) + 1):
while True:
if n % i:
break
ans.append(i)
n //= i
if n == 1:
break
if not n == 1:
ans.append(n)
return ans
def euler_func(n):
p = set(prime_factorize(n))
x = n
for i in p:
x *= (i - 1)
x //= i
return x
n, k = map(int, input().split())
mod = pow(10, 9) + 7
k = (k + 1) // 2
ans = n
for _ in range(k):
if ans == 1:
break
ans = euler_func(ans)
ans %= mod
print(ans)
```
|
899
|
Segments Removal
|
Title: Segments Removal
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya has an array of integers of length *n*.
Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13,<=13,<=7,<=7,<=7,<=2,<=2,<=2], then after one operation it becomes [13,<=13,<=2,<=2,<=2].
Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=200<=000) — the length of the array.
The second line contains a sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109) — Vasya's array.
Output Specification:
Print the number of operations Vasya should make to remove all elements from the array.
Demo Input:
['4\n2 5 5 2\n', '5\n6 3 4 1 5\n', '8\n4 4 4 2 2 100 100 100\n', '6\n10 10 50 10 50 50\n']
Demo Output:
['2\n', '5\n', '3\n', '4\n']
Note:
In the first example, at first Vasya removes two fives at the second and third positions. The array becomes [2, 2]. In the second operation Vasya removes two twos at the first and second positions. After that the array becomes empty.
In the second example Vasya has to perform five operations to make the array empty. In each of them he removes the first element from the array.
In the third example Vasya needs three operations. In the first operation he removes all integers 4, in the second — all integers 100, in the third — all integers 2.
In the fourth example in the first operation Vasya removes the first two integers 10. After that the array becomes [50, 10, 50, 50]. Then in the second operation Vasya removes the two rightmost integers 50, so that the array becomes [50, 10]. In the third operation he removes the remaining 50, and the array becomes [10] after that. In the last, fourth operation he removes the only remaining 10. The array is empty after that.
|
```python
import heapq
class Node:
def __init__(self,idx,freq,val) -> None:
self.value=val
self.index=idx
self.occ=freq
self.front=None
self.back=None
class LinkedList:
def __init__(self) -> None:
self.head=None
self.h=[]
self.seen=[False]*200001
heapq.heapify(self.h)
self.ans=0
self.len=0
def insert(self,node) -> None:
if self.head==None:
self.head=node
else:
h=self.head
node.back=h
h.front=node
self.head=node
node.front=None
self.len+=1
heapq.heappush(self.h,(-1*node.occ,node.index,node))
def merge(self,l,r):
ll=l.back
rr=r.front
new_node=Node(min(r.index,l.index),l.occ+r.occ,l.value)
new_node.front=rr
new_node.back=ll
self.seen[max(l.index,r.index)]=True
if (rr!=None):
rr.back=new_node
if (ll!=None):
ll.front=new_node
heapq.heappush(self.h,(-1*new_node.occ,new_node.index,new_node))
return
def remove(self,node):
self.len-=1
if (self.head==node and self.len==0):
self.head=None
return
l=node.back
r=node.front
if (l!=None):
l.front=r
if r!=None:
r.back=l
if (l!=None and r!=None and l.value==r.value):
self.merge(l,r)
def next_val(self):
if len(self.h)==0:
return -1
f,idx,node=heapq.heappop(self.h)
if (not self.seen[idx]):
self.seen[idx]=True
self.remove(node)
self.ans+=1
return 1
def main(n,arr):
nodes=[]
val=arr[0]
idx=0
freq=1
for i in range(1,len(arr)):
if (arr[i]!=arr[i-1]):
node=Node(idx,freq,val)
nodes.append(node)
val=arr[i]
idx+=1
freq=1
else:
freq+=1
node=Node(idx,freq,val)
nodes.append(node)
l=LinkedList()
for i in range(len(nodes)-1,-1,-1):
l.insert(nodes[i])
s=l.next_val()
while (s!=-1):
s=l.next_val()
return l.ans
n=int(input())
arr=list(map(int,input().split()))
print(main(n,arr))
```
|
559
|
Gerald and Path
|
Title: Gerald and Path
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.
The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.
You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of spotlights. Each of the *n* lines contains two space-separated integers, *a**i* and *l**i* (0<=≤<=*a**i*<=≤<=108, 1<=≤<=*l**i*<=≤<=108). Number *a**i* shows how much further the *i*-th spotlight to the north, and number *l**i* shows the length of the segment it illuminates.
It is guaranteed that all the *a**i*'s are distinct.
Output Specification:
Print a single integer — the maximum total length of the illuminated part of the path.
Demo Input:
['3\n1 1\n2 2\n3 3\n', '4\n1 2\n3 3\n4 3\n6 2\n']
Demo Output:
['5\n', '9\n']
Note:
none
|
```python
import dataclasses
import sys
inf = float('inf')
# change stdout buffer size
buffer = open(1, 'w', 10**6)
# fast printing function
def print(*args, sep=' ', end='\n'):
buffer.write(sep.join(str(arg) for arg in args) + end)
# flush stdout
def flush():
buffer.flush()
def read_ints(index=None):
if index is not None:
return [(int(x), i + index) for i, x in enumerate(sys.stdin.readline().split())]
return [int(x) for x in sys.stdin.readline().split()]
def go(i, j, t):
pass
def solve():
n = int(input())
x = [0] * n
y = [0] * n
vs = set()
for i in range(n):
x[i], y[i] = read_ints()
vs.add(x[i] - y[i])
vs.add(x[i])
vs.add(x[i] + y[i])
v = list(vs)
v.sort()
nv = len(v)
num = dict()
for i in range(nv):
num[v[i]] = i
f = [0] * nv
w = [[] for _ in range(nv)]
for i in range(n):
a = num[x[i] - y[i]]
b = num[x[i]]
c = num[x[i] + y[i]]
f[b] = c
w[a].append(b)
dp = [[[0, 0] for _ in range(nv + 1)] for _ in range(nv + 1)]
for i in range(nv - 1, -1, -1):
for j in range(nv - 1, -1, -1):
for t in range(2):
if j < i:
dp[i][j][t] = dp[i][i][0]
continue
cur = dp[i + 1][j][t]
if (t == 0 or j > i) and f[i] > j:
cur = max(cur, dp[j + 1 if t else i + 1][f[i]][0] + v[f[i]] - v[j])
for k in w[i]:
if k > j:
cur = max(cur, dp[j + 1 if t else i + 1][k][1] + v[k] - v[j])
dp[i][j][t] = cur
print(dp[0][0][0])
flush()
if __name__ == '__main__':
solve()
```
|
676
|
The Last Fight Between Human and AI
|
Title: The Last Fight Between Human and AI
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.
The following game was chosen for the fights: initially there is a polynomial
Polynomial *P*(*x*) is said to be divisible by polynomial *Q*(*x*) if there exists a representation *P*(*x*)<==<=*B*(*x*)*Q*(*x*), where *B*(*x*) is also some polynomial.
Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?
Input Specification:
The first line of the input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000,<=|*k*|<=≤<=10<=000) — the size of the polynomial and the integer *k*.
The *i*-th of the following *n*<=+<=1 lines contain character '?' if the coefficient near *x**i*<=-<=1 is yet undefined or the integer value *a**i*, if the coefficient is already known (<=-<=10<=000<=≤<=*a**i*<=≤<=10<=000). Each of integers *a**i* (and even *a**n*) may be equal to 0.
Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.
Output Specification:
Print "Yes" (without quotes) if the human has winning strategy, or "No" (without quotes) otherwise.
Demo Input:
['1 2\n-1\n?\n', '2 100\n-10000\n0\n1\n', '4 5\n?\n1\n?\n1\n?\n']
Demo Output:
['Yes\n', 'Yes', 'No']
Note:
In the first sample, computer set *a*<sub class="lower-index">0</sub> to - 1 on the first move, so if human can set coefficient *a*<sub class="lower-index">1</sub> to 0.5 and win.
In the second sample, all coefficients are already set and the resulting polynomial is divisible by *x* - 100, so the human has won.
|
```python
n, k = map(int, input().split())
a = [input() for _ in range(n + 1)]
c = len([_ for _ in a if _ == '?'])
print('Yes' if k == 0 and (a[0] == '0' or a[0] == '?' and (n + 1 - c) % 2 == 1) or k != 0 and (c > 0 and n % 2 == 1 or c == 0 and sum([_ * pow(k, i, 10**15 + 91) for i, _ in enumerate(map(int, a))]) % (10**15 + 91) == 0) else 'No')
```
|
979
|
Kuro and Topological Parity
|
Title: Kuro and Topological Parity
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.
Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.
The paper is divided into $n$ pieces enumerated from $1$ to $n$. Shiro has painted some pieces with some color. Specifically, the $i$-th piece has color $c_{i}$ where $c_{i} = 0$ defines black color, $c_{i} = 1$ defines white color and $c_{i} = -1$ means that the piece hasn't been colored yet.
The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by at most one arrow. After that the players must choose the color ($0$ or $1$) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, $[1 \to 0 \to 1 \to 0]$, $[0 \to 1 \to 0 \to 1]$, $[1]$, $[0]$ are valid paths and will be counted. You can only travel from piece $x$ to piece $y$ if and only if there is an arrow from $x$ to $y$.
But Kuro is not fun yet. He loves parity. Let's call his favorite parity $p$ where $p = 0$ stands for "even" and $p = 1$ stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of $p$.
It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo $10^{9} + 7$.
Input Specification:
The first line contains two integers $n$ and $p$ ($1 \leq n \leq 50$, $0 \leq p \leq 1$) — the number of pieces and Kuro's wanted parity.
The second line contains $n$ integers $c_{1}, c_{2}, ..., c_{n}$ ($-1 \leq c_{i} \leq 1$) — the colors of the pieces.
Output Specification:
Print a single integer — the number of ways to put the arrows and choose colors so the number of valid paths of alternating colors has the parity of $p$.
Demo Input:
['3 1\n-1 0 1\n', '2 1\n1 0\n', '1 1\n-1\n']
Demo Output:
['6', '1', '2']
Note:
In the first example, there are $6$ ways to color the pieces and add the arrows, as are shown in the figure below. The scores are $3, 3, 5$ for the first row and $5, 3, 3$ for the second row, both from left to right.
|
```python
n,p=map(int,input().split())
nums=[0]+list(map(int,input().split()))
mod=10**9+7
f=[[[[0]*2 for _ in range(2)] for _ in range(2)] for _ in range(n+1)]
_2=[0]*(n+1)
_2[0]=1
for i in range(1,n+1):
_2[i]=(_2[i-1]<<1)%mod
f[0][0][0][0]=1
if nums[1]!=0:
f[1][1][0][1]+=1
if nums[1]!=1:
f[1][1][1][0]+=1
for i in range(2,n+1):
for j in range(2):
for ob in range(2):
for ow in range(2):
qwq=f[i-1][j][ob][ow]
if nums[i]!=0:
if ob:
f[i][j][ob][ow]=(f[i][j][ob][ow]+qwq*_2[i-2])%mod
f[i][j^1][ob][ow|1]=(f[i][j^1][ob][ow|1]+qwq*_2[i-2])%mod
else:
f[i][j^1][ob][ow|1]=(f[i][j^1][ob][ow|1]+qwq*_2[i-1])%mod
if nums[i]!=1:
if ow:
f[i][j][ob][ow]=(f[i][j][ob][ow]+qwq*_2[i-2])%mod
f[i][j^1][ob|1][ow]=(f[i][j^1][ob|1][ow]+qwq*_2[i-2])%mod
else:
f[i][j^1][ob|1][ow]=(f[i][j^1][ob|1][ow]+qwq*_2[i-1])%mod
ans=0
for i in range(2):
for j in range(2):
ans=(ans+f[n][p][i][j])%mod
print(ans)
```
|
496
|
Tennis Game
|
Title: Tennis Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores *t* points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of *s* sets, he wins the match and the match is over. Here *s* and *t* are some positive integer numbers.
To spice it up, Petya and Gena choose new numbers *s* and *t* before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores *t* points and the match is over as soon as one of the players wins *s* sets.
Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers *s* and *t* for the given match are also lost. The players now wonder what values of *s* and *t* might be. Can you determine all the possible options?
Input Specification:
The first line contains a single integer *n* — the length of the sequence of games (1<=≤<=*n*<=≤<=105).
The second line contains *n* space-separated integers *a**i*. If *a**i*<==<=1, then the *i*-th serve was won by Petya, if *a**i*<==<=2, then the *i*-th serve was won by Gena.
It is not guaranteed that at least one option for numbers *s* and *t* corresponds to the given record.
Output Specification:
In the first line print a single number *k* — the number of options for numbers *s* and *t*.
In each of the following *k* lines print two integers *s**i* and *t**i* — the option for numbers *s* and *t*. Print the options in the order of increasing *s**i*, and for equal *s**i* — in the order of increasing *t**i*.
Demo Input:
['5\n1 2 1 2 1\n', '4\n1 1 1 1\n', '4\n1 2 1 2\n', '8\n2 1 2 1 1 1 1 1\n']
Demo Output:
['2\n1 3\n3 1\n', '3\n1 4\n2 2\n4 1\n', '0\n', '3\n1 6\n2 3\n6 1\n']
Note:
none
|
```python
#!/usr/bin/env python3
import itertools
n = int(input())
a = [int(x) for x in input().split()]
winner = a[-1]
looser = 3 - winner
serve_win_cnt, serve_loose_cnt, win_pos, loose_pos, result = [0], [0], [-1], [-1], []
win_cnt = a.count(winner)
for i in range(n):
if a[i] == winner:
win_pos.append(i)
else:
loose_pos.append(i)
serve_win_cnt.append(serve_win_cnt[-1] + (a[i] == winner))
serve_loose_cnt.append(serve_loose_cnt[-1] + (a[i] == looser))
win_pos += [n * 10] * n
loose_pos += [n * 10] * n
serve_win_cnt += [0] * n
serve_loose_cnt += [0] * n
for t in itertools.chain(range(1, 1 + win_cnt // 2), [win_cnt]):
s = l = i = 0
sw = sl = 0
while i < n:
xw = win_pos[serve_win_cnt[i] + t]
xl = loose_pos[serve_loose_cnt[i] + t]
if xw < xl:
s += 1
else:
l += 1
i = min(xw, xl) + 1
if s > l and i <= n and serve_win_cnt[i] == win_cnt:
result.append((s, t))
print(len(result))
for (x, y) in sorted(result):
print(x, y)
```
|
757
|
Felicity's Big Secret Revealed
|
Title: Felicity's Big Secret Revealed
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The gym leaders were fascinated by the evolutions which took place at Felicity camp. So, they were curious to know about the secret behind evolving Pokemon.
The organizers of the camp gave the gym leaders a PokeBlock, a sequence of *n* ingredients. Each ingredient can be of type 0 or 1. Now the organizers told the gym leaders that to evolve a Pokemon of type *k* (*k*<=≥<=2), they need to make a valid set of *k* cuts on the PokeBlock to get smaller blocks.
Suppose the given PokeBlock sequence is *b*0*b*1*b*2... *b**n*<=-<=1. You have a choice of making cuts at *n*<=+<=1 places, i.e., Before *b*0, between *b*0 and *b*1, between *b*1 and *b*2, ..., between *b**n*<=-<=2 and *b**n*<=-<=1, and after *b**n*<=-<=1.
The *n*<=+<=1 choices of making cuts are as follows (where a | denotes a possible cut):
Consider a sequence of *k* cuts. Now each pair of consecutive cuts will contain a binary string between them, formed from the ingredient types. The ingredients before the first cut and after the last cut are wasted, which is to say they are not considered. So there will be exactly *k*<=-<=1 such binary substrings. Every substring can be read as a binary number. Let *m* be the maximum number out of the obtained numbers. If all the obtained numbers are positive and the set of the obtained numbers contains all integers from 1 to *m*, then this set of cuts is said to be a valid set of cuts.
For example, suppose the given PokeBlock sequence is 101101001110 and we made 5 cuts in the following way:
So the 4 binary substrings obtained are: 11, 010, 01 and 1, which correspond to the numbers 3, 2, 1 and 1 respectively. Here *m*<==<=3, as it is the maximum value among the obtained numbers. And all the obtained numbers are positive and we have obtained all integers from 1 to *m*. Hence this set of cuts is a valid set of 5 cuts.
A Pokemon of type *k* will evolve only if the PokeBlock is cut using a valid set of *k* cuts. There can be many valid sets of the same size. Two valid sets of *k* cuts are considered different if there is a cut in one set which is not there in the other set.
Let *f*(*k*) denote the number of valid sets of *k* cuts. Find the value of . Since the value of *s* can be very large, output *s* modulo 109<=+<=7.
Input Specification:
The input consists of two lines. The first line consists an integer *n* (1<=≤<=*n*<=≤<=75) — the length of the PokeBlock. The next line contains the PokeBlock, a binary string of length *n*.
Output Specification:
Output a single integer, containing the answer to the problem, i.e., the value of *s* modulo 109<=+<=7.
Demo Input:
['4\n1011\n', '2\n10\n']
Demo Output:
['10\n', '1\n']
Note:
In the first sample, the sets of valid cuts are:
Size 2: |1|011, 1|01|1, 10|1|1, 101|1|.
Size 3: |1|01|1, |10|1|1, 10|1|1|, 1|01|1|.
Size 4: |10|1|1|, |1|01|1|.
Hence, *f*(2) = 4, *f*(3) = 4 and *f*(4) = 2. So, the value of *s* = 10.
In the second sample, the set of valid cuts is:
Size 2: |1|0.
Hence, *f*(2) = 1 and *f*(3) = 0. So, the value of *s* = 1.
|
```python
mo = 10**9+7
def calc(l, r, si):
res = 0
for i in range(l, r + 1):
res = res * 2 + int(si[i])
return res
def main():
n, si = int(input()), input()
si = chr(0)+si
f = [[0]*(1<<20) for i in range(6)]
res, r, f[0][0]= 0, 0, 1
for i in range(1, n+1):
r=(r+1)%6
f[r] = [0]*(1<<20)
for j in range(1, min(5, i) + 1):
if si[i-j+1] != '0':
c, p = calc(i-j+1, i, si), (r-j+6)%6
if(c>20 or c<1): break
for s in range(1<<20):
if(f[p][s]):
f[r][s|(1<<(c-1))] = (f[r][s|(1<<(c-1))] + f[p][s]) % mo
for s in range(1, 21):
res = (res + f[r][(1<<s)-1]) % mo
f[r][0] = (f[r][0] + 1) % mo
if(si[i]=='0'):
p=(r-1+6)%6
for s in range(1<<20):
if(f[p][s]):
f[r][s] = (f[r][s] + f[p][s]) % mo
print(res)
main()
```
|
300
|
Beautiful Numbers
|
Title: Beautiful Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vitaly is a very weird man. He's got two favorite digits *a* and *b*. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits *a* and *b*. Vitaly calls a good number excellent, if the sum of its digits is a good number.
For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't.
Now Vitaly is wondering, how many excellent numbers of length exactly *n* are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (109<=+<=7).
A number's length is the number of digits in its decimal representation without leading zeroes.
Input Specification:
The first line contains three integers: *a*, *b*, *n* (1<=≤<=*a*<=<<=*b*<=≤<=9,<=1<=≤<=*n*<=≤<=106).
Output Specification:
Print a single integer — the answer to the problem modulo 1000000007 (109<=+<=7).
Demo Input:
['1 3 3\n', '2 3 10\n']
Demo Output:
['1\n', '165\n']
Note:
none
|
```python
import sys, threading
import math
from os import path
from collections import deque, defaultdict, Counter
from bisect import *
from string import ascii_lowercase
from functools import cmp_to_key
from random import randint
from heapq import *
from array import array
from types import GeneratorType
def readInts():
x = list(map(int, (sys.stdin.readline().rstrip().split())))
return x[0] if len(x) == 1 else x
def readList(type=int):
x = sys.stdin.readline()
x = list(map(type, x.rstrip('\n\r').split()))
return x
def readStr():
x = sys.stdin.readline().rstrip('\r\n')
return x
write = sys.stdout.write
read = sys.stdin.readline
MAXN = 1123456
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
class mydict:
def __init__(self, func=lambda: 0):
self.random = randint(0, 1 << 32)
self.default = func
self.dict = {}
def __getitem__(self, key):
mykey = self.random ^ key
if mykey not in self.dict:
self.dict[mykey] = self.default()
return self.dict[mykey]
def get(self, key, default):
mykey = self.random ^ key
if mykey not in self.dict:
return default
return self.dict[mykey]
def __setitem__(self, key, item):
mykey = self.random ^ key
self.dict[mykey] = item
def getkeys(self):
return [self.random ^ i for i in self.dict]
def __str__(self):
return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'
def lcm(a, b):
return (a*b)//(math.gcd(a,b))
def mod(n):
return n%(1000000007)
def power(bas, exp):
if (exp == 0):
return 1
if (exp == 1):
return bas
if (exp % 2 == 0):
t = power(bas, exp // 2)
t = mod(t * t)
return t
else:
return mod(power(bas, exp-1)*bas)
factr = []
factr = [1]
fact = 1
for i in range(1, MAXN):
fact = mod(mod(fact)*mod(i))
factr.append(fact)
def nCr(n, r):
if r > n:
return 0
n1 = factr[n]
d1 = power(factr[r], 1000000005)
d2 = power(factr[n-r], 1000000005)
return mod(mod(n1)*mod(d1)*mod(d2))
def solve(t):
# print(f'Case #{t}: ', end = '')
a, b, n = readInts()
ans = 0
for i in range(n+1):
sm = i*a + b*(n-i)
st = set(str(sm))
st.discard(str(a))
st.discard(str(b))
if len(st) > 0:
continue
ans = mod(ans + nCr(n, i))
print(ans)
def main():
t = 1
if path.exists("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/input.txt"):
sys.stdin = open("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/input.txt", 'r')
sys.stdout = open("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/output.txt", 'w')
# sys.setrecursionlimit(100000)
# t = readInts()
for i in range(t):
solve(i+1)
if __name__ == '__main__':
main()
```
|
713
|
Sonya and Problem Wihtout a Legend
|
Title: Sonya and Problem Wihtout a Legend
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing *n* positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
Input Specification:
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=3000) — the length of the array.
Next line contains *n* integer *a**i* (1<=≤<=*a**i*<=≤<=109).
Output Specification:
Print the minimum number of operation required to make the array strictly increasing.
Demo Input:
['7\n2 1 5 11 5 9 11\n', '5\n5 4 3 2 1\n']
Demo Output:
['9\n', '12\n']
Note:
In the first sample, the array is going to look as follows:
2 3 5 6 7 9 11
|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9
And for the second sample:
1 2 3 4 5
|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12
|
```python
from bisect import bisect_left as BL
n = int(input())
graph = [(-99**9, 0)] # x, slope
ans = 0
for i,a in enumerate(map(int,input().split())):
a-= i
new = []
turnj = BL(graph, (a,99**9)) - 1
if turnj != len(graph)-1:
ans+= graph[-1][0] - a
# add |x-a|
for j in range(turnj):
x, sl = graph[j]
new.append((x, sl-1))
for j in range(turnj, len(graph)):
x, sl = graph[j]
if j == turnj:
new.append((x, sl-1))
new.append((a, sl+1))
else: new.append((x, sl+1))
# remove positive slopes
graph = new
while graph[-1][1] > 0: x, sl = graph.pop()
if graph[-1][1] != 0: graph.append((x, 0))
print(ans)
```
|
340
|
Tourist Problem
|
Title: Tourist Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are *n* destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The *n* destinations are described by a non-negative integers sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents that the *k*th destination is at distance *a**k* kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer *x* and next destination, located at kilometer *y*, is |*x*<=-<=*y*| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all *n* destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
Input Specification:
The first line contains integer *n* (2<=≤<=*n*<=≤<=105). Next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=107).
Output Specification:
Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
Demo Input:
['3\n2 3 5\n']
Demo Output:
['22 3']
Note:
Consider 6 possible routes:
- [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; - [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; - [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; - [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; - [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; - [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8.
The average travel distance is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29119d3733c79f70eb2d77186ac1606bf938508a.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ee9d5516ed2ca1d2b65ed21f8a64f58f94954c30.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ed5cc8cb7dd43cfb27f2459586062538e44de7bd.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
|
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 3 11:57:46 2020
@author: shailesh
"""
from math import gcd
def reduce_fraction(x,y):
d = gcd(x,y)
x = x//d
y = y//d
return x,y
N = int(input())
A = [int(i) for i in input().split()]
A.sort()
d0 = A[0]
sum_val = 0
for i in range(N-1):
m_bf = i+2
m_af = N - i - 1
d = A[i+1]-A[i]
# d = 1
sum_val +=m_af*(2*m_bf - 1)*d
# print(A[i],A[i+1],sum_val)
numerator = N*d0 + sum_val
denominator = N
numerator,denominator = reduce_fraction(numerator,denominator)
print(numerator,denominator)
#from itertools import permutations
#perms = list(permutations([2,3,5]))
#
#perms = [(0,) + perm for perm in perms]
#
#d = {}
#d['02'] = 0
#d['23'] = 0
#d['35'] = 0
#for perm in perms:
# for i in range(len(perm)-1):
#
# start_end = [perm[i],perm[i+1]]
# start_end.sort()
# rng = range(start_end[0],start_end[1]+1)
# if 0 in rng and 2 in rng:
# d['02'] +=1
# if 2 in rng and 3 in rng:
# d['23'] += 1
# if 3 in rng and 5 in rng:
# d['35'] +=1
```
|
432
|
Prefixes and Suffixes
|
Title: Prefixes and Suffixes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You have a string *s*<==<=*s*1*s*2...*s*|*s*|, where |*s*| is the length of string *s*, and *s**i* its *i*-th character.
Let's introduce several definitions:
- A substring *s*[*i*..*j*] (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|) of string *s* is string *s**i**s**i*<=+<=1...*s**j*. - The prefix of string *s* of length *l* (1<=≤<=*l*<=≤<=|*s*|) is string *s*[1..*l*]. - The suffix of string *s* of length *l* (1<=≤<=*l*<=≤<=|*s*|) is string *s*[|*s*|<=-<=*l*<=+<=1..|*s*|].
Your task is, for any prefix of string *s* which matches a suffix of string *s*, print the number of times it occurs in string *s* as a substring.
Input Specification:
The single line contains a sequence of characters *s*1*s*2...*s*|*s*| (1<=≤<=|*s*|<=≤<=105) — string *s*. The string only consists of uppercase English letters.
Output Specification:
In the first line, print integer *k* (0<=≤<=*k*<=≤<=|*s*|) — the number of prefixes that match a suffix of string *s*. Next print *k* lines, in each line print two integers *l**i* *c**i*. Numbers *l**i* *c**i* mean that the prefix of the length *l**i* matches the suffix of length *l**i* and occurs in string *s* as a substring *c**i* times. Print pairs *l**i* *c**i* in the order of increasing *l**i*.
Demo Input:
['ABACABA\n', 'AAA\n']
Demo Output:
['3\n1 4\n3 2\n7 1\n', '3\n1 3\n2 2\n3 1\n']
Note:
none
|
```python
import sys
input = sys.stdin.readline
from collections import deque
S=input().strip()
LEN=len(S)
i=1
j=0
A=[0]*LEN
A[0]=LEN
while i<LEN:
while i+j<LEN and S[j]==S[i+j]:
j+=1
A[i]=j
if j==0:
i+=1
continue
k=1
while i+k<LEN and k+A[k]<j:
A[i+k]=A[k]
k+=1
i+=k
j-=k
ANS=[0]*(LEN+1)
for a in A:
ANS[a]+=1
for i in range(LEN-1,-1,-1):
ANS[i]+=ANS[i+1]
ANS2=[]
for i in range(1,LEN+1):
if A[LEN-i]==i:
ANS2.append((i,ANS[i]))
print(len(ANS2))
for x,y in ANS2:
print(x,y)
```
|
991
|
Bus Number
|
Title: Bus Number
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.
In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number $n$.
In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.
Given $n$, determine the total number of possible bus number variants.
Input Specification:
The first line contains one integer $n$ ($1 \leq n \leq 10^{18}$) — the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with $0$.
Output Specification:
Output a single integer — the amount of possible variants of the real bus number.
Demo Input:
['97\n', '2028\n']
Demo Output:
['2\n', '13\n']
Note:
In the first sample, only variants $97$ and $79$ are possible.
In the second sample, the variants (in the increasing order) are the following: $208$, $280$, $802$, $820$, $2028$, $2082$, $2208$, $2280$, $2802$, $2820$, $8022$, $8202$, $8220$.
|
```python
fact = [0 for _ in range(35)]
fact[0] = 1
for q in range(1,35):
fact[q] = fact[q-1]*q
amts = []
ans = 0
def multinom():
tot = 0
for i in amts:
tot = tot + i
ret = fact[tot]
for i in amts:
ret = ret / fact[i]
return ret
t = int(input())
digct = []
for i in range(10):
digct.append(0)
tcpy = t
while tcpy > 0:
digct[int(tcpy%10)] = digct[int(tcpy%10)]+1
tcpy = tcpy // 10
def dfs(place):
global ans
if place == 10:
ans = ans + multinom()
if amts[0] > 0:
amts[0] = amts[0]-1
ans = ans - multinom()
amts[0] = amts[0]+1
return
if digct[place] == 0:
amts.append(0)
dfs(place+1)
amts.pop()
else:
for q in range(1, digct[place]+1):
amts.append(q)
dfs(place+1)
amts.pop()
dfs(0)
print(int(ans))
```
|
459
|
Pashmak and Buses
|
Title: Pashmak and Buses
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Pashmak has been employed in a transportation company. The company has *k* buses and has a contract with a school which has *n* students. The school planned to take the students to *d* different places for *d* days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all *d* days.
Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.
Input Specification:
The first line of input contains three space-separated integers *n*,<=*k*,<=*d* (1<=≤<=*n*,<=*d*<=≤<=1000; 1<=≤<=*k*<=≤<=109).
Output Specification:
If there is no valid arrangement just print -1. Otherwise print *d* lines, in each of them print *n* integers. The *j*-th integer of the *i*-th line shows which bus the *j*-th student has to take on the *i*-th day. You can assume that the buses are numbered from 1 to *k*.
Demo Input:
['3 2 2\n', '3 2 1\n']
Demo Output:
['1 1 2 \n1 2 1 \n', '-1\n']
Note:
Note that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.
|
```python
from collections import defaultdict, deque, Counter
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
from random import randint
import math
import operator
import sys
from itertools import accumulate
#sys.stdin = open("sleepy.in", "r")
#sys.stdout = open("sleepy.out","w")
#input = sys.stdin.readline
#print = sys.stdout.write
hpop = heappop
hpush = heappush
MOD = 10**9 + 7
def add_one(arr,k):
for i in range(len(arr)):
if arr[i] < k - 1:
arr[i] += 1
break
arr[i] = 0
def solution():
n,k,d = map(int,input().split())
# check if its possible
if n > k**d:
return print(-1)
res = []
arr = [0]*d
for _ in range(n):
res.append(arr.copy())
add_one(arr, k)
for j in range(len(res[0])):
print(*[res[i][j] + 1 for i in range(len(res))])
# am going to use union find
# wowo
def main():
#test()
t = 1
#t = int(input())
for _ in range(t):
solution()
#import sys
#import threading
#sys.setrecursionlimit(10**6)
#threading.stack_size(1 << 27)
#thread = threading.Thread(target=main)
#thread.start(); thread.join()
main()
```
|
358
|
Dima and Hares
|
Title: Dima and Hares
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.
Dima felt so grateful to Inna about the present that he decided to buy her *n* hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to *n* from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?
Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and *n* don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.
Help Inna maximize the total joy the hares radiate. :)
Input Specification:
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=3000) — the number of hares. Then three lines follow, each line has *n* integers. The first line contains integers *a*1 *a*2 ... *a**n*. The second line contains *b*1,<=*b*2,<=...,<=*b**n*. The third line contains *c*1,<=*c*2,<=...,<=*c**n*. The following limits are fulfilled: 0<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=105.
Number *a**i* in the first line shows the joy that hare number *i* gets if his adjacent hares are both hungry. Number *b**i* in the second line shows the joy that hare number *i* radiates if he has exactly one full adjacent hare. Number *с**i* in the third line shows the joy that hare number *i* radiates if both his adjacent hares are full.
Output Specification:
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
Demo Input:
['4\n1 2 3 4\n4 3 2 1\n0 1 1 0\n', '7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3\n', '3\n1 1 1\n1 2 1\n1 1 1\n']
Demo Output:
['13\n', '44\n', '4\n']
Note:
none
|
```python
"""
Created on Fri Jan 18 12:23:03 2019
@author: nm57315
"""
n = int(input())
a,b,c = (list(map(int,input().strip().split())) for x in range(3))
d,e = a[0],b[0]
for x in range(1,n):
d,e = max(e+a[x],d+b[x]),max(e+b[x],d+c[x])
print(d)
```
|
338
|
GCD Table
|
Title: GCD Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Consider a table *G* of size *n*<=×<=*m* such that *G*(*i*,<=*j*)<==<=*GCD*(*i*,<=*j*) for all 1<=≤<=*i*<=≤<=*n*,<=1<=≤<=*j*<=≤<=*m*. *GCD*(*a*,<=*b*) is the greatest common divisor of numbers *a* and *b*.
You have a sequence of positive integer numbers *a*1,<=*a*2,<=...,<=*a**k*. We say that this sequence occurs in table *G* if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1<=≤<=*i*<=≤<=*n* and 1<=≤<=*j*<=≤<=*m*<=-<=*k*<=+<=1 should exist that *G*(*i*,<=*j*<=+<=*l*<=-<=1)<==<=*a**l* for all 1<=≤<=*l*<=≤<=*k*.
Determine if the sequence *a* occurs in table *G*.
Input Specification:
The first line contains three space-separated integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=1012; 1<=≤<=*k*<=≤<=10000). The second line contains *k* space-separated integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=1012).
Output Specification:
Print a single word "YES", if the given sequence occurs in table *G*, otherwise print "NO".
Demo Input:
['100 100 5\n5 2 1 2 1\n', '100 8 5\n5 2 1 2 1\n', '100 100 7\n1 2 3 4 5 6 7\n']
Demo Output:
['YES\n', 'NO\n', 'NO\n']
Note:
Sample 1. The tenth row of table *G* starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence *a*.
Sample 2. This time the width of table *G* equals 8. Sequence *a* doesn't occur there.
|
```python
from math import gcd
def LCM(a, b):
if min(a, b) == 0: return max(a, b)
return a // gcd(a, b) * b
class Eqn():
def __init__(self, r, mod):
self.r = r
self.mod = mod
def bye():
print("NO")
exit(0)
def exgcd(a, b):
if b == 0:
return (1, 0)
xp, yp = exgcd(b, a % b)
x = yp
y = xp - a // b * yp
return (x, y)
def merge(a, b):
newmode = LCM(a.mod, b.mod)
if (a.r - b.r) % gcd(a.mod, b.mod) != 0:
bye()
newr = exgcd(a.mod, b.mod)[0] * (b.r - a.r) // gcd(a.mod, b.mod) * a.mod + a.r
newr %= newmode
return Eqn(newr, newmode)
x, y = 0, 0
n, m, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
for i in a:
x = LCM(x, i)
if x > n:
bye()
cur = Eqn(0, 1)
for i in range(0, len(a)):
cur = merge(cur, Eqn((-i) % a[i], a[i]))
y = cur.r
if y == 0: y += x
for i in range(0, len(a)):
if gcd(x, y + i) != a[i]:
bye()
if x > n or y + k - 1 > m: bye()
print("YES")
```
|
272
|
Dima and Two Sequences
|
Title: Dima and Two Sequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Little Dima has two sequences of points with integer coordinates: sequence (*a*1,<=1),<=(*a*2,<=2),<=...,<=(*a**n*,<=*n*) and sequence (*b*1,<=1),<=(*b*2,<=2),<=...,<=(*b**n*,<=*n*).
Now Dima wants to count the number of distinct sequences of points of length 2·*n* that can be assembled from these sequences, such that the *x*-coordinates of points in the assembled sequence will not decrease. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.
Dima considers two assembled sequences (*p*1,<=*q*1),<=(*p*2,<=*q*2),<=...,<=(*p*2·*n*,<=*q*2·*n*) and (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x*2·*n*,<=*y*2·*n*) distinct, if there is such *i* (1<=≤<=*i*<=≤<=2·*n*), that (*p**i*,<=*q**i*)<=≠<=(*x**i*,<=*y**i*).
As the answer can be rather large, print the remainder from dividing the answer by number *m*.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). The third line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=109). The numbers in the lines are separated by spaces.
The last line contains integer *m* (2<=≤<=*m*<=≤<=109<=+<=7).
Output Specification:
In the single line print the remainder after dividing the answer to the problem by number *m*.
Demo Input:
['1\n1\n2\n7\n', '2\n1 2\n2 3\n11\n']
Demo Output:
['1\n', '2\n']
Note:
In the first sample you can get only one sequence: (1, 1), (2, 1).
In the second sample you can get such sequences : (1, 1), (2, 2), (2, 1), (3, 2); (1, 1), (2, 1), (2, 2), (3, 2). Thus, the answer is 2.
|
```python
n = int(input()) #tamaño de las sucesiones
a_n = input().split() #sucesion a_n
b_n = input().split() #sucesion b_n
k = int(input()) #numero para obtener un resultado de la forma km + r con 0 <= r < k
def solution(n, a_n, b_n, k):
c_n = {} #sucesion c_n que representa la union de a_n con b_n
d_n = {} #sucesion d_n que representa la intercepcion de a_n con b_n
result = 1 #resultado de la operacion
for a_i, b_i in zip(a_n, b_n): #recorremos a_n y b_n al mismo tiempo
if a_i == b_i: #si ambos elementos son iguales quiere decir que su par <x,y> es el mismo
d_n[a_i] = d_n.get(a_i,0) + 2 #ya que estamos iterando por la misma posicion en ambas sucesiones
#luego estos elementos pertenecen a la sucesion d_n
c_n[a_i] = c_n.get(a_i,0) + 1
c_n[b_i] = c_n.get(b_i,0) + 1 #añadimos ambos elementos a la sucesion c_n
#procedemos a allar el valor del resultado, este seria la combinacion de todas las posibles
#combinaciones de cada uno de los elementos que tengan el mismo valor: c_1*c_2*...*c_n
#por ende recorremos la sucesion c_n completa
for c_i, cant in c_n.items():
#ahora debemos de hallar las posibles combinaciones de c_i, estas se dividen en 2
#las que pertenecen a d_n y las que no pertenecen a d_n; notemos que si esta repetida
#significa que las posibles combinaciones entre ellas se van a repetir por 2,
#ya que solo existen un maximo de 2 elementos repetidos por cada d_i
cant_rep = d_n.get(c_i,0)
#hallamos las combinaciones de los elementos repetidos como
#la combinacion sin repeticion de todos los elementos entre 2
for i in range(cant - cant_rep + 1, cant, 2): result = (result * i * (i + 1) // 2) % k
#hallamos las combinaciones de los elementos no repetidos como
#la combinacion sin repeticion de todos los elementos
for i in range(1, cant - cant_rep + 1): result = (result * i) % k
#repetimos el proceso hasta el final de c_n; nocese que se multiplica directamente
#el valor del resultado y que en cada multiplicacion se aplica el resto de la misma
#esto es porque en la ecuacion general de: combin = km + r; setiene que si multiplicamos
#la ecuacion por un c quedaria: c*combin = c*km + c*r => combin' = km' + c*r => en la
#proxima multiplicacion solo queda hallar de nuevo el % k del resto c*r que queda y seria:
#combin' = km' + km'' + r' => combin' = k(m' + m'') + r'; y r' seria nuestro nuevo resto
return result
print(solution(n, a_n, b_n, k))
```
|
474
|
Flowers
|
Title: Flowers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size *k*.
Now Marmot wonders in how many ways he can eat between *a* and *b* flowers. As the number of ways could be very large, print it modulo 1000000007 (109<=+<=7).
Input Specification:
Input contains several test cases.
The first line contains two integers *t* and *k* (1<=≤<=*t*,<=*k*<=≤<=105), where *t* represents the number of test cases.
The next *t* lines contain two integers *a**i* and *b**i* (1<=≤<=*a**i*<=≤<=*b**i*<=≤<=105), describing the *i*-th test.
Output Specification:
Print *t* lines to the standard output. The *i*-th line should contain the number of ways in which Marmot can eat between *a**i* and *b**i* flowers at dinner modulo 1000000007 (109<=+<=7).
Demo Input:
['3 2\n1 3\n2 3\n4 4\n']
Demo Output:
['6\n5\n5\n']
Note:
- For *K* = 2 and length 1 Marmot can eat (*R*). - For *K* = 2 and length 2 Marmot can eat (*RR*) and (*WW*). - For *K* = 2 and length 3 Marmot can eat (*RRR*), (*RWW*) and (*WWR*). - For *K* = 2 and length 4 Marmot can eat, for example, (*WWWW*) or (*RWWR*), but for example he can't eat (*WWWR*).
|
```python
maxn = 10**5 + 5
mod = 10**9 + 7
test_case, k = map(int, input().split())
dp = [0] * maxn
sum = [0] * maxn
dp[0] = 1
for i in range(1, maxn):
dp[i] = dp[i - 1]
if (i >= k):
dp[i] = (dp[i] + dp[i - k]) % mod
for i in range(1, maxn):
sum[i] = (sum[i - 1] + dp[i]) % mod
for _ in range(test_case):
a, b = map(int, input().split())
print((sum[b] - sum[a - 1] + mod) % mod)
```
|
463
|
Gargari and Permutations
|
Title: Gargari and Permutations
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found *k* permutations. Each of them consists of numbers 1,<=2,<=...,<=*n* in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?
You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Input Specification:
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=1000; 2<=≤<=*k*<=≤<=5). Each of the next *k* lines contains integers 1,<=2,<=...,<=*n* in some order — description of the current permutation.
Output Specification:
Print the length of the longest common subsequence.
Demo Input:
['4 3\n1 4 2 3\n4 1 2 3\n1 2 4 3\n']
Demo Output:
['3\n']
Note:
The answer for the first test sample is subsequence [1, 2, 3].
|
```python
n, k = map(int, input().split())
a = [[]]*6
b = []
for i in range(6):
b.append([0]*(n + 1))
for i in range(k):
a[i] = list(map(int, input().split()))
for j in range(n):
b[i][a[i][j]] = j
dp = [1] * n
for i in range(n):
for j in range(i):
key = 1
for t in range(1, k):
if b[t][a[0][j]] > b[t][a[0][i]]:
key = 0
break
if key:
dp[i] = max(dp[i], dp[j] + 1)
print(max(dp))
```
|
584
|
Dima and Lisa
|
Title: Dima and Lisa
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer *n*. Find a set of numbers *p**i* (1<=≤<=*i*<=≤<=*k*), such that
1. 1<=≤<=*k*<=≤<=31. *p**i* is a prime1.
The numbers *p**i* do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.
Input Specification:
The single line contains an odd number *n* (3<=≤<=*n*<=<<=109).
Output Specification:
In the first line print *k* (1<=≤<=*k*<=≤<=3), showing how many numbers are in the representation you found.
In the second line print numbers *p**i* in any order. If there are multiple possible solutions, you can print any of them.
Demo Input:
['27\n']
Demo Output:
['3\n5 11 11\n']
Note:
A prime is an integer strictly larger than one that is divisible only by one and by itself.
|
```python
import sys
import random
input = sys.stdin.readline
rd = random.randint(10 ** 9, 2 * 10 ** 9)
n = int(input())
def isPrime(x: int) -> bool:
if x < 3:
return x == 2
if x % 2 != 1:
return False
A = [2, 325, 9375, 28178, 450775, 9780504, 1795265022]
d = x - 1
r = 0
while d % 2 == 0:
r += 1
d //= 2
for a in A:
v = pow(a, d, x)
if v <= 1 or v == x - 1:
continue
for i in range(r):
v = v * v % x
if v == x - 1 and i != r - 1:
v = 1
break
# 在中途而非开头得到1,却没有经过 - 1,说明存在其他数字y≠-1满足y ^ 2≡1,则x一定不是奇素数
if v == 1:
return False
if v != 1:
return False
return True
if isPrime(n):
print(1)
print(n)
else:
ps = []
for i in range(2,10 ** 4):
if isPrime(i):
ps.append(i)
for p in ps:
if isPrime(n - p):
print(2)
print(p, n - p)
exit()
else:
for p1 in ps:
for p2 in ps:
if isPrime(n - p1 - p2):
print(3)
print(p1, p2, n - p1 - p2)
exit()
```
|
975
|
Ghosts
|
Title: Ghosts
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.
There are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$ where $V_{x}$ is its speed on the $x$-axis and $V_{y}$ is on the $y$-axis.
A ghost $i$ has experience value $EX_i$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.
As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $GX = \sum_{i=1}^{n} EX_i$ will never increase.
Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $T$, and magically all the ghosts were aligned on a line of the form $y = a \cdot x + b$. You have to compute what will be the experience index of the ghost kind $GX$ in the indefinite future, this is your task for today.
Note that when Tameem took the picture, $GX$ may already be greater than $0$, because many ghosts may have scared one another at any moment between $[-\infty, T]$.
Input Specification:
The first line contains three integers $n$, $a$ and $b$ ($1 \leq n \leq 200000$, $1 \leq |a| \leq 10^9$, $0 \le |b| \le 10^9$) — the number of ghosts in the universe and the parameters of the straight line.
Each of the next $n$ lines contains three integers $x_i$, $V_{xi}$, $V_{yi}$ ($-10^9 \leq x_i \leq 10^9$, $-10^9 \leq V_{x i}, V_{y i} \leq 10^9$), where $x_i$ is the current $x$-coordinate of the $i$-th ghost (and $y_i = a \cdot x_i + b$).
It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all $(i,j)$ $x_i \neq x_j$ for $i \ne j$.
Output Specification:
Output one line: experience index of the ghost kind $GX$ in the indefinite future.
Demo Input:
['4 1 1\n1 -1 -1\n2 1 1\n3 1 1\n4 -1 -1\n', '3 1 0\n-1 1 0\n0 0 -1\n1 -1 -2\n', '3 1 0\n0 0 0\n1 0 0\n2 0 0\n']
Demo Output:
['8\n', '6\n', '0\n']
Note:
There are four collisions $(1,2,T-0.5)$, $(1,3,T-1)$, $(2,4,T+1)$, $(3,4,T+0.5)$, where $(u,v,t)$ means a collision happened between ghosts $u$ and $v$ at moment $t$. At each collision, each ghost gained one experience point, this means that $GX = 4 \cdot 2 = 8$.
In the second test, all points will collide when $t = T + 1$.
The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity.
|
```python
import sys
if locals()['__file__'][-2:] == 'py':
sys.stdin = open('in.txt', 'r')
from sys import stdin
rl = lambda l: tuple(map(int, l.split()))
n, a, b = rl(input())
l = list(map(rl, stdin.readlines()))
c, d = {}, {}
r = 0
for _, x, y in l:
i, j = a * x - y, (x, y)
r += c.get(i, 0) - d.get(j, 0)
c[i] = c.get(i, 0) + 1
d[j] = d.get(j, 0) + 1
print(2 * r)
```
|
765
|
Artsem and Saunders
|
Title: Artsem and Saunders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.
Let [*n*] denote the set {1,<=...,<=*n*}. We will also write *f*:<=[*x*]<=→<=[*y*] when a function *f* is defined in integer points 1, ..., *x*, and all its values are integers from 1 to *y*.
Now then, you are given a function *f*:<=[*n*]<=→<=[*n*]. Your task is to find a positive integer *m*, and two functions *g*:<=[*n*]<=→<=[*m*], *h*:<=[*m*]<=→<=[*n*], such that *g*(*h*(*x*))<==<=*x* for all , and *h*(*g*(*x*))<==<=*f*(*x*) for all , or determine that finding these is impossible.
Input Specification:
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105).
The second line contains *n* space-separated integers — values *f*(1),<=...,<=*f*(*n*) (1<=≤<=*f*(*i*)<=≤<=*n*).
Output Specification:
If there is no answer, print one integer -1.
Otherwise, on the first line print the number *m* (1<=≤<=*m*<=≤<=106). On the second line print *n* numbers *g*(1),<=...,<=*g*(*n*). On the third line print *m* numbers *h*(1),<=...,<=*h*(*m*).
If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.
Demo Input:
['3\n1 2 3\n', '3\n2 2 2\n', '2\n2 1\n']
Demo Output:
['3\n1 2 3\n1 2 3\n', '1\n1 1 1\n2\n', '-1\n']
Note:
none
|
```python
n = int(input())
f = [y for y in map(int, input().split())]
im_f = list(set(f))
ok = True
for y in im_f:
index = y - 1
ok &= f[index] == y
if ok:
m = len(im_f)
ind = {}
for i, y in enumerate(im_f):
ind[y] = i + 1
print(m)
values = []
for y in f:
values.append(ind[y])
print(' '.join(map(str, values)))
print(' '.join(map(str, im_f)))
else:
print(-1)
```
|
190
|
Non-Secret Cypher
|
Title: Non-Secret Cypher
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.
The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number *m*, the enemies use an array of integers *a*. The number of its subarrays, in which there are at least *k* equal numbers, equals *m*. The number *k* has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.
Help Vasya, given an array of integers *a* and number *k*, find the number of subarrays of the array of numbers *a*, which has at least *k* equal numbers.
Subarray *a*[*i*... *j*] (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) of array *a*<==<=(*a*1,<=*a*2,<=...,<=*a**n*) is an array, made from its consecutive elements, starting from the *i*-th one and ending with the *j*-th one: *a*[*i*... *j*]<==<=(*a**i*,<=*a**i*<=+<=1,<=...,<=*a**j*).
Input Specification:
The first line contains two space-separated integers *n*, *k* (1<=≤<=*k*<=≤<=*n*<=≤<=4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.
The second line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=109) — elements of the array.
Output Specification:
Print the single number — the number of such subarrays of array *a*, that they have at least *k* equal integers.
Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.
Demo Input:
['4 2\n1 2 1 2\n', '5 3\n1 2 1 1 3\n', '3 1\n1 1 1\n']
Demo Output:
['3', '2', '6']
Note:
In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).
In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).
In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
|
```python
from collections import defaultdict
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
window = defaultdict(lambda : 0)
window[a[0]] += 1
i, j, ans = 0, 0, 0
while i < n and j < n:
if window[a[j]] >= k:
ans += n-j
window[a[i]] -= 1
i += 1
elif j < n-1:
window[a[j+1]] += 1
j += 1
else: break
print(ans)
```
|
285
|
Permutation Sum
|
Title: Permutation Sum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Permutation *p* is an ordered set of integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n*, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. We'll denote the *i*-th element of permutation *p* as *p**i*. We'll call number *n* the size or the length of permutation *p*1,<=<=*p*2,<=<=...,<=<=*p**n*.
Petya decided to introduce the sum operation on the set of permutations of length *n*. Let's assume that we are given two permutations of length *n*: *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n*. Petya calls the sum of permutations *a* and *b* such permutation *c* of length *n*, where *c**i*<==<=((*a**i*<=-<=1<=+<=*b**i*<=-<=1) *mod* *n*)<=+<=1 (1<=≤<=*i*<=≤<=*n*).
Operation means taking the remainder after dividing number *x* by number *y*.
Obviously, not for all permutations *a* and *b* exists permutation *c* that is sum of *a* and *b*. That's why Petya got sad and asked you to do the following: given *n*, count the number of such pairs of permutations *a* and *b* of length *n*, that exists permutation *c* that is sum of *a* and *b*. The pair of permutations *x*,<=*y* (*x*<=≠<=*y*) and the pair of permutations *y*,<=*x* are considered distinct pairs.
As the answer can be rather large, print the remainder after dividing it by 1000000007 (109<=+<=7).
Input Specification:
The single line contains integer *n* (1<=≤<=*n*<=≤<=16).
Output Specification:
In the single line print a single non-negative integer — the number of such pairs of permutations *a* and *b*, that exists permutation *c* that is sum of *a* and *b*, modulo 1000000007 (109<=+<=7).
Demo Input:
['3\n', '5\n']
Demo Output:
['18\n', '1800\n']
Note:
none
|
```python
import sys
input = sys.stdin.buffer.readline
def process(n):
A = [1, 3, 15, 133, 2025, 37851, 1030367, 36362925, 1606008513, 87656896891, 5778121715415, 452794797220965, 41609568918940625]
if n % 2==0:
sys.stdout.write('0\n')
else:
p = 10**9+7
A1 = A[n//2] % p
for i in range(1, n+1):
A1 = (A1*i) % p
sys.stdout.write(f'{A1}\n')
return
n = int(input())
process(n)
```
|
222
|
Olympiad
|
Title: Olympiad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least *x* points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
Input Specification:
The first line contains two space-separated integers *n*,<=*x* (1<=≤<=*n*<=≤<=105; 0<=≤<=*x*<=≤<=2·105) — the number of Olympiad participants and the minimum number of points Vasya earned.
The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=105) — the participants' points in the first tour.
The third line contains *n* space-separated integers: *b*1,<=*b*2,<=...,<=*b**n* (0<=≤<=*b**i*<=≤<=105) — the participants' points in the second tour.
The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers *i*,<=*j* (1<=≤<=*i*,<=*j*<=≤<=*n*) such, that *a**i*<=+<=*b**j*<=≥<=*x*.
Output Specification:
Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad.
Demo Input:
['5 2\n1 1 1 1 1\n1 1 1 1 1\n', '6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n']
Demo Output:
['1 5\n', '1 5\n']
Note:
In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.
In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.
In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.
In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
|
```python
from sys import stdin,stdout
import bisect as bs
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
n,sm=lst()
a=sorted(lst(),reverse=1)
b=sorted(lst())
used=-1
rank=1
# print(a)
# print(b)
p=-1
for i in range(n):
v1=a[i]
p=bs.bisect_left(b,sm-v1,p+1,n)
# print(a[i],p)
if p>=n:
rank=i
# print(rank)
break
rank=i+1
print(1,rank)
```
|
508
|
Tanya and Password
|
Title: Tanya and Password
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of *n*<=+<=2 characters. She has written all the possible *n* three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with *n* pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2·105), the number of three-letter substrings Tanya got.
Next *n* lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output Specification:
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Demo Input:
['5\naca\naba\naba\ncab\nbac\n', '4\nabc\nbCb\ncb1\nb13\n', '7\naaa\naaa\naaa\naaa\naaa\naaa\naaa\n']
Demo Output:
['YES\nabacaba\n', 'NO\n', 'YES\naaaaaaaaa\n']
Note:
none
|
```python
from collections import defaultdict, deque
def find_eulerian_path(graph):
in_degree = defaultdict(int)
out_degree = defaultdict(int)
for u in graph:
for v in graph[u]:
out_degree[u] += 1
in_degree[v] += 1
start = None
end = None
for node in set(in_degree.keys()) | set(out_degree.keys()):
if in_degree[node] == out_degree[node]:
continue
elif in_degree[node] == out_degree[node] + 1:
if end is not None:
return None
end = node
elif in_degree[node] + 1 == out_degree[node]:
if start is not None:
return None
start = node
else:
return None
if start is None:
start = next(iter(graph))
stack = [start]
path = []
while stack:
u = stack[-1]
if not graph[u]:
path.append(stack.pop())
else:
v = graph[u].pop()
stack.append(v)
if len(path) != sum(out_degree.values()) + 1:
return None
return path[::-1]
n = int(input())
edges = [input().strip() for _ in range(n)]
graph = defaultdict(list)
for edge in edges:
u, v = edge[:2], edge[1:]
graph[u].append(v)
path = find_eulerian_path(graph)
if path is None:
print('NO')
else:
print('YES')
password = path[0]
for node in path[1:]:
password += node[-1]
print(password)
```
|
552
|
Vanya and Triangles
|
Title: Vanya and Triangles
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vanya got bored and he painted *n* distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of the points painted on the plane.
Next *n* lines contain two integers each *x**i*,<=*y**i* (<=-<=100<=≤<=*x**i*,<=*y**i*<=≤<=100) — the coordinates of the *i*-th point. It is guaranteed that no two given points coincide.
Output Specification:
In the first line print an integer — the number of triangles with the non-zero area among the painted points.
Demo Input:
['4\n0 0\n1 1\n2 0\n2 2\n', '3\n0 0\n1 1\n2 0\n', '1\n1 1\n']
Demo Output:
['3\n', '1\n', '0\n']
Note:
Note to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).
Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).
Note to the third sample test. A single point doesn't form a single triangle.
|
```python
import math
from collections import defaultdict
class Solution:
def maxPoints(self, points):
ans=0
n=len(points)
if n<=2:
return ans
def customise_gcd(x,y):
if x==0 and y==0:
return 1
if x==0:
return y
elif y==0:
return x
else:
return math.gcd(x,y)
def substitube(y,x):
if x==0:
y=1
elif y==0:
x=1
elif (x<0 and y<0) or x<0:
return y*(-1),x*(-1)
return y,x
cnt=0
for i in range(n):
mx=0
rp=0
dt=defaultdict(int)
for j in range(i+1,n):
if points[i]==points[j]:
rp+=1
else:
delta_y=points[j][1]-points[i][1]
delta_x=points[j][0]-points[i][0]
gd=customise_gcd(abs(delta_y),abs(delta_x))
delta_y,delta_x=substitube(delta_y//gd,delta_x//gd)
dt[(delta_y,delta_x)]+=1
for val in dt.values():
if val>=2:
cnt+=(val*(val-1))//2
ttl=n*(n-1)*(n-2)//6
ans=ttl-cnt
return ans
I=lambda: map(int,input().split())
ob=Solution()
n=int(input())
points=[]
for i in range(n):
x,y=I()
points+=[[x,y]]
print(ob.maxPoints(points))
```
|
219
|
Choosing Capital for Treeland
|
Title: Choosing Capital for Treeland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The country Treeland consists of *n* cities, some pairs of them are connected with unidirectional roads. Overall there are *n*<=-<=1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city *a* is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city *a* to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input Specification:
The first input line contains integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of cities in Treeland. Next *n*<=-<=1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers *s**i*,<=*t**i* (1<=≤<=*s**i*,<=*t**i*<=≤<=*n*; *s**i*<=≠<=*t**i*) — the numbers of cities, connected by that road. The *i*-th road is oriented from city *s**i* to city *t**i*. You can consider cities in Treeland indexed from 1 to *n*.
Output Specification:
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Demo Input:
['3\n2 1\n2 3\n', '4\n1 4\n2 4\n3 4\n']
Demo Output:
['0\n2 \n', '2\n1 2 3 \n']
Note:
none
|
```python
num_nodes = int(input())
time_array = [0] * (num_nodes + 1)
forward_edges, backward_edges = [[] for _ in range(num_nodes + 1)], [[] for _ in range(num_nodes + 1)]
for _ in range(num_nodes - 1):
x, y = map(int, input().split())
time_array[y] = 1
forward_edges[x].append(y)
backward_edges[y].append(x)
traversal_queue, leaf_count = forward_edges[1] + backward_edges[1], len(backward_edges[1])
for i in forward_edges[1]:
time_array[i] = 1
backward_edges[i].remove(1)
for i in backward_edges[1]:
time_array[i] = -1
forward_edges[i].remove(1)
while traversal_queue:
current_node = traversal_queue.pop()
for i in forward_edges[current_node]:
time_array[i] = time_array[current_node] + 1
backward_edges[i].remove(current_node)
for i in backward_edges[current_node]:
time_array[i] = time_array[current_node] - 1
forward_edges[i].remove(current_node)
traversal_queue += forward_edges[current_node] + backward_edges[current_node]
leaf_count += len(backward_edges[current_node])
min_time = min(time_array)
print(leaf_count + min_time)
print(' '.join(map(str, [i for i in range(1, num_nodes + 1) if time_array[i] == min_time])))
```
|
394
|
Physical Education and Buns
|
Title: Physical Education and Buns
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.
To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum.
Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression.
Input Specification:
The single line contains integer *n* (2<=≤<=*n*<=≤<=103) — the number of students. The second line contains *n* space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 104.
Output Specification:
In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative.
If there are multiple possible answers, you can print any of them.
Demo Input:
['5\n-3 -4 -2 -3 3\n', '5\n2 -3 -1 -4 3\n']
Demo Output:
['2\n-3 1\n', '1\n-4 2\n']
Note:
Lets look at the first sample. We can proceed in the following manner:
- don't feed the 1-st student, his height will stay equal to -3; - give two buns of the first type to the 2-nd student, his height become equal to -2; - give two buns of the first type to the 3-rd student, his height become equal to 0; - give two buns of the first type to the 4-th student, his height become equal to -1; - give two buns of the second type to the 5-th student, his height become equal to 1.
To sum it up, when the students line up in non-decreasing height it will be an arithmetic progression: -3, -2, -1, 0, 1. The height of the lowest student is equal to -3, the step of the progression is equal to 1. The maximum number of buns eaten by one student is equal to 2.
|
```python
q = 10001
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(40000 // (n - 1) + 1):
b = [a[j] - j * i for j in range(n)]
u, v = max(b), min(b)
p = (u - v + 1) // 2
if p < q: q, s, d = p, v + p, i
print(q)
print(s, d)
```
|
295
|
Greg and Caves
|
Title: Greg and Caves
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Greg has a pad. The pad's screen is an *n*<=×<=*m* rectangle, each cell can be either black or white. We'll consider the pad rows to be numbered with integers from 1 to *n* from top to bottom. Similarly, the pad's columns are numbered with integers from 1 to *m* from left to right.
Greg thinks that the pad's screen displays a cave if the following conditions hold:
- There is a segment [*l*,<=*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=*n*), such that each of the rows *l*,<=*l*<=+<=1,<=...,<=*r* has exactly two black cells and all other rows have only white cells. - There is a row number *t* (*l*<=≤<=*t*<=≤<=*r*), such that for all pairs of rows with numbers *i* and *j* (*l*<=≤<=*i*<=≤<=*j*<=≤<=*t*) the set of columns between the black cells in row *i* (with the columns where is these black cells) is the subset of the set of columns between the black cells in row *j* (with the columns where is these black cells). Similarly, for all pairs of rows with numbers *i* and *j* (*t*<=≤<=*i*<=≤<=*j*<=≤<=*r*) the set of columns between the black cells in row *j* (with the columns where is these black cells) is the subset of the set of columns between the black cells in row *i* (with the columns where is these black cells).
Greg wondered, how many ways there are to paint a cave on his pad. Two ways can be considered distinct if there is a cell that has distinct colors on the two pictures.
Help Greg.
Input Specification:
The first line contains two integers *n*, *m* — the pad's screen size (1<=≤<=*n*,<=*m*<=≤<=2000).
Output Specification:
In the single line print the remainder after dividing the answer to the problem by 1000000007 (109<=+<=7).
Demo Input:
['1 1\n', '4 4\n', '3 5\n']
Demo Output:
['0\n', '485\n', '451\n']
Note:
none
|
```python
M=10**9+7
n,m=[int(e) for e in input().split()]
if m<2:
print(0)
else:
F=[[0]*(m+1) for i in range(n+1)]
Fsum=[[0]*(m+1) for i in range(n+1)]
for j in range(2,m+1):
F[1][j]=1
Fsum[1][j]=Fsum[1][j-1]+F[1][j]
for i in range(2,n+1):
s=1
for j in range(2,m+1):
s+=Fsum[i-1][j]
s%=M
F[i][j]=s
Fsum[i][j]=Fsum[i][j-1]+F[i][j]
Fsum[i][j]%=M
s=0
for i in range(1,n+1):
for j in range(2,m+1):
s+=(m-j+1)*(F[i][j]*(F[n-i+1][j]-F[n-i][j]))
s%=M
print(s)
```
|
271
|
Good Substrings
|
Title: Good Substrings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got string *s*, consisting of small English letters. Some of the English letters are good, the rest are bad.
A substring *s*[*l*...*r*] (1<=≤<=*l*<=≤<=*r*<=≤<=|*s*|) of string *s*<=<==<=<=*s*1*s*2...*s*|*s*| (where |*s*| is the length of string *s*) is string <=*s**l**s**l*<=+<=1...*s**r*.
The substring *s*[*l*...*r*] is good, if among the letters <=*s**l*,<=*s**l*<=+<=1,<=...,<=*s**r* there are at most *k* bad ones (look at the sample's explanation to understand it more clear).
Your task is to find the number of distinct good substrings of the given string *s*. Two substrings *s*[*x*...*y*] and *s*[*p*...*q*] are considered distinct if their content is different, i.e. *s*[*x*...*y*]<=≠<=*s*[*p*...*q*].
Input Specification:
The first line of the input is the non-empty string *s*, consisting of small English letters, the string's length is at most 1500 characters.
The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the *i*-th character of this string equals "1", then the *i*-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on.
The third line of the input consists a single integer *k* (0<=≤<=*k*<=≤<=|*s*|) — the maximum acceptable number of bad characters in a good substring.
Output Specification:
Print a single integer — the number of distinct good substrings of string *s*.
Demo Input:
['ababab\n01000000000000000000000000\n1\n', 'acbacbacaa\n00000000000000000000000000\n2\n']
Demo Output:
['5\n', '8\n']
Note:
In the first example there are following good substrings: "a", "ab", "b", "ba", "bab".
In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".
|
```python
s = input()
alpha = input()
k = int(input())
subs = sorted(s[i:] for i in range(len(s)))
prev = ''
ans = 0
for j in subs:
uni = False
bad = 0
for i in range(len(j)):
if i >= len(prev) or prev[i] != j[i]:
uni = True
if alpha[ord(j[i])-ord('a')] == '0':
bad += 1
if bad > k:
break
if uni:
ans += 1
prev = j
print(ans)
```
|
404
|
Minesweeper 1D
|
Title: Minesweeper 1D
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is *n* squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.
For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.
Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of *n* cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.
Input Specification:
The first line contains sequence of characters without spaces *s*1*s*2... *s**n* (1<=≤<=*n*<=≤<=106), containing only characters "*", "?" and digits "0", "1" or "2". If character *s**i* equals "*", then the *i*-th cell of the field contains a bomb. If character *s**i* equals "?", then Valera hasn't yet decided what to put in the *i*-th cell. Character *s**i*, that is equal to a digit, represents the digit written in the *i*-th square.
Output Specification:
Print a single integer — the number of ways Valera can fill the empty cells and get a correct field.
As the answer can be rather large, print it modulo 1000000007 (109<=+<=7).
Demo Input:
['?01???\n', '?\n', '**12\n', '1\n']
Demo Output:
['4\n', '2\n', '0\n', '0\n']
Note:
In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
|
```python
import sys
from collections import Counter, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heapify, heappop, heappush
from queue import deque
input = lambda: sys.stdin.readline().strip()
from math import gcd, inf, sqrt
def mrd(fun=int): return [fun(x) for x in input().split()]
def rd(fun=int): return fun(input())
mod = 10**9 + 7
def solve():
s = input()
f = [0] * 5
f[0] = f[2] = 1
for c in s:
g = [0] * 5
if c == '0':
g[0] = sum(f[:2]) % mod
elif c == '1':
g[1], g[2] = f[4], sum(f[:2]) % mod
elif c == '2':
g[3] = f[4]
elif c == '*':
g[4] = sum(f[2:]) % mod
else:
g[0] = sum(f[:2]) % mod
g[1], g[2] = f[4], sum(f[:2]) % mod
g[3] = f[4]
g[4] = sum(f[2:]) % mod
f = g
print((f[0] + f[1] + f[4]) % mod)
t = 1
for _ in range(t):
solve()
```
|
733
|
Kostya the Sculptor
|
Title: Kostya the Sculptor
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.
Zahar has *n* stones which are rectangular parallelepipeds. The edges sizes of the *i*-th of them are *a**i*, *b**i* and *c**i*. He can take no more than two stones and present them to Kostya.
If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way.
Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
Input Specification:
The first line contains the integer *n* (1<=≤<=*n*<=≤<=105).
*n* lines follow, in the *i*-th of which there are three integers *a**i*,<=*b**i* and *c**i* (1<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=109) — the lengths of edges of the *i*-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
Output Specification:
In the first line print *k* (1<=≤<=*k*<=≤<=2) the number of stones which Zahar has chosen. In the second line print *k* distinct integers from 1 to *n* — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to *n* in the order as they are given in the input data.
You can print the stones in arbitrary order. If there are several answers print any of them.
Demo Input:
['6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4\n', '7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7\n']
Demo Output:
['1\n1\n', '2\n1 5\n']
Note:
In the first example we can connect the pairs of stones:
- 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. - 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 - 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5
Or take only one stone:
- 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 - 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 - 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 - 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5
It is most profitable to take only the first stone.
|
```python
n = int(input())
INF = 10**10
ind = 0
ans = 0
temp = 0
a = []
d = dict()
S = sorted([sorted(list(map(int, input().split())) , reverse = True) + [i + 1] for i in range(n)], reverse = True)
ans = S[0][2]
a = [S[0][-1]]
for i in range(1, n):
if S[i][0] == S[i-1][0] and S[i][1] == S[i-1][1]:
temp = min(S[i][0], S[i][1], S[i][2] + S[i-1][2])
if temp > ans:
ans = temp
a = [S[i][-1],S[i-1][-1]]
elif S[i][2] > ans:
ans =S[i][2]
a = [S[i][-1]]
a.sort()
print(len(a))
print(*a)
```
|
276
|
Little Girl and Maximum XOR
|
Title: Little Girl and Maximum XOR
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A little girl loves problems on bitwise operations very much. Here's one of them.
You are given two integers *l* and *r*. Let's consider the values of for all pairs of integers *a* and *b* (*l*<=≤<=*a*<=≤<=*b*<=≤<=*r*). Your task is to find the maximum value among all considered ones.
Expression means applying bitwise excluding or operation to integers *x* and *y*. The given operation exists in all modern programming languages, for example, in languages *C*++ and *Java* it is represented as "^", in *Pascal* — as "xor".
Input Specification:
The single line contains space-separated integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=1018).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output Specification:
In a single line print a single integer — the maximum value of for all pairs of integers *a*, *b* (*l*<=≤<=*a*<=≤<=*b*<=≤<=*r*).
Demo Input:
['1 2\n', '8 16\n', '1 1\n']
Demo Output:
['3\n', '31\n', '0\n']
Note:
none
|
```python
a,b=map(int,input().split())
a=a^b
def setb(a):
for i in range(63,-1,-1):
if(a&(1<<i)):
return i+1
return 0
z=setb(a)
print((2**z)-1)
```
|
195
|
Analyzing Polyline
|
Title: Analyzing Polyline
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input Specification:
The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of functions. Each of the following *n* lines contains two space-separated integer numbers *k**i*,<=*b**i* (<=-<=109<=≤<=*k**i*,<=*b**i*<=≤<=109) that determine the *i*-th function.
Output Specification:
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Demo Input:
['1\n1 0\n', '3\n1 0\n0 2\n-1 1\n', '3\n-2 -4\n1 7\n-5 1\n']
Demo Output:
['1\n', '2\n', '3\n']
Note:
none
|
```python
from math import gcd
import sys
n = int(sys.stdin.readline())
res = set()
for _ in range(n):
k,b = map(int,sys.stdin.readline().split())
if k!=0:
a = gcd(k,b)
if k*b>0:
res.add((abs(b//a),abs(k//a)))
else:
res.add((-abs(b//a),abs(k//a)))
print(len(res))# 1692458113.5249596
```
|
21
|
Traveling Graph
|
Title: Traveling Graph
Time Limit: 0 seconds
Memory Limit: 64 megabytes
Problem Description:
You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself).
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=15,<=0<=≤<=*m*<=≤<=2000), *n* is the amount of vertices, and *m* is the amount of edges. Following *m* lines contain edges as a triples *x*,<=*y*,<=*w* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=1<=≤<=*w*<=≤<=10000), *x*,<=*y* are edge endpoints, and *w* is the edge length.
Output Specification:
Output minimal cycle length or -1 if it doesn't exists.
Demo Input:
['3 3\n1 2 1\n2 3 1\n3 1 1\n', '3 2\n1 2 3\n2 3 4\n']
Demo Output:
['3\n', '14\n']
Note:
none
|
```python
import math
N = 15
mat = 0
inf = 1000000000
answer = inf
def Get_Cycle_Length(v,graph):
global mat
global answer
if len(v) == 0:
answer = min(answer,mat)
return
end = v.pop()
i = 0
while i<len(v):
se = v.pop(i)
mat += graph[se][end]
Get_Cycle_Length(v,graph)
mat -= graph[se][end]
v.insert(i,se)
i+=1
v.append(end)
def main():
n,m = map(int,input().split())
graph = [[inf] * n for i in range(n)]
deg = [0] * n
sum = 0
for i in range(n):
graph[i][i] = 0
for i in range(m):
x,y,w = map(int,input().split())
x -= 1
y -= 1
deg[x]+=1
deg[y]+=1
graph[x][y] = min(graph[x][y],w)
graph[y][x] = min(graph[y][x],w)
sum += w
for i in range(n):
for j in range(n): # aqui veo si hay algun camino de menos peso
for k in range(n):
graph[j][k] = min(graph[j][k],graph[j][i] + graph[i][k])
for i in range(n):
if graph[0][i] == inf and deg[i] > 0:
print('-1')
return
v = []
for i in range(n):
if deg[i] % 2 != 0:
v.append(i)
#if len(v) == n: #por lo de conf 3
# print(sum)
# return
Get_Cycle_Length(v,graph)
print(sum + answer)
main()
```
|
540
|
Bad Luck Island
|
Title: Bad Luck Island
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Bad Luck Island is inhabited by three kinds of species: *r* rocks, *s* scissors and *p* papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.
Input Specification:
The single line contains three integers *r*, *s* and *p* (1<=≤<=*r*,<=*s*,<=*p*<=≤<=100) — the original number of individuals in the species of rock, scissors and paper, respectively.
Output Specification:
Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10<=-<=9.
Demo Input:
['2 2 2\n', '2 1 2\n', '1 1 3\n']
Demo Output:
['0.333333333333 0.333333333333 0.333333333333\n', '0.150000000000 0.300000000000 0.550000000000\n', '0.057142857143 0.657142857143 0.285714285714\n']
Note:
none
|
```python
def var():
return (map(int,input().split()))
def a():
return list((map(int,input().split())))
import copy
from collections import defaultdict,deque
dp1=[[[-1]*(102) for _ in range(102)] for _ in range(102)]
dp2=[[[-1]*(102) for _ in range(102)] for _ in range(102)]
dp3=[[[-1]*(102) for _ in range(102)] for _ in range(102)]
r,s,p= var()
def solve1(r,s,p):
if dp1[r][s][p]!=-1:
return dp1[r][s][p]
if r==0 :
return 0
if s==0 and p==0:
return 1
all=r*s+s*p+p*r
dp1[r][s][p]=0
if s>0:
dp1[r][s][p]+=((r*s)/(all))*solve1(r,s-1,p)
if p>0:
dp1[r][s][p]+=((r*p)/(all))*solve1(r-1,s,p)
if s>0 and p>0:
dp1[r][s][p]+=((p*s)/(all))*solve1(r,s,p-1)
return dp1[r][s][p]
def solve2(r,s,p):
if dp2[r][s][p]!=-1:
return dp2[r][s][p]
if s==0 :
return 0
if r==0 and p==0:
return 1
all=r*s+s*p+p*r
dp2[r][s][p]=0
if r>0:
dp2[r][s][p]+=((r*s)/(all))*solve2(r,s-1,p)
if p>0 and r>0:
dp2[r][s][p]+=((r*p)/(all))*solve2(r-1,s,p)
if p>0 :
dp2[r][s][p]+=((p*s)/(all))*solve2(r,s,p-1)
return dp2[r][s][p]
def solve3(r,s,p):
if dp3[r][s][p]!=-1:
return dp3[r][s][p]
if p==0 :
return 0
if s==0 and r==0:
return 1
all=r*s+s*p+p*r
dp3[r][s][p]=0
if s>0 and r>0:
dp3[r][s][p]+=((r*s)/(all))*solve3(r,s-1,p)
if r>0:
dp3[r][s][p]+=((r*p)/(all))*solve3(r-1,s,p)
if s>0:
dp3[r][s][p]+=((p*s)/(all))*solve3(r,s,p-1)
return dp3[r][s][p]
# print(str(solve1(r,s,p))+' '+str(round(solve2(r,s,p),10))+' '+str(float(solve3(r,s,p))))
print("{0:.10f}".format(solve1(r,s,p)),"{0:.10f}".format(solve2(r,s,p)),"{0:.10f}".format(solve3(r,s,p)))
# print("{0:.10f}".format(5),'{0:.1f}'.format(7))
```
|
216
|
Hiring Staff
|
Title: Hiring Staff
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store.
Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly *n* consecutive days, then rest for exactly *m* days, then work for *n* more days and rest for *m* more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day *x*, then he should work on days [*x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*n*<=-<=1], [*x*<=+<=*m*<=+<=*n*,<=*x*<=+<=*m*<=+<=*n*<=+<=1,<=...,<=*x*<=+<=*m*<=+<=2*n*<=-<=1], and so on. Day *x* can be chosen arbitrarily by Vitaly.
There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.
Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least *k* working employees, and one of the working employees should have the key to the store.
Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=≤<=*m*<=≤<=*n*<=≤<=1000, *n*<=≠<=1, 1<=≤<=*k*<=≤<=1000).
Output Specification:
In the first line print a single integer *z* — the minimum required number of employees.
In the second line print *z* positive integers, separated by spaces: the *i*-th integer *a**i* (1<=≤<=*a**i*<=≤<=104) should represent the number of the day, on which Vitaly should hire the *i*-th employee.
If there are multiple answers, print any of them.
Demo Input:
['4 3 2\n', '3 3 1\n']
Demo Output:
['4\n1 1 4 5', '3\n1 3 5']
Note:
none
|
```python
n, m, k = map(int, input().split())
span = n+m+1
count = (span+1)*[0]
count[span] = k
key = (span+1)*[False]
key[1] = True
hire = []
day = 1
while True:
while day <= span and count[day] >= k:
day += 1
if day > span:
if key[span]:
break
day -= 1
while not key[day]:
day -= 1
hire.append(day)
last = min(span, day+n-1)
for i in range(day, last+1):
count[i] += 1
key[i] = True
print(len(hire))
print(' '.join([str(x) for x in hire]))
```
|
900
|
Unusual Sequences
|
Title: Unusual Sequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Count the number of distinct sequences *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*) consisting of positive integers such that *gcd*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=*x* and . As this number could be large, print the answer modulo 109<=+<=7.
*gcd* here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Input Specification:
The only line contains two positive integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=109).
Output Specification:
Print the number of such sequences modulo 109<=+<=7.
Demo Input:
['3 9\n', '5 8\n']
Demo Output:
['3\n', '0\n']
Note:
There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).
There are no suitable sequences in the second test.
|
```python
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define PB push_back
#define MP make_pair
#define LL long long
#define int LL
#define FOR(i,a,b) for(int i = (a); i <= (b); i++)
#define RE(i,n) FOR(i,1,n)
#define REP(i,n) FOR(i,0,(int)(n)-1)
#define R(i,n) REP(i,n)
#define VI vector<int>
#define PII pair<int,int>
#define LD long double
#define FI first
#define SE second
#define st FI
#define nd SE
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define unordered_map __fast_unordered_map
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#else
#define debug(...) (__VA_ARGS__)
#define cerr if(0)cout
#endif
#pragma GCC optimize ("O3")
#pragma GCC target ("avx,avx2")
from __future__ import division, print_function
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
def sync_with_stdio(b):
if b: return
import os, sys
from io import BytesIO, IOBase
# FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod
class FastI(object):
def __init__(self, fd=0, buffersize=2**14):
self.stream = stream = BytesIO(); self.bufendl = 0
def read2buffer():
s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell()
stream.seek(0,2); stream.write(s); stream.seek(pos); return s
self.read2buffer = read2buffer
# Read entire input
def read(self):
while self.read2buffer(): pass
return self.stream.read() if self.stream.tell() else self.stream.getvalue()
def readline(self):
while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s)
self.bufendl -= 1; return self.stream.readline()
def input(self): return self.readline().rstrip(b'\r\n')
# Read all remaining integers, type is given by optional argument
def readnumbers(self, zero=0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; c = b'-'[0]
for c in self.read():
if c >= b'0'[0]: numb = 10 * numb + conv(c) - 48
elif c == b'-'[0]: sign = -1
elif c != b'\r'[0]: A.append(sign*numb); numb = zero; sign = 1
if c >= b'0'[0]: A.append(sign*numb)
return A
class FastO(IOBase):
def __init__(self, fd=1):
stream = BytesIO()
self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0)
self.write = stream.write if py2 else lambda s: stream.write(s.encode())
sys.stdin, sys.stdout = FastI(), FastO()
global input
input = sys.stdin.input
import sys
class ostream:
def __lshift__(self,a):
if a == endl:
sys.stdout.write('\n')
sys.stdout.flush()
else:
sys.stdout.write(str(a))
return self
def tie(self, val):pass
cout = ostream()
endl = object()
class istream:
tiedto = cout
inp = None
def __rlshift__(a,b):
if a.tiedto == cout:
sys.stdout.flush()
if type(b)==tuple or type(b)==list:
return type(b)(type(c)(a.get()) for c in b)
return type(b)(a.get())
def tie(self, val):
self.tiedto = val
def get(a):
while not a.inp:
a.inp = sys.stdin.readline().split()[::-1]
return a.inp.pop()
cin = istream()
class Vector:
def __lshift__(self, other):
self.type = other
return self
def __rshift__(self, other):
if type(other) == tuple:
return [self.type(other[1])]*other[0]
else:
return [self.type()]*other
vector = Vector()
######## PYTHON++ ########
sync_with_stdio(False);
cin.tie(0); cout.tie(0);
MOD = 10**9+7;
x = 0;
y = 0;
x <<= cin;
y <<= cin;
mem = {};
def ways(summa):
if summa not in mem:
c = pow(2, summa-1, MOD) - 1;
i = 2;
while i*i < summa:
if summa%i==0:
c = (c - ways(i))%MOD;
i += 1;
if i*i == summa:
c = (c - ways(i))%MOD;
i -= 1;
while i>1:
if summa%i==0:
c = (c - ways(summa//i))%MOD;
i -= 1;
mem[summa] = c;
return mem[summa];
mem[0] = 0;
mem[1] = 1;
ans = ways(y//x) if y%x==0 else 0;
cout << ans << endl;
```
|
471
|
MUH and Cube Walls
|
Title: MUH and Cube Walls
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of *w* towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of *n* towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of *w* contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input Specification:
The first line contains two integers *n* and *w* (1<=≤<=*n*,<=*w*<=≤<=2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — the heights of the towers in the bears' wall. The third line contains *w* integers *b**i* (1<=≤<=*b**i*<=≤<=109) — the heights of the towers in the elephant's wall.
Output Specification:
Print the number of segments in the bears' wall where Horace can "see an elephant".
Demo Input:
['13 5\n2 4 5 5 4 3 2 2 2 3 3 2 1\n3 4 4 3 2\n']
Demo Output:
['2']
Note:
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
|
```python
def diff(s) : return [s[i] - s[i - 1] for i in range(1, len(s))]
n, m = map(int, input().split())
if m > n : print(0) ; exit(0)
if m == 1 : print(n) ; exit(0)
t = diff(list(map(int, input().split())))
p = diff(list(map(int, input().split())))
w = p + [10 ** 9] + t
res = 0
pi = [0] * len(w)
for i in range (1, len(w)):
j = pi[i - 1]
while j > 0 and w[i] != w[j] : j = pi[j - 1]
if w[i] == w[j] : j += 1
pi[i] = j
if j == len(p) : res += 1
print(res)
```
|
638
|
Three-dimensional Turtle Super Computer
|
Title: Three-dimensional Turtle Super Computer
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A super computer has been built in the Turtle Academy of Sciences. The computer consists of *n*·*m*·*k* CPUs. The architecture was the paralellepiped of size *n*<=×<=*m*<=×<=*k*, split into 1<=×<=1<=×<=1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to *n*, the line number from 1 to *m* and the column number from 1 to *k*.
In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (*x*,<=*y*,<=*z*) can send messages to CPUs (*x*<=+<=1,<=*y*,<=*z*), (*x*,<=*y*<=+<=1,<=*z*) and (*x*,<=*y*,<=*z*<=+<=1) (of course, if they exist), there is no feedback, that is, CPUs (*x*<=+<=1,<=*y*,<=*z*), (*x*,<=*y*<=+<=1,<=*z*) and (*x*,<=*y*,<=*z*<=+<=1) cannot send messages to CPU (*x*,<=*y*,<=*z*).
Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (*a*,<=*b*,<=*c*) controls CPU (*d*,<=*e*,<=*f*) , if there is a chain of CPUs (*x**i*,<=*y**i*,<=*z**i*), such that (*x*1<==<=*a*,<=*y*1<==<=*b*,<=*z*1<==<=*c*), (*x**p*<==<=*d*,<=*y**p*<==<=*e*,<=*z**p*<==<=*f*) (here and below *p* is the length of the chain) and the CPU in the chain with number *i* (*i*<=<<=*p*) can send messages to CPU *i*<=+<=1.
Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (*x*,<=*y*,<=*z*) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (*x*,<=*y*,<=*z*) CPUs: (*a*,<=*b*,<=*c*) and (*d*,<=*e*,<=*f*), such that (*a*,<=*b*,<=*c*) controls (*d*,<=*e*,<=*f*) before (*x*,<=*y*,<=*z*) is turned off and stopped controlling it after the turning off.
Input Specification:
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=100) — the dimensions of the Super Computer.
Then *n* blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to *n*. Each block consists of *m* lines, *k* characters in each — the description of a layer in the format of an *m*<=×<=*k* table. Thus, the state of the CPU (*x*,<=*y*,<=*z*) is corresponded to the *z*-th character of the *y*-th line of the block number *x*. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.
Output Specification:
Print a single integer — the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.
Demo Input:
['2 2 3\n000\n000\n\n111\n111\n', '3 3 3\n111\n111\n111\n\n111\n111\n111\n\n111\n111\n111\n', '1 1 10\n0101010101\n']
Demo Output:
['2\n', '19\n', '0\n']
Note:
In the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1).
In the second sample all processors except for the corner ones are critical.
In the third sample there is not a single processor controlling another processor, so the answer is 0.
|
```python
def check(d, i, j, l):
global result, save
if d[i][j][l] == 1:
if d[i + 1][j][l] == 1 and d[i - 1][j][l] == 1:
#save.append([i, j, l])
result += 1
return
if d[i][j + 1][l] == 1 and d[i][j - 1][l] == 1:
result += 1
#save.append([i, j, l])
return
if d[i][j][l + 1] == 1 and d[i][j][l - 1] == 1:
result += 1
#save.append([i, j, l])
return
if d[i - 1][j + 1][l] == 0 and d[i][j + 1][l] == 1 and d[i - 1][j][l] == 1:
result += 1
#save.append([i, j, l])
return
if d[i][j + 1][l - 1] == 0 and d[i][j + 1][l] == 1 and d[i][j][l - 1] == 1:
result += 1
#save.append([i, j, l])
return
if d[i + 1][j][l - 1] == 0 and d[i + 1][j][l] == 1 and d[i][j][l - 1] == 1:
result += 1
#save.append([i, j, l])
return
if d[i + 1][j - 1][l] == 0 and d[i + 1][j][l] == 1 and d[i][j - 1][l] == 1:
result += 1
#save.append([i, j, l])
return
if d[i][j - 1][l + 1] == 0 and d[i][j - 1][l] == 1 and d[i][j][l + 1] == 1:
result += 1
#save.append([i, j, l])
return
if d[i - 1][j][l + 1] == 0 and d[i - 1][j][l] == 1 and d[i][j][l + 1] == 1:
result += 1
#save.append([i, j, l])
return
n, m, k = map(int, input().split())
d = [[[0] * (k + 2) for i in range(m + 2)] for j in range(n + 2)]
for i in range(1, n + 1):
for j in range(1, m + 1):
st = input()
#print(st)
for l in range(k):
d[i][j][l + 1] = int(st[l])
if i != n:
a = input()
result = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
for l in range(1, k + 1):
check(d, i, j, l)
print(result)
```
|
246
|
Colorful Graph
|
Title: Colorful Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You've got an undirected graph, consisting of *n* vertices and *m* edges. We will consider the graph's vertices numbered with integers from 1 to *n*. Each vertex of the graph has a color. The color of the *i*-th vertex is an integer *c**i*.
Let's consider all vertices of the graph, that are painted some color *k*. Let's denote a set of such as *V*(*k*). Let's denote the value of the neighbouring color diversity for color *k* as the cardinality of the set *Q*(*k*)<==<={*c**u* :<= *c**u*<=≠<=*k* and there is vertex *v* belonging to set *V*(*k*) such that nodes *v* and *u* are connected by an edge of the graph}.
Your task is to find such color *k*, which makes the cardinality of set *Q*(*k*) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color *k*, that the graph has at least one vertex with such color.
Input Specification:
The first line contains two space-separated integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=105) — the colors of the graph vertices. The numbers on the line are separated by spaces.
Next *m* lines contain the description of the edges: the *i*-th line contains two space-separated integers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*) — the numbers of the vertices, connected by the *i*-th edge.
It is guaranteed that the given graph has no self-loops or multiple edges.
Output Specification:
Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.
Demo Input:
['6 6\n1 1 2 3 5 8\n1 2\n3 2\n1 4\n4 3\n4 5\n4 6\n', '5 6\n4 2 5 2 4\n1 2\n2 3\n3 1\n5 3\n5 4\n3 4\n']
Demo Output:
['3\n', '2\n']
Note:
none
|
```python
#parsea una línea
def parser():
return [int(x) for x in input().split()]
#Recibiendo n y m
n,m=parser()
#Recibiendo los colores de los vertices
colors_vertices=parser()
#Hallando el mayor de los colores
upper=max(colors_vertices)
#Se crean una cantidad de sets igual al numero mayor
adjacents_sets=[set() for x in range(upper)]
#Se llenan los sets donde el set i contendra los vertices adyacentes al vertice i-1, si este color no existe entonces su set correspondiente se queda vacío
for i in range(m):
#Leyendo una arista
edge=parser()
#Obteniendo los colores de los vértices
color1=colors_vertices[edge[0]-1]
color2=colors_vertices[edge[1]-1]
#Si los colores son diferentes añadimos cada color a el conjunto de adyacencia del otro color
if color1!=color2:
adjacents_sets[color1-1].add(color2)
adjacents_sets[color2-1].add(color1)
#Cantidad máxima de vecinos
max_neighbours=0
#Menor color que tiene dicha cantidad
color=0
#Encontrando dicha cantidad y dicho color
for i in range(upper):
if max_neighbours<len(adjacents_sets[i]):
max_neighbours=len(adjacents_sets[i])
color=i+1
#Si todos estan vacíos se devuelve el menor de los colores, si no se devuelve el calculado anteriormente
if max_neighbours==0:
print(min(colors_vertices))
else:
print(color)
```
|
292
|
Connected Components
|
Title: Connected Components
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of *n* computers and *m* cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with *n* nodes and *m* edges. Let's index the computers with integers from 1 to *n*, let's index the cables with integers from 1 to *m*.
Polycarpus was given an important task — check the reliability of his company's network. For that Polycarpus decided to carry out a series of *k* experiments on the computer network, where the *i*-th experiment goes as follows:
1. Temporarily disconnect the cables with indexes from *l**i* to *r**i*, inclusive (the other cables remain connected). 1. Count the number of connected components in the graph that is defining the computer network at that moment. 1. Re-connect the disconnected cables with indexes from *l**i* to *r**i* (that is, restore the initial network).
Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.
Input Specification:
The first line contains two space-separated integers *n*, *m* (2<=≤<=*n*<=≤<=500; 1<=≤<=*m*<=≤<=104) — the number of computers and the number of cables, correspondingly.
The following *m* lines contain the cables' description. The *i*-th line contains space-separated pair of integers *x**i*, *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*; *x**i*<=≠<=*y**i*) — the numbers of the computers that are connected by the *i*-th cable. Note that a pair of computers can be connected by multiple cables.
The next line contains integer *k* (1<=≤<=*k*<=≤<=2·104) — the number of experiments. Next *k* lines contain the experiments' descriptions. The *i*-th line contains space-separated integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*) — the numbers of the cables that Polycarpus disconnects during the *i*-th experiment.
Output Specification:
Print *k* numbers, the *i*-th number represents the number of connected components of the graph that defines the computer network during the *i*-th experiment.
Demo Input:
['6 5\n1 2\n5 4\n2 3\n3 1\n3 6\n6\n1 3\n2 5\n1 5\n5 5\n2 4\n3 3\n']
Demo Output:
['4\n5\n6\n3\n4\n2\n']
Note:
none
|
```python
import os,sys,collections,heapq,itertools,functools
from functools import reduce , lru_cache
from itertools import accumulate,chain,combinations,count
from itertools import groupby,permutations,product,zip_longest
from heapq import heapify,heappush,heappop,heapreplace,merge,nlargest,nsmallest
from collections import Counter,defaultdict,deque
from bisect import bisect_left, bisect_right
from math import comb,floor,ceil,inf ,gcd ,sqrt ,atan2
from copy import copy
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")
if os.path.exists('in.txt'):
file = open('in.txt')
input = file.readline
else :
input = IOWrapper(sys.stdin).readline
readi = lambda: int(input())
readis = lambda: list(map(int,input().split()))
reads = lambda: input().rstrip()
readss = lambda: input().split()
class UF:
def __init__(self,n,cp=None):
if cp: self.Fa = cp.Fa[:]
else : self.Fa = [n] + [-1] * n
def getroot(self,i):
root = i
while self.Fa[root] >= 0 :
root =self.Fa[root]
while i != root :
nex,self.Fa[i] =self.Fa[i], root
i = nex
return root
def union(self,a,b):
ra,rb = self.getroot(a),self.getroot(b)
if ra != rb:
self.Fa[0] -= 1
if self.Fa[ra] < self.Fa[rb] :
ra,rb = rb,ra
self.Fa[rb] += self.Fa[ra]
self.Fa[ra] = rb
def solution():
BLOCK = 60
n, m = readis()
edges = [[0,0]] + [readis() for _ in range(m)]
L = UF(n)
mp = {}
for i in range(m+1):
if i: L.union(*edges[i])
if i % BLOCK == 0:
mp[(i,m+1)] = UF(n,L)
R = UF(n,L)
for j in range(m,i,-1):
R.union(*edges[j])
if j % BLOCK == 0 :
mp[(i,j)] = UF(n,R)
res=[]
for _ in range(readi()):
a,b = readis()
l = (a-1)//BLOCK * BLOCK
r = min(m+1,ceil((b+1)/BLOCK)*BLOCK)
uf = UF(n,mp[(l,r)])
for i in range(l+1,a): uf.union(*edges[i])
for i in range(r-1,b,-1): uf.union(*edges[i])
res.append(uf.Fa[0])
print(*res,sep='\n')
for i in range( 1 ):
solution()
```
|
371
|
Vessels
|
Title: Vessels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a system of *n* vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to *n*, in the order from the highest to the lowest, the volume of the *i*-th vessel is *a**i* liters.
Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the *i*-th vessel goes to the (*i*<=+<=1)-th one. The liquid that overflows from the *n*-th vessel spills on the floor.
Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries:
1. Add *x**i* liters of water to the *p**i*-th vessel; 1. Print the number of liters of water in the *k**i*-th vessel.
When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
Input Specification:
The first line contains integer *n* — the number of vessels (1<=≤<=*n*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* — the vessels' capacities (1<=≤<=*a**i*<=≤<=109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer *m* — the number of queries (1<=≤<=*m*<=≤<=2·105). Each of the next *m* lines contains the description of one query. The query of the first type is represented as "1 *p**i* *x**i*", the query of the second type is represented as "2 *k**i*" (1<=≤<=*p**i*<=≤<=*n*, 1<=≤<=*x**i*<=≤<=109, 1<=≤<=*k**i*<=≤<=*n*).
Output Specification:
For each query, print on a single line the number of liters of water in the corresponding vessel.
Demo Input:
['2\n5 10\n6\n1 1 4\n2 1\n1 2 5\n1 1 4\n2 1\n2 2\n', '3\n5 10 8\n6\n1 1 12\n2 2\n1 1 6\n1 3 2\n2 2\n2 3\n']
Demo Output:
['4\n5\n8\n', '7\n10\n5\n']
Note:
none
|
```python
#kylin1993
n=int(input());
water=(n+2)*[0];
vol=[int(i) for i in input().split()];
trace=(n+2)*[0];
next = [i+1 for i in range(n+2)];
m=int(input());
out=[]
for i in range(m):
c=[int(i) for i in input().split()];
if c[0]==1 :
w=c[2];
k=c[1]-1;
r=0;
while((w>0)and(k<n)):
if(w<=vol[k]-water[k]):
water[k]=water[k]+w;
break;
else:
w=w-(vol[k]-water[k]);
water[k]=vol[k];
trace[r]=k;
r=r+1;
k=next[k];
for j in range(r):
next[trace[j]]=k;
if c[0]==2:
out.append(water[c[1]-1]);
for i in out:
print(i)
```
|
761
|
Dasha and Very Difficult Problem
|
Title: Dasha and Very Difficult Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences *a* and *b* of length *n* each you need to write a sequence *c* of length *n*, the *i*-th element of which is calculated as follows: *c**i*<==<=*b**i*<=-<=*a**i*.
About sequences *a* and *b* we know that their elements are in the range from *l* to *r*. More formally, elements satisfy the following conditions: *l*<=≤<=*a**i*<=≤<=*r* and *l*<=≤<=*b**i*<=≤<=*r*. About sequence *c* we know that all its elements are distinct.
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence *a* and the compressed sequence of the sequence *c* were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence *c* of length *n* is a sequence *p* of length *n*, so that *p**i* equals to the number of integers which are less than or equal to *c**i* in the sequence *c*. For example, for the sequence *c*<==<=[250,<=200,<=300,<=100,<=50] the compressed sequence will be *p*<==<=[4,<=3,<=5,<=2,<=1]. Pay attention that in *c* all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to *n* inclusively.
Help Dasha to find any sequence *b* for which the calculated compressed sequence of sequence *c* is correct.
Input Specification:
The first line contains three integers *n*, *l*, *r* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*l*<=≤<=*r*<=≤<=109) — the length of the sequence and boundaries of the segment where the elements of sequences *a* and *b* are.
The next line contains *n* integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n* (*l*<=≤<=*a**i*<=≤<=*r*) — the elements of the sequence *a*.
The next line contains *n* distinct integers *p*1,<=<=*p*2,<=<=...,<=<=*p**n* (1<=≤<=*p**i*<=≤<=*n*) — the compressed sequence of the sequence *c*.
Output Specification:
If there is no the suitable sequence *b*, then in the only line print "-1".
Otherwise, in the only line print *n* integers — the elements of any suitable sequence *b*.
Demo Input:
['5 1 5\n1 1 1 1 1\n3 1 5 4 2\n', '4 2 9\n3 4 8 9\n3 2 1 4\n', '6 1 5\n1 1 1 1 1 1\n2 3 5 4 1 6\n']
Demo Output:
['3 1 5 4 2 ', '2 2 2 9 ', '-1\n']
Note:
Sequence *b* which was found in the second sample is suitable, because calculated sequence *c* = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that *c*<sub class="lower-index">*i*</sub> = *b*<sub class="lower-index">*i*</sub> - *a*<sub class="lower-index">*i*</sub>) has compressed sequence equals to *p* = [3, 2, 1, 4].
|
```python
n,l,r = map(int,input().split())
A = list(map(int,input().split()))
P = list(map(int,input().split()))
s = [0] * n
per=0
for j in range(n):
s[P[j] - 1] = j
b = [0] * n
b[s[0]] = l
for j in range(1,n):
last = b[s[j-1]] - A[s[j-1]]
nexs = last+1
if r - A[s[j]] > last:
b[s[j]] = max(nexs +A[s[j]],l)
else:
per = 1
break
if per == 1:
print(-1)
else:
print(' '.join(map(str,b)))
```
|
159
|
Palindrome pairs
|
Title: Palindrome pairs
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a non-empty string *s* consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.
In a more formal way, you have to find the quantity of tuples (*a*,<=*b*,<=*x*,<=*y*) such that 1<=≤<=*a*<=≤<=*b*<=<<=*x*<=≤<=*y*<=≤<=|*s*| and substrings *s*[*a*... *b*], *s*[*x*... *y*] are palindromes.
A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.
A substring *s*[*i*... *j*] (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|) of string *s* = *s*1*s*2... *s*|*s*| is a string *s**i**s**i*<=+<=1... *s**j*. For example, substring *s*[2...4] of string *s* = "abacaba" equals "bac".
Input Specification:
The first line of input contains a non-empty string *s* which consists of lowercase letters ('a'...'z'), *s* contains at most 2000 characters.
Output Specification:
Output a single number — the quantity of pairs of non-overlapping palindromic substrings of *s*.
Please do not use the %lld format specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d format specifier.
Demo Input:
['aa\n', 'aaa\n', 'abacaba\n']
Demo Output:
['1\n', '5\n', '36\n']
Note:
none
|
```python
s = input()
n = len(s)
beg = [0] * n
end = [0] * n
for i in range(n):
for j in range(n):
if i-j < 0 or i+j >= n: break
if s[i-j] != s[i+j]: break
beg[i-j] += 1
end[i+j] += 1
for j in range(n):
if i-j < 0 or i+j+1 >= n: break
if s[i-j] != s[i+j+1]: break
beg[i-j] += 1
end[i+j+1] += 1
suf = [0] * (n+1)
for i in range(n-1, -1, -1):
suf[i] = suf[i+1] + beg[i]
print(sum(end[i] * suf[i+1] for i in range(n)))
```
|
592
|
Super M
|
Title: Super M
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of *n* cities, connected by *n*<=-<=1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are *m* cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.
However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.
You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.
Input Specification:
The first line of the input contains two integers *n* and *m* (1<=≤<=*m*<=≤<=*n*<=≤<=123456) - the number of cities in Byteforces, and the number of cities being attacked respectively.
Then follow *n*<=-<=1 lines, describing the road system. Each line contains two city numbers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*) - the ends of the road *i*.
The last line contains *m* distinct integers - numbers of cities being attacked. These numbers are given in no particular order.
Output Specification:
First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number.
Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons.
Note that the correct answer is always unique.
Demo Input:
['7 2\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n2 7\n', '6 4\n1 2\n2 3\n2 4\n4 5\n4 6\n2 4 5 6\n']
Demo Output:
['2\n3\n', '2\n4\n']
Note:
In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are:
<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/93d3c0306b529e9c2324f68158ca2156587473a2.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/df80aa84591eaa7b9f52c88cc43b5f7da5bfead3.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
However, you should choose the first one as it starts in the city with the lower number.
|
```python
from collections import deque
n,m = [int(x) for x in input().split()]
adj = [[] for x in range(n+1)]
for _ in range(1,n):
a,b = [int(x) for x in input().split()]
adj[a].append(b)
adj[b].append(a)
chaos = [int(x) for x in input().split()]
s = chaos[0]
chaos = set(chaos)
cc = [0]*(n+1)
st = deque()
st.append((s,-1))
while len(st):
u,e = st.pop()
if u<0:
if e>=0:
cc[e] += cc[-u]
continue
if u in chaos:
cc[u] +=1
st.append((-u,e))
for v in adj[u]:
if v!=e:
st.append((v,u))
#dfs(s,-1)
adj = [list(filter(lambda v:cc[v]>0,u)) for u in adj]
a = (s,0)
st = deque()
st.append((a[0],-1,0))
while len(st):
u,e,h = st.pop()
if h>a[1]:
a = (u,h)
elif h==a[1] and u<a[0]:
a = (u,h)
for v in adj[u]:
if v!=e:
st.append((v,u,h+1))
b = a
a = (a[0],0)
st = deque()
st.append((a[0],-1,0))
while len(st):
u,e,h = st.pop()
if h>a[1]:
a = (u,h)
elif h==a[1] and u<a[0]:
a = (u,h)
for v in adj[u]:
if v!=e:
st.append((v,u,h+1))
print(min(a[0],b[0]))
print(2*(n-cc.count(0))-a[1])
```
|
858
|
Polycarp's phone book
|
Title: Polycarp's phone book
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:
- if he enters 00 two numbers will show up: 100000000 and 100123456, - if he enters 123 two numbers will show up 123456789 and 100123456, - if he enters 01 there will be only one number 100123456.
For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
Input Specification:
The first line contains single integer *n* (1<=≤<=*n*<=≤<=70000) — the total number of phone contacts in Polycarp's contacts.
The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
Output Specification:
Print exactly *n* lines: the *i*-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the *i*-th number from the contacts. If there are several such sequences, print any of them.
Demo Input:
['3\n123456789\n100000000\n100123456\n', '4\n123456789\n193456789\n134567819\n934567891\n']
Demo Output:
['9\n000\n01\n', '2\n193\n81\n91\n']
Note:
none
|
```python
from sys import stdin
input=stdin.readline
import heapq
import string
rd=lambda: map(lambda s: int(s), input().strip().split())
ri=lambda: int(input())
rs=lambda :input().strip()
from collections import defaultdict,deque
from bisect import bisect_left as bl, bisect_right as br
from random import randint
from math import gcd, ceil, floor
random = randint(1, 10 ** 9)
class wrapper(int):
def __hash__(self):
return super(wrapper, self).__hash__() ^ random
n=ri()
d=defaultdict(int)
q=[]
for i in range(n):
s=rs()
q.append(s)
st=set()
for j in range(9):
for k in range(j,9):
st.add(s[j:k+1])
for pp in st:
d[pp]+=1
for i in range(n):
mx=9
ans=q[i]
s=q[i]
for j in range(9):
for k in range(j,9):
t=s[j:k+1]
if d[t]==1:
if mx>len(t):
ans=t
mx=len(ans)
print(ans)
```
|
689
|
Friends and Subsequences
|
Title: Friends and Subsequences
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows?
Every one of them has an integer sequences *a* and *b* of length *n*. Being given a query of the form of pair of integers (*l*,<=*r*), Mike can instantly tell the value of while !Mike can instantly tell the value of .
Now suppose a robot (you!) asks them all possible different queries of pairs of integers (*l*,<=*r*) (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) (so he will make exactly *n*(*n*<=+<=1)<=/<=2 queries) and counts how many times their answers coincide, thus for how many pairs is satisfied.
How many occasions will the robot count?
Input Specification:
The first line contains only integer *n* (1<=≤<=*n*<=≤<=200<=000).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the sequence *a*.
The third line contains *n* integer numbers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=109<=≤<=*b**i*<=≤<=109) — the sequence *b*.
Output Specification:
Print the only integer number — the number of occasions the robot will count, thus for how many pairs is satisfied.
Demo Input:
['6\n1 2 3 2 1 4\n6 7 1 2 3 2\n', '3\n3 3 3\n1 1 1\n']
Demo Output:
['2\n', '0\n']
Note:
The occasions in the first sample case are:
1.*l* = 4,*r* = 4 since *max*{2} = *min*{2}.
2.*l* = 4,*r* = 5 since *max*{2, 1} = *min*{2, 3}.
There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.
|
```python
dx=[[0]*(1<<20) for _ in range(20)]
dy=[[0]*(1<<20) for _ in range(20)]
lg=[0]*(1<<20)
def mx(l,r):
p=lg[r-l+1]
return max(dx[p][l],dx[p][r-(1<<p)+1])
def mn(l,r):
p=lg[r-l+1]
return min(dy[p][l],dy[p][r-(1<<p)+1])
if __name__ == '__main__':
n=int(input())
dx[0][1:n]=[int(x) for x in input().split()]
dy[0][1:n]=[int(x) for x in input().split()]
for p in range(1,20):
if (1<<p)>n:
break
for i in range(1,n+2-(1<<p)):
dx[p][i]=max(dx[p-1][i],dx[p-1][i+(1<<(p-1))])
dy[p][i]=min(dy[p-1][i],dy[p-1][i+(1<<(p-1))])
for i in range(2,n+1):
lg[i]=lg[i>>1]+1
ans=0
for i in range(1,n+1):
if mx(i,i)<=mn(i,i):
l=i-1
r=i
p=1<<lg[n-i+1]
while p:
if p+l<=n and mx(i,l+p)<mn(i,l+p):l+=p
if p+r<=n and mx(i,r+p)<=mn(i,r+p):r+=p
p>>=1
ans+=r-l
print(ans)
```
|
645
|
Robot Rapping Results Report
|
Title: Robot Rapping Results Report
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot *i* will beat robot *j* if and only if robot *i* has a higher skill level than robot *j*. And if robot *i* beats robot *j* and robot *j* beats robot *k*, then robot *i* will beat robot *k*. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input Specification:
The first line of the input consists of two integers, the number of robots *n* (2<=≤<=*n*<=≤<=100<=000) and the number of rap battles *m* ().
The next *m* lines describe the results of the rap battles in the order they took place. Each consists of two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), indicating that robot *u**i* beat robot *v**i* in the *i*-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all *m* relations.
Output Specification:
Print the minimum *k* such that the ordering of the robots by skill level is uniquely defined by the first *k* rap battles. If there exists more than one ordering that satisfies all *m* relations, output -1.
Demo Input:
['4 5\n2 1\n1 3\n2 3\n4 2\n4 3\n', '3 2\n1 2\n3 2\n']
Demo Output:
['4\n', '-1\n']
Note:
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
|
```python
def g(k):
p = [[] for i in range(n)]
d = [0] * n
for u, v in t[:k]:
p[u].append(v)
d[v] += 1
if d.count(0) > 2: return 0
x = d.index(0, 1)
while x:
q, x = p[x], 0
for y in q:
d[y] -= 1
if d[y] == 0:
if x: return 0
x = y
return 1
f = lambda: map(int, input().split())
n, m = f()
t = [list(f()) for i in range(m)]
n += 1
m += 1
l, r = 1, m
while l < r:
s = l + r >> 1
if g(s): r = s
else: l = s + 1
print(-1 if r == m else l)
```
|
557
|
Vitaly and Cycle
|
Title: Vitaly and Cycle
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of *n* vertices and *m* edges, not necessarily connected, without parallel edges and loops. You need to find *t* — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find *w* — the number of ways to add *t* edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input Specification:
The first line of the input contains two integers *n* and *m* ( — the number of vertices in the graph and the number of edges in the graph.
Next *m* lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) — the vertices that are connected by the *i*-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output Specification:
Print in the first line of the output two space-separated integers *t* and *w* — the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Demo Input:
['4 4\n1 2\n1 3\n4 2\n4 3\n', '3 3\n1 2\n2 3\n3 1\n', '3 0\n']
Demo Output:
['1 2\n', '0 1\n', '3 1\n']
Note:
The simple cycle is a cycle that doesn't contain any vertex twice.
|
```python
def read_data():
n, m = map(int, input().split())
Es = [[] for v in range(n)]
for e in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
Es[a].append(b)
Es[b].append(a)
return n, m, Es
def solve(n, m, Es):
if m == 0:
return 3, n * (n - 1) * (n - 2) // 6
if max(map(len, Es)) == 1:
return 2, m * (n-2)
patterns = 0
color = [0] * n
for u in range(n):
if color[u]:
continue
color[u] = 1
stack = [u]
n_color = [1, 0]
while stack:
v = stack.pop()
prev_color = color[v]
for w in Es[v]:
current_color = color[w]
if current_color == prev_color:
return 0, 1
if current_color == 0:
color[w] = - prev_color
n_color[(prev_color + 1)//2] += 1
stack.append(w)
n_even = n_color[0]
n_odd = n_color[1]
patterns += n_even * (n_even - 1) // 2 + n_odd * (n_odd - 1) // 2
return 1, patterns
if __name__ == '__main__':
n, m, Es = read_data()
print(*solve(n, m, Es))
```
|
939
|
Love Rescue
|
Title: Love Rescue
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.
This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.
More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length *n* consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (*c*1,<=*c*2) (where *c*1 and *c*2 are some lowercase English letters), which can arbitrary number of times transform a single letter *c*1 to *c*2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.
Input Specification:
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the length of the letterings.
The second line contains a string with length *n*, consisting of lowercase English letters — the lettering on Valya's pullover.
The third line contains the lettering on Tolya's t-shirt in the same format.
Output Specification:
In the first line output a single integer — the minimum amount of mana *t* required for rescuing love of Valya and Tolya.
In the next *t* lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order.
If there are many optimal answers, output any.
Demo Input:
['3\nabb\ndad\n', '8\ndrpepper\ncocacola\n']
Demo Output:
['2\na d\nb a', '7\nl e\ne d\nd c\nc p\np o\no r\nr a\n']
Note:
In first example it's enough to buy two spells: ('a','d') and ('b','a'). Then first letters will coincide when we will replace letter 'a' with 'd'. Second letters will coincide when we will replace 'b' with 'a'. Third letters will coincide when we will at first replace 'b' with 'a' and then 'a' with 'd'.
|
```python
from collections import defaultdict
n=int(input())
s1=input().strip()
s2=input().strip()
g=defaultdict(list)
tq=[]
for i in range(n):
ord1=ord(s1[i])-ord("a")
ord2=ord(s2[i])-ord("a")
g[ord1].append(ord2)
tq.append(ord1)
g[ord2].append(ord1)
vis=[0]*26
# vis[ord(s1[0])-ord("a")]=1
ans=[]
for i in tq:
if vis[i]==0:
vis[i]=1
q=[i]
while q:
t=q.pop(0)
for i in g[t]:
if vis[i]==0:
vis[i]=1
ans.append((chr(t+97),chr(i+97)))
q.append(i)
print(len(ans))
for i in ans:
print(*i)
```
|
471
|
MUH and House of Cards
|
Title: MUH and House of Cards
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of *n* playing cards. Let's describe the house they want to make:
1. The house consists of some non-zero number of floors. 1. Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card. 1. Each floor besides for the lowest one should contain less rooms than the floor below.
Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more.
While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of *n* cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using exactly *n* cards.
Input Specification:
The single line contains integer *n* (1<=≤<=*n*<=≤<=1012) — the number of cards.
Output Specification:
Print the number of distinct heights that the houses made of exactly *n* cards can have.
Demo Input:
['13\n', '6\n']
Demo Output:
['1', '0']
Note:
In the first sample you can build only these two houses (remember, you must use all the cards):
Thus, 13 cards are enough only for two floor houses, so the answer is 1.
The six cards in the second sample are not enough to build any house.
|
```python
n,a,b=int(input()),0,0
for i in range(1,int(1e12)+1):
if i**2>1e12:break
a+=3*i-1
if a>n:break
if(n-a)%3==0:b+=1
print(b)
```
|
864
|
Make a Permutation!
|
Title: Make a Permutation!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan has an array consisting of *n* elements. Each of the elements is an integer from 1 to *n*.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to *n* was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.
Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.
In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations *x* and *y*, then *x* is lexicographically smaller if *x**i*<=<<=*y**i*, where *i* is the first index in which the permutations *x* and *y* differ.
Determine the array Ivan will obtain after performing all the changes.
Input Specification:
The first line contains an single integer *n* (2<=≤<=*n*<=≤<=200<=000) — the number of elements in Ivan's array.
The second line contains a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=*n*) — the description of Ivan's array.
Output Specification:
In the first line print *q* — the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with *q* changes.
Demo Input:
['4\n3 2 2 3\n', '6\n4 5 6 3 2 1\n', '10\n6 8 4 6 7 1 6 3 4 5\n']
Demo Output:
['2\n1 2 4 3 \n', '0\n4 5 6 3 2 1 \n', '3\n2 8 4 6 7 1 9 3 10 5 \n']
Note:
In the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers — this permutation is lexicographically minimal among all suitable.
In the second example Ivan does not need to change anything because his array already is a permutation.
|
```python
n = int(input())
a = [int(x) for x in input().split(' ')]
b = [0] * (n + 1)
arr = []
used = [0] * (n + 1)
for i in range(0, n):
b[a[i]] += 1
for i in range(1, n + 1):
if b[i] == 0:
arr.append(i)
cnt = 0
j = 0;
for i in range(0, n):
if b[a[i]] == 1:
continue;
if used[a[i]] == 1:
cnt += 1
b[a[i]] -= 1
a[i] = arr[j]
j += 1
else:
if arr[j] < a[i]:
cnt += 1
b[a[i]] -= 1
a[i] = arr[j]
j += 1
used[a[i]] = 1
else:
used[a[i]] = 1
print(cnt)
for i in range(0, n):
print(a[i], end = " ")
```
|
439
|
Devu and his Brother
|
Title: Devu and his Brother
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays *a* and *b* by their father. The array *a* is given to Devu and *b* to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array *a* should be at least as much as the maximum value of his brother's array *b*.
Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.
You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
Input Specification:
The first line contains two space-separated integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=105). The second line will contain *n* space-separated integers representing content of the array *a* (1<=≤<=*a**i*<=≤<=109). The third line will contain *m* space-separated integers representing content of the array *b* (1<=≤<=*b**i*<=≤<=109).
Output Specification:
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
Demo Input:
['2 2\n2 3\n3 5\n', '3 2\n1 2 3\n3 4\n', '3 2\n4 5 6\n1 2\n']
Demo Output:
['3\n', '4\n', '0\n']
Note:
In example 1, you can increase *a*<sub class="lower-index">1</sub> by 1 and decrease *b*<sub class="lower-index">2</sub> by 1 and then again decrease *b*<sub class="lower-index">2</sub> by 1. Now array *a* will be [3; 3] and array *b* will also be [3; 3]. Here minimum element of *a* is at least as large as maximum element of *b*. So minimum number of operations needed to satisfy Devu's condition are 3.
In example 3, you don't need to do any operation, Devu's condition is already satisfied.
|
```python
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
n,m = map(int,input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
A.sort()
B.sort(reverse = True)
ans =0
for i in range(min(n, m)):
if(A[i]>=B[i]):
break
ans += B[i] - A[i]
print(ans)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.