name
stringlengths 9
112
| description
stringlengths 29
13k
| solutions
stringlengths 24
49.8k
|
---|---|---|
15_C. Industrial Nim | There are n stone quarries in Petrograd.
Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.
Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.
Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».
Input
The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.
Output
Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.
Examples
Input
2
2 1
3 2
Output
tolik
Input
4
1 1
1 1
1 1
1 1
Output
bolik | ```python
__author__ = 'Darren'
def solve():
n = int(input())
xor = 0
for _i in range(n):
x, m = map(int, input().split())
xor ^= xor_range(x - 1) ^ xor_range(x + m - 1)
print(["tolik", "bolik"][xor == 0])
def xor_range(n):
return [n, 1, n+1, 0][n % 4]
if __name__ == '__main__':
solve()
# Made By Mostafa_Khaled
``` |
202_A. LLPS | This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1 = y1, x2 = y2, ..., x|y| = y|y|, or there exists such number r (r < |x|, r < |y|) that x1 = y1, x2 = y2, ..., xr = yr and xr + 1 > yr + 1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s| - 1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
Input
The only input line contains a non-empty string s consisting of lowercase English letters only. Its length does not exceed 10.
Output
Print the lexicographically largest palindromic subsequence of string s.
Examples
Input
radar
Output
rr
Input
bowwowwow
Output
wwwww
Input
codeforces
Output
s
Input
mississipp
Output
ssss
Note
Among all distinct subsequences of string "radar" the following ones are palindromes: "a", "d", "r", "aa", "rr", "ada", "rar", "rdr", "raar" and "radar". The lexicographically largest of them is "rr". | ```python
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 19:56:34 2020
@author: roastedcoder
This is for CodeForces
"""
mod = 1000000007
ssi = lambda : map(int,input().split())
# RoastedCoder
s = input()
l = [0]*26
for i in range(len(s)):
l[ord(s[i])-97] += 1
for i in range(25,-1,-1):
if(l[i] >= 1):
print(chr(i+97)*l[i])
break
``` |
250_C. Movie Critics | A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.
On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.
Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.
As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.
Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.
Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
Input
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres.
The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
Output
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
Examples
Input
10 3
1 1 2 3 2 3 3 1 1 3
Output
3
Input
7 3
3 1 3 2 3 1 2
Output
1
Note
In the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.
In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses. | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
b = [a[0]]
for i in range(1, n):
if a[i] == b[-1]:
continue
else:
b += [a[i]]
di = {}
for i in range(len(b)):
if b[i] not in di:
di[b[i]] = []
di[b[i]] += [i]
total = len(b) - 1
ans = [0]*(k+1)
for i in range(1, k+1):
ans[i] = total - len(di[i])
for i in range(1, k+1):
for j in range(len(di[i])):
if di[i][j] and di[i][j]+1 != len(b) and b[di[i][j]-1] == b[di[i][j]+1]:
ans[i] -= 1
ans[0] = 9999999999999
print(ans.index(min(ans)))
``` |
275_D. Zero Tree | A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:
1. Select the subtree of the given tree that includes the vertex with number 1.
2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
Input
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).
Output
Print the minimum number of operations needed to solve the task.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2
1 3
1 -1 1
Output
3 | ```python
import sys
def minp():
return sys.stdin.readline().strip()
n = int(minp())
e = [0]
p = [None]*(n+1)
for i in range(n):
e.append([])
for i in range(n-1):
a, b = map(int,minp().split())
e[a].append(b)
e[b].append(a)
v = list(map(int,minp().split()))
plus = [0]*(n+1)
minus = [0]*(n+1)
was = [False]*(n+1)
was[1] = True
i = 0
j = 1
q = [0]*(n+100)
q[0] = 1
p[1] = 0
while i < j:
x = q[i]
i += 1
for y in e[x]:
if not was[y]:
was[y] = True
p[y] = x
q[j] = y
j += 1
i = j-1
while i >= 0:
x = q[i]
i -= 1
s = minus[x] - plus[x]
z = v[x-1] + s
pp = p[x]
#print(x, p[x], plus[x], minus[x], '-', s[x], v[x-1]+s[x], v[0]+s[1])
#print(-(plus[x]-minus[x]),s[x])
minus[pp] = max(minus[x],minus[pp])
plus[pp] = max(plus[x],plus[pp])
if z > 0:
plus[pp] = max(plus[pp],plus[x]+z)
elif z < 0:
minus[pp] = max(minus[pp],minus[x]-z)
#print(v[0])
#print(plus[0], minus[0])
print(plus[0] + minus[0])
``` |
299_A. Ksusha and Array | Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.
Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
Input
The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array elements.
Output
Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1.
If there are multiple answers, you are allowed to print any of them.
Examples
Input
3
2 2 4
Output
2
Input
5
2 1 3 1 6
Output
1
Input
3
2 3 5
Output
-1 | ```python
input()
line = list(map(int, input().split()))
line.sort()
for i in line:
if i % line[0] != 0:
print(-1)
break
else:
print(line[0])
``` |
346_B. Lucky Common Subsequence | In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0 | ```python
#Not actually my code, solved mentally, only submitting to mark as solved so I don't do it again.
def gen(i, j):
if a[i][j] == -1:
a[i][j] = max(gen(i - 1, j - 1) + s2[i - 1] * (s2[i - 1] == s1[j - 1]), gen(i - 1, j), gen(i, j - 1), key = lambda x: [len(x), -x.count(viru)])
return a[i][j]
s1, s2, viru = [input() for x in range(3)]
a = [[''] * (len(s1) + 1)] + [[''] + [-1] * (len(s1)) for x in range(len(s2))]
ans = gen(len(s2), len(s1))
while viru in ans:
ans = min(ans.replace(viru, viru[:-1]), ans.replace(viru, viru[1:]), key = lambda x: x.count(viru))
print(ans + '0' * (ans == ''))
``` |
414_A. Mashmokh and Numbers | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y. | ```python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
n, k = [ int(x) for x in input().split() ]
x = k - (n // 2 - 1)
if x < 1 or (n < 2 and k > 0):
print(-1)
return
sequence = [0] * n
sequence[0] = x
if n > 1:
sequence[1] = 2*x
if n >= 3:
newValue = 1
while newValue == x or newValue == 2*x \
or newValue + 1 == x or newValue + 1 == 2*x:
newValue += 1
sequence[2] = newValue
for i in range(3, n):
newValue = sequence[i-1] + 1
if not(i & 1):
while newValue == x or newValue == 2*x \
or newValue + 1 == x or newValue + 1 == 2*x:
newValue += 1
sequence[i] = newValue
print(' '.join(map(lambda x: str(x), sequence)))
BUFFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFFSIZE))
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, BUFFSIZE))
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")
input = lambda: sys.stdin.readline().rstrip("\r\n")
def print(*args, **kwargs):
sep = kwargs.pop("sep", " ")
file = kwargs.pop("file", sys.stdout)
atStart = True
for x in args:
if not atStart:
file.write(sep)
file.write(str(x))
atStart = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
main()
``` |
440_C. One-Based Arithmetic | Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6 | ```python
import math
def find(n,i):
ans = 0
k = n // ones[i]
n = n % ones[i]
ans = ans + k * i
if n == 0:
return ans
return ans + min(find(n, i-1), i + find(ones[i] - n, i-1))
n = int(input())
ones = [0]
for i in range(1,17):
one = 10 * ones[i-1] + 1
ones.append(one)
print(find(n,16))
``` |
486_D. Valid Sets | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | ```python
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
# def print(x):
# sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = readInts()
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(0, n):
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
``` |
50_C. Happy Farm 5 | The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image> | ```python
import math
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def orientation(p0, p1, p2):
x = (p1[1] - p0[1]) * (p2[0] - p1[0]) - (p1[0] - p0[0]) * (p2[1] - p1[1])
if(x < 0):
return -1
if(x > 0):
return 1
return 0
l = [(p[0] - l[0][0], p[1] - l[0][1]) for p in l[1:]]
l.sort(key = lambda p: (-p[0]/p[1] if(p[1] != 0) else -10e14, p[0] ** 2 + p[1] ** 2))
l = [(0, 0)] + l
t = [l[0]]
i = 1
n = len(l)
while(1):
while(i < n - 1 and orientation(l[0], l[i], l[i + 1]) == 0):
i += 1
if(i >= n - 1):
break
t.append(l[i])
i += 1
t.append(l[-1])
if(len(t) == 1):
print(4)
elif(len(t) == 2):
print(max(abs(t[1][1] - t[0][1]), abs(t[1][0] - t[0][0])) * 2 + 4)
else:
stack = [t[0], t[1], t[2]]
for i in range(3, len(t)):
while(orientation(stack[-2], stack[-1], t[i]) == 1):
stack.pop()
stack.append(t[i])
n = len(stack)
s = 4
for i in range(n - 1):
s += max(abs(stack[i + 1][1] - stack[i][1]), abs(stack[i + 1][0] - stack[i][0]))
s += max(abs(stack[0][1] - stack[n - 1][1]), abs(stack[0][0] - stack[n - 1][0]))
print(s)
``` |
534_E. Berland Local Positioning System | 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 ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, ai < ai + 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: <image>, 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
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of stops.
The second line contains n integers (1 ≤ ai ≤ 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 ≤ bi ≤ 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
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print - 1.
Examples
Input
6
2 3 5 7 11 13
5
3 4 5 5 6
Output
10
Input
6
2 3 5 7 11 13
9
1 2 2 3 3 4 5 5 6
Output
16
Input
3
10 200 300
4
1 2 2 3
Output
-1
Input
3
1 2 3
4
1 2 2 3
Output
3
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)
``` |
585_C. Alice, Bob, Oranges and Apples | Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples. | ```python
import fractions
def solve(x, y):
if fractions.gcd(x, y) > 1: return 'Impossible'
turn = x > y
if not turn: x, y = y, x
ans = []
while x != 0 and y != 0:
ans.append((x//y, 'A' if turn else 'B'))
x, y = y, x%y
turn = not turn
ans[-1] = (ans[-1][0]-1, ans[-1][1])
return ''.join(str(n) + l for n, l in ans)
x, y = [int(x) for x in input().split()]
print(solve(x, y))
``` |
607_C. Marbles | In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end. | ```python
from time import time
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
otr = str.maketrans(opposite)
bits = {
'N': 0,
'S': 1,
'E': 2,
'W': 3,
}
Q = 4294967291
def combine(h, v, q):
return (h<<2 | v) % q
def combinel(h, v, q, s):
return (v*s + h) % q
def flip(s):
return ''.join(reversed(s.translate(otr)))
def solvable(p1, p2):
h1 = 0
h2 = 0
s = 1
for i in reversed(range(len(p1))):
n1 = bits[p1[i]]
n2 = bits[opposite[p2[i]]]
h1 = combine(h1, n1, Q)
h2 = combinel(h2, n2, Q, s)
if h1 == h2 and p1[i:] == flip(p2[i:]):
return False
s = (s<<2) % Q
return True
if __name__ == '__main__':
n = int(input())
p1 = input()
p2 = input()
print('YES' if solvable(p1, p2) else 'NO')
# Made By Mostafa_Khaled
``` |
629_B. Far Relative’s Problem | Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140. | ```python
n = (int)(input())
F1=[0]*n
F2=[0]*n
M1=[0]*n
M2=[0]*n
m=0
f=0
for i in range(n):
c = (input().split())
if(c[0]=='M'):
M1[m]=(int)(c[1])
M2[m]=(int)(c[2])
m=m+1
if(c[0]=='F'):
F1[f]=(int)(c[1])
F2[f]=(int)(c[2])
f=f+1
F=[0]*3232
M=[0]*3266
for i in range(f):
for j in range(F1[i], F2[i]+1):
F[j]=F[j]+1
for i in range(m):
for j in range(M1[i], M2[i]+1):
M[j]=M[j]+1
max=0
for j in range(367):
if((F[j]>max)and(M[j]>max)):
max=F[j]
if(max>M[j]):
max=M[j]
print(max*2)
``` |
653_C. Bear and Up-Down | The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.
Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence.
The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.
Output
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
Examples
Input
5
2 8 4 7 7
Output
2
Input
4
200 150 100 50
Output
1
Input
10
3 2 1 4 1 4 1 4 1 4
Output
8
Input
9
1 2 3 4 5 6 7 8 9
Output
0
Note
In the first sample, there are two ways to get a nice sequence with one swap:
1. Swap t2 = 8 with t4 = 7.
2. Swap t1 = 2 with t5 = 7.
In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50. | ```python
def main():
n, l = int(input()), list(map(int, input().split()))
if not (n & 1):
l.append(0)
l.append(150001)
a, b, fails, res = 0, 150001, [], 0
for i, c in enumerate(l, -1):
if i & 1:
if a >= b or b <= c:
if len(fails) > 5:
print(0)
return
fails.append(i)
else:
if a <= b or b >= c:
if len(fails) > 5:
print(0)
return
fails.append(i)
a, b = b, c
check = compile("and".join(
"(l[{:n}]{:s}l[{:n}]{:s}l[{:n}])".format(i - 1, "><"[i & 1], i, "<>"[i & 1], i + 1) for i in fails),
"<string>", "eval")
for i in fails:
a = l[i]
for j in range(n):
l[i], l[j] = l[j], a
if eval(check) and ((l[j - 1] < l[j] > l[j + 1]) if j & 1 else (l[j - 1] > l[j] < l[j + 1])):
res += 1 if j in fails else 2
l[j] = l[i]
l[i] = a
print(res // 2)
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` |
679_A. Bear and Prime 100 | This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.
You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".
For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.
When you are done asking queries, print "prime" or "composite" and terminate your program.
You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.
You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
Input
After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.
Output
Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input.
In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.
Examples
Input
yes
no
yes
Output
2
80
5
composite
Input
no
yes
no
no
no
Output
58
59
78
78
2
prime
Note
The hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.
<image>
The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.
<image>
59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries). | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def primeN(n):
prime = [True for i in range(n+1)]
prime[0]=False
prime[1]=False
p=2
while(p*p<=n):
if(prime[p]):
for i in range(p*p,n+1,p):
prime[i]=False
p+=1
return [p for p in range(n+1) if(prime[p])]
primes=primeN(50)
found=0
for i in primes:
print(i,flush=True)
res=input()
if(res=='yes'):found+=1
if(i>7):continue
print(i*i,flush=True)
res=input()
if(res=='yes'):found+=1
if(found>1): print("composite",flush=True)
else: print("prime",flush=True)
exit()
``` |
701_B. Cells Not Under Attack | Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.
You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n2)) — the size of the board and the number of rooks.
Each of the next m lines contains integers xi and yi (1 ≤ xi, yi ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
Output
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
Examples
Input
3 3
1 1
3 1
2 2
Output
4 2 0
Input
5 2
1 5
5 1
Output
16 9
Input
100000 1
300 400
Output
9999800001
Note
On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
<image> | ```python
n, m = map(int, input().strip().split())
remains = n*n
deleted_rows = set()
deleted_cols = set()
answer = []
for _ in range(m):
c, r = map(int, input().strip().split())
col_deleted = c in deleted_cols
row_deleted = r in deleted_rows
if not (col_deleted and row_deleted):
if col_deleted:
remains -= (n - len(deleted_cols))
elif row_deleted:
remains -= (n - len(deleted_rows))
else: # not x_in and not y_in
remains -= (2*n - len(deleted_cols) - len(deleted_rows) - 1)
deleted_cols.add(c)
deleted_rows.add(r)
answer.append(str(remains))
print(' '.join(answer))
``` |
723_C. Polycarp at the Radio | Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others.
We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1, b2, ..., bm will be as large as possible.
Find this maximum possible value of the minimum among the bj (1 ≤ j ≤ m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group.
Input
The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 2000).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the performer of the i-th song.
Output
In the first line print two integers: the maximum possible value of the minimum among the bj (1 ≤ j ≤ m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make.
In the second line print the changed playlist.
If there are multiple answers, print any of them.
Examples
Input
4 2
1 2 3 2
Output
2 1
1 2 1 2
Input
7 3
1 3 2 2 2 2 1
Output
2 1
1 3 3 2 2 2 1
Input
4 4
1000000000 100 7 1000000000
Output
1 4
1 2 3 4
Note
In the first sample, after Polycarp's changes the first band performs two songs (b1 = 2), and the second band also performs two songs (b2 = 2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist.
In the second sample, after Polycarp's changes the first band performs two songs (b1 = 2), the second band performs three songs (b2 = 3), and the third band also performs two songs (b3 = 2). Thus, the best minimum value is 2. | ```python
from collections import Counter
n, m = map(int, input().split())
nums = list(map(int, input().split()))
cnts = dict(Counter(nums))
for i in range(1, m+1):
if i not in cnts:
cnts[i] = 0
def minner():
return min(cnts.items(), key=lambda x: x[1])
n //= m
res = 0
for i, num in enumerate(nums):
if num > m or cnts[num] > n:
for r in range(1, m+1):
if cnts[r] < n:
cnts[num] -= 1
nums[i] = r
cnts[r] += 1
res += 1
break
print(n, res)
print(' '.join(map(str, nums)))
``` |
745_B. Hongcow Solves A Puzzle | Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| ```python
n, m = map(int, input().split())
o1 = set()
for i in range(n):
s = input()
if s.count('X') != 0:
o1.add((s.count('X'), s.find('X'), s.rfind('X')))
if len(o1) == 1:
print('YES')
else:
print('NO')
``` |
768_D. Jon and Orbs | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2 | ```python
k, q = map(int, input().split())
t = [0] * (k + 1)
t[1] = 1
c = [0]
n = i = 1
while i < 1001:
if (2000 * t[k] > i - (10**-7)):
c.append(n)
i += 1
else:
t = [0] + [(j * t[j] + (k - j + 1) * t[j - 1]) / k for j in range(1, k + 1)]
n += 1
for i in range(q):
print(c[int(input())])
``` |
792_C. Divide by Three | A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | ```python
a = input()
if len(a) == 1:
if int(a) % 3 == 0:
print(a)
else:
print(-1)
exit(0)
one = []
two = []
sum = 0
zs, zf = 0, 0
for i in range(len(a)):
q = int(a[i])
sum += q
if q == 0:
if zs == 0:
zs = i
else:
if zs != 0 and zf == 0:
zf = i
if q % 3 == 1:
if len(one) <= 4:
one.append(i)
elif q % 3 == 2:
if len(two) <= 4:
two.append(i)
if zf == 0 and zs != 0:
zf = len(a) - 1
sol = []
s = ""
if sum % 3 == 1:
if len(one) > 0:
s = a[:one[-1]] + a[one[-1] + 1:]
sol.append(s)
if len(a) > 1 and len(two) > 1:
s = a[:two[-2]] + a[two[-2] + 1:two[-1]] + a[two[-1] + 1:]
sol.append(s)
if sum % 3 == 2:
if len(two) > 0:
s = a[:two[-1]] + a[two[-1] + 1:]
sol.append(s)
if len(a) > 1 and len(one) > 1:
s = a[:one[-2]] + a[one[-2] + 1:one[-1]] + a[one[-1] + 1:]
sol.append(s)
if sum % 3 == 0:
print(a)
else:
mini = 0
max = 0
for i in range(len(sol)):
if sol[i] == "":
sol[i] = "-1"
elif sol[i][0] == "0":
sol[i] = sol[i][zf - zs:]
if len(sol[i]) > 0:
if sol[i][0] == "0":
f = -1
for j in range(len(sol[i])):
if sol[i][j] != "0":
f = j
break
if f != -1:
sol[i] = sol[i][f:]
else:
sol[i] = "0"
if len(sol[i]) == 0:
sol[i] = "0"
if len(sol[i]) > max:
max = len(sol[i])
mini = i
print(sol[mini])
``` |
812_E. Sagheer and Apple Tree | Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).
Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.
In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:
1. eat the apples, if the node is a leaf.
2. move the apples to one of the children, if the node is non-leaf.
Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.
Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.
Input
The first line will contain one integer n (2 ≤ n ≤ 105) — the number of nodes in the apple tree.
The second line will contain n integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the number of apples on each node of the tree.
The third line will contain n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n) — the parent of each node of the tree. Node i has parent pi (for 2 ≤ i ≤ n). Node 1 is the root of the tree.
It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
Output
On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.
Examples
Input
3
2 2 3
1 1
Output
1
Input
3
1 2 3
1 1
Output
0
Input
8
7 2 2 5 4 3 1 1
1 1 1 4 4 5 6
Output
4
Note
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.
In the second sample, There is no swap that will make Sagheer win the game.
Note that Sagheer must make the swap even if he can win with the initial tree. | ```python
n= int(input())
a = [int(_) for _ in input().split()]
c = [int(_) for _ in input().split()]
depth = [0] * (n)
for i in range(1,n):
depth[i] = depth[c[i-1]-1] + 1
MAX = max(depth)
t = 0
store = {}
todo = []
p = 0
for i in range(n):
if (MAX-depth[i]) % 2 == 0: # odd, useful
t ^= a[i]
todo.append(a[i])
else:
store[a[i]] = store.get(a[i],0) + 1
p += 1
ans = 0
for i in todo:
ans += store.get(i^t,0)
if t == 0:
ans += (p*(p-1)//2) + (n-p)*(n-p-1)//2
print(ans)
``` |
859_B. Lazy Security Guard | Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.
Input
Input will consist of a single integer N (1 ≤ N ≤ 106), the number of city blocks that must be enclosed by the route.
Output
Print the minimum perimeter that can be achieved.
Examples
Input
4
Output
8
Input
11
Output
14
Input
22
Output
20
Note
Here are some possible shapes for the examples:
<image> | ```python
import math
n=int(input())
print(math.ceil(math.sqrt(n)*2)*2)
``` |
884_A. Book Reading | Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed n.
Remember that there are 86400 seconds in a day.
Input
The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 106) — the number of days and the time required to read the book.
The second line contains n integers ai (0 ≤ ai ≤ 86400) — the time Luba has to spend on her work during i-th day.
Output
Print the minimum day Luba can finish reading the book.
It is guaranteed that answer doesn't exceed n.
Examples
Input
2 2
86400 86398
Output
2
Input
2 86400
0 86400
Output
1 | ```python
n,t=map(int,input().split())
a=input().split()
i=0
while t > 0:
t-=(86400-int(a[i]))
i += 1
print(i)
``` |
908_C. New Year and Curling | Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk.
Compute the y-coordinates of centers of all the disks after all disks have been pushed.
Input
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively.
The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.
Output
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6.
Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates.
Example
Input
6 2
5 5 6 8 3 12
Output
2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613
Note
The final positions of the disks will look as follows:
<image>
In particular, note the position of the last disk. | ```python
n, r = map(int, input().split())
a = input().split()
ans = []
for i in range(n):
res = r
for j in range(i):
if (abs(int(a[j]) - int(a[i])) <= 2 * r):
res = max(res, ans[j] + (4 * r * r - abs(int(a[j]) - int(a[i])) ** 2) ** 0.5)
ans.append(res)
for i in range(n):
print(ans[i], end = ' ')
``` |
92_B. Binary Number | Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.
How many actions should Fangy perform to get a number one from number x?
Input
The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.
Output
Print the required number of actions.
Examples
Input
1
Output
0
Input
1001001
Output
12
Input
101110
Output
8
Note
Let's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1. | ```python
from collections import *
def add(n):
for i in range(len(n) - 1, -1, -1):
if n[i] == '1':
n[i] = '0'
else:
n[i] = '1'
return n
n.appendleft('1')
return n
def main():
n, ans = deque(input()), 0
while (len(n) != 1):
if n[-1] == '1':
n = add(n)
else:
n.pop()
ans += 1
print(ans)
if __name__ == '__main__':
main()
``` |
983_B. XOR-pyramid | For an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases}
where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6,6⊕12)=f(5,10)=f(5⊕10)=f(15)=15
You are given an array a and a few queries. Each query is represented as two integers l and r. The answer is the maximum value of f on all continuous subsegments of the array a_l, a_{l+1}, …, a_r.
Input
The first line contains a single integer n (1 ≤ n ≤ 5000) — the length of a.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2^{30}-1) — the elements of the array.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries.
Each of the next q lines contains a query represented as two integers l, r (1 ≤ l ≤ r ≤ n).
Output
Print q lines — the answers for the queries.
Examples
Input
3
8 4 1
2
2 3
1 2
Output
5
12
Input
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2
Output
60
30
12
3
Note
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.
In second sample, optimal segment for first query are [3,6], for second query — [2,5], for third — [3,4], for fourth — [1,2]. | ```python
n = int(input())
arr = list(map(int, input().split()))
aux = [[0] * n for i in range(n)]
for i in range(n):
aux[0][i] = arr[i]
for i in range(1, n):
for j in range(n-i):
aux[i][j] = aux[i-1][j] ^ aux[i-1][j+1]
for i in range(1, n):
for j in range(n-i):
aux[i][j] = max(aux[i][j], aux[i-1][j], aux[i-1][j+1])
q = int(input())
for i in range(q):
buscaEsquerda, buscaDireita = map(int, input().split())
buscaEsquerda, buscaDireita = buscaEsquerda-1, buscaDireita-1
print(aux[buscaDireita-buscaEsquerda][buscaEsquerda])
``` |
p02565 AtCoder Library Practice Contest - Two SAT | Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | ```python
class Two_SAT:
"""2-SATを定義する.
"""
#入力定義
def __init__(self,variable=[]):
self.variable=set(variable)
self.clause_number=0
self.variable_number=len(variable)
self.adjacent_out={(v,b):set() for v in variable for b in [True,False]} #出近傍(vが始点)
self.adjacent_in={(v,b):set() for v in variable for b in [True,False]} #入近傍(vが終点)
#※ (X,False)が not Xに対応
#変数の追加
def add_variable(self,*adder):
"""変数を加える.
adder(可変長):加える変数の名前
"""
for v in adder:
if v not in self.variable:
self.adjacent_in[(v,True)]=set()
self.adjacent_in[(v,False)]=set()
self.adjacent_out[(v,True)]=set()
self.adjacent_out[(v,False)]=set()
self.variable_number+=1
self.variable.add(v)
#節の追加
def add_clause(self,X,F,Y,G):
"""(X=F) or (Y=G) という節を加える.
X,Y:変数の名前
F,G:真偽値(True or False)
"""
assert isinstance(F,bool),"Fが真偽値ではない"
assert isinstance(G,bool),"Gが真偽値ではない"
for v in [X,Y]:
if v not in self.variable:
self.add_variable(v)
if (Y,G) not in self.adjacent_out[(X,not F)]:
self.clause_number+=1
#(X,not F)→(Y,G)を追加
self.adjacent_out[(X,not F)].add((Y,G))
self.adjacent_in[(Y,G)].add((X,not F))
#(Y,not G) → (X,F)を追加
self.adjacent_out[(Y,not G)].add((X,F))
self.adjacent_in[(X,F)].add((Y,not G))
#節を除く
def remove_edge(self,X,F,Y,G):
pass
#変数を除く
def remove_vertex(self,*vertexes):
pass
#変数が存在するか否か
def variable_exist(self,v):
"""変数 X が存在するか?
X,Y:変数の名前
"""
return v in self.variable
#グラフに節が存在するか否か
def clause_exist(self,X,F,Y,G):
"""(X=F) or (Y=G) という節が存在するか?
X,Y:変数の名前
F,G:真偽値(True or False)
"""
if not(self.variable_exist(X) and self.variable_exist(Y)):
return False
return (Y,G) in self.adjacent_out[(X,not F)]
#近傍
def neighbohood(self,v):
pass
#出次数
def out_degree(self,v):
pass
#入次数
def in_degree(self,v):
pass
#次数
def degree(self,v):
pass
#変数の数
def variable_count(self):
return len(self.vertex)
#節の数
def clause_count(self):
return self.edge_number
#充足可能?
def Is_Satisfy(self,Mode):
"""有向グラフDを強連結成分に分解
Mode:
0(Defalt)---充足可能?
1 ---充足可能ならば,その変数の割当を変える.(不可能なときはNone)
"""
import sys
from collections import deque
T={(x,b):-1 for b in [True,False] for x in self.variable}
Q=deque([])
def f(v):
T[v]=0
for w in self.adjacent_out[v]:
if T[w]==-1:
f(w)
Q.appendleft(v)
T[v]=len(Q)
x=self.variable.pop()
self.variable.add(x)
RT=sys.getrecursionlimit()
sys.setrecursionlimit(3*10**5)
for b in [True,False]:
for v in self.variable:
w=(v,b)
if T[w]==-1:
f(w)
sys.setrecursionlimit(RT)
T={(x,b):-1 for b in [True,False] for x in self.variable }
C=[]
p=0
for v in Q:
if T[v]==-1:
T[v]=p
P=[v]
R=deque([v])
while R:
u=R.popleft()
for w in self.adjacent_in[u]:
if T[w]==-1:
T[w]=p
R.append(w)
P.append(w)
C.append(P)
p+=1
if Mode==0:
for x in self.variable:
if T[(x,True)]==T[(x,False)]:
return False
return True
else:
X={x:None for x in self.variable}
for x in self.variable:
if T[(x,True)]==T[(x,False)]:
return None
else:
X[x]=(T[(x,False)]<T[(x,True)])
return X
#================================================
N,D=map(int,input().split())
X=[0]*N
Y=[0]*N
for i in range(N):
x,y=map(int,input().split())
X[i]=x
Y[i]=y
T=Two_SAT(list(range(N))) # True→Xiに建てる,False→Yiに建てる
for i in range(N):
for j in range(i+1,N):
#XX
if abs(X[i]-X[j])<D:
T.add_clause(i,False,j,False)
#XY
if abs(X[i]-Y[j])<D:
T.add_clause(i,False,j,True)
#YX
if abs(Y[i]-X[j])<D:
T.add_clause(i,True,j,False)
#YY
if abs(Y[i]-Y[j])<D:
T.add_clause(i,True,j,True)
H=T.Is_Satisfy(Mode=1)
if H==None:
print("No")
else:
Z=[0]*N
for i in range(N):
if H[i]:
Z[i]=X[i]
else:
Z[i]=Y[i]
print("Yes")
print("\n".join(map(str,Z)))
``` |
p02696 AtCoder Beginner Contest 165 - Floor Function | Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B N
Output
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.
Examples
Input
5 7 4
Output
2
Input
11 10 9
Output
9 | ```python
A,B,N = map(int,input().split())
c = min(B - 1,N)
print((A * c)//B)
``` |
p02825 AtCoder Grand Contest 041 - Domino Quality | Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row. We define the quality of each column similarly.
Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column, or determine that such a placement doesn't exist.
Constraints
* 2 \le N \le 1000
Input
Input is given from Standard Input in the following format:
N
Output
If the required domino placement doesn't exist, print a single integer `-1`.
Otherwise, output your placement as N strings of N characters each. If a square is not covered, the corresponding character must be `.` (a dot). Otherwise, it must contain a lowercase English letter. Squares covered by the same domino piece must contain the same letter. If two squares have a common side but belong to different pieces, they must contain different letters.
Examples
Input
6
Output
aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b
Input
2
Output
-1 | ```python
n = int(input())
s3=["abb","a.d","ccd"]
s = [["abcc", "abdd", "ddba", "ccba"],
["dccdd", "daa.c", "c..bc", "c..bd", "ddccd"],
["abbc..", "a.ac..", "bba.cc", "a..aab", "a..b.b", ".aabaa"],
["aba....","aba....","bab....","bab....","a..bbaa","a..aabb",".aabbaa"]]
if n == 2:
print(-1)
elif n == 3:
[print(x) for x in s3]
else:
d, m = divmod(n, 4)
d -= 1
m += 4
for i in range(d):
[print("." * 4 * i + x + "." * (4 * (d - i - 1) + m)) for x in s[0]]
[print("." * 4 * d + x) for x in s[m - 4]]
``` |
p02962 AtCoder Beginner Contest 135 - Strings of Eternity | Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.
Constraints
* 1 \leq |s| \leq 5 \times 10^5
* 1 \leq |t| \leq 5 \times 10^5
* s and t consist of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print `-1`.
Examples
Input
abcabab
ab
Output
3
Input
aa
aaaaaaa
Output
-1
Input
aba
baaab
Output
0 | ```python
# AOJ ALDS1_14_B "String Search"
# returns i s.t. S[i+j] = T[j] for 0 <= j < len(T)
def RollingHash(S, T, ls):
if len(S) < len(T):
return []
# gcd(h, b) = 1
h = 10**11+7
b = 10**7+7
L = len(T)
bL = 1
for i in range(L):
bL = bL * b % h
hashS = 0
for i in range(L):
hashS = (hashS * b + S[i]) % h
hashT = 0
for i in range(L):
hashT = (hashT * b + T[i]) % h
correctIndexes = [0]*len(S)
ret = 0
if hashS == hashT:
correctIndexes[0] = 1
for j in range(len(S)-L):
hashS = (hashS * b - S[j]*bL + S[L+j]) % h
if hashS == hashT:
tmp = correctIndexes[j+1-L] + 1
correctIndexes[j+1] = tmp
if tmp > ret: ret = tmp
if ret*L > 2*ls:
return -1
return ret
import sys
input = sys.stdin.buffer.readline
S = input().rstrip()
T = input().rstrip()
ls = len(S)
lt = len(T)
S = S*((2*lt+3*ls-1)//ls)
ans = RollingHash(S, T, ls)
print(ans)
``` |
p03097 AtCoder Grand Contest 031 - Differ by 1 Bit | You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO | ```python
N, A, B = map(int, input().split())
def f(n, a, b):
if n == 1:
return [a, b]
mask = 1 << (n-1)
if a & mask == b & mask:
v1 = f(n-1, a, b)
v2 = f(n-1, a ^ mask, v1[1] ^ mask)
ret = v1[:1]
ret.extend(v2)
ret.extend(v1[1:])
return ret
else:
v1 = f(n-1, a, a ^ 1)
v2 = f(n-1, a ^ 1 ^ mask, b)
v1.extend(v2)
return v1
if bin(A ^ B).count('1') % 2 == 0:
print("NO")
else:
print("YES")
res = f(N, A, B)
for p in res:
print(p)
``` |
p03243 AtCoder Beginner Contest 111 - AtCoder Beginner Contest 111 | Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N \leq 999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
Examples
Input
111
Output
111
Input
112
Output
222
Input
750
Output
777 | ```python
N=int(input());print(111*(-(-N//111)))
``` |
p03561 AtCoder Regular Contest 084 - Finite Encyclopedia of Integer Sequences | In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
Constraints
* 1 \leq N,K \leq 3 × 10^5
* N and K are integers.
Input
Input is given from Standard Input in the following format:
K N
Output
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
Examples
Input
3 2
Output
2 1
Input
2 4
Output
1 2 2 2
Input
5 14
Output
3 3 3 3 3 3 3 3 3 3 3 3 2 2 | ```python
import sys
input = sys.stdin.readline
K,N = map(int,input().split())
if K % 2 == 0:
L = K // 2
R = L + 1
# 先頭の文字が L のものの最後、R のものの最初、で境界
arr = [L] + [K] * (N-1)
else:
"""
[3,3,3,3,3] だと 手前に3 33 333 3333 が余分。2歩戻る。
"""
arr = [(K+1)//2] * N
x = N//2# x歩 戻る
for i in range(x):
arr[-1] -= 1
if arr[-1] == 0:
arr.pop()
continue
L = len(arr)
if L < N:
arr += [K] * (N-L)
answer = ' '.join(map(str,arr))
print(answer)
``` |
p03714 AtCoder Beginner Contest 062 - 3N Numbers | Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'.
Constraints
* 1 ≤ N ≤ 10^5
* a_i is an integer.
* 1 ≤ a_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N}
Output
Print the maximum possible score of a'.
Examples
Input
2
3 1 4 1 5 9
Output
1
Input
1
1 2 3
Output
-1
Input
3
8 2 2 7 4 6 5 3 8
Output
5 | ```python
def f(x):
y=x[:n];heapify(y);z=sum(y);s=[z]
for i in x[n:n*2]:z+=i-heappushpop(y,i);s+=[z]
return s
from heapq import*;n,*a=map(int,open(0).read().split());print(max(map(sum,zip(f([-i for i in a[n:][::-1]]),f(a)[::-1]))))
``` |
p04037 AtCoder Grand Contest 002 - Candy Piles | There are N piles of candies on the table. The piles are numbered 1 through N. At first, pile i contains a_i candies.
Snuke and Ciel are playing a game. They take alternating turns. Snuke goes first. In each turn, the current player must perform one of the following two operations:
1. Choose a pile with the largest number of candies remaining, then eat all candies of that pile.
2. From each pile with one or more candies remaining, eat one candy.
The player who eats the last candy on the table, loses the game. Determine which player will win if both players play the game optimally.
Constraints
* 1≤N≤10^5
* 1≤a_i≤10^9
Input
The input is given from Standard Input in the following format:
N
a_1 a_2 … a_N
Output
If Snuke will win, print `First`. If Ciel will win, print `Second`.
Examples
Input
2
1 3
Output
First
Input
3
1 2 1
Output
First
Input
3
1 2 3
Output
Second | ```python
N=int(input())
A=list(map(int,input().split()))
A.append(0)
A.sort()
winner=""
for i in range(N+1):
if A[N-i]>i:
if (A[N-i]-i)%2==0:
winner="First"
else:
winner="Second"
elif A[N-i]==i:
if (A[N-i+1]-A[N-i])%2==1:
winner="First"
break
else:
count=0
for j in range(N-i,-1,-1):
if A[j]==i:
count+=1
else:
break
if count%2==1:
winner="First"
else:
winner="Second"
break
else:
break
print(winner)
``` |
p00118 Property Distribution | Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will.
Divide the orchard into as many relatives as possible on a parcel basis. However, if the same kind of fruit is planted in a plot that is located in either the north, south, east, or west direction of a plot, treat them as one large plot because the boundaries of the plot are unknown.
For example, in the following 3 × 10 section ('li' represents an apple,'ka' represents an oyster, and'mi' represents a mandarin orange)
<image>
Eliminating the boundaries between plots with the same tree gives:
<image>
In the end, it will be divided into 10 compartments, or 10 people.
The distribution must be completed before it snows and the boundaries of the plot disappear. Your job is to determine the number of plots to distribute based on the map of the orchard.
Create a program that reads the map of the orchard and outputs the number of relatives who can receive the distribution.
Input
Given multiple datasets. Each dataset is given a string of H lines consisting of the characters H x W, starting with a line containing H, W (H, W ≤ 100) separated by blanks. Only three characters appear in this string:'@' for apples,'#' for oysters, and'*' for oranges.
The input ends with two lines of zeros. The number of datasets does not exceed 20.
Output
For each dataset, output the number of people to be distributed on one line.
Examples
Input
10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0
Output
33
Input
10 10
*****@
@#@@@@#*#*
@##***@@@*
****#*@**
@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0
Output
33 | ```python
import sys
sys.setrecursionlimit(100000)
def solve(x, y, char):
for deltaX in [1, -1]:
if 0 <= x + deltaX and x + deltaX < w and matrix[y][x + deltaX] == char:
matrix[y][x + deltaX] = "."
solve(x+deltaX, y, char)
for deltaY in [1, -1]:
if 0 <= y + deltaY and y + deltaY < h and matrix[y + deltaY][x] == char:
matrix[y+deltaY][x] = "."
solve(x, y+deltaY, char)
while (True):
line = sys.stdin.readline().rstrip()
if line == "" or line == "0 0":
break
h, w = (int(i) for i in line.split())
matrix = []
count = 0
for i in range(h):
matrix.append(list(input().rstrip()))
for j, row in enumerate(matrix):
for i, cell in enumerate(row):
char = matrix[j][i]
if (char != "."):
matrix[j][i] = "."
count += 1
solve(i, j, char)
print(count)
``` |
p00251 Points for a Perfect Scorer | Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a program that outputs the total of them.
input
The input is given in the following format.
s1
s2
..
..
s10
The input consists of 10 lines, and the i line is given the integer si (0 ≤ si ≤ 100) representing the score of problem i.
output
Output the total score on one line.
Example
Input
1
2
3
4
5
6
7
8
9
10
Output
55 | ```python
s1=int(input())
s2=int(input())
s3=int(input())
s4=int(input())
s5=int(input())
s6=int(input())
s7=int(input())
s8=int(input())
s9=int(input())
s10=int(input())
total=0
total+=s1
total+=s2
total+=s3
total+=s4
total+=s5
total+=s6
total+=s7
total+=s8
total+=s9
total+=s10
print(total)
``` |
p00628 Yes | Dr .: Peter, do you know "Yes, I have a number"?
Peter: I used to do it on TV the other day. You remember something by the number of characters in each word contained in a sentence. "Yes, I have a number", so it means "the number 3.14" and is a keyword for remembering pi.
Dr .: Peter, that's not the case. This should be interpreted as 3.1416. The circumference ratio is 3.14159 ... That's why.
Peter: Then, did you forcibly omit that program just because Japan teaches that the circumference ratio is 3.14? ??
Dr .: ... Let's just say that the pi taught in elementary school has finally returned from 3 to 3.14.
Peter: Do you really remember this in the first place?
Dr .: It may be difficult for Japanese people. It seems that English-speaking people use it, because it is difficult to make a ground ball in English.
Peter: Even so, it seems to be a hassle to check.
Dr .: Then, I want you to make a program that converts sentences into a sequence of the number of characters in a word.
Peter: I understand. Please tell me the detailed specifications.
Dr .: Let's enter one line of text. For simplicity, you can use sentences that contain only alphabets and blanks. For this sentence, output the length of the character string between the blank, the beginning of the sentence, and the end of the sentence in order. You can proceed if the number of characters in the string does not exceed 9.
For example, Yes in "Yes I have" has 3 characters because it is separated by the beginning and the first space, and I is separated by the first and second spaces and has 1 character.
Dr .: Then, don't forget the character string where the number of characters becomes 0 when there are consecutive blanks.
Input
Multiple datasets are given as input. For each dataset, a string containing alphabets and spaces is given on one line.
When the character string is "END OF INPUT", it is the end of input. Do not output to this input.
Output
For each dataset, output a sequence of the number of characters for the string on one line.
Example
Input
Yes I have a number
How I wish I could calculate an unused color for space
Thank you
END OF INPUT
Output
31416
31415926535
53 | ```python
import sys
sys.setrecursionlimit(10**6)
def main():
s = input()
if s == "END OF INPUT":
return False
if s[0] == " ":
s[0] = "."
for _ in range(100):
s = s.replace(" ", " . ")
lst = s.split()
ans = []
for i in lst:
if i == ".":
ans += [0]
else:
ans += [len(i)]
print("".join(map(str, ans)))
return True
while main():
pass
``` |
p00903 Round Trip | Jim is planning to visit one of his best friends in a town in the mountain area. First, he leaves his hometown and goes to the destination town. This is called the go phase. Then, he comes back to his hometown. This is called the return phase. You are expected to write a program to find the minimum total cost of this trip, which is the sum of the costs of the go phase and the return phase.
There is a network of towns including these two towns. Every road in this network is one-way, i.e., can only be used towards the specified direction. Each road requires a certain cost to travel.
In addition to the cost of roads, it is necessary to pay a specified fee to go through each town on the way. However, since this is the visa fee for the town, it is not necessary to pay the fee on the second or later visit to the same town.
The altitude (height) of each town is given. On the go phase, the use of descending roads is inhibited. That is, when going from town a to b, the altitude of a should not be greater than that of b. On the return phase, the use of ascending roads is inhibited in a similar manner. If the altitudes of a and b are equal, the road from a to b can be used on both phases.
Input
The input consists of multiple datasets, each in the following format.
n m
d2 e2
d3 e3
.
.
.
dn-1 en-1
a1 b1 c1
a2 b2 c2
.
.
.
am bm cm
Every input item in a dataset is a non-negative integer. Input items in a line are separated by a space.
n is the number of towns in the network. m is the number of (one-way) roads. You can assume the inequalities 2 ≤ n ≤ 50 and 0 ≤ m ≤ n(n−1) hold. Towns are numbered from 1 to n, inclusive. The town 1 is Jim's hometown, and the town n is the destination town.
di is the visa fee of the town i, and ei is its altitude. You can assume 1 ≤ di ≤ 1000 and 1≤ei ≤ 999 for 2≤i≤n−1. The towns 1 and n do not impose visa fee. The altitude of the town 1 is 0, and that of the town n is 1000. Multiple towns may have the same altitude, but you can assume that there are no more than 10 towns with the same altitude.
The j-th road is from the town aj to bj with the cost cj (1 ≤ j ≤ m). You can assume 1 ≤ aj ≤ n, 1 ≤ bj ≤ n, and 1 ≤ cj ≤ 1000. You can directly go from aj to bj, but not from bj to aj unless a road from bj to aj is separately given. There are no two roads connecting the same pair of towns towards the same direction, that is, for any i and j such that i ≠ j, ai ≠ aj or bi ≠ bj. There are no roads connecting a town to itself, that is, for any j, aj ≠ bj.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, a line containing the minimum total cost, including the visa fees, of the trip should be output. If such a trip is not possible, output "-1".
Example
Input
3 6
3 1
1 2 1
2 3 1
3 2 1
2 1 1
1 3 4
3 1 4
3 6
5 1
1 2 1
2 3 1
3 2 1
2 1 1
1 3 4
3 1 4
4 5
3 1
3 1
1 2 5
2 3 5
3 4 5
4 2 5
3 1 5
2 1
2 1 1
0 0
Output
7
8
36
-1 | ```python
from heapq import heappush, heappop
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
if N == M == 0:
return False
D = [0]*N; E = [0]*N
B = [0]*N
H = defaultdict(int)
H[0] = 1
H[1000] += 1
E[N-1] = 1000
for i in range(1, N-1):
D[i], e = map(int, readline().split())
E[i] = e
B[i] = H[e]
H[e] += 1
G = [[] for i in range(N)]
RG = [[] for i in range(N)]
for i in range(M):
a, b, c = map(int, readline().split()); a -= 1; b -= 1
if E[a] <= E[b]:
G[a].append((b, c))
if E[b] <= E[a]:
RG[b].append((a, c))
dist = {(0, 0, 1): 0}
que = [(0, 0, 0, 1)]
INF = 10**18
while que:
cost, v0, v1, state = heappop(que)
if dist[v0, v1, state] < cost:
continue
d0 = E[v0]; d1 = E[v1]
if d0 < d1:
for w0, d in G[v0]:
if E[w0] == d1:
if w0 == v1:
de = cost + d
n_state = (1 << B[w0])
else:
de = cost + d + D[w0]
n_state = (1 << B[w0]) | (1 << B[v1])
n_key = (w0, v1, n_state)
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, w0, v1, n_state))
else:
n_key = (w0, v1, 0)
de = cost + d + D[w0]
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, w0, v1, 0))
elif d0 > d1:
for w1, d in RG[v1]:
if E[w1] == d0:
if w1 == v0:
de = cost + d
n_state = (1 << B[w1])
else:
de = cost + d + D[w1]
n_state = (1 << B[w1]) | (1 << B[v0])
n_key = (v0, w1, n_state)
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, v0, w1, n_state))
else:
n_key = (v0, w1, 0)
de = cost + d + D[w1]
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, v0, w1, 0))
else:
ds = d0
for w0, d in G[v0]:
if ds == E[w0]:
b = (1 << B[w0])
if state & b:
de = cost + d
n_state = state
else:
de = cost + d + D[w0]
n_state = state | b
n_key = (w0, v1, n_state)
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, w0, v1, n_state))
else:
n_key = (w0, v1, 0)
de = cost + d + D[w0]
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, w0, v1, 0))
for w1, d in RG[v1]:
if ds == E[w1]:
b = (1 << B[w1])
if state & b:
de = cost + d
n_state = state
else:
de = cost + d + D[w1]
n_state = state | b
n_key = (v0, w1, n_state)
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, v0, w1, n_state))
else:
n_key = (v0, w1, 0)
de = cost + d + D[w1]
if de < dist.get(n_key, INF):
dist[n_key] = de
heappush(que, (de, v0, w1, 0))
g_key = (N-1, N-1, 1)
if g_key in dist:
write("%d\n" % dist[g_key])
else:
write("-1\n")
return True
while solve():
...
``` |
p01036 Yu-kun Likes To Play Darts | Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves darts as much as programming. Yu-kun was addicted to darts recently, but he got tired of ordinary darts, so he decided to make his own darts board.
See darts for darts.
Problem
The contents of the darts that Yu-kun thought about are as follows.
The infinitely wide darts board has several polygons with scores. The player has only one darts arrow. The player throws an arrow and stabs the arrow into one of the polygons to get the score written there. If you stab it in any other way, you will not get any points.
Yu-kun decided where to throw the arrow, but it doesn't always stick exactly. The darts board is a two-dimensional plane, and the position Yu-kun is aiming for is a point (cx, cy). The place where the arrow thrown by Yu-kun sticks is selected with a uniform probability from any point included in the circle with radius r centered on the point (cx, cy). The coordinates of the exposed points do not have to be integers.
Since the information on the darts board, the position (cx, cy) that Yu-kun aims at, and the radius r are given, answer the expected value of the score that Yu-kun can get.
Constraints
The input satisfies the following conditions.
* All inputs are given as integers
* 1 ≤ n ≤ 50
* 0 ≤ cx, cy, x, y ≤ 1000
* 1 ≤ r ≤ 100
* 3 ≤ p ≤ 10
* 1 ≤ score ≤ 100
* Polygon vertices are given in such an order that they visit adjacent vertices clockwise or counterclockwise.
* The sides of a polygon do not have anything in common with the sides of another polygon
* A polygon does not contain another polygon
* If the arrow sticks on the side of the polygon, no score will be given.
Input
n cx cy r
Information on the 0th polygon
Information on the first polygon
...
Information on the (n-1) th polygon
n is the number of polygons on the darts board. Polygonal information is given in the following format.
p score
x0 y0
x1 y1
...
x (p-1) y (p-1)
p represents the number of vertices of the polygon, and score represents the score written on the polygon. Each line segment of the polygon is a line segment connecting the vertices of (xi, yi) and (xi + 1, yi + 1) (i <p-1), and (xp-1, yp-1) and (x0, It is a line segment connecting the vertices of y0).
Output
Output the expected value of the score that Yu-kun can get in one line. Any number of digits after the decimal point may be output. However, the error in the answer must not exceed 0.000001 (10-6).
Examples
Input
1 2 2 1
4 1
0 0
2 0
2 2
0 2
Output
0.2500000000
Input
1 2 2 1
4 1
0 0
5 0
5 5
0 5
Output
1.0000000000
Input
4 3 3 2
3 1
1 1
3 3
1 5
4 2
2 0
5 0
4 2
3 2
3 3
4 3
6 1
6 5
4 4
3 4
4 4
5 6
2 6
Output
1.0574955319
Input
1 10 10 1
4 10
0 0
1 0
1 1
0 1
Output
0.0000000000 | ```python
# 参考 http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3277276#1
from math import acos, hypot, isclose, sqrt
def intersection(circle, polygon):
# 円と多角形の共通部分の面積
# 多角形の点が反時計回りで与えられれば正の値、時計回りなら負の値を返す
x, y, r = circle
polygon = [(xp-x, yp-y) for xp, yp in polygon]
area = 0.0
for p1, p2 in zip(polygon, polygon[1:] + [polygon[0]]):
ps = seg_intersection((0, 0, r), (p1, p2))
for pp1, pp2 in zip([p1] + ps, ps + [p2]):
c = cross(pp1, pp2) # pp1 と pp2 の位置関係によって正負が変わる
if c == 0: # pp1, pp2, 原点が同一直線上にある場合
continue
d1 = hypot(*pp1)
d2 = hypot(*pp2)
if le(d1, r) and le(d2, r):
area += c / 2 # pp1, pp2, 原点を結んだ三角形の面積
else:
t = acos(dot(pp1, pp2) / (d1 * d2)) # pp1-原点とpp2-原点の成す角
sign = 1.0 if c >= 0 else -1.0
area += sign * r * r * t / 2 # 扇形の面積
return area
def cross(v1, v2): # 外積
x1, y1 = v1
x2, y2 = v2
return x1 * y2 - x2 * y1
def dot(v1, v2): # 内積
x1, y1 = v1
x2, y2 = v2
return x1 * x2 + y1 * y2
def seg_intersection(circle, seg):
# 円と線分の交点(円の中心が原点でない場合は未検証)
x0, y0, r = circle
p1, p2 = seg
x1, y1 = p1
x2, y2 = p2
p1p2 = (x2 - x1) ** 2 + (y2 - y1) ** 2
op1 = (x1 - x0) ** 2 + (y1 - y0) ** 2
rr = r * r
dp = dot((x1 - x0, y1 - y0), (x2 - x1, y2 - y1))
d = dp * dp - p1p2 * (op1 - rr)
ps = []
if isclose(d, 0.0, abs_tol=1e-9):
t = -dp / p1p2
if ge(t, 0.0) and le(t, 1.0):
ps.append((x1 + t * (x2 - x1), y1 + t * (y2 - y1)))
elif d > 0.0:
t1 = (-dp - sqrt(d)) / p1p2
if ge(t1, 0.0) and le(t1, 1.0):
ps.append((x1 + t1 * (x2 - x1), y1 + t1 * (y2 - y1)))
t2 = (-dp + sqrt(d)) / p1p2
if ge(t2, 0.0) and le(t2, 1.0):
ps.append((x1 + t2 * (x2 - x1), y1 + t2 * (y2 - y1)))
# assert all(isclose(r, hypot(x, y)) for x, y in ps)
return ps
def le(f1, f2): # less equal
return f1 < f2 or isclose(f1, f2, abs_tol=1e-9)
def ge(f1, f2): # greater equal
return f1 > f2 or isclose(f1, f2, abs_tol=1e-9)
N, cx, cy, r = map(int, input().split())
ans = 0
from math import pi
circle_area = pi * r * r
for _ in range(N):
p, score = map(int, input().split())
ps = []
for _ in range(p):
x, y = map(int, input().split())
ps.append((x, y))
area = intersection((cx, cy, r), ps)
ans += abs(area) * score / circle_area
print(f"{ans:.10f}")
``` |
p01306 Unit Converter | In the International System of Units (SI), various physical quantities are expressed in the form of "numerical value + prefix + unit" using prefixes such as kilo, mega, and giga. For example, "3.5 kilometers", "5.1 milligrams", and so on.
On the other hand, these physical quantities can be expressed as "3.5 * 10 ^ 3 meters" and "5.1 * 10 ^ -3 grams" using exponential notation.
Measurement of physical quantities always includes errors. Therefore, there is a concept of significant figures to express how accurate the measured physical quantity is. In the notation considering significant figures, the last digit may contain an error, but the other digits are considered reliable. For example, if you write "1.23", the true value is 1.225 or more and less than 1.235, and the digits with one decimal place or more are reliable, but the second decimal place contains an error. The number of significant digits when a physical quantity is expressed in the form of "reliable digit + 1 digit including error" is called the number of significant digits. For example, "1.23" has 3 significant digits.
If there is a 0 before the most significant non-zero digit, that 0 is not included in the number of significant digits. For example, "0.45" has two significant digits. If there is a 0 after the least significant non-zero digit, whether or not that 0 is included in the number of significant digits depends on the position of the decimal point. If there is a 0 to the right of the decimal point, that 0 is included in the number of significant digits. For example, "12.300" has 5 significant digits. On the other hand, when there is no 0 to the right of the decimal point like "12300", it is not clear whether to include the 0 on the right side in the number of significant digits, but it will be included in this problem. That is, the number of significant digits of "12300" is five.
Natsume was given a physics problem as a school task. I have to do calculations related to significant figures and units, but the trouble is that I still don't understand how to use significant figures and units. Therefore, I would like you to create a program that automatically calculates them and help Natsume.
What you write is a program that, given a prefixed notation, converts it to exponential notation with the same number of significant digits. The following 20 prefixes are used.
* yotta = 10 ^ 24
* zetta = 10 ^ 21
* exa = 10 ^ 18
* peta = 10 ^ 15
* tera = 10 ^ 12
* giga = 10 ^ 9
* mega = 10 ^ 6
* kilo = 10 ^ 3
* hecto = 10 ^ 2
* deca = 10 ^ 1
* deci = 10 ^ -1
* centi = 10 ^ -2
* milli = 10 ^ -3
* micro = 10 ^ -6
* nano = 10 ^ -9
* pico = 10 ^ -12
* femto = 10 ^ -15
* ato = 10 ^ -18
* zepto = 10 ^ -21
* yocto = 10 ^ -24
Notes on Submission
Multiple datasets are given in the above format. The first line of input data gives the number of datasets. Create a program that outputs the output for each data set in order in the above format.
Input
The input consists of only one line, which contains numbers, unit prefixes (if any), and units. Each is separated by a blank. In some cases, there is no unit prefix, in which case only numbers and units are included in the line. Units with the same name as the unit prefix do not appear. The most significant digit is never 0, except for the ones digit when a decimal is given. The number given is positive. The number given is 1000 digits or less including the decimal point, and the unit name is 50 characters or less.
Output
Output the quantity expressed in exponential notation in the form of a * 10 ^ b [unit]. However, 1 <= a <10. The difference between the singular and plural forms of the unit name is not considered. Output the unit name given to the input as it is.
Example
Input
7
12.3 kilo meters
0.45 mega watts
0.000000000000000000000001 yotta grams
1000000000000000000000000 yocto seconds
42 amperes
0.42 joules
1234.56789012345678901234567890 hecto pascals
Output
1.23 * 10^4 meters
4.5 * 10^5 watts
1 * 10^0 grams
1.000000000000000000000000 * 10^0 seconds
4.2 * 10^1 amperes
4.2 * 10^-1 joules
1.23456789012345678901234567890 * 10^5 pascals | ```python
m = {"yotta":24, "zetta":21, "exa":18, "peta":15, "tera":12, "giga":9, "mega":6, "kilo":3, "hecto":2, "deca":1, "deci":-1, "centi":-2, "milli":-3, "micro":-6, "nano":-9, "pico":-12, "femto":-15, "ato":-18, "zepto":-21, "yocto":-24}
for _ in range(int(input())):
v, *b = input().split()
if len(b) == 2:
k, b = b[0], b[1]
a = m[k]
else:b = b[0];a = 0
s = 0
for i in range(len(v)):
if v[i] in "123456789":
if i != 0:
a -= i - 1
if i != len(v) - 1:v = v[i] + "." + v[i + 1:]
else:v = v[i]
else:
try:
j = v[i:].index(".")
a += j - 1
v = v[0] + "." + v[1:j] + v[j + 1:]
except:
a += len(v) - 1
v = v[0] + "." + v[1:]
break
print("{} * 10^{} {}".format(v, a, b))
``` |
p01787 RLE Replacement | H - RLE Replacement
Problem Statement
In JAG Kingdom, ICPC (Intentionally Compressible Programming Code) is one of the common programming languages. Programs in this language only contain uppercase English letters and the same letters often appear repeatedly in ICPC programs. Thus, programmers in JAG Kingdom prefer to compress ICPC programs by Run Length Encoding in order to manage very large-scale ICPC programs.
Run Length Encoding (RLE) is a string compression method such that each maximal sequence of the same letters is encoded by a pair of the letter and the length. For example, the string "RRRRLEEE" is represented as "R4L1E3" in RLE.
Now, you manage many ICPC programs encoded by RLE. You are developing an editor for ICPC programs encoded by RLE, and now you would like to implement a replacement function. Given three strings $A$, $B$, and $C$ that are encoded by RLE, your task is to implement a function replacing the first occurrence of the substring $B$ in $A$ with $C$, and outputting the edited string encoded by RLE. If $B$ does not occur in $A$, you must output $A$ encoded by RLE without changes.
Input
The input consists of three lines.
> $A$
> $B$
> $C$
The lines represent strings $A$, $B$, and $C$ that are encoded by RLE, respectively. Each of the lines has the following format:
> $c_1$ $l_1$ $c_2$ $l_2$ $\ldots$ $c_n$ $l_n$ \$
Each $c_i$ ($1 \leq i \leq n$) is an uppercase English letter (`A`-`Z`) and $l_i$ ($1 \leq i \leq n$, $1 \leq l_i \leq 10^8$) is an integer which represents the length of the repetition of $c_i$. The number $n$ of the pairs of a letter and an integer satisfies $1 \leq n \leq 10^3$. A terminal symbol `$` indicates the end of a string encoded by RLE. The letters and the integers are separated by a single space. It is guaranteed that $c_i \neq c_{i+1}$ holds for any $1 \leq i \leq n-1$.
Output
Replace the first occurrence of the substring $B$ in $A$ with $C$ if $B$ occurs in $A$, and output the string encoded by RLE. The output must have the following format:
> $c_1$ $l_1$ $c_2$ $l_2$ $\ldots$ $c_m$ $l_m$ \$
Here, $c_i \neq c_{i+1}$ for $1 \leq i \leq m-1$ and $l_i \gt 0$ for $1 \leq i \leq m$ must hold.
Sample Input 1
R 100 L 20 E 10 \$
R 5 L 10 \$
X 20 \$
Output for the Sample Input 1
R 95 X 20 L 10 E 10 \$
Sample Input 2
A 3 B 3 A 3 \$
A 1 B 3 A 1 \$
A 2 \$
Output for the Sample Input 2
A 6 \$
Example
Input
R 100 L 20 E 10 \$
R 5 L 10 \$
X 20 \$
Output
R 95 X 20 L 10 E 10 \$ | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
def inp():
s = LS()
a = []
for i in range(len(s)-1):
if i % 2 == 0:
a.append(s[i])
else:
a.append(int(s[i]))
return a
def com(a):
r = a[:2]
for i in range(2,len(a), 2):
if a[i] == r[-2]:
r[-1] += a[i+1]
else:
r += a[i:i+2]
return r
a = com(inp())
b = com(inp())
c = com(inp())
r = []
ff = True
if len(b) == 2:
b0 = b[0]
b1 = b[1]
for i in range(0,len(a),2):
if a[i] == b0:
while a[i+1] >= b1 and ff:
r += c
a[i+1] -= b1
ff = False
if a[i+1] > 0:
r += a[i:i+2]
else:
r += a[i:i+2]
else:
i = 0
al = len(a)
bl = len(b)
be = bl - 2
while i < al:
f = True
for j in range(0,bl,2):
ii = i + j
if al <= ii or a[ii] != b[j] or (a[ii+1] < b[j+1] if j in [0, be] else a[ii+1] != b[j+1]) or not ff:
f = False
break
if f:
for j in range(0,bl,2):
ii = i + j
a[ii+1] -= b[j+1]
if a[i+1] > 0:
r += a[i:i+2]
if f:
r += c
ff = False
i += 2
r += '$'
return ' '.join(map(str,com(r)))
print(main())
``` |
p02060 Four Tea | A: four tea
problem
Tea is indispensable for programming contests. Tea has the effect of relieving constant tension [citation needed]
There are N players participating in the contest, so I would like to prepare tea for this number of people. There are four types of tea packages, A, B, C, and D, all of which are the same variety but have different contents. For a package X, the price of one package is p_X yen, and it is known that if you buy one, you can make t_X cups of tea.
Find the minimum amount needed to make tea for N people. You may have a package that you don't buy at all, and you don't have to buy a package for just N people (if you can make more than N people).
Input format
The input is given in the following format.
N
p_A p_B p_C p_D
t_A t_B t_C t_D
* The first line gives the number of players participating in the contest.
* In the second line, the prices of tea in packages A, B, C and D are given separated by blanks.
* The third line gives the number of cups of tea that can be made from packages A, B, C, and D, separated by blanks.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq p_X \ leq 100
* 1 \ leq t_X \ leq 100
* All inputs are given as integers.
Output format
Output the minimum amount required to make tea for N people in one line.
Input example 1
Ten
1 2 3 4
1 2 4 8
Output example 1
6
* It's best to buy one package B and one D.
Input example 2
Five
2 9 9 8
1 4 5 100
Output example 2
8
* You will have 20 times more tea than you need, but buying one Package D is the cheapest way to get more than 5 cups of tea.
Input example 3
twenty four
2 3 4 7
7 9 11 20
Output example 3
8
* It's best to buy two packages A and one C. It may not be possible to make just enough tea for the number of people as in this case.
Example
Input
10
1 2 3 4
1 2 4 8
Output
6 | ```python
n,pa,pb,pc,pd,ta,tb,tc,td=map(int,open(0).read().split())
r=range(n+1)
m=1e9
for i in r:
for j in r:
for k in r:
l=0--(n-ta*i-tb*j-tc*k)//td
m=min(m,pa*i+pb*j+pc*k+pd*l*(l>=0))
print(m)
``` |
p02202 Gag | Gag
Segtree has $ N $ of "gags", each with a value of $ V_i $.
Segtree decided to publish all the gags in any order.
Here, the "joy" you get when you publish the $ i $ th gag to the $ j $ th is expressed as $ V_i --j $.
Find the maximum sum of the "joy" you can get.
input
Input is given from standard input in the following format.
$ N $
$ V_1 $ $ V_2 $ $ \ ldots $ $ V_N $
output
Please output the maximum value of the sum of "joy". However, the value does not always fit in a 32-bit integer.
Insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq V_i \ leq 10 ^ 5 $
* All inputs are integers.
Input example 1
1
59549
Output example 1
59548
Input example 2
Five
2 1 8 5 7
Output example 2
8
Example
Input
1
59549
Output
59548 | ```python
n = int(input())
v = list(map(int,input().split()))
count = 0
ans = 0
s = -1
while count != n:
ans -= s
s -= 1
count += 1
print(sum(v)-ans)
``` |
p02356 The Number of Windows | For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and $Q$ integers $x_i$ as queries, for each query, print the number of combinations of two integers $(l, r)$ which satisfies the condition: $1 \leq l \leq r \leq N$ and $a_l + a_{l+1} + ... + a_{r-1} + a_r \leq x_i$.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq Q \leq 500$
* $1 \leq a_i \leq 10^9$
* $1 \leq x_i \leq 10^{14}$
Input
The input is given in the following format.
$N$ $Q$
$a_1$ $a_2$ ... $a_N$
$x_1$ $x_2$ ... $x_Q$
Output
For each query, print the number of combinations in a line.
Example
Input
6 5
1 2 3 4 5 6
6 9 12 21 15
Output
9
12
15
21
18 | ```python
from bisect import bisect_right
def main():
N, Q = map(int, input().split())
a = [-1 for i in range(N)]
sum = [0 for i in range(N + 1)]
for i, val in enumerate(input().split()):
a[i] = int(val)
sum[i + 1] = sum[i] + a[i]
X = list(map(int, input().split()))
# print("DEBUG: sum={}".format(sum))
for x in X:
ans = solve3(a, x, N, sum)
print(ans)
def solve1(a, x, N, sum):
l, r = 0, 0
ret = 0
while l < N:
if r < N + 1:
r = bisect_right(sum, sum[l] + x, r)
if r > l:
ret += (r - 1 - l)
l += 1
return ret
def solve2(a, x, N, sum):
l, r, sum = 0, 0, 0
ret = 0
while l < N:
while r < N and sum + a[r] <= x:
sum += a[r]
r += 1
ret += (r - l)
sum -= a[l]
l += 1
return ret
def solve3(a, x, N, sum):
l, sum, ans = 0, 0, 0
for r in range(N):
sum += a[r]
while sum > x:
sum -= a[l]
l += 1
ans += r - l + 1
return ans
main()
``` |
1015_A. Points in Segments | You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider all integer points between 1 and m inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment [l; r] if and only if l ≤ x ≤ r.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of segments and the upper bound for coordinates.
The next n lines contain two integers each l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — the endpoints of the i-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that l_i=r_i, i.e. a segment can degenerate to a point.
Output
In the first line print one integer k — the number of points that don't belong to any segment.
In the second line print exactly k integers in any order — the points that don't belong to any segment. All points you print should be distinct.
If there are no such points at all, print a single integer 0 in the first line and either leave the second line empty or do not print it at all.
Examples
Input
3 5
2 2
1 2
5 5
Output
2
3 4
Input
1 7
1 7
Output
0
Note
In the first example the point 1 belongs to the second segment, the point 2 belongs to the first and the second segments and the point 5 belongs to the third segment. The points 3 and 4 do not belong to any segment.
In the second example all the points from 1 to 7 belong to the first segment. | ```python
n, m = [int(x) for x in input().split()]
s = set(range(1, m+1))
for _ in range(n):
a, b = [int(x) for x in input().split()]
s -= set(range(a, b+1))
print(len(s))
print(*s)
``` |
1038_E. Maximum Matching | You are given n blocks, each of them is of the form [color_1|value|color_2], where the block can also be flipped to get [color_2|value|color_1].
A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.
The value of the sequence is defined as the sum of the values of the blocks in this sequence.
Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of given blocks.
Each of the following n lines describes corresponding block and consists of color_{1,i}, value_i and color_{2,i} (1 ≤ color_{1,i}, color_{2,i} ≤ 4, 1 ≤ value_i ≤ 100 000).
Output
Print exactly one integer — the maximum total value of the subset of blocks, which makes a valid sequence.
Examples
Input
6
2 1 4
1 2 4
3 4 4
2 8 3
3 16 3
1 32 2
Output
63
Input
7
1 100000 1
1 100000 2
1 100000 2
4 50000 3
3 50000 4
4 50000 4
3 50000 3
Output
300000
Input
4
1 1000 1
2 500 2
3 250 3
4 125 4
Output
1000
Note
In the first example, it is possible to form a valid sequence from all blocks.
One of the valid sequences is the following:
[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]
The first block from the input ([2|1|4] → [4|1|2]) and second ([1|2|4] → [4|2|1]) are flipped.
In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):
[2|100000|1] [1|100000|1] [1|100000|2]
In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value. | ```python
def min(a, b):
if a < b:
return a
return b
def max(a,b):
return abs(min(-a,-b))
been = [0 for i in range(4)]
ans = 0
minw = 10**18
degpar = [0 for i in range(4)]
w = [0 for i in range(4)]
gr = [list() for i in range(4)]
rem = [[0 for i in range(4)] for j in range(4)]
def dfs(x, l):
l.append(w[x])
if been[x]:
return
been[x] = 1
for i in gr[x]:
if been[i] == 0 and rem[x][i] > 0:
dfs(i, l)
n = int(input())
blocks = []
for i in range(n):
a,v,b = map(int, input().split())
a -= 1
b -= 1
if a != b:
blocks.append([a,v,b])
w[b] += v
if a != b:
minw = min(minw, v)
degpar[a] += 1
degpar[a] %= 2
degpar[b] += 1
degpar[b] %= 2
gr[a].append(b)
gr[b].append(a)
rem[a][b] += 1
rem[b][a] += 1
ok = True
for i in range(4):
l = []
if been[i] == 0:
dfs(i, l)
if i == 0 and all(been) and all(degpar):
ok = False
break
ans = max(ans, sum(l))
if ok:
print(ans)
exit()
for p in blocks:
i = p[0]
j = p[2]
w[j] -= p[1]
been = [0 for i in range(4)]
rem[i][j] -= 1
rem[j][i] -= 1
#print(i)
#print(j)
#print(':')
for x in range(4):
l = []
if been[x] == 0:
dfs(x,l)
ans = max(ans, sum(l))
#print(sum(l))
w[j] += p[1]
rem[i][j] += 1
rem[j][i] += 1
print(ans)
``` |
1061_A. Coins | You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S (1 ≤ n ≤ 100 000, 1 ≤ S ≤ 10^9)
Output
Print exactly one integer — the minimum number of coins required to obtain sum S.
Examples
Input
5 11
Output
3
Input
6 16
Output
3
Note
In the first example, some of the possible ways to get sum 11 with 3 coins are:
* (3, 4, 4)
* (2, 4, 5)
* (1, 5, 5)
* (3, 3, 5)
It is impossible to get sum 11 with less than 3 coins.
In the second example, some of the possible ways to get sum 16 with 3 coins are:
* (5, 5, 6)
* (4, 6, 6)
It is impossible to get sum 16 with less than 3 coins. | ```python
n, s = map(int, input().split())
print((s + n - 1) // n)
``` |
1082_G. Petya and Graph | Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.
Input
The first line contains two numbers n and m (1 ≤ n ≤ 10^3, 0 ≤ m ≤ 10^3) - the number of vertices and edges in the graph, respectively.
The next line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) - the weights of the vertices of the graph.
The following m lines contain edges: the i-e edge is defined by a triple of integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n, 1 ≤ w_i ≤ 10^9, v_i ≠ u_i). This triple means that between the vertices v_i and u_i there is an edge of weight w_i. It is guaranteed that the graph does not contain loops and multiple edges.
Output
Print one integer — the maximum weight of the subgraph of the given graph.
Examples
Input
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
Output
8
Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3
Output
0
Note
In the first test example, the optimal subgraph consists of the vertices {1, 3, 4} and has weight 4 + 4 + 5 - (1 + 2 + 2) = 8. In the second test case, the optimal subgraph is empty. | ```python
class edge(object):
def __init__(self,ne,to,fl):
self.ne=ne
self.to=to
self.fl=fl
def add(x,y,z):
global tot
tot+=1
e.append(edge(he[x],y,z))
he[x]=tot
def addedge(x,y,z):
add(x,y,z)
add(y,x,0)
def bfs():
global deep
deep=[0 for i in range(T+1)]
q=[]
q.append(S)
deep[S]=1
while (len(q)>0):
x=q[0]
del(q[0])
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==0)and(e[i].fl!=0)):
deep[y]=deep[x]+1
q.append(y)
i=e[i].ne
return deep[T]!=0
def dfs(x,flow):
global deep
if ((x==T)or(flow==0)):
return flow
used=0
i=he[x]
while (i):
y=e[i].to
if ((deep[y]==deep[x]+1)and(e[i].fl!=0)):
now=dfs(y,min(flow-used,e[i].fl))
used+=now
e[i].fl-=now
e[i^1].fl+=now
if (flow==used):
break;
i=e[i].ne
if (used==0):
deep[x]=-1
return used
def dinic():
res=0
while (bfs()):
res+=dfs(S,INF)
return res
n,m=map(int,input().split())
ans=0
weight=[0]+list(map(int,input().split()))
e=[0,0]
tot=1
S=n+m+1
T=S+1
he=[0 for i in range(T+1)]
INF=1000000007
for i in range(1,n+1):
addedge(S,i,weight[i]);
for i in range(1,m+1):
x,y,w=map(int,input().split())
addedge(n+i,T,w)
addedge(x,n+i,INF)
addedge(y,n+i,INF)
ans+=w
ans-=dinic()
print(ans)
``` |
1102_B. Array K-Coloring | You are given an array a consisting of n integer numbers.
You have to color this array in k colors in such a way that:
* Each element of the array should be colored in some color;
* For each i from 1 to k there should be at least one element colored in the i-th color in the array;
* For each i from 1 to k all elements colored in the i-th color should be distinct.
Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, ... c_n, where 1 ≤ c_i ≤ k and c_i is the color of the i-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the length of the array a and the number of colors, respectively.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 5000) — elements of the array a.
Output
If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, ... c_n, where 1 ≤ c_i ≤ k and c_i is the color of the i-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.
Examples
Input
4 2
1 2 2 3
Output
YES
1 1 2 2
Input
5 2
3 2 1 2 3
Output
YES
2 1 1 2 1
Input
5 2
2 1 1 2 1
Output
NO
Note
In the first example the answer 2~ 1~ 2~ 1 is also acceptable.
In the second example the answer 1~ 1~ 1~ 2~ 2 is also acceptable.
There exist other acceptable answers for both examples. | ```python
from collections import defaultdict
n,k=map(int,input().split())
arr=list(map(int,input().split()))
temp=[0]*5001
for i in arr:
temp[i]+=1
if(max(temp)>k):
print('NO')
elif(k>n):
print('NO')
else:
print('YES')
d=defaultdict(list)
c=0
t=[0]*n
for i in range(n):
t[i]=arr[i]
t.sort()
for i in range(len(t)):
d[t[i]].append(c+1)
c=(c+1)%k
p=[0]*5001
for i in range(len(arr)):
print(d[arr[i]][p[arr[i]]],end=' ')
p[arr[i]]+=1
``` |
1130_B. Two Cakes | Sasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom).
They live on the same street, there are 2 ⋅ n houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the i-th house you can buy a tier of the size a_i (1 ≤ a_i ≤ n).
Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: 1, then 2, then 3 and so on up to n.
Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly 1.
Input
The first line of the input contains an integer number n — the number of tiers in each cake (1 ≤ n ≤ 10^5).
The second line contains 2 ⋅ n integers a_1, a_2, ..., a_{2n} (1 ≤ a_i ≤ n), where a_i is equal to the size of the tier, which can be bought in the i-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from 1 to n occurs in a exactly two times.
Output
Print one number — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy n tiers in ascending order of their sizes.
Examples
Input
3
1 1 2 2 3 3
Output
9
Input
2
2 1 1 2
Output
5
Input
4
4 1 3 2 2 3 1 4
Output
17
Note
In the first example, the possible optimal sequence of actions is:
* Sasha buys a tier of size 1 near the 1-st house (a_1=1);
* Dima goes to the house 2;
* Dima buys a tier of size 1 near the 2-nd house (a_2=1);
* Sasha goes to the house 4;
* Sasha buys a tier of size 2 near the 4-th house (a_4=2);
* Sasha goes to the house 5;
* Sasha buys a tier of size 3 near the 5-th house (a_5=3);
* Dima goes to the house 3;
* Dima buys a tier of size 2 near the 3-rd house (a_3=2);
* Dima goes to the house 6;
* Dima buys a tier of size 3 near the 6-th house (a_6=3).
So, Sasha goes the distance 3+1=4, and Dima goes the distance 1+1+3=5. In total, they cover a distance of 4+5=9. You can make sure that with any other sequence of actions they will walk no less distance. | ```python
l2=[]
n=int(input())
l=list(map(int,input().split()))
for i in range(2*n):
l2.append([l[i],i])
l2.sort()
sd,dd=l2[0][1],l2[1][1]
for i in range(2,2*n):
if i%2:
dd+=abs(l2[i][1]-l2[i-2][1])
else:
sd+=abs(l2[i][1]-l2[i-2][1])
print(sd+dd)
``` |
1150_C. Prefix Sum Primes | We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.
Can you win the prize? Hurry up, the bags are waiting!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of number tiles in the bag. The following line contains n space-separated integers a_1, a_2, ..., a_n (a_i ∈ \{1, 2\}) — the values written on the tiles.
Output
Output a permutation b_1, b_2, ..., b_n of the input sequence (a_1, a_2, ..., a_n) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
Examples
Input
5
1 2 1 2 1
Output
1 1 1 2 2
Input
9
1 1 2 1 1 1 2 1 1
Output
1 1 1 2 1 1 1 2 1
Note
The first solution produces the prefix sums 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}} (four primes constructed), while the prefix sums in the second solution are 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}} (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible. | ```python
n=int(input())
l=list(map(int,input().split()))
n1,n2=0,0
for i in l:
if i==1:
n1+=1
else:
n2+=1
r=[]
if n1==0 or n2==0:
r=l
else:
r.append(2)
r.append(1)
n1-=1
n2-=1
while n2!=0:
r.append(2)
n2-=1
while n1!=0:
r.append(1)
n1-=1
for i in range(n):
print(r[i],end=" ")
print()
``` |
1172_C2. Nauuo and Pictures (hard version) | The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{∑_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.
However, Nauuo discovered that some pictures she does not like were displayed too often.
To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.
Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?
The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0≤ r_i<998244353 and r_i⋅ p_i≡ q_i\pmod{998244353}. It can be proved that such r_i exists and is unique.
Input
The first line contains two integers n and m (1≤ n≤ 2⋅ 10^5, 1≤ m≤ 3000) — the number of pictures and the number of visits to the website.
The second line contains n integers a_1,a_2,…,a_n (a_i is either 0 or 1) — if a_i=0 , Nauuo does not like the i-th picture; otherwise Nauuo likes the i-th picture. It is guaranteed that there is at least one picture which Nauuo likes.
The third line contains n positive integers w_1,w_2,…,w_n (w_i ≥ 1) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed 998244352-m.
Output
The output contains n integers r_1,r_2,…,r_n — the expected weights modulo 998244353.
Examples
Input
2 1
0 1
2 1
Output
332748119
332748119
Input
1 2
1
1
Output
3
Input
3 3
0 1 1
4 3 5
Output
160955686
185138929
974061117
Note
In the first example, if the only visit shows the first picture with a probability of \frac 2 3, the final weights are (1,1); if the only visit shows the second picture with a probability of \frac1 3, the final weights are (2,2).
So, both expected weights are \frac2 3⋅ 1+\frac 1 3⋅ 2=\frac4 3 .
Because 332748119⋅ 3≡ 4\pmod{998244353}, you need to print 332748119 instead of \frac4 3 or 1.3333333333.
In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, w_1 will be increased by 1.
So, the expected weight is 1+2=3.
Nauuo is very naughty so she didn't give you any hint of the third example. | ```python
P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
PO[i] = pow((SU+i)%P, P-2, P)
def calc(L):
su = sum(L)
pl = 0
pd = 0
RE = []
for i in range(len(L)):
a = li + i
b = di - (len(L) - 1 - i)
pd = b * L[i] * PO[a+b-SU]
RE.append((pl+pd)%P)
pl = a * L[i] * PO[a+b-SU]
RE.append(pl%P)
return RE
for i in range(M):
X = calc(X)
ne = 0
po = 0
for i in range(M+1):
po = (po + X[i] * (li + i)) % P
ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P)
``` |
118_E. Bertown roads | Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 3·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of junctions it connects.
It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.
Output
If there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi — each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.
Examples
Input
6 8
1 2
2 3
1 3
4 5
4 6
5 6
2 4
3 5
Output
1 2
2 3
3 1
4 5
5 6
6 4
4 2
3 5
Input
6 7
1 2
2 3
1 3
4 5
4 6
5 6
2 4
Output
0 | ```python
from sys import stdin,setrecursionlimit
import threading
input = lambda: stdin.readline().rstrip("\r\n")
from collections import deque as que
inin = lambda: int(input())
inar = lambda: list(map(int,input().split()))
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
from collections import defaultdict
adj=defaultdict(list)
visited=[False]*(100001)
intime=[0]*(100001)
outtime=[0]*(100001)
res=[]
bridge=False
timer=0
@bootstrap
def dfs(node,par):
global adj, visited, intime, outtime, res, bridge,timer
visited[node]=True
intime[node]=timer
outtime[node]=timer
timer+=1
for j in adj[node]:
if j==par:
continue
if visited[j]:
outtime[node]=min(outtime[node],intime[j])
if intime[node]>intime[j]:
res.append((node,j))
else:
yield dfs(j,node)
if outtime[j]>intime[node]:
bridge=True
yield None
res.append((node,j))
outtime[node] = min(outtime[node], outtime[j])
yield
def main():
n,m=map(int,input().split())
global adj,visited,intime,outtime,res,bridge,timer
timer=0
bridge=False
for i in range(m):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
dfs(1,-1)
if bridge:
print(0)
else:
for i in range(len(res)):
print(*res[i])
main()
``` |
1209_D. Cow and Snacks | The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are n snacks flavors, numbered with integers 1, 2, …, n. Bessie has n snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows:
* First, Bessie will line up the guests in some way.
* Then in this order, guests will approach the snacks one by one.
* Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.
Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
Input
The first line contains integers n and k (2 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^5), the number of snacks and the number of guests.
The i-th of the following k lines contains two integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), favorite snack flavors of the i-th guest.
Output
Output one integer, the smallest possible number of sad guests.
Examples
Input
5 4
1 2
4 3
1 4
3 4
Output
1
Input
6 5
2 3
2 1
3 4
6 5
4 5
Output
0
Note
In the first example, Bessie can order the guests like this: 3, 1, 2, 4. Guest 3 goes first and eats snacks 1 and 4. Then the guest 1 goes and eats the snack 2 only, because the snack 1 has already been eaten. Similarly, the guest 2 goes up and eats the snack 3 only. All the snacks are gone, so the guest 4 will be sad.
In the second example, one optimal ordering is 2, 1, 3, 5, 4. All the guests will be satisfied. | ```python
from collections import defaultdict
import sys
import typing
class DSU:
'''
Implement (union by size) + (path halving)
Reference:
Zvi Galil and Giuseppe F. Italiano,
Data structures and algorithms for disjoint set union problems
'''
def __init__(self, n: int = 0) -> None:
self._n = n
self.parent_or_size = [-1] * n
def merge(self, a: int, b: int) -> int:
assert 0 <= a < self._n
assert 0 <= b < self._n
x = self.leader(a)
y = self.leader(b)
if x == y:
return x
if -self.parent_or_size[x] < -self.parent_or_size[y]:
x, y = y, x
self.parent_or_size[x] += self.parent_or_size[y]
self.parent_or_size[y] = x
return x
def same(self, a: int, b: int) -> bool:
assert 0 <= a < self._n
assert 0 <= b < self._n
return self.leader(a) == self.leader(b)
def leader(self, a: int) -> int:
assert 0 <= a < self._n
parent = self.parent_or_size[a]
while parent >= 0:
if self.parent_or_size[parent] < 0:
return parent
self.parent_or_size[a], a, parent = (
self.parent_or_size[parent],
self.parent_or_size[parent],
self.parent_or_size[self.parent_or_size[parent]]
)
return a
def size(self, a: int) -> int:
assert 0 <= a < self._n
return -self.parent_or_size[self.leader(a)]
def groups(self) -> typing.List[typing.List[int]]:
leader_buf = [self.leader(i) for i in range(self._n)]
result: typing.List[typing.List[int]] = [[] for _ in range(self._n)]
for i in range(self._n):
result[leader_buf[i]].append(i)
return list(filter(lambda r: r, result))
def input():
return sys.stdin.readline().rstrip()
def slv():
n, k = map(int, input().split())
dsu = DSU(n)
Edge = []
for i in range(k):
u, v = map(int, input().split())
u -= 1
v -= 1
Edge.append((u, v))
dsu.merge(u, v)
ans = k - n + len(set([dsu.leader(i) for i in range(n)]))
print(ans)
return
def main():
t = 1
for i in range(t):
slv()
return
if __name__ == "__main__":
main()
``` |
1228_C. Primes and Multiplication | Let's introduce some definitions that will be needed later.
Let prime(x) be the set of prime divisors of x. For example, prime(140) = \{ 2, 5, 7 \}, prime(169) = \{ 13 \}.
Let g(x, p) be the maximum possible integer p^k where k is an integer such that x is divisible by p^k. For example:
* g(45, 3) = 9 (45 is divisible by 3^2=9 but not divisible by 3^3=27),
* g(63, 7) = 7 (63 is divisible by 7^1=7 but not divisible by 7^2=49).
Let f(x, y) be the product of g(y, p) for all p in prime(x). For example:
* f(30, 70) = g(70, 2) ⋅ g(70, 3) ⋅ g(70, 5) = 2^1 ⋅ 3^0 ⋅ 5^1 = 10,
* f(525, 63) = g(63, 3) ⋅ g(63, 5) ⋅ g(63, 7) = 3^2 ⋅ 5^0 ⋅ 7^1 = 63.
You have integers x and n. Calculate f(x, 1) ⋅ f(x, 2) ⋅ … ⋅ f(x, n) mod{(10^{9} + 7)}.
Input
The only line contains integers x and n (2 ≤ x ≤ 10^{9}, 1 ≤ n ≤ 10^{18}) — the numbers used in formula.
Output
Print the answer.
Examples
Input
10 2
Output
2
Input
20190929 1605
Output
363165664
Input
947 987654321987654321
Output
593574252
Note
In the first example, f(10, 1) = g(1, 2) ⋅ g(1, 5) = 1, f(10, 2) = g(2, 2) ⋅ g(2, 5) = 2.
In the second example, actual value of formula is approximately 1.597 ⋅ 10^{171}. Make sure you print the answer modulo (10^{9} + 7).
In the third example, be careful about overflow issue. | ```python
"""
import math
MOD=1000000007
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
x,n=map(int,input().split())
n1=x
L=[]
while(n1%2==0):
L.append(2)
n1=n1//2
for i in range(3,int(math.sqrt(n1))+1,2):
while(n1%i==0):
L.append(i)
n1=n1//i
if(n1>2):
L.append(n1)
L=list(set(L))
mul=1
for i in range(0,len(L)):
d=L[i]
nn=n
tot=0
while(nn>0):
tot=(tot+(nn//d))%MOD
nn=(nn//d)%MOD
mul=(mul*powr(d,tot))%MOD
print(mul)
"""
"""
import math
MOD=1000000007
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
def MODI(a,b):
ans=(powr(a,b)%MOD)
return ans
x,n=map(int,input().split())
n1=x
L=[]
while(n1%2==0):
L.append(2)
n1=n1//2
for i in range(3,int(math.sqrt(n1))+1,2):
while(n1%i==0):
L.append(i)
n1=n1//i
if(n1>2):
L.append(n1)
L=list(set(L))
mul=1
for i in range(0,len(L)):
d=L[i]
t=MODI(d,MOD-2)%MOD
nn=n
while(nn>0):
rem=nn%d
nn=(nn-rem)%MOD
nn=(nn*t)%MOD
mul=(mul*powr(d,nn))%MOD
print(mul)
"""
import math
MOD=1000000007
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
x,n=map(int,input().split())
n1=x
L=[]
while(n1%2==0):
L.append(2)
n1=n1//2
for i in range(3,int(math.sqrt(n1))+1,2):
while(n1%i==0):
L.append(i)
n1=n1//i
if(n1>2):
L.append(n1)
L=list(set(L))
mul=1
for i in range(0,len(L)):
d=L[i]
nn=n
while(nn>0):
mul=(mul*powr(d,nn//d))%MOD
nn=nn//d
print(mul)
``` |
1270_C. Make Good | Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). At the same time, array [1, 2, 1, 3] isn't good, as 1 + 2 + 1 + 3 = 7 ≠ 2⋅ 1 = 2⋅(1⊕ 2 ⊕ 1 ⊕ 3).
You are given an array of length n: a_1, a_2, ..., a_n. Append at most 3 elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10 000). The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 10^5) — the size of the array.
The second line of each test case contains n integers a_1, a_2, ..., a_n (0≤ a_i ≤ 10^9) — the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, output two lines.
In the first line, output a single integer s (0≤ s≤ 3) — the number of elements you want to append.
In the second line, output s integers b_1, ..., b_s (0≤ b_i ≤ 10^{18}) — the elements you want to append to the array.
If there are different solutions, you are allowed to output any of them.
Example
Input
3
4
1 2 3 6
1
8
2
1 1
Output
0
2
4 4
3
2 6 2
Note
In the first test case of the example, the sum of all numbers is 12, and their ⊕ is 6, so the condition is already satisfied.
In the second test case of the example, after adding 4, 4, the array becomes [8, 4, 4]. The sum of numbers in it is 16, ⊕ of numbers in it is 8. | ```python
from functools import reduce
from operator import xor
for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
print(2)
print(sum(a) + reduce(xor, a), reduce(xor, a))
``` |
1293_A. ConneR and the A.R.C. Markland-N | [Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.
ConneR's office is at floor s of the building. On each floor (including floor s, of course), there is a restaurant offering meals. However, due to renovations being in progress, k of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.
CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.
Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first line of a test case contains three integers n, s and k (2 ≤ n ≤ 10^9, 1 ≤ s ≤ n, 1 ≤ k ≤ min(n-1, 1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.
The second line of a test case contains k distinct integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n) — the floor numbers of the currently closed restaurants.
It is guaranteed that the sum of k over all test cases does not exceed 1000.
Output
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor s to a floor with an open restaurant.
Example
Input
5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
Output
2
0
4
0
2
Note
In the first example test case, the nearest floor with an open restaurant would be the floor 4.
In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.
In the third example test case, the closest open restaurant is on the 6-th floor. | ```python
t = int(input())
for _ in range(t):
variables = [int(_) for _ in input().split()]
n = variables[0]
s = variables[1]
k = variables[2]
closed = set([int(i) for i in input().split()])
minimum = n
tmp = n
for x in range(s, 0, -1):
if x not in closed:
tmp = abs(s-x)
if tmp < minimum:
minimum = tmp
break
for x in range(s, n+1):
if x not in closed:
tmp = abs(s-x)
if tmp < minimum:
minimum = tmp
break
print(minimum)
``` |
1313_A. Fast Food Restaurant | Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:
* every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);
* each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;
* all visitors should receive different sets of dishes.
What is the maximum number of visitors Denis can feed?
Input
The first line contains an integer t (1 ≤ t ≤ 500) — the number of test cases to solve.
Each of the remaining t lines contains integers a, b and c (0 ≤ a, b, c ≤ 10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.
Output
For each test case print a single integer — the maximum number of visitors Denis can feed.
Example
Input
7
1 2 1
0 0 0
9 1 7
2 2 3
2 3 2
3 2 2
4 4 4
Output
3
0
4
5
5
5
7
Note
In the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.
In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.
In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | ```python
import os
import sys
from io import BytesIO, IOBase
def solution(a, b, c):
if a == 0 and b == 0 and c == 0:
print(0)
return
res = 0
comb = ['001', '010', '100', '011', '101', '110', '111']
comb2 = ['01', '10', '11']
a, b, c = sorted([a, b, c])
if a == 0 and b == 0:
print(1)
return
if a == 0:
for co in comb2:
bb, cc = map(int, co)
b -= bb
c -= cc
if b < 0 or c < 0:
break
res += 1
else:
for co in comb:
aa, bb, cc = map(int, co)
a -= aa
b -= bb
c -= cc
if a < 0 or b < 0 or c < 0:
break
res += 1
print(res)
def main():
for _ in range(int(input())):
a, b, c = [int(x) for x in input().split()]
solution(a, b, c)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input():
return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` |
1335_E1. Three Blocks Palindrome (easy version) | The only difference between easy and hard versions is constraints.
You are given a sequence a consisting of n positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ..., a}_{x}, \underbrace{b, b, ..., b}_{y}, \underbrace{a, a, ..., a}_{x}]. There x, y are integers greater than or equal to 0. For example, sequences [], [2], [1, 1], [1, 2, 1], [1, 2, 2, 1] and [1, 1, 2, 1, 1] are three block palindromes but [1, 2, 3, 2, 1], [1, 2, 1, 2, 1] and [1, 2] are not.
Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.
You have to answer t independent test cases.
Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2000) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2000) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 26), where a_i is the i-th element of a. Note that the maximum value of a_i can be up to 26.
It is guaranteed that the sum of n over all test cases does not exceed 2000 (∑ n ≤ 2000).
Output
For each test case, print the answer — the maximum possible length of some subsequence of a that is a three blocks palindrome.
Example
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3 | ```python
T = int(input())
Q = []
# Read all inputs before computing (see last comment, the goal is to print once)
for t in range(T):
N = int(input())
A = [int(_) for _ in input().split()]
Q.append((N, A))
R = []
for N, A in Q:
# Switch the 2 dimensions of the array to maybe prevent cache miss on loops l26 and l30
prefC = [[0] * (26) for _ in range(N+1)]
for c in range(26):
for i in range(N):
prefC[i+1][c] = prefC[i][c]
if A[i] == c+1:
prefC[i+1][c] += 1
answer = 0
for l in range(N):
for r in range(l, N):
cntin = 0
# Write the explicit loop, don't use max on the list comprehension (x2 constant factor inside the N² loop)
for c in range(26):
cntin = max(cntin, prefC[r+1][c] - prefC[l][c])
cntout = 0
# Write the explicit loop, don't use max on the list comprehension (x2 constant factor inside the N² loop)
for c in range(26):
cntout = max(cntout, min(prefC[l][c], prefC[N][c] - prefC[r+1][c]))
answer = max(answer, 2 * cntout + cntin)
R.append(answer)
# Do only one print instead of T prints (less stdout flushing I guess)
print('\n'.join(map(str, R)))
``` |
1358_A. Park Lighting | Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length 1. For example, park with n=m=2 has 12 streets.
You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).
<image> The park sizes are: n=4, m=5. The lighted squares are marked yellow. Please note that all streets have length 1. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit.
Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow.
Each test case is a line containing two integers n, m (1 ≤ n, m ≤ 10^4) — park sizes.
Output
Print t answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.
Example
Input
5
1 1
1 3
2 2
3 3
5 3
Output
1
2
2
5
8
Note
Possible optimal arrangement of the lanterns for the 2-nd test case of input data example: <image>
Possible optimal arrangement of the lanterns for the 3-rd test case of input data example: <image> | ```python
import math
t=int(input())
while(t>0):
t-=1
n,m=map(int,input().split())
print(math.floor((n*m+1)/2))
``` |
1399_B. Gifts Fixing | You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly one candy from this gift (decrease a_i by one);
* eat exactly one orange from this gift (decrease b_i by one);
* eat exactly one candy and exactly one orange from this gift (decrease both a_i and b_i by one).
Of course, you can not eat a candy or orange if it's not present in the gift (so neither a_i nor b_i can become less than zero).
As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: a_1 = a_2 = ... = a_n and b_1 = b_2 = ... = b_n (and a_i equals b_i is not necessary).
Your task is to find the minimum number of moves required to equalize all the given gifts.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 50) — the number of gifts. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the number of candies in the i-th gift. The third line of the test case contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the number of oranges in the i-th gift.
Output
For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.
Example
Input
5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
Output
6
16
0
4999999995
7
Note
In the first test case of the example, we can perform the following sequence of moves:
* choose the first gift and eat one orange from it, so a = [3, 5, 6] and b = [2, 2, 3];
* choose the second gift and eat one candy from it, so a = [3, 4, 6] and b = [2, 2, 3];
* choose the second gift and eat one candy from it, so a = [3, 3, 6] and b = [2, 2, 3];
* choose the third gift and eat one candy and one orange from it, so a = [3, 3, 5] and b = [2, 2, 2];
* choose the third gift and eat one candy from it, so a = [3, 3, 4] and b = [2, 2, 2];
* choose the third gift and eat one candy from it, so a = [3, 3, 3] and b = [2, 2, 2]. | ```python
# Gifts Fixing
# https://codeforces.com/problemset/problem/1399/B
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
min_a = min(a)
min_b = min(b)
count = 0
for i in range(n):
diff_a = a[i] - min_a
diff_b = b[i] - min_b
count += max(diff_a, diff_b)
print(count)
``` |
1422_E. Minlexes | Some time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.
Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the following conditions are satisfied:
* for each pair (i, i + 1) the inequality 0 ≤ i < |s| - 1 holds;
* for each pair (i, i + 1) the equality s_i = s_{i + 1} holds;
* there is no index that is contained in more than one pair.
After that Lesha removes all characters on indexes contained in these pairs and the algorithm is over.
Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string.
Input
The only line contains the string s (1 ≤ |s| ≤ 10^5) — the initial string consisting of lowercase English letters only.
Output
In |s| lines print the lengths of the answers and the answers themselves, starting with the answer for the longest suffix. The output can be large, so, when some answer is longer than 10 characters, instead print the first 5 characters, then "...", then the last 2 characters of the answer.
Examples
Input
abcdd
Output
3 abc
2 bc
1 c
0
1 d
Input
abbcdddeaaffdfouurtytwoo
Output
18 abbcd...tw
17 bbcdd...tw
16 bcddd...tw
15 cddde...tw
14 dddea...tw
13 ddeaa...tw
12 deaad...tw
11 eaadf...tw
10 aadfortytw
9 adfortytw
8 dfortytw
9 fdfortytw
8 dfortytw
7 fortytw
6 ortytw
5 rtytw
6 urtytw
5 rtytw
4 tytw
3 ytw
2 tw
1 w
0
1 o
Note
Consider the first example.
* The longest suffix is the whole string "abcdd". Choosing one pair (4, 5), Lesha obtains "abc".
* The next longest suffix is "bcdd". Choosing one pair (3, 4), we obtain "bc".
* The next longest suffix is "cdd". Choosing one pair (2, 3), we obtain "c".
* The next longest suffix is "dd". Choosing one pair (1, 2), we obtain "" (an empty string).
* The last suffix is the string "d". No pair can be chosen, so the answer is "d".
In the second example, for the longest suffix "abbcdddeaaffdfouurtytwoo" choose three pairs (11, 12), (16, 17), (23, 24) and we obtain "abbcdddeaadfortytw" | ```python
import sys
s = input().strip()
N = len(s)
if len(s) == 1:
print(1, s[0])
sys.exit()
X = [s[-1], s[-2]+s[-1] if s[-2]!=s[-1] else ""]
Y = [1, 2 if s[-2]!=s[-1] else 0]
for i in range(N-3, -1, -1):
c = s[i]
k1 = c+X[-1]
ng = Y[-1]+1
if ng > 10:
k1 = k1[:5] + "..." + k1[-2:]
if c == s[i+1] and k1 > X[-2]:
k1 = X[-2]
ng = Y[-2]
X.append(k1)
Y.append(ng)
for i in range(N-1, -1, -1):
print(Y[i], X[i])
``` |
1440_C2. Binary Table (Hard Version) | This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).
Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.
It can be proved, that it is always possible.
Input
The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).
Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.
It is guaranteed, that the sum of nm for all test cases does not exceed 20000.
Output
For each test case print the integer k (0 ≤ k ≤ nm) — the number of operations.
In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong to some 2 × 2 square.
Example
Input
5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101
Output
1
1 1 2 1 2 2
2
2 1 3 1 3 2
1 2 1 3 2 3
4
1 1 1 2 2 2
1 3 1 4 2 3
3 2 4 1 4 2
3 3 4 3 4 4
4
1 2 2 1 2 2
1 4 1 5 2 5
4 1 4 2 5 1
4 4 4 5 3 4
2
1 3 2 2 2 3
1 2 2 1 2 2
Note
In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.
In the second test case:
* operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:
011
001
000
* operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:
000
000
000
In the fifth test case:
* operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:
010
110
* operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:
000
000
| ```python
import sys
input=sys.stdin.readline
def change(x1,x2,x3,y1,y2,y3,ll):
ll[x1][y1]=1-ll[x1][y1]
ll[x2][y2]=1-ll[x2][y2]
#print(x3,y3,ll)
ll[x3][y3]=1-ll[x3][y3]
t=int(input())
while t:
n,m=map(int,input().split())
ll=[]
for i in range(n):
l=list(map(int,input().strip()))
ll.append(l)
ans=[]
#print(ll)
for i in range(n-1):
for j in range(m):
if(i==n-2 and j==m-2):
break
if(ll[i][j]):
#print("lol")
if(j+1<m):
#print("lol")
ans.append((i+1,i+2,i+2,j+1,j+1,j+2))
#print(i+1,j+1,n,m)
change(i,i+1,i+1,j,j,j+1,ll)
else:
ans.append((i+1,i+2,i+2,j+1,j+1,j))
change(i,i+1,i+1,j,j,j-1,ll)
#print(ans,ll)
for i in range(m-1):
if(ll[n-1][i] and ll[n-2][i]):
ans.append((n-1,n,n,i+1,i+1,i+2))
change(n-2,n-1,n-1,i,i,i+1,ll)
elif(ll[n-1][i]):
ans.append((n,n,n-1,i+1,i+2,i+2))
change(n-1,n-1,n-2,i,i+1,i+1,ll)
elif(ll[n-2][i]):
ans.append((n-1,n-1,n,i+1,i+2,i+2))
change(n-2,n-2,n-1,i,i+1,i+1,ll)
#for i in ll:
#print(*i)
#print(ans,ll)
if(ll[n-1][m-1] and ll[n-2][m-1]):
ans.append((n,n-1,n,m,m-1,m-1))
ans.append((n,n-1,n-1,m-1,m-1,m))
elif(ll[n-2][m-1]):
#print("lol")
ans.append((n-1,n,n,m,m,m-1))
change(n-2,n-1,n-1,m-1,m-1,m-2,ll)
#print()
#for i in ll:
#print(*i)
ans.append((n,n-1,n-1,m,m-1,m))
change(n-1,n-2,n-2,m-1,m-2,m-1,ll)
#print()
#for i in ll:
#print(*i)
ans.append((n,n-1,n-1,m-1,m,m-1))
change(n-1,n-2,n-2,m-2,m-1,m-2,ll)
#print()
#for i in ll:
#print(*i)
elif(ll[n-1][m-1]):
ans.append((n,n,n-1,m,m-1,m-1))
ans.append((n-1,n-1,n,m-1,m,m))
ans.append((n,n,n-1,m-1,m,m))
print(len(ans))
#for i in ll:
#print(*i)
for i in ans:
x1,x2,x3,y1,y2,y3=i
print(x1,y1,x2,y2,x3,y3)
t-=1
``` |
1467_E. Distinctive Roots in a Tree | You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.
Find the number of distinctive roots in the tree.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 2⋅10^5) — the number of vertices in the tree.
The next line contains n space-separated integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
The following n-1 lines each contain two space-separated integers u and v (1 ≤ u, v ≤ n), denoting an edge from u to v.
It is guaranteed that the edges form a tree.
Output
Print a single integer — the number of distinctive roots in the tree.
Examples
Input
5
2 5 1 1 4
1 2
1 3
2 4
2 5
Output
3
Input
5
2 1 1 1 4
1 2
1 3
2 4
2 5
Output
0
Note
In the first example, 1, 2 and 5 are distinctive roots. | ```python
import io, os
from collections import Counter, defaultdict, deque
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
_default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size : _size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
idx >>= 1
while idx:
self.data[idx] = (
self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
)
idx >>= 1
def add(self, start, stop, value):
if start == stop:
return
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=0):
start += self._size
stop += self._size
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
def solve(N, A, edges):
graph = [[] for i in range(N)]
for u, indices in edges:
graph[u].append(indices)
graph[indices].append(u)
# Build euler tour
eulerTour = []
root = 0
stack = [root]
seen = [False] * len(graph)
while stack:
node = stack.pop()
eulerTour.append(node)
if not seen[node]:
seen[node] = True
for nbr in graph[node]:
if not seen[nbr]:
stack.append(node)
stack.append(nbr)
assert eulerTour[0] == eulerTour[-1]
eulerTour.pop()
tourByValues = defaultdict(list)
for i, x in enumerate(eulerTour):
tourByValues[A[x]].append(i)
segTree = LazySegmentTree([0] * len(eulerTour), 0, lambda x, y: x + y)
for k, indices in tourByValues.items():
nodes = set(eulerTour[i] for i in indices)
if len(nodes) >= 2:
for i in indices:
segTree.add(i, i + 1, 1)
subtour = []
for i, j in zip(indices, indices[1:]):
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, j + 1, 1)
else:
subtour.append(i)
i = indices[-1]
j = indices[0]
x = eulerTour[i]
y = eulerTour[j]
if x == y:
segTree.add(i, len(eulerTour), 1)
segTree.add(0, j + 1, 1)
else:
subtour.append(i)
if len(nodes) != len(subtour):
# Subtour has non leaves, impossible
return 0
if False:
print("label", k, "visits", indices, "nodes", nodes)
print(
"\t".join(
str(eulerTour[i]) + ":" + str(A[eulerTour[i]])
for i in range(len(eulerTour))
)
)
for i in range(len(eulerTour)):
if segTree.query(i, i + 1) != 0:
print("x", end="\t")
else:
print("o", end="\t")
print()
print()
return N - len(set([eulerTour[i] for i in range(len(eulerTour)) if segTree.query(i, i + 1) != 0]))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N = int(input());A = [int(x) for x in input().split()];e = [[int(x) - 1 for x in input().split()] for i in range(N - 1)];print(solve(N, A, e))
``` |
1541_E1. Converging Array (Easy Version) | This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 ≤ i ≤ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 ≤ a_i ≤ c_i for 1 ≤ i ≤ n.
Your task is to count the number of good arrays a where F(a, b) ≥ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 ≤ n ≤ 100).
The second line contains n integers c_1, c_2 …, c_n (0 ≤ c_i ≤ 100).
The third line contains n-1 integers b_1, b_2, …, b_{n-1} (0 ≤ b_i ≤ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, …, x_q (-10^5 ≤ x_i ≤ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) ≥ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2. | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
C = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
Q = int(input())
x = int(input())
P = 10 ** 9 + 7
dp = [[0] * 20100 for _ in range(N + 1)]
dp[0][0] = 1
ans = 0
s = x
t = s
for i in range(N):
for j in range(20050, t - 1, -1):
if j < 0: break
dp[i+1][j] = (dp[i+1][j+1] + dp[i][max(j-C[i], 0)] - dp[i][j+1]) % P
for j in range(min(t - 1, 20050), -1, -1):
dp[i+1][j] = dp[i+1][j+1]
if i < N - 1:
s += B[i]
t += s
print(dp[-1][0] % P)
``` |
18_B. Platforms | In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.
Input
The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l < m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].
Output
Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.
Examples
Input
2 2 5 3
Output
4
Input
5 4 11 8
Output
20 | ```python
class Platforms:
@classmethod
def read_input(cls):
nums = list(map(int, input('').split()))
return nums[0], nums[1], nums[2], nums[3]
@classmethod
def run(cls):
n, d, m, l = cls.read_input()
end_plat = (n - 1) * m + l
for cur_jump in range(d, (m + 1) * d, d):
if (cur_jump % m) > l or cur_jump > end_plat:
print(cur_jump)
return
print(end_plat - (end_plat % d) + d)
if __name__ == "__main__":
Platforms.run()
``` |
213_B. Numbers | Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.
There is integer n and array a, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive integers with the following properties:
* the number's length does not exceed n;
* the number doesn't have leading zeroes;
* digit i (0 ≤ i ≤ 9) occurs in the number at least a[i] times.
Input
The first line contains integer n (1 ≤ n ≤ 100). The next line contains 10 integers a[0], a[1], ..., a[9] (0 ≤ a[i] ≤ 100) — elements of array a. The numbers are separated by spaces.
Output
On a single line print the remainder of dividing the answer to the problem by 1000000007 (109 + 7).
Examples
Input
1
0 0 0 0 0 0 0 0 0 1
Output
1
Input
2
1 1 0 0 0 0 0 0 0 0
Output
1
Input
3
1 1 0 0 0 0 0 0 0 0
Output
36
Note
In the first sample number 9 meets the requirements.
In the second sample number 10 meets the requirements.
In the third sample numbers 10, 110, 210, 120, 103 meet the requirements. There are other suitable numbers, 36 in total. | ```python
from math import factorial
dp=[[-1 for i in range (101)] for j in range(101)]
def solve(n,p,a):
if dp[n][p] is not -1:
return dp[n][p]
elif p is 9:
if n>=a[9]:
return 1
else:
return 0
elif p is 0:
ans=0
for i in range(a[0],n):
z=solve(n-i,1,a)
z*=factorial(n-1)
z//=factorial(i)
z//=factorial(n-1-i)
ans+=z
dp[n][p]=ans
return ans
else:
ans=0
for i in range(a[p],n+1):
z=solve(n-i,p+1,a)
z*=factorial(n)
z//=factorial(i)
z//=factorial(n-i)
ans+=z
dp[n][p]=ans
return ans
hell=1000000007
n=int(input())
a=input().rstrip().split(' ');
for i in range(0,len(a)):
a[i]=int(a[i])
ans=0
for i in range(1,n+1):
ans+=solve(i,0,a)
ans%=hell
print(ans)
``` |
237_B. Young Table | You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≤ n) holds ci ≤ ci - 1.
Let's denote s as the total number of cells of table a, that is, <image>. We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct.
Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai, j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions:
1. for all i, j (1 < i ≤ n; 1 ≤ j ≤ ci) holds ai, j > ai - 1, j;
2. for all i, j (1 ≤ i ≤ n; 1 < j ≤ ci) holds ai, j > ai, j - 1.
In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap.
Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) that shows the number of rows in the table. The second line contains n space-separated integers ci (1 ≤ ci ≤ 50; ci ≤ ci - 1) — the numbers of cells on the corresponding rows.
Next n lines contain table а. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai, j.
It is guaranteed that all the given numbers ai, j are positive and do not exceed s. It is guaranteed that all ai, j are distinct.
Output
In the first line print a single integer m (0 ≤ m ≤ s), representing the number of performed swaps.
In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi, yi, pi, qi (1 ≤ xi, pi ≤ n; 1 ≤ yi ≤ cxi; 1 ≤ qi ≤ cpi). The printed numbers denote swapping the contents of cells axi, yi and api, qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed.
Examples
Input
3
3 2 1
4 3 5
6 1
2
Output
2
1 1 2 2
2 1 3 1
Input
1
4
4 3 2 1
Output
2
1 1 1 4
1 2 1 3 | ```python
n = int(input())
I = lambda : map(int,input().split())
li = list (I())
dd = {}
arr = [ [0 for i in range(51)] for j in range(51) ]
l2 = [ ]
c=0
for i in range (1,n+1) :
l1 = list(I())
l2 = l2 + l1
c = c + len(l1)
for j in range(li[i-1]) :
arr[i][j+1] = l1[j]
dd[l1[j]] = [i , j+1]
#print(dd)
#print(l2)
l3 = l2[:]
l3.sort()
#print(l3)
ans= 0
d1 = {}
for i,j in enumerate(l2) :
d1[j]=i
#print(d1)
answer = [ ]
#print(dd)
#print(l2)
for i in range(c) :
if l2[i]!=l3[i] :
t1 = l2[i]
t2 = i+1
#print(t1,t2)
#temp = dd[t1]
#temp1 = dd[t2]
answer = answer + [dd[t1] + dd[t2]]
l2[i] = i+1
l2[d1[t2]] = t1
d1[t1] = d1[t2]
d1[i+1] = i
temp2 = dd[t1]
dd[t1] = dd[t2]
dd[t2] = temp2
ans+=1
#print(l2)
print(ans)
for i in range(ans) :
print(*answer[i])
``` |
285_E. Positions in Permutations | Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
We'll call position i (1 ≤ i ≤ n) in permutation p1, p2, ..., pn good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 0 ≤ k ≤ n).
Output
Print the number of permutations of length n with exactly k good positions modulo 1000000007 (109 + 7).
Examples
Input
1 0
Output
1
Input
2 1
Output
0
Input
3 2
Output
4
Input
4 1
Output
6
Input
7 4
Output
328
Note
The only permutation of size 1 has 0 good positions.
Permutation (1, 2) has 0 good positions, and permutation (2, 1) has 2 positions.
Permutations of size 3:
1. (1, 2, 3) — 0 positions
2. <image> — 2 positions
3. <image> — 2 positions
4. <image> — 2 positions
5. <image> — 2 positions
6. (3, 2, 1) — 0 positions | ```python
mod=10**9+7
n,k=map(int,input().split())
A=[0]*(n+1)
B=[0]*(n+1)
C=[0]*(n+1)
F=[0]*(n+1)
G=[0]*(n+1)
F[0]=G[0]=1
for i in range(1,n+1):
G[i]=F[i]=F[i-1]*i%mod
G[i]=pow(F[i],(mod-2),mod)
for i in range(0,n):
if i*2>n:
break
B[i]=(F[n-i]*G[i]*G[n-i*2])%mod
for i in range(0,n//2+1):
for j in range(0,n//2+1):
A[i+j]=(A[i+j]+B[i]*B[j])%mod
for i in range(0,n+1):
A[i]=A[i]*F[n-i]%mod
for i in range(0,n+1):
for j in range(0,i+1):
C[j]=(C[j]+A[i]*F[i]*G[j]*G[i-j]*(1-(i-j)%2*2))%mod
print(C[k]%mod)
``` |
356_C. Compartments | A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.
The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.
However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.
After all the swaps each compartment should either have no student left, or have a company of three or four students.
Input
The first line contains integer n (1 ≤ n ≤ 106) — the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≤ ai ≤ 4). It is guaranteed that at least one student is riding in the train.
Output
If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.
Examples
Input
5
1 2 2 4 3
Output
2
Input
3
4 1 1
Output
2
Input
4
0 3 0 4
Output
0 | ```python
n = int(input())
A = [0, 0, 0, 0, 0]
B = map(int, input().split(' '))
for i in B:
A[i] += 1
res = min(A[1], A[2])
A[1] -= res
A[2] -= res
A[3] += res
res += 2 * (A[1] // 3)
A[3] += A[1] // 3
A[1] %= 3
res += 2 * (A[2] // 3)
A[3] += 2 * (A[2] // 3)
A[2] %= 3
assert(A[1] == 0 or A[2] == 0)
if (A[1] == 1):
if (A[3] > 0):
res += 1 #; A[1] = 0; A[3] -= 1; A[4] += 1
elif (A[4] > 1):
res += 2 #; A[1] = 0; A[4] -= 2; A[3] += 3
else:
print(-1)
exit()
elif (A[1] == 2):
if (A[4] > 0):
res += 2 #; A[1] = 0; A[4] -= 1; A[3] += 1
elif (A[3] > 1):
res += 2 #; A[1] = 0; A[3] -= 2; A[4] += 2
else:
print(-1)
exit()
if (A[2] == 1):
if (A[4] > 0):
res += 1 #; A[4] -= 1; A[2] = 0; A[3] += 1
elif (A[3] > 1):
res += 2; #; A[2] = 0; A[3] -= 2; A[4] += 2
else:
print(-1)
exit()
elif (A[2] == 2):
res += 2 #; A[2] = 0; A[4] += 1
print(res)
``` |
37_B. Computer Game | Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.
While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:
1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.
2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.
During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).
The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.
Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.
Input
The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).
Output
In case Petya can’t complete this level, output in the single line NO.
Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds.
Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.
Examples
Input
2 10 3
100 3
99 1
Output
NO
Input
2 100 10
100 11
90 9
Output
YES
19 2
0 1
10 2 | ```python
class Scroll:
def __init__(self, id, power, damage):
self.id = id
self.power = power
self.damage = damage
self.active = False
num_scrolls, boss_max, regenerate = map(int, input().split())
scrolls = [Scroll(i+1, *map(int, input().split())) for i in range(num_scrolls)]
scrolls.sort(key = lambda scroll: -scroll.damage)
boss_curr = boss_max
scroll_damage = 0
active_scrolls = []
tick = 0
while True:
boss_prev = boss_curr
boss_curr -= scroll_damage
boss_curr = min(boss_max, boss_curr + regenerate)
if boss_curr <= 0:
print('YES')
print(tick, len(active_scrolls))
for scroll in active_scrolls:
print(scroll.start, scroll.id)
break
found = False
for scroll in scrolls:
if not scroll.active and 100*boss_curr <= scroll.power*boss_max:
scroll.start = tick
scroll.active = True
active_scrolls.append(scroll)
scroll_damage += scroll.damage
found = True
break
if not found and boss_curr >= boss_prev:
print('NO')
break
tick += 1
``` |
400_A. Inna and Choose Options | There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.
Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.
Input
The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line.
The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.
Output
For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.
Examples
Input
4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO
Output
3 1x12 2x6 4x3
4 1x12 2x6 3x4 6x2
6 1x12 2x6 3x4 4x3 6x2 12x1
0 | ```python
n = int(input())
a = [1, 2, 3, 4, 6, 12]
for i in range(0, n):
s = str(input())
ans = [False for x in range(0, 6)]
nans = 0;
for i in range (0, 6):
for j in range (0, 12 // a[i]):
good = True
for k in range(0, a[i]):
if s[k * 12 // a[i] + j] is 'O':
good = False
break
if good:
nans = nans + 1
ans[i] = True
break
print(nans, end = ' ')
for i in range (0, 6):
if ans[i]:
print(str(a[i]) + 'x' + str(12 // a[i]), end = ' ')
print()
``` |
427_B. Prison Transfer | The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.
For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.
Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,
* The chosen c prisoners has to form a contiguous segment of prisoners.
* Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.
Find the number of ways you can choose the c prisoners.
Input
The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.
Output
Print a single integer — the number of ways you can choose the c prisoners.
Examples
Input
4 3 3
2 3 1 1
Output
2
Input
1 1 1
2
Output
0
Input
11 4 2
2 2 0 7 3 2 2 4 9 1 4
Output
6 | ```python
a=list(map(int,input().split()[1:]))
b=list(map(int,input().split()))
m=0
c=0
for i in b:
if i>a[0]:
if not c<a[1]:
m+=c-a[1]+1
c=0
else:c+=1
print(m+c-a[1]+1 if c>=a[1]else m)
``` |
472_A. Design Tutorial: Learn from Math | One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer n no less than 12, express it as a sum of two composite numbers.
Input
The only line contains an integer n (12 ≤ n ≤ 106).
Output
Output two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.
Examples
Input
12
Output
4 8
Input
15
Output
6 9
Input
23
Output
8 15
Input
1000000
Output
500000 500000
Note
In the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.
In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number. | ```python
def isprime(k):
m=0
for j in range(2,k):
if k%j==0:
m=m+1
if m==0:
return 0
else:
return 1
n=int(input())
for i in range(4,n-3):
if isprime(i)==1 and isprime(n-i)==1:
print(i,n-i)
exit()
``` |
496_B. Secret Combination | You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.
The second line contains n digits — the initial state of the display.
Output
Print a single line containing n digits — the desired state of the display containing the smallest possible number.
Examples
Input
3
579
Output
024
Input
4
2014
Output
0142 | ```python
n = int(input())
s = input()
i = 0
min_ = int(s)
s1 = s
i = 0
while (i <= n):
s = s[1::] + s[0]
if (int(s[0]) != 0):
g = (9 - int(s[0])) + 1
s2 = ''
for j in range(len(s)):
h = int(s[j]) + g
if (h >= 10):
h = abs(10 - h)
s2 = s2 + str(h)
s = s2
if (int(s) < min_):
min_ = int(s)
s1 = s
i = i + 1
print(s1)
``` |
547_A. Mike and Frog | Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.
<image>
So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become <image> and height of Abol will become <image> where x1, y1, x2 and y2 are some integer numbers and <image> denotes the remainder of a modulo b.
Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.
Mike has asked you for your help. Calculate the minimum time or say it will never happen.
Input
The first line of input contains integer m (2 ≤ m ≤ 106).
The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m).
The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m).
The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m).
The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m).
It is guaranteed that h1 ≠ a1 and h2 ≠ a2.
Output
Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.
Examples
Input
5
4 2
1 1
0 1
2 3
Output
3
Input
1023
1 2
1 0
1 2
1 1
Output
-1
Note
In the first sample, heights sequences are following:
Xaniar: <image>
Abol: <image> | ```python
def main():
m, tt = int(input()), [0] * 4
for i in 0, 2:
h, a = map(int, input().split())
x, y = map(int, input().split())
ha = (h, a)
for t in range(1, m * 2):
h = (h * x + y) % m
if h in ha:
if h == ha[0]:
if tt[i]:
tt[i] = t - tt[i]
break
else:
tt[i] = t
else:
if tt[i + 1]:
tt[i] = t - tt[i + 1]
break
else:
tt[i + 1] = t
step1, shift1, step2, shift2 = tt if tt[0] > tt[2] else tt[2:] + tt[:2]
if shift1 == shift2 != 0:
print(shift1)
return
if step1 and not step2 and shift1 and shift1 <= shift2 and not (shift2 - shift1) % step1:
print(shift2)
return
if all(tt):
if step2 == 1:
print(shift1 if shift1 >= shift2 else shift2 + (shift2 - shift1) % step1)
return
for t in range(shift1 - shift2, shift1 - shift2 + step1 * step2, step1):
if not t % step2:
print(t + shift2)
return
print(-1)
if __name__ == '__main__':
main()
``` |
595_A. Vitaly and Night | One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.
Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.
Input
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively.
Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.
Output
Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.
Examples
Input
2 2
0 0 0 1
1 0 1 1
Output
3
Input
1 3
1 1 0 1 0 0
Output
2
Note
In the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.
In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off. | ```python
etaj, kvart = map(int, input().split())
Okna = []
notsleep = 0
for i in range(0, etaj):
Okna.append(list(map(int, input().split())))
for i in range(0, etaj):
for j in range(0, (kvart*2)-1, 2):
if Okna[i][j] or Okna[i][j+1] == 1:
notsleep += 1
print(notsleep)
``` |
616_D. Longest k-Good Segment | The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input
The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k.
The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.
Output
Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.
Examples
Input
5 5
1 2 3 4 5
Output
1 5
Input
9 3
6 5 1 2 3 2 1 4 5
Output
3 7
Input
3 1
1 2 3
Output
1 1 | ```python
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rln=sys.stdin.readline
rl=lambda:rln().rstrip('\n')
rfs=lambda:rln().split()
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
########################################################################
n,k=ris()
a=ris()
beg=end=i=0
occ=ddict(int)
for j in range(n):
occ[a[j]]+=1
while len(occ)>k:
occ[a[i]]-=1
if occ[a[i]]==0:
del occ[a[i]]
i+=1
if end-beg<j-i:
beg,end=i,j
print(beg+1,end+1)
``` |
689_B. Mike and Shortcuts | Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to <image> units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.
Input
The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.
The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , <image>, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).
Output
In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.
Examples
Input
3
2 2 3
Output
0 1 2
Input
5
1 2 3 4 5
Output
0 1 2 3 4
Input
7
4 4 4 4 7 7 7
Output
0 1 2 1 2 3 3
Note
In the first sample case desired sequences are:
1: 1; m1 = 0;
2: 1, 2; m2 = 1;
3: 1, 3; m3 = |3 - 1| = 2.
In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.
In the third sample case — consider the following intersection sequences:
1: 1; m1 = 0;
2: 1, 2; m2 = |2 - 1| = 1;
3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;
4: 1, 4; m4 = 1;
5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;
6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;
7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3. | ```python
def amount_of_total_energy(n, a):
dist = [-1] * n
dist[0] = 0
pos = [0]
for u in pos:
for v in [u - 1, u + 1, a[u] - 1]:
if v >= 0 and v < n and dist[v] == -1:
dist[v] = dist[u] + 1
pos.append(v)
return dist
n = int(input())
a = list(map(int,input().split()))
print(*amount_of_total_energy(n, a))
``` |
731_F. Video Cards | Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are n video cards in the shop, the power of the i-th video card is equal to integer value ai. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.
Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 200 000) — powers of video cards.
Output
The only line of the output should contain one integer value — the maximum possible total power of video cards working together.
Examples
Input
4
3 2 15 9
Output
27
Input
4
8 2 2 7
Output
18
Note
In the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28.
In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18. | ```python
n = int(input())
s = list(map(int, input().split()))
h = max(s)
ss = [0] * (h + 1)
for i in s:
ss[i] += 1
f, x = [0] * h, 0
for j in reversed(ss):
x += j
f.append(x)
f.reverse()
res = []
for i, x in enumerate(ss):
if x:
summ, x = 0, f[i]
for j in range(i, h + 1, i):
o = f[j + i]
summ += (x - o) * j
x = o
res.append(summ)
print(max(res))
``` |
756_A. Pavel and barbecue | Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.
Pavel has a plan: a permutation p and a sequence b1, b2, ..., bn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.
Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.
There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k ≥ 2n), so that after k seconds each skewer visits each of the 2n placements.
It can be shown that some suitable pair of permutation p and sequence b exists for any n.
Input
The first line contain the integer n (1 ≤ n ≤ 2·105) — the number of skewers.
The second line contains a sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation, according to which Pavel wants to move the skewers.
The third line contains a sequence b1, b2, ..., bn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.
Output
Print single integer — the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.
Examples
Input
4
4 3 2 1
0 1 1 1
Output
2
Input
3
2 3 1
0 0 0
Output
1
Note
In the first example Pavel can change the permutation to 4, 3, 1, 2.
In the second example Pavel can change any element of b to 1. | ```python
import sys
input = sys.stdin.readline
n = int(input())
permutation = list(map(int, input().split()))
go = set(range(1,n+1))
reached = set()
ans = 0
while go:
x = go.pop()
while x not in reached:
reached.add(x)
x = permutation[x-1]
if x in go:
go.remove(x)
ans += 1
if ans == 1:
ans = 0
permutation = input().split()
if permutation.count('1') % 2 == 0:
ans += 1
print(ans)#
``` |
777_B. Game of Credit Cards | After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use.
The second line contains n digits — Sherlock's credit card number.
The third line contains n digits — Moriarty's credit card number.
Output
First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.
Examples
Input
3
123
321
Output
0
2
Input
2
88
00
Output
2
0
Note
First sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks. | ```python
n = int(input())
s = list(map(int, list(input())))
m = map(int, list(input()))
ma = [0] * 10
for dig in m:
ma[dig] += 1
ma2 = list(ma)
min_f = 0
for nu in s:
for x in range(nu, 10):
if ma[x] > 0:
ma[x] -= 1
break
else:
min_f += 1
for z in range(len(ma)):
if ma[z] > 0:
ma[z] -= 1
break
print(min_f)
ma = ma2
max_f = 0
for nu in s:
for x in range(nu+1, 10):
if ma[x] > 0:
ma[x] -= 1
max_f += 1
break
else:
for z in range(len(ma)):
if ma[z] > 0:
ma[z] -= 1
break
print(max_f)
``` |
822_B. Crossword solving | Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?
Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.
Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.
Input
The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly.
The second line contains n lowercase English letters — string s.
The third line contains m lowercase English letters — string t.
Output
In the first line print single integer k — the minimal number of symbols that need to be replaced.
In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.
Examples
Input
3 5
abc
xaybz
Output
2
2 3
Input
4 10
abcd
ebceabazcd
Output
1
2 | ```python
n, m = map(int, input().split())
s = input()
t = input()
res = 1001
res_ind = []
b = 0
e = len(s)
while b <= len(t)-len(s):
sr = t[b:e]
k = 0
ind = []
for i in range(len(s)):
if s[i] != sr[i]:
k += 1
else:
ind.append(i+1)
if k < res:
res = k
res_ind = ind
b += 1
e += 1
print(res)
res_ind = [x for x in range(1, len(s)+1) if x not in res_ind]
print(*res_ind)
``` |
847_G. University Classes | There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.
The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.
Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.
Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.
Output
Print minimum number of rooms needed to hold all groups classes on Monday.
Examples
Input
2
0101010
1010101
Output
1
Input
3
0101011
0011001
0110111
Output
3
Note
In the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.
In the second example three rooms is enough, because in the seventh time slot all three groups have classes. | ```python
n = int(input())
schedules = []
for i in range(n):
schedules.append(input())
minimum = 0
for i in range(7):
activeSlots = 0
for j in range(n):
activeSlots += int(schedules[j][i])
if activeSlots > minimum:
minimum = activeSlots
print(minimum)
``` |
869_B. The Eternal Immortality | Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a! = 1 × 2 × ... × a. Specifically, 0! = 1.
Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, <image>. Note that when b ≥ a this value is always integer.
As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.
Input
The first and only line of input contains two space-separated integers a and b (0 ≤ a ≤ b ≤ 1018).
Output
Output one line containing a single decimal digit — the last digit of the value that interests Koyomi.
Examples
Input
2 4
Output
2
Input
0 10
Output
0
Input
107 109
Output
2
Note
In the first example, the last digit of <image> is 2;
In the second example, the last digit of <image> is 0;
In the third example, the last digit of <image> is 2. | ```python
# Main maut ko takiya, aur kafan ko chaadar banakkar audhta hoon!
a,b=input().split()
if a[:-1]!=b[:-1]:
print("0")
else:
ans=1
for i in range(int(a[-1])+1,int(b[-1])+1):
ans*=i
ans=ans%10
print(ans)
``` |
895_A. Pizza Separation | Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.
Input
The first line contains one integer n (1 ≤ n ≤ 360) — the number of pieces into which the delivered pizza was cut.
The second line contains n integers ai (1 ≤ ai ≤ 360) — the angles of the sectors into which the pizza was cut. The sum of all ai is 360.
Output
Print one integer — the minimal difference between angles of sectors that will go to Vasya and Petya.
Examples
Input
4
90 90 90 90
Output
0
Input
3
100 100 160
Output
40
Input
1
360
Output
360
Input
4
170 30 150 10
Output
0
Note
In first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.
In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.
In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.
Picture explaning fourth sample:
<image>
Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector. | ```python
n=int(input())
a=list(map(int,input().split()))
print(2*min(abs(180-sum(a[l:r])) for l in range(n) for r in range(l,n)))
``` |
916_B. Jamie and Binary Sequence (changed after round) | Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.
To be more clear, consider all integer sequence with length k (a1, a2, ..., ak) with <image>. Give a value <image> to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.
For definitions of powers and lexicographical order see notes.
Input
The first line consists of two integers n and k (1 ≤ n ≤ 1018, 1 ≤ k ≤ 105) — the required sum and the length of the sequence.
Output
Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence.
It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].
Examples
Input
23 5
Output
Yes
3 3 2 1 0
Input
13 2
Output
No
Input
1 2
Output
Yes
-1 -1
Note
Sample 1:
23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23
Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.
Answers like (4, 1, 1, 1, 0) do not have the minimum y value.
Sample 2:
It can be shown there does not exist a sequence with length 2.
Sample 3:
<image>
Powers of 2:
If x > 0, then 2x = 2·2·2·...·2 (x times).
If x = 0, then 2x = 1.
If x < 0, then <image>.
Lexicographical order:
Given two different sequences of the same length, (a1, a2, ... , ak) and (b1, b2, ... , bk), the first one is smaller than the second one for the lexicographical order, if and only if ai < bi, for the first i where ai and bi differ. | ```python
n, k = map(int, input().split())
cnt = [0] * 200010
ans = ''
for i in range(64):
if (n >> i)&1:
k -= 1
cnt[i] = 1;
if k < 0:
print("No")
else:
print("Yes")
for i in range(64, -64, -1):
if k >= cnt[i]:
cnt[i - 1] += cnt[i] * 2
k -= cnt[i]
cnt[i] = 0
else: break
for i in range(-64, 64):
if cnt[i]:
while k:
cnt[i] -= 1
cnt[i - 1] += 2
i -= 1
k-= 1
break
for i in range(64, -100010, -1): ans += (str(i) + ' ') * cnt[i]
print(ans)
``` |
939_C. Convenient For Everybody | In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.
Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.
Help platform select such an hour, that the number of people who will participate in the contest is maximum.
Input
The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest.
The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).
Output
Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.
Examples
Input
3
1 2 3
1 3
Output
3
Input
5
1 2 3 4 1
1 3
Output
4
Note
In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.
In second example only people from the third and the fourth timezones will participate. | ```python
# Problem D
n = int(input())
inp = input().split(" ")
people = [ int(x) for x in inp ]
inp = input().split(" ")
s, f = int(inp[0]), int(inp[1])
r = f-s#+1 # tamaño de la ventana
max_s, idx_max = sum( people[i] for i in range(r) ), 0
sum_ac = max_s
res = (n-idx_max+s)%n if (n-idx_max+s)%n else n
for j in range(n):
# print(sum_ac, idx_max, res)
sum_ac = sum_ac - people[j] + people[(r+j)%n]
if sum_ac>max_s:
max_s, idx_max = sum_ac, (j+1)%n
res = (n-(j+1)+s)%n if (n-(j+1)+s)%n else n
elif sum_ac==max_s:
res_1 = (n-(j+1)+s)%n if (n-(j+1)+s)%n else n
if res_1<res:
res=res_1
# res = (n-idx_max+s)%n if (n-idx_max+s)%n else n
print(res)
``` |
991_F. Concise and clear | Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write 10^{6}, instead of 1000000000 —10^{9}, instead of 1000000007 — 10^{9}+7.
Vasya decided that, to be concise, the notation should follow several rules:
* the notation should only consist of numbers, operations of addition ("+"), multiplication ("*") and exponentiation ("^"), in particular, the use of braces is forbidden;
* the use of several exponentiation operations in a row is forbidden, for example, writing "2^3^4" is unacceptable;
* the value of the resulting expression equals to the initial number;
* the notation should consist of the minimal amount of symbols.
Given n, find the equivalent concise notation for it.
Input
The only line contains a single integer n (1 ≤ n ≤ 10 000 000 000).
Output
Output a concise notation of the number n. If there are several concise notations, output any of them.
Examples
Input
2018
Output
2018
Input
1000000007
Output
10^9+7
Input
10000000000
Output
100^5
Input
2000000000
Output
2*10^9
Note
The third sample allows the answer 10^10 also of the length 5. | ```python
import math
import itertools
pow10 = [1]
for i in range(10):
pow10.append(pow10[-1] * 10)
def getlen(x):
"""length of the decimal representation of integer x"""
return int(math.log10(x)) + 1
class ShortestRepresentation:
def __init__(self, n):
self.n = n
self._m = {}
self._s = [set() for i in range(10)]
self._generate_powers()
self._generate_power_and_power(7)
self._generate_simple_and_power(7)
def _generate_powers(self):
"""add to the collection all expressions of the form a^b"""
range_x = itertools.takewhile(
lambda x: x**2 <= self.n,
itertools.count(2))
for x in range_x:
c = x**2
p = 2
while c <= self.n:
self.update(c, '{}^{}'.format(x, p))
c *= x
p += 1
def _generate_power_and_power(self, maxlen):
"""add to the collection all expressions of the form a^b*c^d"""
for i in range(1, maxlen + 1):
range_j = itertools.takewhile(
lambda j: i + j + 1 <= maxlen,
itertools.count(i))
for j in range_j:
for x, y in itertools.product(self._s[i], self._s[j]):
x2 = self.get(x)
y2 = self.get(y)
self.update(x * y, '{}*{}'.format(x2, y2))
def _generate_simple_and_power(self, maxlen):
"""add to the collection all expressions of the form a^b*c"""
for i in range(1, maxlen - 1):
range_xy = itertools.product(
range(1, pow10[maxlen - 1 - i]),
self._s[i])
for x, y in range_xy:
y2 = self.get(y)
self.update(x * y, '{}*{}'.format(x, y2))
def update(self, x, s):
"""update with s x'th entry of the collection"""
if x > self.n:
return
ls = len(s)
if ls >= getlen(x): # length of s should be at least shorter
return
if x not in self._m:
self._m[x] = s
self._s[ls].add(x)
else:
lm = len(self._m[x])
if ls < lm:
self._s[lm].remove(x)
self._m[x] = s
self._s[ls].add(x)
def get(self, x):
"""retrieve shortest valid representation of number x"""
return self._m[x] if x in self._m else str(x)
n = int(input())
if n < 10**10:
sr = ShortestRepresentation(n)
ans = sr.get(n)
# check a*b and a+b
range_i = itertools.takewhile(
lambda i: i * 2 + 1 < len(ans),
itertools.count())
for i in range_i:
range_x = itertools.chain(
range(1, pow10[i] + 1),
sr._s[i])
for x in range_x:
ans = min(
ans, '{}+{}'.format(sr.get(x), sr.get(n - x)), key=len)
if n % x > 0:
continue
ans = min(
ans, '{}*{}'.format(sr.get(x), sr.get(n // x)), key=len)
print(ans)
else:
print('100^5')
``` |
p02621 AtCoder Beginner Contest 172 - Calc | Given an integer a as input, print the value a + a^2 + a^3.
Constraints
* 1 \leq a \leq 10
* a is an integer.
Input
Input is given from Standard Input in the following format:
a
Output
Print the value a + a^2 + a^3 as an integer.
Examples
Input
2
Output
14
Input
10
Output
1110 | ```python
a= int(input())
eq= a+(a**2)+(a**3)
print(eq)
``` |
p02752 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Preserve Diameter | We have a tree G with N vertices numbered 1 to N. The i-th edge of G connects Vertex a_i and Vertex b_i.
Consider adding zero or more edges in G, and let H be the graph resulted.
Find the number of graphs H that satisfy the following conditions, modulo 998244353.
* H does not contain self-loops or multiple edges.
* The diameters of G and H are equal.
* For every pair of vertices in H that is not directly connected by an edge, the addition of an edge directly connecting them would reduce the diameter of the graph.
Constraints
* 3 \le N \le 2 \times 10^5
* 1 \le a_i, b_i \le N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
\vdots
a_{N-1} b_{N-1}
Output
Print the answer.
Examples
Input
6
1 6
2 1
5 2
3 4
2 3
Output
3
Input
3
1 2
2 3
Output
1
Input
9
1 2
2 3
4 2
1 7
6 1
2 5
5 9
6 8
Output
27
Input
19
2 4
15 8
1 16
1 3
12 19
1 18
7 11
11 15
12 9
1 6
7 14
18 2
13 12
13 5
16 13
7 1
11 10
7 17
Output
78732 | ```python
import sys
input = sys.stdin.readline
mod=998244353
N=int(input())
E=[[] for i in range(N+1)]
for i in range(N-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
Q=[1]
D=[-1]*(N+1)
D[1]=0
while Q:
x=Q.pop()
for to in E[x]:
if D[to]==-1:
D[to]=D[x]+1
Q.append(to)
f=D.index(max(D))
Q=[f]
D=[-1]*(N+1)
D[f]=0
while Q:
x=Q.pop()
for to in E[x]:
if D[to]==-1:
D[to]=D[x]+1
Q.append(to)
MAX=max(D)
l=D.index(MAX)
Q=[l]
D2=[-1]*(N+1)
D2[l]=0
while Q:
x=Q.pop()
for to in E[x]:
if D2[to]==-1:
D2[to]=D2[x]+1
Q.append(to)
if MAX%2==0:
for i in range(N+1):
if D[i]==MAX//2 and D2[i]==MAX//2:
c=i
break
TOP_SORT=[]
Q=[c]
D=[-1]*(N+1)
P=[-1]*(N+1)
D[c]=0
while Q:
x=Q.pop()
TOP_SORT.append(x)
for to in E[x]:
if D[to]==-1:
D[to]=D[x]+1
Q.append(to)
P[to]=x
DP=[[[0,0,0] for i in range(3)] for i in range(N+1)]
# DP[x][p][m]で, plusのものが0個, 1個, 2個以上, minusのものが0個, 1個, 2個以上
for x in TOP_SORT[::-1]:
if D[x]==MAX//2:
DP[x][1][1]=1
elif len(E[x])==1:
DP[x][0][0]=1
else:
for to in E[x]:
if to==P[x]:
continue
X=[[0,0,0] for i in range(3)]
for i in range(3):
for j in range(3):
X[0][0]+=DP[to][i][j]
X[i][0]+=DP[to][i][j]
X[0][j]+=DP[to][i][j]
if DP[x]==[[0,0,0] for i in range(3)]:
DP[x]=X
else:
Y=[[0,0,0] for i in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
Y[min(2,i+k)][min(2,j+l)]=(Y[min(2,i+k)][min(2,j+l)]+X[i][j]*DP[x][k][l])%mod
DP[x]=Y
#print(DP)
print(DP[c][1][1]*pow(2,mod-2,mod)%mod)
else:
for i in range(N+1):
if D[i]==MAX//2 and D2[i]==MAX//2+1:
c1=i
elif D[i]==MAX//2+1 and D2[i]==MAX//2:
c2=i
TOP_SORT=[]
Q=[c1,c2]
D=[-1]*(N+1)
P=[-1]*(N+1)
D[c1]=0
D[c2]=0
P[c1]=c2
P[c2]=c1
while Q:
x=Q.pop()
TOP_SORT.append(x)
for to in E[x]:
if D[to]==-1:
D[to]=D[x]+1
Q.append(to)
P[to]=x
DP=[[[0,0,0] for i in range(3)] for i in range(N+1)]
# DP[x][p][m]で, plusのものが0個, 1個, 2個以上, minusのものが0個, 1個, 2個以上
for x in TOP_SORT[::-1]:
if D[x]==MAX//2:
DP[x][1][1]=1
elif len(E[x])==1:
DP[x][0][0]=1
else:
for to in E[x]:
if to==P[x]:
continue
X=[[0,0,0] for i in range(3)]
for i in range(3):
for j in range(3):
X[0][0]+=DP[to][i][j]
X[i][0]+=DP[to][i][j]
X[0][j]+=DP[to][i][j]
if DP[x]==[[0,0,0] for i in range(3)]:
DP[x]=X
else:
Y=[[0,0,0] for i in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
Y[min(2,i+k)][min(2,j+l)]=(Y[min(2,i+k)][min(2,j+l)]+X[i][j]*DP[x][k][l])%mod
DP[x]=Y
#print(DP[c1])
#print(DP[c2])
print(sum(DP[c1][1])*sum(DP[c2][1])%mod)
``` |
p02887 AtCoder Beginner Contest 143 - Slimes | There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.
Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.
Ultimately, how many slimes will be there?
Constraints
* 1 \leq N \leq 10^5
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the final number of slimes.
Examples
Input
10
aabbbbaaca
Output
5
Input
5
aaaaa
Output
1
Input
20
xxzaffeeeeddfkkkkllq
Output
10 | ```python
n=int(input())
cnt=0
s=input()
for i in range(1,n):
if s[i]!=s[i-1]:
cnt+=1
print(cnt+1)
``` |
p03022 AtCoder Grand Contest 034 - RNG and XOR | Snuke found a random number generator. It generates an integer between 0 and 2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq 2^N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{2^N-1} A_i. The process of generating an integer is done independently each time the generator is executed.
Snuke has an integer X, which is now 0. He can perform the following operation any number of times:
* Generate an integer v with the generator and replace X with X \oplus v, where \oplus denotes the bitwise XOR.
For each integer i (0 \leq i \leq 2^N-1), find the expected number of operations until X becomes i, and print it modulo 998244353. More formally, represent the expected number of operations as an irreducible fraction P/Q. Then, there exists a unique integer R such that R \times Q \equiv P \mod 998244353,\ 0 \leq R < 998244353, so print this R.
We can prove that, for every i, the expected number of operations until X becomes i is a finite rational number, and its integer representation modulo 998244353 can be defined.
Constraints
* 1 \leq N \leq 18
* 1 \leq A_i \leq 1000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0 A_1 \cdots A_{2^N-1}
Output
Print 2^N lines. The (i+1)-th line (0 \leq i \leq 2^N-1) should contain the expected number of operations until X becomes i, modulo 998244353.
Examples
Input
2
1 1 1 1
Output
0
4
4
4
Input
2
1 2 1 2
Output
0
499122180
4
499122180
Input
4
337 780 799 10 796 875 331 223 941 67 148 483 390 565 116 355
Output
0
468683018
635850749
96019779
657074071
24757563
745107950
665159588
551278361
143136064
557841197
185790407
988018173
247117461
129098626
789682908 | ```python
# Σ(i ^ j = k) ai * bj = ckという形で式が表されるとき
# fwht(a)*fwht(b)=fwht(c)が成り立ち高速化できる
# すごく必死に考えると
# a = [p0 p1 p2 ... p2^N-1]
# b = [x0 x1 x2 ... x2^N-1]
# c = [2^N-1 -1 -1 -1 .... -1]
# とするとうまいことaとcに変数が入らない形になるのでfwht(c)/fwht(a)を計算し
# fwht(b)がわかるのでこれを逆変換すればbが求められる
# なお逆変換は b = fwht(fwht(b)) / 要素数で求められる、なぜかは知らない
# またまたなぜかは知らないがこうして求めた答えは各要素に定数が足されたものになるらしい
# 今回はx0 = 0と分かっているのbを[0 x1-x0 ... x2^N-1-x0]と補正してやればよい
N = int(input())
A = [int(i) for i in input().split()]
MOD = 998244353
NN = 1 << N
def fwht(a) :
i = 1
while i < NN :
j = 0
while j < NN :
for k in range(i) :
x, y = a[j+k], a[i+j+k]
a[j+k], a[i+j+k] = (x + y) % MOD, (x - y) % MOD
j += i << 1
i <<= 1
def inv(x) :
return pow(x, MOD - 2, MOD)
s = inv(sum(A) % MOD)
for i in range(NN) :
A[i] = (A[i] * s) % MOD
A[0] = (A[0] - 1) % MOD
fwht(A)
B = [- 1] * (NN)
B[0] = (NN-1) % MOD
fwht(B)
C = [(inv(A[i]) * B[i]) % MOD for i in range(NN)]
fwht(C)
for i in range(NN) :
C[i] = (C[i] * inv(NN)) % MOD
for i in range(NN) :
print((C[i] - C[0]) % MOD)
``` |
p03162 Educational DP Contest - Vacation | Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.
The vacation consists of N days. For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:
* A: Swim in the sea. Gain a_i points of happiness.
* B: Catch bugs in the mountains. Gain b_i points of happiness.
* C: Do homework at home. Gain c_i points of happiness.
As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.
Find the maximum possible total points of happiness that Taro gains.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq a_i, b_i, c_i \leq 10^4
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N
Output
Print the maximum possible total points of happiness that Taro gains.
Examples
Input
3
10 40 70
20 50 80
30 60 90
Output
210
Input
1
100 10 1
Output
100
Input
7
6 7 8
8 8 3
2 5 2
7 8 6
4 6 8
2 3 4
7 5 1
Output
46 | ```python
n=int(input())
a,b,c=map(int,input().split())
for _ in range(1,n):
aa,bb,cc=map(int,input().split())
a,b,c=aa+max(b,c),bb+max(a,c),cc+max(a,b)
print(max(a,b,c))
``` |
p03305 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - Saving Snuuk | Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains.
Two currencies are used in the country: yen and snuuk. Any train fare can be paid by both yen and snuuk. The fare of the i-th train is a_i yen if paid in yen, and b_i snuuk if paid in snuuk.
In a city with a money exchange office, you can change 1 yen into 1 snuuk. However, when you do a money exchange, you have to change all your yen into snuuk. That is, if Kenkoooo does a money exchange when he has X yen, he will then have X snuuk. Currently, there is a money exchange office in every city, but the office in City i will shut down in i years and can never be used in and after that year.
Kenkoooo is planning to depart City s with 10^{15} yen in his pocket and head for City t, and change his yen into snuuk in some city while traveling. It is acceptable to do the exchange in City s or City t.
Kenkoooo would like to have as much snuuk as possible when he reaches City t by making the optimal choices for the route to travel and the city to do the exchange. For each i=0,...,n-1, find the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i years. You can assume that the trip finishes within the year.
Constraints
* 2 \leq n \leq 10^5
* 1 \leq m \leq 10^5
* 1 \leq s,t \leq n
* s \neq t
* 1 \leq u_i < v_i \leq n
* 1 \leq a_i,b_i \leq 10^9
* If i\neq j, then u_i \neq u_j or v_i \neq v_j.
* Any city can be reached from any city by changing trains.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
n m s t
u_1 v_1 a_1 b_1
:
u_m v_m a_m b_m
Output
Print n lines. In the i-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i-1 years.
Examples
Input
4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1
Output
999999999999998
999999999999989
999999999999979
999999999999897
Input
8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879
Output
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994 | ```python
import math, string, itertools, fractions, collections, re, array, bisect, sys, random, time, copy, functools
from heapq import heappush, heappop, heappushpop, heapify, heapreplace
N, M, S, T = [int(_) for _ in input().split()]
UVAB = [[int(_) for _ in input().split()] for _ in range(M)]
G1 = collections.defaultdict(lambda: collections.defaultdict(int))
G2 = collections.defaultdict(lambda: collections.defaultdict(int))
for u, v, a, b in UVAB:
u -= 1
v -= 1
G1[u][v] = G1[v][u] = a
G2[u][v] = G2[v][u] = b
def dijkstra(V, G, start):
INF = float('inf')
D = [INF for _ in range(V)]
D[start] = 0
H = [(0, start)]
while H:
du, u = heappop(H)
if D[u] < du:
continue
for v, d in G[u].items():
if D[v] > du + d:
D[v] = du + d
heappush(H, (D[v], v))
return D
D1 = dijkstra(N, G1, S - 1)
D2 = dijkstra(N, G2, T - 1)
D = [10**15 - sum(_) for _ in zip(D1, D2)]
for i in range(N - 1, 0, -1):
D[i - 1] = max(D[i - 1], D[i])
print(*D, sep='\n')
``` |
p03465 AtCoder Grand Contest 020 - Median Sum | You are given N integers A_1, A_2, ..., A_N.
Consider the sums of all non-empty subsequences of A. There are 2^N - 1 such sums, an odd number.
Let the list of these sums in non-decreasing order be S_1, S_2, ..., S_{2^N - 1}.
Find the median of this list, S_{2^{N-1}}.
Constraints
* 1 \leq N \leq 2000
* 1 \leq A_i \leq 2000
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the median of the sorted list of the sums of all non-empty subsequences of A.
Examples
Input
3
1 2 1
Output
2
Input
1
58
Output
58 | ```python
n = int(input())
a = list(map(int, input().split()))
d = (sum(a)+1)//2
c = 1
for x in a:
c |= c << x
c >>= d
for i in range(d+5):
if c & (1 << i):
print(d+i)
break
``` |
p03625 AtCoder Beginner Contest 071 - Make a Rectangle | We have N sticks with negligible thickness. The length of the i-th stick is A_i.
Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle.
Constraints
* 4 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* A_i is an integer.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the maximum possible area of the rectangle. If no rectangle can be formed, print 0.
Examples
Input
6
3 1 2 4 2 1
Output
2
Input
4
1 2 3 4
Output
0
Input
10
3 3 3 3 4 4 4 5 5 5
Output
20 | ```python
N = int(input())
A = sorted([int(_) for _ in input().split()], reverse=True)
e = []
pre = 0
for i in range(N):
if pre == A[i]:
e.append(A[i])
if len(e) >= 2: break
pre = 0
else:
pre = A[i]
if len(e) < 2: print(0)
else: print(e[0] * e[1])
``` |
p03785 AtCoder Grand Contest 011 - Airport Bus | Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
Output
3 | ```python
N,C,K=map(int,input().split())
T=[int(input()) for i in range(N)]
T.sort()
S=[[T[0]]]
t=T[0]
k=0
for i in range(1,N):
if T[i]<=t+K and len(S[k])<C:
S[k].append(T[i])
else:
k+=1
S.append([T[i]])
t=T[i]
print(len(S))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.