index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
2,200 | 9 | The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).
The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.
Input
The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.
Output
In the single line print the number that is written without leading zeroes in the binary notation β the answer to the problem.
Examples
Input
101
Output
11
Input
110010
Output
11010
Note
In the first sample the best strategy is to delete the second digit. That results in number 112 = 310.
In the second sample the best strategy is to delete the third or fourth digits β that results in number 110102 = 2610. | 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():
s = [c for c in S()]
r = []
if '0' in s:
i = s.index('0')
r = s[:i] + s[i+1:]
else:
r = s[1:]
return ''.join(r)
print(main())
| {
"input": [
"101\n",
"110010\n"
],
"output": [
"11\n",
"11010\n"
]
} |
2,201 | 9 | The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.
A Bitlandish string is a string made only of characters "0" and "1".
BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.
The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.
So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.
You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.
Input
The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths.
It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.
Output
Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.
Examples
Input
11
10
Output
YES
Input
1
01
Output
NO
Input
000
101
Output
NO | def xor(x,y):
return int(x != y)
a = input()
b = input()
print('YES') if (not xor('1' in a, '1' in b)) and len(a) == len(b) else print('NO')
| {
"input": [
"1\n01\n",
"11\n10\n",
"000\n101\n"
],
"output": [
"NO\n",
"YES\n",
"NO\n"
]
} |
2,202 | 8 | A continued fraction of height n is a fraction of form <image>. You are given two rational numbers, one is represented as <image> and the other one is represented as a finite fraction of height n. Check if they are equal.
Input
The first line contains two space-separated integers p, q (1 β€ q β€ p β€ 1018) β the numerator and the denominator of the first fraction.
The second line contains integer n (1 β€ n β€ 90) β the height of the second fraction. The third line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 1018) β the continued fraction.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print "YES" if these fractions are equal and "NO" otherwise.
Examples
Input
9 4
2
2 4
Output
YES
Input
9 4
3
2 3 1
Output
YES
Input
9 4
3
1 2 4
Output
NO
Note
In the first sample <image>.
In the second sample <image>.
In the third sample <image>. | def solve (p, q, a, st, n):
if st == n-1:
return p == q*a[st]
return solve(q, p-a[st]*q, a, st+1, n);
p, q = map(int, input().split())
n = int(input())
a = list(map(int, input().split()))
if solve(p, q, a, 0, n):
print("YES")
else:
print("NO") | {
"input": [
"9 4\n3\n1 2 4\n",
"9 4\n3\n2 3 1\n",
"9 4\n2\n2 4\n"
],
"output": [
"NO",
"YES",
"YES"
]
} |
2,203 | 7 | Valera has got n domino pieces in a row. Each piece consists of two halves β the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
Input
The first line contains integer n (1 β€ n β€ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers xi, yi (1 β€ xi, yi β€ 6). Number xi is initially written on the upper half of the i-th domino, yi is initially written on the lower half.
Output
Print a single number β the minimum required number of seconds. If Valera can't do the task in any time, print - 1.
Examples
Input
2
4 2
6 4
Output
0
Input
1
2 3
Output
-1
Input
3
1 4
2 3
4 4
Output
1
Note
In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.
In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.
In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8. | def readln(): return tuple(map(int, input().split()))
n, = readln()
a = b = c = 0
for _ in range(n):
x, y = readln()
a += x
b += y
c += (x % 2) ^ (y % 2)
if a % 2 == 0 and b % 2 == 0:
print(0)
elif (a % 2) == (b % 2) and c:
print(1)
else:
print(-1)
| {
"input": [
"3\n1 4\n2 3\n4 4\n",
"2\n4 2\n6 4\n",
"1\n2 3\n"
],
"output": [
"1\n",
"0\n",
"-1\n"
]
} |
2,204 | 8 | Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).
Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi β₯ aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.
The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.
Input
The first line contains three space-separated integers: n, m and s (1 β€ n, m β€ 105, 0 β€ s β€ 109) β the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students.
The next line contains m space-separated integers a1, a2, ..., am (1 β€ ai β€ 109) β the bugs' complexities.
The next line contains n space-separated integers b1, b2, ..., bn (1 β€ bi β€ 109) β the levels of the students' abilities.
The next line contains n space-separated integers c1, c2, ..., cn (0 β€ ci β€ 109) β the numbers of the passes the students want to get for their help.
Output
If the university can't correct all bugs print "NO".
Otherwise, on the first line print "YES", and on the next line print m space-separated integers: the i-th of these numbers should equal the number of the student who corrects the i-th bug in the optimal answer. The bugs should be corrected as quickly as possible (you must spend the minimum number of days), and the total given passes mustn't exceed s. If there are multiple optimal answers, you can output any of them.
Examples
Input
3 4 9
1 3 1 2
2 1 3
4 3 6
Output
YES
2 3 2 3
Input
3 4 10
2 3 1 2
2 1 3
4 3 6
Output
YES
1 3 1 3
Input
3 4 9
2 3 1 2
2 1 3
4 3 6
Output
YES
3 3 2 3
Input
3 4 5
1 3 1 2
2 1 3
5 3 6
Output
NO
Note
Consider the first sample.
The third student (with level 3) must fix the 2nd and 4th bugs (complexities 3 and 2 correspondingly) and the second student (with level 1) must fix the 1st and 3rd bugs (their complexity also equals 1). Fixing each bug takes one day for each student, so it takes 2 days to fix all bugs (the students can work in parallel).
The second student wants 3 passes for his assistance, the third student wants 6 passes. It meets the university's capabilities as it is ready to give at most 9 passes. | # from sys import stdin
import heapq
def f(x):
budzet=0
ost_wrzucony=-1
kolejka=[]
for i in range(0,il_bugow,x):
bug=bugi[i][0]
for j in range(ost_wrzucony+1,il_stud):
if studenci[j][1]>=bug:
heapq.heappush(kolejka,studenci[j])
ost_wrzucony=j
else:
break
if len(kolejka)<=0:
return False
st=heapq.heappop(kolejka)
budzet+=st[0]
if budzet>il_kasy:
return False
return True
def fw(x):
kolejka=[]
budzet=0
ost_wrzucony=-1
kolejnosc=[-1 for x in range(il_bugow)]
# print("x:",x)
for i in range(0,il_bugow,x):
bug=bugi[i][0]
for j in range(ost_wrzucony+1,il_stud):
if studenci[j][1]>=bug:
heapq.heappush(kolejka,studenci[j])
ost_wrzucony=j
else:
break
if len(kolejka)<=0:
return False,[]
st=heapq.heappop(kolejka)
budzet+=st[0]
for c in range(i,min(i+x,il_bugow)):
# print(f"c {c}, bugi[c][1]={bugi[c][1]}, st[1]={st[1]}, budzet={budzet} ")
kolejnosc[bugi[c][1]]=st[2]
if budzet>il_kasy:
return False, []
# print("x:",x)
return True, kolejnosc
def bs(start,koniec,zmi):
while start<koniec:
srodek=(start+koniec)//2
# print(f" bin_serach{start},{koniec},{srodek}")
if f(srodek):
koniec=srodek
else:
start=srodek+1
# print(f" bin_serach_koniec {start},{koniec},{srodek}")
return fw(koniec)
# return zmi,[]
zmi=0
il_stud, il_bugow, il_kasy=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
bugi=[]
for i in range(il_bugow):
bugi.append((b[i],i))
u=[int(x) for x in input().split()]
k=[int(x) for x in input().split()]
studenci=list(zip(k,u,range(1,il_stud+1)))
# print(studenci)
# studenci=[]
# for i in range(il_stud):
# studenci.append((k[i],u[i],i+1))
# print(studenci)
studenci.sort(reverse=True, key= lambda a: a[1])
bugi.sort(reverse= True)
# print(studenci, bugi)
zmi,kol=bs(1,il_bugow+1,zmi)
if zmi:
print('YES')
print(*kol)
else:
print('NO') | {
"input": [
"3 4 10\n2 3 1 2\n2 1 3\n4 3 6\n",
"3 4 9\n2 3 1 2\n2 1 3\n4 3 6\n",
"3 4 5\n1 3 1 2\n2 1 3\n5 3 6\n",
"3 4 9\n1 3 1 2\n2 1 3\n4 3 6\n"
],
"output": [
"YES\n1 3 1 3\n",
"YES\n3 3 2 3 \n",
"NO\n",
"YES\n2 3 2 3 \n"
]
} |
2,205 | 11 | The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1 | import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
| {
"input": [
"3 2\n1 2\n1 1\n",
"3 3\n1 3\n2 3\n1 3\n",
"2 1\n2 1\n"
],
"output": [
"2 1 3 ",
"-1\n",
"2 1 "
]
} |
2,206 | 9 | Bizon the Champion isn't just attentive, he also is very hardworking.
Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.
Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.
Input
The first line contains integer n (1 β€ n β€ 5000) β the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the minimum number of strokes needed to paint the whole fence.
Examples
Input
5
2 2 1 2 1
Output
3
Input
2
2 2
Output
2
Input
1
5
Output
1
Note
In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.
In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.
In the third sample there is only one plank that can be painted using a single vertical stroke. | import sys
ar=[]
def solve(l, r, val):
if(r<l): return 0
indx=l+ar[l:r+1].index(min(ar[l:r+1]))
tot=r-l+1
cur=ar[indx]-val+solve(l, indx-1, ar[indx])+solve(indx+1, r, ar[indx])
return min(tot, cur)
sys.setrecursionlimit(10000)
n=int(input())
ar=list(map(int, input().split()))
print(solve(0, n-1, 0)) | {
"input": [
"2\n2 2\n",
"1\n5\n",
"5\n2 2 1 2 1\n"
],
"output": [
"2\n",
"1\n",
"3\n"
]
} |
2,207 | 10 | Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Input
The first line contains three integers L, b ΠΈ f (10 β€ L β€ 100000, 1 β€ b, f β€ 100). The second line contains an integer n (1 β€ n β€ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.
Output
For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.
Examples
Input
30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
23
Input
30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4
Output
0
6
11
17
6
Input
10 1 1
1
1 12
Output
-1 | class Car:
def __init__(self, id, size, location):
self.id = id
self.size = size
self.location = location
print(location)
cars = []
lot_size, back_gap, front_gap = map(int, input().split())
q = int(input())
for id in range(1, q + 1):
request, value = map(int, input().split())
if request == 1:
size = value
# Only car in the lot.
if len(cars) == 0:
if size <= lot_size:
cars.append(Car(id, size, 0))
else:
print(-1)
continue
# Park before first car.
if size + front_gap <= cars[0].location:
cars.insert(0, Car(id, size, 0))
continue
# Park between two cars.
found = False
for pos in range(1, len(cars)):
a, b = cars[pos - 1], cars[pos]
x = a.location + a.size + back_gap
if x + size + front_gap <= b.location:
cars.insert(pos, Car(id, size, x))
found = True
break
if found:
continue
# Park after last car.
a = cars[len(cars) - 1]
x = a.location + a.size + back_gap
if x + size <= lot_size:
cars.append(Car(id, size, x))
continue
# Fail.
print(-1)
else:
id = value
for pos, car in enumerate(cars):
if car.id == id:
del cars[pos]
break
| {
"input": [
"10 1 1\n1\n1 12\n",
"30 1 2\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n",
"30 1 1\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4\n"
],
"output": [
"-1\n",
"0\n6\n11\n17\n23\n",
"0\n6\n11\n17\n6\n"
]
} |
2,208 | 11 | Vanya decided to walk in the field of size n Γ n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell <image>. The following condition is satisfied for the vector: <image>, where <image> is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited.
Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
Input
The first line contains integers n, m, dx, dy(1 β€ n β€ 106, 1 β€ m β€ 105, 1 β€ dx, dy β€ n) β the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 β€ xi, yi β€ n - 1) β the coordinates of apples. One cell may contain multiple apple trees.
Output
Print two space-separated numbers β the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
Examples
Input
5 5 2 3
0 0
1 2
1 3
2 4
3 1
Output
1 3
Input
2 3 1 1
0 0
0 1
1 1
Output
0 0
Note
In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)
In the second sample: (0, 0) - (1, 1) - (0, 0) | def gcd(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = gcd(b, a % b)
return d, y, x - y * (a // b)
n,m,dx,dy = map(int,input().split())
c = [0]*1000000
d, x, y = gcd(-n, dx)
mu = dy * y % n
for i in range(m):
a, b = map(int,input().split())
c[(b-a*mu)%n]+=1
print(0, c.index(max(c))) | {
"input": [
"5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1\n",
"2 3 1 1\n0 0\n0 1\n1 1\n"
],
"output": [
"0 4\n",
"0 0\n"
]
} |
2,209 | 10 | The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.
Your task is β for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
Input
The first line of the input contains a single integer n (2 β€ n β€ 2Β·105) β the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 β€ pi β€ i - 1) β the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.
Output
Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.
Examples
Input
3
1 1
Output
4 3 3
Input
5
1 2 3 4
Output
5 8 9 8 5 |
class Graph:
def __init__(self, n_vertices, edges, directed=True, weighted=False):
self.n_vertices = n_vertices
self.edges = edges
self.directed = directed
self.weighted = weighted
@property
def adj(self):
try:
return self._adj
except AttributeError:
adj = [[] for _ in range(self.n_vertices)]
def d_w(e):
adj[e[0]].append((e[1],e[2]))
def ud_w(e):
adj[e[0]].append((e[1],e[2]))
adj[e[1]].append((e[0],e[2]))
def d_uw(e):
adj[e[0]].append(e[1])
def ud_uw(e):
adj[e[0]].append(e[1])
adj[e[1]].append(e[0])
helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2]
for e in self.edges:
helper(e)
self._adj = adj
return adj
class RootedTree(Graph):
def __init__(self, n_vertices, edges, root_vertex):
self.root = root_vertex
super().__init__(n_vertices, edges, False, False)
@property
def parent(self):
try:
return self._parent
except AttributeError:
adj = self.adj
parent = [None]*self.n_vertices
parent[self.root] = -1
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
for u in adj[v]:
if parent[u] is None:
parent[u] = v
stack.append(u)
self._parent = parent
return parent
@property
def children(self):
try:
return self._children
except AttributeError:
children = [None]*self.n_vertices
for v,(l,p) in enumerate(zip(self.adj,self.parent)):
children[v] = [u for u in l if u != p]
self._children = children
return children
@property
def dfs_order(self):
try:
return self._dfs_order
except AttributeError:
order = [None]*self.n_vertices
children = self.children
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
order[i] = v
for u in children[v]:
stack.append(u)
self._dfs_order = order
return order
from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
N = rooted_tree.n_vertices
parent = rooted_tree.parent
children = rooted_tree.children
order = rooted_tree.dfs_order
# from leaf to parent
dp_down = [None]*N
for v in reversed(order[1:]):
dp_down[v] = finalize(reduce(merge,
(dp_down[c] for c in children[v]),
identity))
# from parent to leaf
dp_up = [None]*N
dp_up[0] = identity
for v in order:
if len(children[v]) == 0:
continue
temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
left = accumulate(temp[:-2],merge)
right = tuple(accumulate(reversed(temp[2:]),merge))
for u,l,r in zip(children[v],left,reversed(right)):
dp_up[u] = finalize(merge(l,r))
res = [None]*N
for v,l in enumerate(children):
res[v] = reduce(merge,
(dp_down[u] for u in children[v]),
identity)
res[v] = finalize(merge(res[v], dp_up[v]))
return res
def solve(T):
MOD = 10**9 + 7
def merge(x,y):
return (x*y)%MOD
def finalize(x):
return x+1
return [v-1 for v in rerooting(T,merge,1,finalize)]
if __name__ == '__main__':
N = int(input())
edges = [(i+1,p-1) for i,p in enumerate(map(int,input().split()))]
T = RootedTree(N, edges, 0)
print(*solve(T))
| {
"input": [
"3\n1 1\n",
"5\n1 2 3 4\n"
],
"output": [
"4 3 3 ",
"5 8 9 8 5 "
]
} |
2,210 | 7 | The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.
The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.
At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.
Determine who will win the elections.
Input
The first line of the input contains two integers n, m (1 β€ n, m β€ 100) β the number of candidates and of cities, respectively.
Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 β€ j β€ n, 1 β€ i β€ m, 0 β€ aij β€ 109) denotes the number of votes for candidate j in city i.
It is guaranteed that the total number of people in all the cities does not exceed 109.
Output
Print a single number β the index of the candidate who won the elections. The candidates are indexed starting from one.
Examples
Input
3 3
1 2 3
2 3 1
1 2 1
Output
2
Input
3 4
10 10 3
5 1 6
2 2 2
1 5 7
Output
1
Note
Note to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.
Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index. | n, m = map(int, input().split())
def f(a):
m = max(a)
return min(i for i in range(n) if a[i] == m) + 1
b = [0] * n
for i in range(m):
a = list(map(int, input().split()))
b[f(a) - 1] += 1
print(f(b))
| {
"input": [
"3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7\n",
"3 3\n1 2 3\n2 3 1\n1 2 1\n"
],
"output": [
"1\n",
"2\n"
]
} |
2,211 | 10 | A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.
We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).
Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed <image> meters per second.
Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after <image> seconds the new position of the dirigible will be <image>.
Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.
It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.
Input
The first line of the input contains four integers x1, y1, x2, y2 (|x1|, |y1|, |x2|, |y2| β€ 10 000) β the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively.
The second line contains two integers <image> and t (0 < v, t β€ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively.
Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that <image> and <image>.
Output
Print a single real value β the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
0 0 5 5
3 2
-1 -1
-1 0
Output
3.729935587093555327
Input
0 0 0 1000
100 1000
-50 0
50 0
Output
11.547005383792516398 | import math
x1, y1, x2, y2 = map(float, input().split()[:4])
v_max, t = map(float, input().split()[:2])
vx, vy = map(float, input().split()[:2])
wx, wy = map(float, input().split()[:2])
def f(x1, y1, x2, y2, v_max, vx, vy):
low = 0
high = math.hypot(x2 - x1, y2 - y1) / (v_max - math.hypot(vx, vy))
while (high - low > 10**-8):
middle = (low + high) / 2.0
x = x2 + vx * middle
y = y2 + vy * middle
t = math.hypot(x - x1, y - y1) / v_max
if t > middle:
low = middle
else:
high = middle
return (low + high) / 2.0
time = f(x1, y1, x2, y2, v_max, -vx, -vy)
if time > t:
time = f(x1, y1, x2 - vx * t + wx * t, y2 - vy * t + wy * t, v_max, -wx, -wy)
print(time)
| {
"input": [
"0 0 5 5\n3 2\n-1 -1\n-1 0\n",
"0 0 0 1000\n100 1000\n-50 0\n50 0\n"
],
"output": [
"3.7299356163\n",
"11.5470054150\n"
]
} |
2,212 | 8 | Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai β the current skill level. All skills have the same maximum level A.
Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values:
* The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf.
* The minimum skill level among all skills (min ai), multiplied by coefficient cm.
Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.
Input
The first line of the input contains five space-separated integers n, A, cf, cm and m (1 β€ n β€ 100 000, 1 β€ A β€ 109, 0 β€ cf, cm β€ 1000, 0 β€ m β€ 1015).
The second line contains exactly n integers ai (0 β€ ai β€ A), separated by spaces, β the current levels of skills.
Output
On the first line print the maximum value of the Force that the character can achieve using no more than m currency units.
On the second line print n integers a'i (ai β€ a'i β€ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.
Examples
Input
3 5 10 1 5
1 3 1
Output
12
2 5 2
Input
3 5 10 1 339
1 3 1
Output
35
5 5 5
Note
In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.
In the second test one should increase all skills to maximum. | def main():
from bisect import bisect
n, A, cf, cm, m = map(int, input().split())
skills = list(map(int, input().split()))
xlat = sorted(range(n), key=skills.__getitem__)
sorted_skills = [skills[_] for _ in xlat]
bottom_lift, a, c = [], 0, 0
for i, b in enumerate(sorted_skills):
c += i * (b - a)
bottom_lift.append(c)
a = b
root_lift, a = [0], 0
for b in reversed(sorted_skills):
a += A - b
root_lift.append(a)
max_level = -1
for A_width, a in enumerate(root_lift):
if m < a:
break
money_left = m - a
floor_width = bisect(bottom_lift, money_left)
if floor_width > n - A_width:
floor_width = n - A_width
money_left -= bottom_lift[floor_width - 1]
if floor_width > 0:
floor = sorted_skills[floor_width - 1] + money_left // floor_width
if floor > A:
floor = A
else:
floor = A
level = cf * A_width + cm * floor
if max_level < level:
max_level, save = level, (A_width, floor, floor_width)
A_width, floor, floor_width = save
for id in xlat[:floor_width]:
skills[id] = floor
for id in xlat[n - A_width:]:
skills[id] = A
print(max_level)
print(' '.join(map(str, skills)))
if __name__ == '__main__':
main()
| {
"input": [
"3 5 10 1 339\n1 3 1\n",
"3 5 10 1 5\n1 3 1\n"
],
"output": [
" 35\n 5 5 5 ",
" 12\n 2 5 2 "
]
} |
2,213 | 8 | Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem?
Input
The only line of input contains an integer m (1 β€ m β€ 100 000) β the required number of trailing zeroes in factorial.
Output
First print k β the number of values of n such that the factorial of n ends with m zeroes. Then print these k integers in increasing order.
Examples
Input
1
Output
5
5 6 7 8 9
Input
5
Output
0
Note
The factorial of n is equal to the product of all integers from 1 to n inclusive, that is n! = 1Β·2Β·3Β·...Β·n.
In the first sample, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880. | import sys
def cnt(x):
ret = 0
while x > 0:
ret += x // 5
x //= 5
return ret
want = int(input())
a = []
for x in range(1, 5 * 10**5):
if cnt(x) == want:
a.append(x)
print(len(a))
for x in a:
print(x, end=" ") | {
"input": [
"1\n",
"5\n"
],
"output": [
"5\n5 6 7 8 9 ",
"0\n"
]
} |
2,214 | 7 | A group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is ri.
The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all n friends. So the friends are faced with the problem: how to make all their ratings equal.
One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than n) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so ri = 0 doesn't change after losing.
The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).
The friends want to make their ratings equal but as high as possible.
Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.
Input
The first line contains a single integer n (2 β€ n β€ 100) β the number of friends.
The second line contains n non-negative integers r1, r2, ..., rn (0 β€ ri β€ 100), where ri is the initial rating of the i-th friend.
Output
In the first line, print a single integer R β the final rating of each of the friends.
In the second line, print integer t β the number of matches the friends have to play. Each of the following t lines should contain n characters '0' or '1', where the j-th character of the i-th line is equal to:
* '0', if friend j should not play in match i,
* '1', if friend j should play in match i.
Each line should contain between two and five characters '1', inclusive.
The value t should not exceed 104, it is guaranteed that such solution exists.
Remember that you shouldn't minimize the value t, but you should maximize R. If there are multiple solutions, print any of them.
Examples
Input
5
4 5 1 7 4
Output
1
8
01010
00011
01010
10010
00011
11000
00011
11000
Input
2
1 2
Output
0
2
11
11
Input
3
1 1 1
Output
1
0 | import collections
def temp(list1):
list2 = list(list1)
list3=[]
cnt = collections.Counter()
for i in range(len(list1)):
cnt[list1[i]]+=1
tep = max(list1)
if cnt[tep] != 1:
if cnt[tep] <= 5:
for i in range(5):
if tep in list2:
list3.append(list2.index(tep))
list2[list2.index(tep)] = -1
else:
break
else:
for i in range(4):
if tep in list2:
list3.append(list2.index(tep))
list2[list2.index(tep)] = -1
else:
break
else:
list3.append(list1.index(tep))
list2.remove(tep)
list3.append(list1.index(max(list2)))
return list3
n = int(input())
intgrade = list(map(int, input().split()))
bitlists=[]
if len(set(intgrade)) == 1:
print(intgrade[0])
print(0)
else:
while len(set(intgrade)) != 1:
listA = temp(intgrade)
bitlist=''
for i in range(len(listA)):
if intgrade[listA[i]] > 0:
intgrade[listA[i]]-=1
for i in range(n):
if i in listA:
bitlist+="1"
else:
bitlist+="0"
bitlists.append(bitlist)
print(intgrade[0])
print(len(bitlists))
for i in range(len(bitlists)):
print(bitlists[i])
| {
"input": [
"5\n4 5 1 7 4\n",
"3\n1 1 1\n",
"2\n1 2\n"
],
"output": [
"1\n8\n01010\n00011\n01010\n10010\n00011\n11000\n00011\n11000\n",
"1\n0\n",
"0\n2\n11\n11\n"
]
} |
2,215 | 11 | In order to fly to the Moon Mister B just needs to solve the following problem.
There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.
We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?
Input
The only line contains single integer n (3 β€ n β€ 300).
Output
If there is no answer, print -1.
Otherwise, in the first line print k (1 β€ k β€ n2) β the number of cycles in your solution.
In each of the next k lines print description of one cycle in the following format: first print integer m (3 β€ m β€ 4) β the length of the cycle, then print m integers v1, v2, ..., vm (1 β€ vi β€ n) β the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.
Examples
Input
3
Output
2
3 1 2 3
3 1 2 3
Input
5
Output
6
3 5 4 2
3 3 1 5
4 4 5 2 3
4 4 3 2 1
3 4 2 1
3 3 1 5 | import sys
def solve(n):
if n == 3:
return [(1, 2, 3)]*2
if n == 4:
return [(1, 2, 3, 4), (1, 2, 4, 3), (1, 4, 2, 3)]
else:
return [*solve(n-2), (n, n - 1, 1), (n, n - 1, n - 2), *[(n, i, n - 1, i + 1) for i in range(1, n - 2)]]
answer = solve(int(sys.stdin.readline()))
sys.stdout.write(str(len(answer)) + "\n")
for ans in answer:
sys.stdout.write("{} {}\n".format(len(ans), " ".join(map(str, ans))))
| {
"input": [
"5\n",
"3\n"
],
"output": [
"6\n3 1 2 3\n3 1 2 3\n3 1 4 5\n3 1 4 5\n4 4 2 5 3\n4 4 2 5 3\n",
"2\n3 1 2 3\n3 1 2 3\n"
]
} |
2,216 | 9 | Polycarp is a great fan of television.
He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.
Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.
Polycarp wants to check out all n shows. Are two TVs enough to do so?
Input
The first line contains one integer n (1 β€ n β€ 2Β·105) β the number of shows.
Each of the next n lines contains two integers li and ri (0 β€ li < ri β€ 109) β starting and ending time of i-th show.
Output
If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).
Examples
Input
3
1 2
2 3
4 5
Output
YES
Input
4
1 2
2 3
2 3
1 2
Output
NO | def main(d,t):
for i in d:
t += i[1]
if t < -2:
return("NO")
return ("YES")
d = []
n = int(input())
for i in range(n):
a,b=input().split()
a=int(a)
b=int(b)
d.append([a,-1])
d.append([b,1])
d.sort()
t = 0
ans=main(d,t)
print (ans) | {
"input": [
"4\n1 2\n2 3\n2 3\n1 2\n",
"3\n1 2\n2 3\n4 5\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
2,217 | 8 | Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced.
Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.
Your task is to help Petya find out if he can win the game or at least draw a tie.
Input
The first line of input contain two integers n and m β the number of vertices and the number of edges in the graph (2 β€ n β€ 105, 0 β€ m β€ 2Β·105).
The next n lines contain the information about edges of the graph. i-th line (1 β€ i β€ n) contains nonnegative integer ci β number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j β indices of these vertices (1 β€ ai, j β€ n, ai, j β i).
It is guaranteed that the total sum of ci equals to m.
The next line contains index of vertex s β the initial position of the chip (1 β€ s β€ n).
Output
If Petya can win print Β«WinΒ» in the first line. In the next line print numbers v1, v2, ..., vk (1 β€ k β€ 106) β the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game.
If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ».
Examples
Input
5 6
2 2 3
2 4 5
1 4
1 5
0
1
Output
Win
1 2 4 5
Input
3 2
1 3
1 1
0
2
Output
Lose
Input
2 2
1 2
1 1
1
Output
Draw
Note
In the first example the graph is the following:
<image>
Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins.
In the second example the graph is the following:
<image>
Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses.
In the third example the graph is the following:
<image>
Petya can't win, but he can move along the cycle, so the players will draw a tie. | # 936B
import collections
def do():
nodes, edges = map(int, input().split(" "))
outd = [0] * (nodes + 1)
g = collections.defaultdict(list)
for i in range(1, nodes + 1):
tmp = [int(c) for c in input().split(" ")]
outd[i] = tmp[0]
g[i] = tmp[1:]
dp = [[0] * 2 for _ in range(nodes + 1)]
pre = [[0] * 2 for _ in range(nodes + 1)]
st = int(input())
mask = [0] * (nodes + 1)
def dfs(entry):
has_loop = False
stack = [[entry, 0, True]]
dp[entry][0] = 1 # d[st][0], 0 means reach here by even(0) steps
while stack:
cur, step, first = stack.pop()
if first:
mask[cur] = 1
stack.append([cur, -1, False])
for nei in g[cur]:
if mask[nei]:
has_loop = True
if dp[nei][step ^ 1]:
continue
pre[nei][step ^ 1] = cur
dp[nei][step ^ 1] = 1
stack.append([nei, step ^ 1, first])
else:
mask[cur] = 0
return has_loop
has_loop = dfs(st)
for i in range(1, nodes + 1):
if outd[i] == 0: # out degree
if dp[i][1]: # must reach here by odd steps
print("Win")
res = []
cur = i
step = 1
while cur != st or step:
res.append(cur)
cur = pre[cur][step]
step ^= 1
res.append(st)
print(" ".join(str(c) for c in res[::-1]))
return
res = "Draw" if has_loop else "Lose"
print(res)
do()
| {
"input": [
"5 6\n2 2 3\n2 4 5\n1 4\n1 5\n0\n1\n",
"3 2\n1 3\n1 1\n0\n2\n",
"2 2\n1 2\n1 1\n1\n"
],
"output": [
"Win\n1 2 4 5 \n",
"Lose\n",
"Draw\n"
]
} |
2,218 | 7 | Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.
The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)
Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.
Input
The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} β they are the colors of gems with which the box should be decorated.
Output
Print the required number of different ways to decorate the box.
Examples
Input
YYYYYY
Output
1
Input
BOOOOB
Output
2
Input
ROYGBV
Output
30 | from functools import reduce
def factorial(n):
return reduce(lambda x, y: x*y, range(1,n+1))
colors = {
'R' : 0,
'O' : 0,
'Y' : 0,
'G' : 0,
'B' : 0,
'V' : 0
}
for c in list(input()):
colors[c] += 1
amount = list(reversed(sorted([(colors[key], key) for key in colors])))
amount = [x[0] for x in amount]
if amount[0] == 6 or amount[0] == 5:
print("1")
elif amount[0] == 4:
print("2")
elif amount[0] == 3:
if amount[1] == 3:
print("2")
elif amount[1] == 2:
print("3")
elif amount[1] == 1:
print("5")
elif amount[0] == 2:
if amount[1] == amount[2] == 2:
print("6")
elif amount[1] == 2:
print("8")
else:
print(factorial(6) // 48)
elif amount[0] == 1:
print(factorial(6) // 24)
| {
"input": [
"YYYYYY\n",
"ROYGBV\n",
"BOOOOB\n"
],
"output": [
"1\n",
"30\n",
"2\n"
]
} |
2,219 | 11 | You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence.
Find the number of pairs of indices (l, r) (1 β€ l β€ r β€ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m.
The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.
For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence.
Write a program to find the number of pairs of indices (l, r) (1 β€ l β€ r β€ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m.
Input
The first line contains integers n and m (1 β€ n β€ 2β
10^5, 1 β€ m β€ n) β the length of the given sequence and the required value of the median.
The second line contains a permutation p_1, p_2, ..., p_n (1 β€ p_i β€ n). Each integer between 1 and n occurs in p exactly once.
Output
Print the required number.
Examples
Input
5 4
2 4 5 3 1
Output
4
Input
5 5
1 2 3 4 5
Output
1
Input
15 8
1 15 2 14 3 13 4 8 12 5 11 6 10 7 9
Output
48
Note
In the first example, the suitable pairs of indices are: (1, 3), (2, 2), (2, 3) and (2, 4). | def ask(x):
s={}
s[0]=1
sum,cnt,res=0,0,0
for i in range(n):
if(a[i]<x):
sum-=1
cnt-=s.get(sum,0)
else:
cnt+=s.get(sum,0)
sum+=1
s[sum]=s.get(sum,0)+1
res+=cnt
return res
n,m=map(int,input().split())
a=list(map(int,input().split()))
print(ask(m)-ask(m+1))
| {
"input": [
"5 4\n2 4 5 3 1\n",
"15 8\n1 15 2 14 3 13 4 8 12 5 11 6 10 7 9\n",
"5 5\n1 2 3 4 5\n"
],
"output": [
"4",
"48",
"1"
]
} |
2,220 | 9 | You are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.
The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or 0 in case the intersection is an empty set.
For example, the intersection of segments [1;5] and [3;10] is [3;5] (length 2), the intersection of segments [1;5] and [5;7] is [5;5] (length 0) and the intersection of segments [1;5] and [6;6] is an empty set (length 0).
Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining (n - 1) segments has the maximal possible length.
Input
The first line contains a single integer n (2 β€ n β€ 3 β
10^5) β the number of segments in the sequence.
Each of the next n lines contains two integers l_i and r_i (0 β€ l_i β€ r_i β€ 10^9) β the description of the i-th segment.
Output
Print a single integer β the maximal possible length of the intersection of (n - 1) remaining segments after you remove exactly one segment from the sequence.
Examples
Input
4
1 3
2 6
0 4
3 3
Output
1
Input
5
2 6
1 3
0 4
1 20
0 4
Output
2
Input
3
4 5
1 2
9 20
Output
0
Input
2
3 10
1 5
Output
7
Note
In the first example you should remove the segment [3;3], the intersection will become [2;3] (length 1). Removing any other segment will result in the intersection [3;3] (length 0).
In the second example you should remove the segment [1;3] or segment [2;6], the intersection will become [2;4] (length 2) or [1;3] (length 2), respectively. Removing any other segment will result in the intersection [2;3] (length 1).
In the third example the intersection will become an empty set no matter the segment you remove.
In the fourth example you will get the intersection [3;10] (length 7) if you remove the segment [1;5] or the intersection [1;5] (length 4) if you remove the segment [3;10]. | def f(a):
l = 0
r = 1000000001
for x, y in a:
l = max(l, x)
r = min(r, y)
return r-l
n = int(input())
a = [tuple(map(int, input().split())) for i in range(n)]
l = sorted(a, key = lambda val: val[0] - val[1]/1000000001)
l.pop()
r = sorted(a, key = lambda val: -val[1] + val[0]/1000000001)
r.pop()
print(max(f(l), f(r), 0))
| {
"input": [
"2\n3 10\n1 5\n",
"5\n2 6\n1 3\n0 4\n1 20\n0 4\n",
"4\n1 3\n2 6\n0 4\n3 3\n",
"3\n4 5\n1 2\n9 20\n"
],
"output": [
"7\n",
"2\n",
"1\n",
"0\n"
]
} |
2,221 | 8 | The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".
The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct.
A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.
Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
Input
The first line contains a positive integer n (1 β€ n β€ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 β€ ai β€ 109), the number of answer variants to question i.
Output
Print a single number β the minimal number of clicks needed to pass the test it the worst-case scenario.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
2
1 1
Output
2
Input
2
2 2
Output
5
Input
1
10
Output
10
Note
Note to the second sample. In the worst-case scenario you will need five clicks:
* the first click selects the first variant to the first question, this answer turns out to be wrong.
* the second click selects the second variant to the first question, it proves correct and we move on to the second question;
* the third click selects the first variant to the second question, it is wrong and we go back to question 1;
* the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question;
* the fifth click selects the second variant to the second question, it proves correct, the test is finished. | def arr_inp():
return [int(x) for x in stdin.readline().split()]
from sys import *
n, a = int(input()), arr_inp()
print(sum([a[i] + (a[i] - 1) * i for i in range(n)]))
| {
"input": [
"2\n1 1\n",
"1\n10\n",
"2\n2 2\n"
],
"output": [
"2\n",
"10\n",
"5\n"
]
} |
2,222 | 9 | You are given an array a of length n that consists of zeros and ones.
You can perform the following operation multiple times. The operation consists of two steps:
1. Choose three integers 1 β€ x < y < z β€ n, that form an arithmetic progression (y - x = z - y).
2. Flip the values a_x, a_y, a_z (i.e. change 1 to 0, change 0 to 1).
Determine if it is possible to make all elements of the array equal to zero. If yes, print the operations that lead the the all-zero state. Your solution should not contain more than (β n/3 β + 12) operations. Here β q β denotes the number q rounded down. We can show that it is possible to make all elements equal to zero in no more than this number of operations whenever it is possible to do so at all.
Input
The first line contains a single integer n (3 β€ n β€ 10^5) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1) β the elements of the array.
Output
Print "YES" (without quotes) if the answer exists, otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).
If there is an answer, in the second line print an integer m (0 β€ m β€ (β n/3 β + 12)) β the number of operations in your answer.
After that in (i + 2)-th line print the i-th operations β the integers x_i, y_i, z_i. You can print them in arbitrary order.
Examples
Input
5
1 1 0 1 1
Output
YES
2
1 3 5
2 3 4
Input
3
0 1 0
Output
NO
Note
In the first sample the shown output corresponds to the following solution:
* 1 1 0 1 1 (initial state);
* 0 1 1 1 0 (the flipped positions are the first, the third and the fifth elements);
* 0 0 0 0 0 (the flipped positions are the second, the third and the fourth elements).
Other answers are also possible. In this test the number of operations should not exceed β 5/3 β + 12 = 1 + 12 = 13.
In the second sample the only available operation is to flip all the elements. This way it is only possible to obtain the arrays 0 1 0 and 1 0 1, but it is impossible to make all elements equal to zero. | def solve(a):
l = len(a)
d = sum(a[i] * 2 ** i for i in range(l))
if d == 0:
return []
usable = []
if l >= 3:
for i in range(l - 2):
usable.append(0b111 << i)
if l >= 5:
for i in range(l - 4):
usable.append(0b10101 << i)
if l >= 7:
for i in range(l - 6):
usable.append(0b1001001 << i)
ul = len(usable)
best_answer = None
for mask in range(1 << ul):
start = 0
clone = mask
cnt = 0
while clone:
if clone % 2 == 1:
start ^= usable[cnt]
clone //= 2
cnt += 1
if start == d:
answer = []
clone = mask
cnt = 0
while clone:
if clone % 2 == 1:
answer.append([])
used = usable[cnt]
cnt2 = 1
while used:
if used % 2 == 1:
answer[-1].append(cnt2)
cnt2 += 1
used //= 2
clone //= 2
cnt += 1
if best_answer is None or len(best_answer) > len(answer):
best_answer = answer
return best_answer
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
if len(a) <= 10:
sol = solve(a)
if sol is None:
print("NO")
exit(0)
print("YES")
print(len(sol))
for t in sol:
print(' '.join(map(str, t)))
exit(0)
operations = []
while len(a) > 10:
l = len(a)
last = a[-3:]
if last == [1, 1, 1]:
operations.append([l - 2, l - 1, l])
elif last == [1, 1, 0]:
operations.append([l - 3, l - 2, l - 1])
a[-4] ^= 1
elif last == [1, 0, 1]:
operations.append([l - 4, l - 2, l])
a[-5] ^= 1
elif last == [0, 1, 1]:
nxt = a[-6:-3]
if nxt == [1, 1, 1]:
operations.append([l - 8, l - 4, l])
operations.append([l - 5, l - 3, l - 1])
a[-9] ^= 1
elif nxt == [1, 1, 0]:
operations.append([l - 8, l - 4, l])
operations.append([l - 9, l - 5, l - 1])
a[-9] ^= 1
a[-10] ^= 1
elif nxt == [1, 0, 1]:
operations.append([l - 6, l - 3, l])
operations.append([l - 9, l - 5, l - 1])
a[-7] ^= 1
a[-10] ^= 1
elif nxt == [0, 1, 1]:
operations.append([l - 6, l - 3, l])
operations.append([l - 7, l - 4, l - 1])
a[-7] ^= 1
a[-8] ^= 1
elif nxt == [1, 0, 0]:
operations.append([l - 2, l - 1, l])
operations.append([l - 8, l - 5, l - 2])
a[-9] ^= 1
elif nxt == [0, 1, 0]:
operations.append([l - 2, l - 1, l])
operations.append([l - 6, l - 4, l - 2])
a[-7] ^= 1
elif nxt == [0, 0, 1]:
operations.append([l - 10, l - 5, l])
operations.append([l - 5, l - 3, l - 1])
a[-11] ^= 1
elif nxt == [0, 0, 0]:
operations.append([l - 8, l - 4, l])
operations.append([l - 7, l - 4, l - 1])
a[-9] ^= 1
a[-8] ^= 1
a.pop()
a.pop()
a.pop()
elif last == [1, 0, 0]:
operations.append([l - 4, l - 3, l - 2])
a[-5] ^= 1
a[-4] ^= 1
elif last == [0, 1, 0]:
operations.append([l - 5, l - 3, l - 1])
a[-6] ^= 1
a[-4] ^= 1
elif last == [0, 0, 1]:
operations.append([l - 6, l - 3, l])
a[-7] ^= 1
a[-4] ^= 1
a.pop()
a.pop()
a.pop()
while len(a) < 8:
a.append(0)
sol = solve(a)
print("YES")
sol = operations + sol
print(len(sol))
for t in sol:
print(' '.join(map(str, t)))
| {
"input": [
"5\n1 1 0 1 1\n",
"3\n0 1 0\n"
],
"output": [
"YES\n2\n3 4 5\n1 2 3\n",
"NO\n"
]
} |
2,223 | 8 | You are given two n Γ m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing.
For example, the matrix \begin{bmatrix} 9&10&11\\\ 11&12&14\\\ \end{bmatrix} is increasing because each individual row and column is strictly increasing. On the other hand, the matrix \begin{bmatrix} 1&1\\\ 2&3\\\ \end{bmatrix} is not increasing because the first row is not strictly increasing.
Let a position in the i-th row (from top) and j-th column (from left) in a matrix be denoted as (i, j).
In one operation, you can choose any two numbers i and j and swap the number located in (i, j) in the first matrix with the number in (i, j) in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.
You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible".
Input
The first line contains two integers n and m (1 β€ n,m β€ 50) β the dimensions of each matrix.
Each of the next n lines contains m integers a_{i1}, a_{i2}, β¦, a_{im} (1 β€ a_{ij} β€ 10^9) β the number located in position (i, j) in the first matrix.
Each of the next n lines contains m integers b_{i1}, b_{i2}, β¦, b_{im} (1 β€ b_{ij} β€ 10^9) β the number located in position (i, j) in the second matrix.
Output
Print a string "Impossible" or "Possible".
Examples
Input
2 2
2 10
11 5
9 4
3 12
Output
Possible
Input
2 3
2 4 5
4 5 6
3 6 7
8 10 11
Output
Possible
Input
3 2
1 3
2 4
5 10
3 1
3 6
4 8
Output
Impossible
Note
The first example, we can do an operation on the top left and bottom right cells of the matrices. The resulting matrices will be \begin{bmatrix} 9&10\\\ 11&12\\\ \end{bmatrix} and \begin{bmatrix} 2&4\\\ 3&5\\\ \end{bmatrix}.
In the second example, we don't need to do any operations.
In the third example, no matter what we swap, we can't fix the first row to be strictly increasing in both matrices. | i=lambda:[*map(int,input().split())]
n,m=i()
a,b=[[i()for _ in range(n)]for _ in[0,1]]
for x in range(n):
for y in range(m):
if a[x][y] > b[x][y]:a[x][y], b[x][y] = b[x][y], a[x][y]
def g(c):
for x in range(n-1):
for y in range(m):
if c[x][y] >= c[x+1][y]: return 1
for x in range(n):
for y in range(m-1):
if c[x][y] >= c[x][y+1]: return 1
return 0
print(('Imp'if(g(a)|g(b))else'P')+'ossible') | {
"input": [
"2 2\n2 10\n11 5\n9 4\n3 12\n",
"3 2\n1 3\n2 4\n5 10\n3 1\n3 6\n4 8\n",
"2 3\n2 4 5\n4 5 6\n3 6 7\n8 10 11\n"
],
"output": [
"Possible\n",
"Impossible",
"Possible\n"
]
} |
2,224 | 7 | Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.
Help Polycarp find the nearest larger or equal interesting number for the given number a. That is, find the interesting number n such that n β₯ a and n is minimal.
Input
The only line in the input contains an integer a (1 β€ a β€ 1000).
Output
Print the nearest greater or equal interesting number for the given number a. In other words, print the interesting number n such that n β₯ a and n is minimal.
Examples
Input
432
Output
435
Input
99
Output
103
Input
237
Output
237
Input
42
Output
44 | def gh(a):
if sum(map(int,str(a)))%4:return gh(a+1)
else:return a
print(gh(int(input()))) | {
"input": [
"99\n",
"432\n",
"237\n",
"42\n"
],
"output": [
"103\n",
"435\n",
"237\n",
"44\n"
]
} |
2,225 | 8 | Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column.
Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the 1-st column. The goal of the game is to move the character to the top of the n-th column.
The character also has a bag that can hold infinitely many blocks. When the character is on the top of the i-th column, Gildong can take one of the following three actions as many times as he wants:
* if there is at least one block on the column, remove one block from the top of the i-th column and put it in the bag;
* if there is at least one block in the bag, take one block out of the bag and place it on the top of the i-th column;
* if i < n and |h_i - h_{i+1}| β€ k, move the character to the top of the i+1-st column. k is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column.
In actions of the first two types the character remains in the i-th column, and the value h_i changes.
The character initially has m blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains three integers n, m, and k (1 β€ n β€ 100, 0 β€ m β€ 10^6, 0 β€ k β€ 10^6) β the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer k described in the statement.
The second line of each test case contains n integers. The i-th integer is h_i (0 β€ h_i β€ 10^6), the initial height of the i-th column.
Output
For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
3 0 1
4 3 5
3 1 2
1 4 7
4 10 0
10 20 10 20
2 5 5
0 11
1 9 9
99
Output
YES
NO
YES
NO
YES
Note
In the first case, Gildong can take one block from the 1-st column, move to the 2-nd column, put the block on the 2-nd column, then move to the 3-rd column.
In the second case, Gildong has to put the block in his bag on the 1-st column to get to the 2-nd column. But it is impossible to get to the 3-rd column because |h_2 - h_3| = 3 > k and there is no way to decrease the gap.
In the fifth case, the character is already on the n-th column from the start so the game is won instantly. | t = int(input())
def go():
n, m, k = map(int, input().split())
h = list(map(int, input().split()))
for i in range(n - 1):
m += h[i] - max(0, h[i + 1] - k)
if m < 0:
return "NO"
return "YES"
for _ in range(t):
print(go())
| {
"input": [
"5\n3 0 1\n4 3 5\n3 1 2\n1 4 7\n4 10 0\n10 20 10 20\n2 5 5\n0 11\n1 9 9\n99\n"
],
"output": [
"YES\nNO\nYES\nNO\nYES\n"
]
} |
2,226 | 7 | Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.
The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n mod |i-j| = 0 (where x mod y is the remainder when dividing x by y).
Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?
Input
The first line of input contains a single integer n (1 β€ n β€ 10^{12}), the length of the path.
Output
Output a single integer, the maximum possible number of colors that the path can be painted in.
Examples
Input
4
Output
2
Input
5
Output
5
Note
In the first sample, two colors is the maximum number. Tiles 1 and 3 should have the same color since 4 mod |3-1| = 0. Also, tiles 2 and 4 should have the same color since 4 mod |4-2| = 0.
In the second sample, all five colors can be used.
<image> |
def mdc( a, b ):
if ( b == 0 ):
return a
return mdc(b, a % b)
n = int(input())
a = n
for i in range(2, int(n ** .5) + 1):
if ( n % i == 0 ):
a = mdc(a, i)
a = mdc(a, n // i)
print(a) | {
"input": [
"5\n",
"4\n"
],
"output": [
"5\n",
"2\n"
]
} |
2,227 | 8 | This is the easier version of the problem. In this version 1 β€ n, m β€ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 β€ k β€ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 β€ t β€ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 β€ n β€ 100) β the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The third line contains an integer m (1 β€ m β€ 100) β the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j) β the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 β€ r_j β€ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10]. | def main():
n = int(input())
a = list(enumerate(map(int, (input().split()))))
a.sort(key = lambda item: (item[1], -item[0]))
#print(a)
m = int(input())
for i in range(m):
k, pos = map(int, input().split())
s = a[-k:]
s = sorted(s)
print(s[pos - 1][1])
main() | {
"input": [
"7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4\n",
"3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3\n"
],
"output": [
"2\n3\n2\n3\n2\n3\n1\n1\n3\n",
"20\n10\n20\n10\n20\n10\n"
]
} |
2,228 | 9 | There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or 1 β€ f_i β€ n if the i-th friend wants to give the gift to the friend f_i.
You want to fill in the unknown values (f_i = 0) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.
If there are several answers, you can print any.
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the number of friends.
The second line of the input contains n integers f_1, f_2, ..., f_n (0 β€ f_i β€ n, f_i β i, all f_i β 0 are distinct), where f_i is the either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or 1 β€ f_i β€ n if the i-th friend wants to give the gift to the friend f_i. It is also guaranteed that there is at least two values f_i = 0.
Output
Print n integers nf_1, nf_2, ..., nf_n, where nf_i should be equal to f_i if f_i β 0 or the number of friend whom the i-th friend wants to give the gift to. All values nf_i should be distinct, nf_i cannot be equal to i. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself.
If there are several answers, you can print any.
Examples
Input
5
5 0 0 2 4
Output
5 3 1 2 4
Input
7
7 0 0 1 4 0 6
Output
7 3 2 1 4 5 6
Input
7
7 4 0 3 0 5 1
Output
7 4 2 3 6 5 1
Input
5
2 1 0 0 0
Output
2 1 4 5 3 | def swap(list,p1,p2):
list[p1],list[p2]=list[p2],list[p1]
n=int(input())
l=list(map(int,input().split()))
l1=[i for i in range(1,n+1)]
l2=list(set(l1)-set(l))
#print(*l2)
l3=list()
j=0
for i in range(n):
if l[i]==0:
l3.append(i)
if l2[j]!=i+1:l[i]=l2[j]
else:
if len(l2)!=j+1:l[i]=l2[j+1];swap(l2,j,j+1)
else:l[i]=l[l3[-2]];l[l3[-2]]=l2[j]
j+=1
print(*l)
| {
"input": [
"7\n7 4 0 3 0 5 1\n",
"5\n5 0 0 2 4\n",
"5\n2 1 0 0 0\n",
"7\n7 0 0 1 4 0 6\n"
],
"output": [
"7 4 2 3 6 5 1 ",
"5 3 1 2 4 \n",
"2 1 4 5 3 ",
"7 3 2 1 4 5 6 "
]
} |
2,229 | 12 | This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). You can perform the following operations on array elements:
1. choose any index i (1 β€ i β€ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 β€ i β€ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 2, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 2, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 2, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities a[1] β€ a[2] β€ β¦ β€ a[n].
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 β€ n β€ 2 β
10^5) β the size of the array a.
Then follow n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β an array that needs to be sorted by the given operations. The given array can contain equal elements.
The sum of n for all test cases in one test does not exceed 2 β
10^5.
Output
For each test case output one integer β the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
Output
2
2
0
0
1
1
1
1
16
Note
In the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 2, 9] β [2, 4, 7, 2, 9] β [2, 2, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 β to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] β [1, 3, 5, 8, 7] β [1, 3, 5, 7, 8].
In the third test case, the array is already sorted. | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
b = [None]*n
i = 0
for v in mints():
b[i] = (v, i)
i += 1
b.sort()
c = [0]*n # how many moves to sort all after i with same value + all below
ans = int(1e9)
s = None
i = 0
while i < n:
j = i + 1
v = b[i][0]
while j < n and b[j][0] == v:
j += 1
if s is None:
for z in range(i, j):
c[z] = j - z - 1
ans = n - j
else:
k = s
while k < e and b[k][1] < b[i][1]:
k += 1
for z in range(i, j - 1):
c[z] = j - z - 1 + e
if k == e:
c[j - 1] = c[e - 1]
else:
c[j - 1] = s + e - k
v = n - i - j
for z in range(i, j):
while k < e and b[k][1] < b[z][1]:
k += 1
ans = min(ans, z + (e if k == s else c[k - 1]) + v)
s, e, i = i, j, j
print(ans)
for i in range(mint()):
solve()
| {
"input": [
"9\n5\n4 7 2 2 9\n5\n3 5 8 1 7\n5\n1 2 2 4 5\n2\n0 1\n3\n0 1 0\n4\n0 1 0 0\n4\n0 1 0 1\n4\n0 1 0 2\n20\n16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9\n"
],
"output": [
"2\n2\n0\n0\n1\n1\n1\n1\n16\n"
]
} |
2,230 | 8 | You are given an array a_1, a_2, ..., a_n, consisting of n positive integers.
Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves:
1. move right β go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n.
2. move left β go from your current index x to x-1 and add a_{x-1} to your score. This move can only be performed if x>1. Also, you can't perform two or more moves to the left in a row.
You want to perform exactly k moves. Also, there should be no more than z moves to the left among them.
What is the maximum score you can achieve?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of testcases.
The first line of each testcase contains three integers n, k and z (2 β€ n β€ 10^5, 1 β€ k β€ n - 1, 0 β€ z β€ min(5, k)) β the number of elements in the array, the total number of moves you should perform and the maximum number of moves to the left you can perform.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^4) β the given array.
The sum of n over all testcases does not exceed 3 β
10^5.
Output
Print t integers β for each testcase output the maximum score you can achieve if you make exactly k moves in total, no more than z of them are to the left and there are no two or more moves to the left in a row.
Example
Input
4
5 4 0
1 5 4 3 2
5 4 1
1 5 4 3 2
5 4 4
10 20 30 40 50
10 7 3
4 6 8 2 9 9 7 4 10 9
Output
15
19
150
56
Note
In the first testcase you are not allowed to move left at all. So you make four moves to the right and obtain the score a_1 + a_2 + a_3 + a_4 + a_5.
In the second example you can move one time to the left. So we can follow these moves: right, right, left, right. The score will be a_1 + a_2 + a_3 + a_2 + a_3.
In the third example you can move four times to the left but it's not optimal anyway, you can just move four times to the right and obtain the score a_1 + a_2 + a_3 + a_4 + a_5. | def put(): return map(int, input().split())
n = int(input())
for _ in range(n):
n,k,z = put()
l = list(put())
ans,k,dp = 0,k+1, []
for i in range(k-1):
dp.append(l[i]+l[i+1])
for i in range(z+1):
if k-2*i>0:
#print(sum(l[:k-2*i]), max(dp[:k-2*i]) )
ans = max(ans, sum(l[:k-2*i])+i*max(dp[:k-2*i]))
print(ans)
| {
"input": [
"4\n5 4 0\n1 5 4 3 2\n5 4 1\n1 5 4 3 2\n5 4 4\n10 20 30 40 50\n10 7 3\n4 6 8 2 9 9 7 4 10 9\n"
],
"output": [
"15\n19\n150\n56\n"
]
} |
2,231 | 11 | There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the right border is (x + k, y) and all points between borders (including borders) belong to the platform.
Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same y-coordinate.
When you place both platforms on a plane, all points start falling down decreasing their y-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.
Your task is to find the maximum number of points you can save if you place both platforms optimally.
You have to answer t independent test cases.
For better understanding, please read the Note section below to see a picture for the first test case.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 10^9) β the number of points and the length of each platform, respectively. The second line of the test case contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ 10^9), where x_i is x-coordinate of the i-th point. The third line of the input contains n integers y_1, y_2, ..., y_n (1 β€ y_i β€ 10^9), where y_i is y-coordinate of the i-th point. All points are distinct (there is no pair 1 β€ i < j β€ n such that x_i = x_j and y_i = y_j).
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.
Example
Input
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
Output
6
1
5
10
Note
The picture corresponding to the first test case of the example:
<image>
Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points (1, -1) and (2, -1) and the second one between points (4, 3) and (5, 3). Vectors represent how the points will fall down. As you can see, the only point we can't save is the point (3, 7) so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point (5, 3) doesn't fall at all because it is already on the platform. | def solve():
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
input()
dp=[0]*(n+10)
ma=[0]*(n+10)
r=-1
a.sort()
for i in range(n):
r=max(r,i)
for j in range(r,n):
if a[j]<=a[i]+k:r=j
else: break
dp[i]=r-i+1
for i in range(n,-1,-1):
ma[i]=max(dp[i],ma[i+1])
ans = 0
for i in range(n):
ans=max(dp[i]+ma[i+dp[i]],ans)
print(ans)
t = int(input())
for i in range(t):solve()
| {
"input": [
"4\n7 1\n1 5 2 3 1 5 4\n1 3 6 7 2 5 4\n1 1\n1000000000\n1000000000\n5 10\n10 7 5 15 8\n20 199 192 219 1904\n10 10\n15 19 8 17 20 10 9 2 10 19\n12 13 6 17 1 14 7 9 19 3\n"
],
"output": [
"6\n1\n5\n10\n"
]
} |
2,232 | 9 | Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as small as possible.
For example, if n = 4, the following course of action is optimal:
1. choose a = 4 and b = 2, so the new number is 3, and the whiteboard contains [1, 3, 3];
2. choose a = 3 and b = 3, so the new number is 3, and the whiteboard contains [1, 3];
3. choose a = 1 and b = 3, so the new number is 2, and the whiteboard contains [2].
It's easy to see that after n - 1 operations, there will be left only one number. Your goal is to minimize it.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains one integer n (2 β€ n β€ 2 β
10^5) β the number of integers written on the board initially.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 β
10^5.
Output
For each test case, in the first line, print the minimum possible number left on the board after n - 1 operations. Each of the next n - 1 lines should contain two integers β numbers a and b chosen and erased in each operation.
Example
Input
1
4
Output
2
2 4
3 3
3 1 | def recal(n):
print(2)
print(n-1, n)
r = n
while r > 2:
print(r - 2, r)
r -= 1
t = int(input())
while t > 0:
recal(int(input()))
t -= 1
| {
"input": [
"1\n4\n"
],
"output": [
"2\n4 3\n4 2\n3 1\n"
]
} |
2,233 | 11 | Gildong is playing with his dog, Badugi. They're at a park that has n intersections and n-1 bidirectional roads, each 1 meter in length and connecting two intersections with each other. The intersections are numbered from 1 to n, and for every a and b (1 β€ a, b β€ n), it is possible to get to the b-th intersection from the a-th intersection using some set of roads.
Gildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the 1-st intersection, and he will move by the following rules:
* Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to k meters, so he can only find snacks that are less than or equal to k meters away from himself. If he cannot find any such snack, he fails the mission.
* Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily.
* He repeats this process until he eats all n snacks. After that, he has to find the 1-st intersection again which also must be less than or equal to k meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission.
Unfortunately, Gildong doesn't know the value of k. So, he wants you to find the minimum value of k that makes it possible for Badugi to complete his mission, if Badugi moves optimally.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 10^4).
The first line of each test case contains one integer n (2 β€ n β€ 2 β
10^5) β the number of intersections of the park.
The next n-1 lines contain two integers u and v (1 β€ u,v β€ n, u β v) each, which means there is a road between intersection u and v. All roads are bidirectional and distinct.
It is guaranteed that:
* For each test case, for every a and b (1 β€ a, b β€ n), it is possible to get to the b-th intersection from the a-th intersection.
* The sum of n in all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print one integer β the minimum possible value of k such that Badugi can complete the mission.
Example
Input
3
3
1 2
1 3
4
1 2
2 3
3 4
8
1 2
2 3
3 4
1 5
5 6
6 7
5 8
Output
2
3
3
Note
In the first case, Badugi can complete his mission with k=2 by moving as follows:
1. Initially, Badugi is at the 1-st intersection. The closest snack is obviously at the 1-st intersection, so he just eats it.
2. Next, he looks for the closest snack, which can be either the one at the 2-nd or the one at the 3-rd intersection. Assume that he chooses the 2-nd intersection. He moves to the 2-nd intersection, which is 1 meter away, and eats the snack.
3. Now the only remaining snack is on the 3-rd intersection, and he needs to move along 2 paths to get to it.
4. After eating the snack at the 3-rd intersection, he needs to find the 1-st intersection again, which is only 1 meter away. As he gets back to it, he completes the mission.
In the second case, the only possible sequence of moves he can make is 1 β 2 β 3 β 4 β 1. Since the distance between the 4-th intersection and the 1-st intersection is 3, k needs to be at least 3 for Badugi to complete his mission.
In the third case, Badugi can make his moves as follows: 1 β 5 β 6 β 7 β 8 β 2 β 3 β 4 β 1. It can be shown that this is the only possible sequence of moves for Badugi to complete his mission with k=3.
<image> | from sys import stdin, stdout
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
@bootstrap
def f(v,p):
if v == 0:
for w in edges[0]:
temp = (yield f(w, 0))
depths[0] = min(depths[0], temp)
depths[0] += 1
yield
elif len(edges[v]) == 1:
depths[v] = 0
yield depths[v]
else:
for w in edges[v]:
if w != p:
temp = (yield f(w, v))
depths[v] = min(depths[v], temp)
depths[v] += 1
yield depths[v]
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
edges = []
for foo in range(n):
edges.append([])
for bar in range(n-1):
u, v = [int(x) for x in stdin.readline().split()]
u -= 1
v -= 1
edges[u].append(v)
edges[v].append(u)
depths = [9999999999]*n
f(0,0)
exception = -1
current_max = 0
for w in edges[0]:
if depths[w] > current_max:
current_max = depths[w]
exception = w
final = [depths[w] + 2 for w in range(n)]
final[exception] -= 1
final[0] = 0
stdout.write(str(max(final)) + '\n')
| {
"input": [
"3\n3\n1 2\n1 3\n4\n1 2\n2 3\n3 4\n8\n1 2\n2 3\n3 4\n1 5\n5 6\n6 7\n5 8\n"
],
"output": [
"\n2\n3\n3\n"
]
} |
2,234 | 9 | Nezzar loves the game osu!.
osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees.
<image> Points A,B,C on the left have angle less than 90 degrees, so they can be three consecutive points of a nice beatmap; Points A',B',C' on the right have angle greater or equal to 90 degrees, so they cannot be three consecutive points of a nice beatmap.
Now Nezzar has a beatmap of n distinct points A_1,A_2,β¦,A_n. Nezzar would like to reorder these n points so that the resulting beatmap is nice.
Formally, you are required to find a permutation p_1,p_2,β¦,p_n of integers from 1 to n, such that beatmap A_{p_1},A_{p_2},β¦,A_{p_n} is nice. If it is impossible, you should determine it.
Input
The first line contains a single integer n (3 β€ n β€ 5000).
Then n lines follow, i-th of them contains two integers x_i, y_i (-10^9 β€ x_i, y_i β€ 10^9) β coordinates of point A_i.
It is guaranteed that all points are distinct.
Output
If there is no solution, print -1.
Otherwise, print n integers, representing a valid permutation p.
If there are multiple possible answers, you can print any.
Example
Input
5
0 0
5 0
4 2
2 1
3 0
Output
1 2 5 3 4
Note
Here is the illustration for the first test:
<image>
Please note that the angle between A_1, A_2 and A_5, centered at A_2, is treated as 0 degrees. However, angle between A_1, A_5 and A_2, centered at A_5, is treated as 180 degrees. | def solve(N,A):
def check(a,b,c):
ax,ay = a
bx,by = b
cx,cy = c
return (bx-ax) * (cx-bx) + (by-ay) * (cy-by) < 0
ans = [i for i in range(N)]
for i in range(N-2):
for j in range(i,-1,-1):
a,b,c = ans[j],ans[j+1],ans[j+2]
if not check(A[a],A[b],A[c]):
ans[j+1],ans[j+2] = ans[j+2],ans[j+1]
return ans
n = int(input())
A = [tuple(map(int,input().split())) for i in range(n)]
ans = solve(n,A)
for i in range(n):
ans[i] += 1
print(*ans)
| {
"input": [
"5\n0 0\n5 0\n4 2\n2 1\n3 0\n"
],
"output": [
"\n1 2 5 3 4\n"
]
} |
2,235 | 7 | A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you dΓ©jΓ vu.
There is a string s. You must insert exactly one character 'a' somewhere in s. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.
For example, suppose s= "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.
Input
The first line contains a single integer t (1β€ tβ€ 10^4) β the number of test cases.
The only line of each test case contains a string s consisting of lowercase English letters.
The total length of all strings does not exceed 3β
10^5.
Output
For each test case, if there is no solution, output "NO".
Otherwise, output "YES" followed by your constructed string of length |s|+1 on the next line. If there are multiple solutions, you may print any.
You can print each letter of "YES" and "NO" in any case (upper or lower).
Example
Input
6
cbabc
ab
zza
ba
a
nutforajaroftuna
Output
YES
cbabac
YES
aab
YES
zaza
YES
baa
NO
YES
nutforajarofatuna
Note
The first test case is described in the statement.
In the second test case, we can make either "aab" or "aba". But "aba" is a palindrome, so "aab" is the only correct answer.
In the third test case, "zaza" and "zzaa" are correct answers, but not "azza".
In the fourth test case, "baa" is the only correct answer.
In the fifth test case, we can only make "aa", which is a palindrome. So the answer is "NO".
In the sixth test case, "anutforajaroftuna" is a palindrome, but inserting 'a' elsewhere is valid. | def is_pal(s):
return s == s[::-1]
def solve():
s = input()
if max(s) == 'a':
print('NO')
return
print('YES')
if not is_pal('a' + s):
print('a' + s)
else:
print(s + 'a')
for _ in range(int(input())):
solve() | {
"input": [
"6\ncbabc\nab\nzza\nba\na\nnutforajaroftuna\n"
],
"output": [
"\nYES\ncbabac\nYES\naab\nYES\nzaza\nYES\nbaa\nNO\nYES\nnutforajarofatuna\n"
]
} |
2,236 | 10 | You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.
In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 β€ a β€ b < x β€ y β€ |s| and substrings s[a... b], s[x... y] are palindromes.
A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.
A substring s[i... j] (1 β€ i β€ j β€ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".
Input
The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.
Output
Output a single number β the quantity of pairs of non-overlapping palindromic substrings of s.
Please do not use the %lld format specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d format specifier.
Examples
Input
aa
Output
1
Input
aaa
Output
5
Input
abacaba
Output
36 | def f(t):
m=len(t)
flag=True
for i in range(m//2):
if t[i]!=t[m-1-i]:
flag=False
return flag
s=input()
n=len(s)
l=[0]*n
r=[0]*n
arr=[(i,i) for i in range(n)]+[(i,i+1) for i in range(n-1) if s[i]==s[i+1]]
for x,y in arr:
while x>=0 and y<n and s[x]==s[y]:
r[x]+=1
l[y]+=1
x-=1
y+=1
ans=0
for i in range(n):
for j in range(i+1,n):
ans+=l[i]*r[j]
print(ans) | {
"input": [
"aa\n",
"aaa\n",
"abacaba\n"
],
"output": [
"1\n",
"5\n",
"36\n"
]
} |
2,237 | 8 | A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has n + 1 dividing lines drawn from west to east and m + 1 dividing lines drawn from north to south, which divide the parking lot into nΒ·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i, j) so that the square in the north-west corner has coordinates (1, 1) and the square in the south-east corner has coordinates (n, m). See the picture in the notes for clarifications.
Before the game show the organizers offer Yura to occupy any of the (n + 1)Β·(m + 1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes cΒ·d2 seconds. The time Yura spends on turning his head can be neglected.
It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.
Input
The first line contains two integers n and m (1 β€ n, m β€ 1000) β the sizes of the parking lot. Each of the next n lines contains m integers: the j-th number in the i-th line describes the "rarity" cij (0 β€ cij β€ 100000) of the car that is located in the square with coordinates (i, j).
Output
In the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers li and lj (0 β€ li β€ n, 0 β€ lj β€ m) β the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller li. If there are still multiple such points, print the point with smaller lj.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
2 3
3 4 5
3 9 1
Output
392
1 1
Input
3 4
1 0 0 0
0 0 3 0
0 0 5 5
Output
240
2 3
Note
In the first test case the total time of guessing all cars is equal to 3Β·8 + 3Β·8 + 4Β·8 + 9Β·8 + 5Β·40 + 1Β·40 = 392.
The coordinate system of the field:
<image> | import os
import sys
from io import BytesIO, IOBase
from collections import Counter
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 gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
# = int(input())
# = list(map(int, input().split()))
# = input()
n,m=map(int, input().split())
a=[]
somrows=[]
somcols=[]
for i in range(n):
a.append(list(map(int, input().split())))
somrows.append(sum(a[i]))
for j in range(m):
curr=0
for i in range(n):
curr+=a[i][j]
somcols.append(curr)
xs=[]
ys=[]
xmin=ymin=float('inf')
xind=yind=-1
for i in range(0, 4*m+1, 4):
curr=0
for j in range(2, 4*m, 4):
curr+=(j-i)*(j-i)*(somcols[j//4])
if curr<xmin:
xmin=curr
xind=i//4
xs.append(curr)
#print('')
for i in range(0, 4*n+1, 4):
curr=0
for j in range(2, 4*n, 4):
curr+=(j-i)*(j-i)*(somrows[j//4])
ys.append(curr)
if curr<ymin:
ymin=curr
yind=i//4
print(xmin+ymin)
print(yind, xind)
return
if __name__ == "__main__":
main() | {
"input": [
"2 3\n3 4 5\n3 9 1\n",
"3 4\n1 0 0 0\n0 0 3 0\n0 0 5 5\n"
],
"output": [
" 392\n1 1\n",
" 240\n2 3\n"
]
} |
2,238 | 7 | An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one β to the 1-st and the 3-rd ones, the 3-rd one β only to the 2-nd one. The transitions are possible only between the adjacent sections.
The spacecraft team consists of n aliens. Each of them is given a rank β an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.
Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.
At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.
Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m.
Input
The first line contains two space-separated integers: n and m (1 β€ n, m β€ 109) β the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.
Output
Print a single number β the answer to the problem modulo m.
Examples
Input
1 10
Output
2
Input
3 8
Output
2
Note
In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.
To briefly describe the movements in the second sample we will use value <image>, which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. | import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
n,m = get_ints()
ans = (pow(3,n,m)-1+m)%m
print(ans) | {
"input": [
"3 8\n",
"1 10\n"
],
"output": [
"2\n",
"2\n"
]
} |
2,239 | 10 | You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost (N-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row.
Input
On the first line you will be given two space separated integers N and M (1 β€ N, M β€ 1000). On the second line you will be given another two space separated integers i and j (1 β€ i β€ N, 1 β€ j β€ M) β the number of the initial row and the number of the initial column. Note that, (1, 1) is the upper left corner of the board and (N, M) is the bottom right corner.
Output
Output the expected number of steps on a line of itself with at least 4 digits after the decimal point.
Examples
Input
10 10
10 4
Output
0.0000000000
Input
10 14
5 14
Output
18.0038068653 | n,m = (int(s) for s in input().split())
i,j = (int(s) for s in input().split())
def find(n,m,i,j):
if i==n:
return 0
if m==1:
return 2*(n-i)
e,a,b = [0.]*m,[0]*m,[0]*m
for l in range(n-1,0,-1):
a[0],b[0]=.5,.5*(3+e[0])
for k in range(1,m-1):
a[k] = 1/(3-a[k-1])
b[k] = a[k]*(b[k-1]+4+e[k])
e[m-1] = (3+b[m-2]+e[m-1])/(2-a[m-2])
for k in range(m-2,-1,-1):
e[k]=a[k]*e[k+1]+b[k]
if l == i: return e[j]
print (find(n,m,i,m-j)) | {
"input": [
"10 14\n5 14\n",
"10 10\n10 4\n"
],
"output": [
"18.0038068653",
"0.0000000000"
]
} |
2,240 | 8 | The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).
* If the wind blows to the east, the boat will move to (x + 1, y).
* If the wind blows to the south, the boat will move to (x, y - 1).
* If the wind blows to the west, the boat will move to (x - 1, y).
* If the wind blows to the north, the boat will move to (x, y + 1).
Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?
Input
The first line contains five integers t, sx, sy, ex, ey (1 β€ t β€ 105, - 109 β€ sx, sy, ex, ey β€ 109). The starting location and the ending location will be different.
The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).
Output
If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).
Examples
Input
5 0 0 1 1
SESNW
Output
4
Input
10 5 3 3 6
NENSWESNEE
Output
-1
Note
In the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.
In the second sample, they cannot sail to the destination. | def main():
t,sx,sy,ex,ey = map(int,input().split())
dirs=input()
x_dist = (ex-sx)
x_dir = 'E' if(x_dist>=0) else 'W'
x_dist = x_dist if(x_dist>=0) else (-x_dist)
y_dist = (ey-sy)
y_dir = 'N' if(y_dist>=0) else 'S'
y_dist = y_dist if(y_dist>=0) else (-y_dist)
for i in range(t):
if dirs[i]==x_dir and x_dist>0:
x_dist-=1
elif dirs[i]==y_dir and y_dist>0:
y_dist-=1
if(y_dist==0 and x_dist==0):
return i+1
return -1
print(main())
| {
"input": [
"10 5 3 3 6\nNENSWESNEE\n",
"5 0 0 1 1\nSESNW\n"
],
"output": [
"-1\n",
"4\n"
]
} |
2,241 | 8 | Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.
After the contest was over, Valera was interested in results. He found out that:
* each student in the team scored at least l points and at most r points;
* in total, all members of the team scored exactly sall points;
* the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 β₯ a2 β₯ ... β₯ an), then sk = a1 + a2 + ... + ak.
However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
Input
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 β€ n, k, l, r β€ 1000; l β€ r; k β€ n; 1 β€ sk β€ sall β€ 106).
It's guaranteed that the input is such that the answer exists.
Output
Print exactly n integers a1, a2, ..., an β the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
Examples
Input
5 3 1 3 13 9
Output
2 3 2 3 3
Input
5 3 1 3 15 9
Output
3 3 3 3 3 | def f(n, m):
if not n:
return []
b = [m // n] * n
for i in range(m % n):
b[i] += 1
return b
a = list(map(int, input().split()))
print (*(f(a[1], a[5]) + f(a[0] - a[1], a[4] - a[5]))) | {
"input": [
"5 3 1 3 15 9\n",
"5 3 1 3 13 9\n"
],
"output": [
"3 3 3 3 3 \n",
"3 3 3 2 2 \n"
]
} |
2,242 | 9 | This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points.
Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort.
After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.
Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
Input
The first line contains a pair of integers n and k (1 β€ k β€ n + 1). The i-th of the following n lines contains two integers separated by a single space β pi and ei (0 β€ pi, ei β€ 200000).
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem C1 (4 points), the constraint 1 β€ n β€ 15 will hold.
* In subproblem C2 (4 points), the constraint 1 β€ n β€ 100 will hold.
* In subproblem C3 (8 points), the constraint 1 β€ n β€ 200000 will hold.
Output
Print a single number in a single line β the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1.
Examples
Input
3 2
1 1
1 4
2 2
Output
3
Input
2 1
3 2
4 0
Output
-1
Input
5 2
2 10
2 10
1 1
3 1
3 1
Output
12
Note
Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place.
Consider the second test case. Even if Manao wins against both opponents, he will still rank third. | m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0
def add(b, k):
k = t[k]
while k:
e = es[k]
if b[-1] > e: b[-1] = e
b[e] += 1
k = ns[k]
def delete(b):
for i in range(b[m - 1], m + 1):
if b[i]:
b[i] -= 1
b[-1] = i
return i
def calc(k):
global b
q = 0
b = [0] * m
b[-1] = m
take = rank - dn
if take < 0: take = 0
add(b, k)
add(b, k - 1)
for i in range(1, take + 1): q += delete(b)
for i in range(k - 1): add(b, i)
for i in range(k + 1, P + 1): add(b, i)
for i in range(1, k - take + 1): q += delete(b)
return q
n, k = map(int, input().split())
rank = n - k + 1
if rank == 0:
print('0')
exit(0)
for i in range(1, n + 1):
p, e = map(int, input().split())
if p > P: P = p
c[p] += 1
es[i], ns[i] = e, t[p]
t[p] = i
dn = 0
for i in range(1, n + 1):
if i > 1: dn += c[i - 2]
if c[i] + c[i - 1] + dn >= rank and rank <= i + dn:
u = calc(i)
if i < n:
dn += c[i - 1]
v = calc(i + 1)
if u > v: u = v
if i < n - 1:
dn += c[i]
v = calc(i + 2)
if u > v: u = v
print(u)
exit(0)
print('-1')
| {
"input": [
"5 2\n2 10\n2 10\n1 1\n3 1\n3 1\n",
"2 1\n3 2\n4 0\n",
"3 2\n1 1\n1 4\n2 2\n"
],
"output": [
"12\n",
"-1\n",
"3\n"
]
} |
2,243 | 10 | The territory of Berland is represented by a rectangular field n Γ m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 100, 2 β€ n Β· m) β the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
Output
On the first line output integer k β the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2).
Then print nm + 1 lines containing 2 numbers each β the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
Examples
Input
2 2
Output
0
1 1
1 2
2 2
2 1
1 1
Input
3 3
Output
1
3 3 1 1
1 1
1 2
1 3
2 3
2 2
2 1
3 1
3 2
3 3
1 1 | def p(a, b, swap):
if swap:
a, b = b, a
print(a, b)
n, m = [int(x) for x in input().split()]
if (n == 1 or m == 1) and n * m > 2:
print(1)
print(n, m, 1, 1)
for r in range(n):
for c in range(m):
print(r + 1, c + 1)
print(1, 1)
exit(0)
if n * m % 2 == 0:
print(0)
print(1, 1)
swap = m % 2 != 0
if swap:
m, n = n, m
for c in range(m):
for r in range(n - 1):
if c % 2 == 0:
p(r + 2, c + 1, swap)
else:
p(n - r, c + 1, swap)
for c in range(m):
p(1, m - c, swap)
else:
print(1)
print(n, m, 1, 1)
for c in range(m):
for r in range(n):
if c % 2 == 0:
print(r + 1, c + 1)
else:
print(n - r, c + 1)
print(1, 1) | {
"input": [
"2 2\n",
"3 3\n"
],
"output": [
"0\n1 1\n1 2\n2 2\n2 1\n1 1\n",
"1\n3 3 1 1\n1 1\n1 2\n1 3\n2 3\n2 2\n2 1\n3 1\n3 2\n3 3\n1 1\n"
]
} |
2,244 | 7 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n Γ n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
Input
The first line contains an integer n (1 β€ n β€ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
Output
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
Examples
Input
3
xxo
xox
oxx
Output
YES
Input
4
xxxo
xoxo
oxox
xxxx
Output
NO | def f(x): return 1 if x == 'x' else 0
n = int(input())
t = [list(map(f, input())) + [1] for i in range(n)] + [[1] * (n + 1)]
for i in range(n):
for j in range(n):
if t[i - 1][j] + t[i + 1][j] + t[i][j + 1] + t[i][j - 1] & 1:
print('NO')
exit(0)
print('YES') | {
"input": [
"3\nxxo\nxox\noxx\n",
"4\nxxxo\nxoxo\noxox\nxxxx\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
2,245 | 11 | When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.
Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.
More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i β€ j).
Then the simple prettiness of s is defined by the formula:
<image>
The prettiness of s equals
<image>
Find the prettiness of the given song title.
We assume that the vowels are I, E, A, O, U, Y.
Input
The input contains a single string s (1 β€ |s| β€ 5Β·105) β the title of the song.
Output
Print the prettiness of the song with the absolute or relative error of at most 10 - 6.
Examples
Input
IEAIAIO
Output
28.0000000
Input
BYOB
Output
5.8333333
Input
YISVOWEL
Output
17.0500000
Note
In the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28. | from math import fsum
def main():
l, x = [0, 0], 0
for c in input():
if c in ('I', 'E', 'A', 'O', 'U', 'Y'):
x += 1
l.append(x)
n = l[-1]
res = [float(n)]
for m in range(2, len(l) - 1):
n += l[-m] - l[m]
res.append(n / m)
print('{:.7f}'.format(fsum(res)))
if __name__ == '__main__':
main()
| {
"input": [
"BYOB\n",
"YISVOWEL\n",
"IEAIAIO\n"
],
"output": [
"5.83333333\n",
"17.05000000\n",
"28.00000000\n"
]
} |
2,246 | 7 | An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
Input
A single line contains integer n (1 β€ n β€ 5000) β the number of students at an exam.
Output
In the first line print integer k β the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print k distinct integers a1, a2, ..., ak (1 β€ ai β€ n), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |ai - ai + 1| β 1 for all i from 1 to k - 1.
If there are several possible answers, output any of them.
Examples
Input
6
Output
6
1 5 3 6 2 4
Input
3
Output
2
1 3 | import math
import string
def main():
n = int(input())
if n <= 2:
ans = [1]
elif n == 3:
ans = [1, 3]
else:
ans = list(range(2, n + 1, 2)) + list(range(1, n + 1, 2))
print(len(ans))
print(' '.join(map(str, ans)))
if __name__ == '__main__':
main() | {
"input": [
"3\n",
"6"
],
"output": [
"2\n1 3\n",
"6\n1 3 5 2 4 6\n"
]
} |
2,247 | 7 | Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Input
The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 β€ ai β€ 1000) β the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
Output
Print a single integer β the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
Examples
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
Note
This is what Gerald's hexagon looks like in the first sample:
<image>
And that's what it looks like in the second sample:
<image> | def S(a):
return a * a
a1, a2, a3, a4, a5, a6 = map(int, input().split())
print(S(a1 + a2 + a6) - S(a2) - S(a6) - S(a4))
| {
"input": [
"1 1 1 1 1 1\n",
"1 2 1 2 1 2\n"
],
"output": [
"6\n",
"13\n"
]
} |
2,248 | 10 | Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 β€ i β€ k), such that
1. 1 β€ k β€ 3
2. pi is a prime
3. <image>
The numbers pi do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.
Input
The single line contains an odd number n (3 β€ n < 109).
Output
In the first line print k (1 β€ k β€ 3), showing how many numbers are in the representation you found.
In the second line print numbers pi in any order. If there are multiple possible solutions, you can print any of them.
Examples
Input
27
Output
3
5 11 11
Note
A prime is an integer strictly larger than one that is divisible only by one and by itself. | def prm(n):
i = 2
n = int(n)
while i*i<=n:
if n%i==0:
return False
i+=1
return True
a = int(input())
if prm(a):
print("1")
print(a)
else:
a-=3;
b = 3;
while True:
if prm(b):
if prm(a-b):
print(3)
print("3 ",b," ",a-b)
break
b+=2
| {
"input": [
"27\n"
],
"output": [
"3\n23 2 2\n"
]
} |
2,249 | 10 | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | def parse(i):
t = input().split()
return int(t[0]), int(t[1]), i
n, m = [int(x) for x in input().split()]
list = [parse(i) for i in range(m)]
list.sort(key=lambda x: (x[0], -x[1]))
# print(list)
f = 0
t = 1
fakeFrom = 1
fakeTo = 2
graph = []
for i in range(m):
if list[i][1] == 1:
graph.append((f + 1, t + 1, list[i][2]))
t += 1
else:
graph.append((fakeFrom + 1, fakeTo + 1, list[i][2]))
if fakeTo >= t:
print(-1)
exit(0)
fakeFrom += 1
if fakeFrom == fakeTo:
fakeFrom = 1
fakeTo += 1
# if fakeTo >= t:
# print(-1)
# exit(0)
# print(graph)
graph.sort(key=lambda x: x[2])
for x in graph:
print(x[0], x[1])
| {
"input": [
"4 5\n2 1\n3 1\n4 0\n1 1\n5 0\n",
"3 3\n1 0\n2 1\n3 1\n"
],
"output": [
"1 3\n1 4\n2 3\n1 2\n2 4\n",
"-1\n"
]
} |
2,250 | 10 | Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.
For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.
Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).
Input
The first line contains two integers m, d (1 β€ m β€ 2000, 0 β€ d β€ 9) β the parameters from the problem statement.
The second line contains positive integer a in decimal presentation (without leading zeroes).
The third line contains positive integer b in decimal presentation (without leading zeroes).
It is guaranteed that a β€ b, the number of digits in a and b are the same and don't exceed 2000.
Output
Print the only integer a β the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.
Examples
Input
2 6
10
99
Output
8
Input
2 0
1
9
Output
4
Input
19 7
1000
9999
Output
6
Note
The numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.
The numbers from the answer of the second example are 2, 4, 6 and 8.
The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747. | import sys
m, d = map(int, input().split())
mod = 10**9 + 7
def solve(a: list):
dp = [0]*m
border = a[0] % m if a[0] != d else -1
m10 = 10 % m
for i in range(a[0]):
if i != d:
dp[i % m] += 1
for i, digit in enumerate(a[1:], start=1):
next_dp = [0]*m
if i & 1:
t = d % m
for j in range(m):
next_dp[t] += dp[j]
t = t + m10 if t + m10 < m else t + m10 - m
if border != -1:
if d < digit:
next_dp[(border * 10 + d) % m] += 1
border = -1
elif d == digit:
border = (border * 10 + d) % m
else:
border = -1
else:
for j in range(m):
if dp[j] == 0:
continue
if dp[j] >= mod:
dp[j] -= mod
t = (j * 10 - 1) % m
for k in range(10):
t += 1
if t == m:
t = 0
if k == d:
continue
next_dp[t] += dp[j]
if next_dp[t] >= mod:
next_dp[t] -= mod
if border != -1:
for k in range(digit):
if k == d:
continue
next_dp[(border * 10 + k) % m] += 1
if digit != d:
border = (border * 10 + digit) % m
else:
border = -1
dp = next_dp
return dp[0] + (1 if border == 0 else 0)
a = list(map(int, input()))
b = list(map(int, input()))
a[-1] -= 1
for i in range(len(a)-1, 0, -1):
if a[i] < 0:
a[i] = 9
a[i-1] -= 1
else:
break
ans = solve(b) - solve(a)
print(ans % mod)
| {
"input": [
"2 6\n10\n99\n",
"2 0\n1\n9\n",
"19 7\n1000\n9999\n"
],
"output": [
"8\n",
"4\n",
"6\n"
]
} |
2,251 | 9 | Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a and b can be either painted Red or Blue.
After her painting is done, she will get p chocolates for each tile that is painted Red and q chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get.
Input
The only line contains five integers n, a, b, p and q (1 β€ n, a, b, p, q β€ 109).
Output
Print the only integer s β the maximum number of chocolates Joty can get.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
Examples
Input
5 2 3 12 15
Output
39
Input
20 2 3 3 5
Output
51 | n,a,b,p,q=map(int,input().split())
def gcd(a,b):
while b: a,b=b,a%b
return a
print(n//a*p+n//b*q-n//(a*b//gcd(a,b))*min(p,q)) | {
"input": [
"5 2 3 12 15\n",
"20 2 3 3 5\n"
],
"output": [
"39\n",
"51\n"
]
} |
2,252 | 10 | A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.
Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.
Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.
For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.
Input
The first line of the input contains two integers n and k (2 β€ n β€ 200 000, 1 β€ k β€ 5) β the number of vertices in the tree and the maximum allowed jump distance respectively.
The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1 β€ ai, bi β€ n) β the indices on vertices connected with i-th edge.
It's guaranteed that the given edges form a tree.
Output
Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.
Examples
Input
6 2
1 2
1 3
2 4
2 5
4 6
Output
20
Input
13 3
1 2
3 2
4 2
5 2
3 6
10 6
6 7
6 13
5 8
5 9
9 11
11 12
Output
114
Input
3 5
2 1
3 1
Output
3
Note
In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself).
<image>
There are <image> pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20.
In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 3. | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 10**9+7
"""
Each edge goes from parent U to child V
Edge appears on S_V * (N - S_V) paths
For each path of length L, (L + (-L)%K)/K
L%K 0, 1, 2, 3, 4
(K - L%K)%K K K-1 K-2 ...
0 K-1 K-2 ...
"""
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
def solve():
N, K = getInts()
graph = dd(set)
for i in range(N-1):
A, B = getInts()
graph[A].add(B)
graph[B].add(A)
dp_count = [[0 for j in range(5)] for i in range(N+1)]
dp_total = [0 for j in range(N+1)]
global ans
ans = 0
@bootstrap
def dfs(node,parent,depth):
global ans
dp_count[node][depth % K] = 1
dp_total[node] = 1
for neigh in graph[node]:
if neigh != parent:
yield dfs(neigh,node,depth+1)
for i in range(K):
for j in range(K):
diff = (i+j-2*depth)%K
req = (-diff)%K
ans += req * dp_count[node][i] * dp_count[neigh][j]
for i in range(K):
dp_count[node][i] += dp_count[neigh][i]
dp_total[node] += dp_total[neigh]
ans += dp_total[node] * (N - dp_total[node])
yield
dfs(1,-1,0)
return ans//K
print(solve())
| {
"input": [
"13 3\n1 2\n3 2\n4 2\n5 2\n3 6\n10 6\n6 7\n6 13\n5 8\n5 9\n9 11\n11 12\n",
"6 2\n1 2\n1 3\n2 4\n2 5\n4 6\n",
"3 5\n2 1\n3 1\n"
],
"output": [
"114\n",
"20\n",
"3\n"
]
} |
2,253 | 7 | Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (l β left, s β straight, r β right) and a light p for a pedestrian crossing.
<image>
An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.
Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.
Input
The input consists of four lines with each line describing a road part given in a counter-clockwise order.
Each line contains four integers l, s, r, p β for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light.
Output
On a single line, print "YES" if an accident is possible, and "NO" otherwise.
Examples
Input
1 0 0 1
0 1 0 0
0 0 1 0
0 0 0 1
Output
YES
Input
0 1 1 0
1 0 1 0
1 1 0 0
0 0 0 1
Output
NO
Input
1 0 0 0
0 0 0 1
0 0 0 0
1 0 1 0
Output
NO
Note
In the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4.
In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. | def int_map():
return map(int, input().split(' '))
sem = []
for _ in range(4):
sem.append(list(int_map()))
for i in range(4):
if sem[i][3]*(sem[i][0]+sem[i][1]+sem[i][2]+sem[(i+1) % 4][0]+sem[(i+2) % 4][1]+sem[(i+3) % 4][2]) !=0:
print('YES')
exit()
print('NO')
| {
"input": [
"1 0 0 1\n0 1 0 0\n0 0 1 0\n0 0 0 1\n",
"1 0 0 0\n0 0 0 1\n0 0 0 0\n1 0 1 0\n",
"0 1 1 0\n1 0 1 0\n1 1 0 0\n0 0 0 1\n"
],
"output": [
"YES\n",
"NO\n",
"NO\n"
]
} |
2,254 | 7 | You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.
Input
The first line of input will contain two integers n, m (2 β€ n, m β€ 2 500), the dimensions of the image.
The next n lines of input will contain a binary string with exactly m characters, representing the image.
Output
Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.
Example
Input
3 5
00100
10110
11001
Output
5
Note
We first choose k = 2.
The image is padded as follows:
001000
101100
110010
000000
We can toggle the image to look as follows:
001100
001100
000000
000000
We can see that this image is compressible for k = 2. | def debug(*a):
return
print('[DEBUG]', *a)
is_prime = [False, False] + [True] * (2600-2)
for i in range(2, 2600):
if is_prime[i]:
for j in range(i+i, 2600, i):
is_prime[j] = False
n, m = map(int, input().split())
a = [None] * n
for i in range(n):
a[i] = input()
b = [None] * (n+1)
b[n] = [0] * (m+1)
for i in range(n-1, -1, -1):
b[i] = [0] * (m+1)
for j in range(m-1, -1, -1):
b[i][j] = b[i+1][j] + b[i][j+1] - b[i+1][j+1] + int(a[i][j])
# debug(b[i])
ans = None
for k in range(2, max(n, m)+1):
if is_prime[k]:
# debug('k=', k)
kk = k*k
aa = 0
for i in range(0, n, k):
for j in range(0, m, k):
bb = b[i][j]
if i + k < n:
bb -= b[i+k][j]
if j + k < m:
bb -= b[i][j+k]
if i + k < n and j + k < m:
bb += b[i+k][j+k]
# debug(i, j, bb)
aa += min(bb, kk-bb)
# debug('aa=', aa)
if ans == None or aa < ans:
ans = aa
print(ans)
| {
"input": [
"3 5\n00100\n10110\n11001\n"
],
"output": [
"5"
]
} |
2,255 | 10 | There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:
* if he enters 00 two numbers will show up: 100000000 and 100123456,
* if he enters 123 two numbers will show up 123456789 and 100123456,
* if he enters 01 there will be only one number 100123456.
For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
Input
The first line contains single integer n (1 β€ n β€ 70000) β the total number of phone contacts in Polycarp's contacts.
The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
Output
Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.
Examples
Input
3
123456789
100000000
100123456
Output
9
000
01
Input
4
123456789
193456789
134567819
934567891
Output
2
193
81
91 | def podstroki(s):
return sorted(set(s[i: i1] for i in range(9) for i1 in range (i+1, 10)), key=len)
res = {}
spisok = [podstroki(input()) for i in range (int(input()))]
for s in spisok:
for podstr in s:
if podstr in res:
res[podstr] += 1
else:
res[podstr] = 1
for s in spisok:
for podstr in s:
if res[podstr] == 1:
print(podstr)
break
| {
"input": [
"3\n123456789\n100000000\n100123456\n",
"4\n123456789\n193456789\n134567819\n934567891\n"
],
"output": [
"7\n000\n01\n",
"2\n193\n13\n91\n"
]
} |
2,256 | 8 | There are times you recall a good old friend and everything you've come through together. Luckily there are social networks β they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.
Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.
Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.
Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 0 β€ k β€ n) β the total amount of messages and the number of previous and next messages visible.
The second line features a sequence of integers a1, a2, ..., an (0 β€ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.
Output
Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.
Examples
Input
6 0
0 1 1 2 3 2
Output
1 2 2 3 3 3
Input
10 1
0 1 0 3 4 5 2 3 7 0
Output
2 3 3 4 5 6 6 6 8 2
Input
2 2
0 1
Output
2 2
Note
Consider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.
In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6. | def read():
return list(map(int,input().split()))
n,k=read()
a=read()
b=[min(k,n-1)+1]
for i in range(1,n):
if a[i]==0:
b.append(min(i,k)+1+min(n-i-1,k))
else:
b.append(b[a[i]-1]-min(k,n-a[i])+min(i-a[i],2*k)+min(n-i-1,k)+1)
print(*b)
| {
"input": [
"6 0\n0 1 1 2 3 2\n",
"2 2\n0 1\n",
"10 1\n0 1 0 3 4 5 2 3 7 0\n"
],
"output": [
"1 2 2 3 3 3 \n",
"2 2 \n",
"2 3 3 4 5 6 6 6 8 2 \n"
]
} |
2,257 | 10 | Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.
Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.
Input
The first line contains a single positive integer n (1 β€ n β€ 105) β the number of days.
The second line contains n space-separated integers m1, m2, ..., mn (0 β€ mi < i) β the number of marks strictly above the water on each day.
Output
Output one single integer β the minimum possible sum of the number of marks strictly below the water level among all days.
Examples
Input
6
0 1 0 3 0 2
Output
6
Input
5
0 1 2 1 2
Output
1
Input
5
0 1 1 2 2
Output
0
Note
In the first example, the following figure shows an optimal case.
<image>
Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.
In the second example, the following figure shows an optimal case.
<image> | #!/usr/bin/env python3
from sys import stdin, stdout
def rint():
return map(int, stdin.readline().split())
#lines = stdin.readlines()
n = int(input())
u = list(rint())
u = [0] + u
mark = 0
b = [0]
for i in range(1,n+1):
uu = u[i]
b.append(i)
if uu >= mark:
inc = uu - mark + 1
l = len(b)
for i in range(inc):
b.pop()
mark += inc
tot = [1 for i in range(n+1)]
for bb in b:
tot[bb] = 0
for i in range(1, n+1):
tot[i] = tot[i-1] + tot[i]
ans = 0
for i in range(1, n+1):
ans += tot[i] - u[i] - 1
print(ans) | {
"input": [
"5\n0 1 1 2 2\n",
"5\n0 1 2 1 2\n",
"6\n0 1 0 3 0 2\n"
],
"output": [
"0\n",
"1\n",
"6\n"
]
} |
2,258 | 10 | For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.
Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer k that if the shark in some day traveled the distance strictly less than k, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to k; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least k.
The shark never returned to the same location after it has moved from it. Thus, in the sequence of n days we can find consecutive nonempty segments when the shark traveled the distance less than k in each of the days: each such segment corresponds to one location. Max wants to choose such k that the lengths of all such segments are equal.
Find such integer k, that the number of locations is as large as possible. If there are several such k, print the smallest one.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of days.
The second line contains n distinct positive integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the distance traveled in each of the day.
Output
Print a single integer k, such that
1. the shark was in each location the same number of days,
2. the number of locations is maximum possible satisfying the first condition,
3. k is smallest possible satisfying the first and second conditions.
Examples
Input
8
1 2 7 3 4 8 5 6
Output
7
Input
6
25 1 2 3 14 36
Output
2
Note
In the first example the shark travels inside a location on days 1 and 2 (first location), then on 4-th and 5-th days (second location), then on 7-th and 8-th days (third location). There are three locations in total.
In the second example the shark only moves inside a location on the 2-nd day, so there is only one location. | BigNum = 10 ** 10
n = int(input())
aa = [BigNum] + list(map(int, input().split(' '))) + [BigNum]
appear = sorted([(v, i) for i, v in enumerate(aa)])
ans = -1
maxLocations = 0
intervals = [(i, i) for i in range(len(aa))]
lengths = {}
def incCount(val):
global lengths
lengths[val] = lengths.get(val, 0) + 1
def decCount(val):
global lengths
if lengths[val] == 1:
del lengths[val]
else:
lengths[val] -= 1
def mergeIntervals(a, b):
return (min(a[0], b[0]), max(a[1], b[1]))
for v, i in appear:
if v == BigNum:
continue
inter = intervals[i]
if aa[i - 1] < aa[i]:
li = intervals[i - 1]
decCount(li[1] - li[0] + 1)
inter = mergeIntervals(li, inter)
if aa[i] > aa[i + 1]:
ri = intervals[i + 1]
decCount(ri[1] - ri[0] + 1)
inter = mergeIntervals(ri, inter)
intervals[inter[0]] = inter
intervals[inter[1]] = inter
incCount(inter[1] - inter[0] + 1)
if len(lengths) == 1:
count = list(lengths.values())[0]
if count > maxLocations:
maxLocations = count
ans = v + 1
#print(v + 1, count)
print(ans)
| {
"input": [
"8\n1 2 7 3 4 8 5 6\n",
"6\n25 1 2 3 14 36\n"
],
"output": [
"7\n",
"2\n"
]
} |
2,259 | 7 | Alice and Bob are playing chess on a huge chessboard with dimensions n Γ n. Alice has a single piece left β a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers.
But Bob has made a devious plan to seize the victory for himself β he needs to march his king to (c_x, c_y) in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.
Bob will win if he can move his king from (b_x, b_y) to (c_x, c_y) without ever getting in check. Remember that a king can move to any of the 8 adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen.
Find whether Bob can win or not.
Input
The first line contains a single integer n (3 β€ n β€ 1000) β the dimensions of the chessboard.
The second line contains two integers a_x and a_y (1 β€ a_x, a_y β€ n) β the coordinates of Alice's queen.
The third line contains two integers b_x and b_y (1 β€ b_x, b_y β€ n) β the coordinates of Bob's king.
The fourth line contains two integers c_x and c_y (1 β€ c_x, c_y β€ n) β the coordinates of the location that Bob wants to get to.
It is guaranteed that Bob's king is currently not in check and the target location is not in check either.
Furthermore, the king is not located on the same square as the queen (i.e. a_x β b_x or a_y β b_y), and the target does coincide neither with the queen's position (i.e. c_x β a_x or c_y β a_y) nor with the king's position (i.e. c_x β b_x or c_y β b_y).
Output
Print "YES" (without quotes) if Bob can get from (b_x, b_y) to (c_x, c_y) without ever getting in check, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
8
4 4
1 3
3 1
Output
YES
Input
8
4 4
2 3
1 6
Output
NO
Input
8
3 5
1 2
6 1
Output
NO
Note
In the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.
In the first case, the king can move, for instance, via the squares (2, 3) and (3, 2). Note that the direct route through (2, 2) goes through check.
<image>
In the second case, the queen watches the fourth rank, and the king has no means of crossing it.
<image>
In the third case, the queen watches the third file.
<image> | def r():return map(int,input().split(' '))
input()
ax,ay=r()
bx,by=r()
cx,cy=r()
print(['NO', 'YES'][(cx<ax)==(bx<ax)and(cy<ay)==(by<ay)]) | {
"input": [
"8\n4 4\n2 3\n1 6\n",
"8\n3 5\n1 2\n6 1\n",
"8\n4 4\n1 3\n3 1\n"
],
"output": [
"NO\n",
"NO\n",
"YES\n"
]
} |
2,260 | 12 | The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th picture has beauty a_i.
Vova wants to repost exactly x pictures in such a way that:
* each segment of the news feed of at least k consecutive pictures has at least one picture reposted by Vova;
* the sum of beauty values of reposted pictures is maximum possible.
For example, if k=1 then Vova has to repost all the pictures in the news feed. If k=2 then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
Input
The first line of the input contains three integers n, k and x (1 β€ k, x β€ n β€ 5000) β the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the beauty of the i-th picture.
Output
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.
Otherwise print one integer β the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
Examples
Input
5 2 3
5 1 3 10 1
Output
18
Input
6 1 5
10 30 30 70 10 10
Output
-1
Input
4 3 1
1 100 1 1
Output
100 | n, k, x = map(int, input().split())
a = [None] + list(map(int, input().split()))
lo, hi = 0, 10 ** 9 * 5000
q = [None] * (n + 1)
def get(mid):
f, r = 0, 0
q[0] = 0, 0, 0
for i in range(1, n + 1):
if q[r][2] == i - k - 1: r += 1
cur = q[r][0] + a[i] - mid, q[r][1] + 1, i
while r <= f and q[f] <= cur: f -= 1
f += 1
q[f] = cur
if q[r][2] == n - k: r += 1
return q[r]
while lo < hi:
mid = (lo + hi + 1) >> 1
_, cnt, _ = get(mid)
if cnt >= x:
lo = mid
else:
hi = mid - 1
sm, _, _ = get(lo)
ans = max(-1, sm + x * lo)
print(ans)
| {
"input": [
"4 3 1\n1 100 1 1\n",
"5 2 3\n5 1 3 10 1\n",
"6 1 5\n10 30 30 70 10 10\n"
],
"output": [
"100\n",
"18\n",
"-1\n"
]
} |
2,261 | 10 | A frog is initially at position 0 on the number line. The frog has two positive integers a and b. From a position k, it can either jump to position k+a or k-b.
Let f(x) be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval [0, x]. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from 0.
Given an integer m, find β_{i=0}^{m} f(i). That is, find the sum of all f(i) for i from 0 to m.
Input
The first line contains three integers m, a, b (1 β€ m β€ 10^9, 1 β€ a,b β€ 10^5).
Output
Print a single integer, the desired sum.
Examples
Input
7 5 3
Output
19
Input
1000000000 1 2019
Output
500000001500000001
Input
100 100000 1
Output
101
Input
6 4 5
Output
10
Note
In the first example, we must find f(0)+f(1)+β¦+f(7). We have f(0) = 1, f(1) = 1, f(2) = 1, f(3) = 1, f(4) = 1, f(5) = 3, f(6) = 3, f(7) = 8. The sum of these values is 19.
In the second example, we have f(i) = i+1, so we want to find β_{i=0}^{10^9} i+1.
In the third example, the frog can't make any jumps in any case. | M, a, b = map(int, input().split())
mod = 10**9+7
D = [mod]*a
maxi = 0
D[0] = 0
Q = [0]
def f(x, i):
t = (x+1-i)//a
r = (x+1-i)%a
return a*t*(t+1)//2+r*(t+1)
while Q:
q = Q.pop()
D[q] = maxi
k = max(0, -((-(b-q))//a))
maxi = max(maxi, q+k*a)
if D[(q-b)%a] == mod and maxi <= M:
Q.append((q-b)%a)
ans = 0
for i, d in enumerate(D):
if d > M:
continue
ans += f(M, i) - f(d-1, i)
print(ans) | {
"input": [
"1000000000 1 2019\n",
"7 5 3\n",
"6 4 5\n",
"100 100000 1\n"
],
"output": [
"500000001500000001\n",
"19\n",
"10\n",
"101\n"
]
} |
2,262 | 10 | A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.
We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the 2-nd pair lies inside the 1-st one, the 3-rd one β inside the 2-nd one and so on. For example, nesting depth of "" is 0, "()()()" is 1 and "()((())())" is 3.
Now, you are given RBS s of even length n. You should color each bracket of s into one of two colors: red or blue. Bracket sequence r, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets b, should be RBS. Any of them can be empty. You are not allowed to reorder characters in s, r or b. No brackets can be left uncolored.
Among all possible variants you should choose one that minimizes maximum of r's and b's nesting depth. If there are multiple solutions you can print any of them.
Input
The first line contains an even integer n (2 β€ n β€ 2 β
10^5) β the length of RBS s.
The second line contains regular bracket sequence s (|s| = n, s_i β \{"(", ")"\}).
Output
Print single string t of length n consisting of "0"-s and "1"-s. If t_i is equal to 0 then character s_i belongs to RBS r, otherwise s_i belongs to b.
Examples
Input
2
()
Output
11
Input
4
(())
Output
0101
Input
10
((()())())
Output
0110001111
Note
In the first example one of optimal solutions is s = "\color{blue}{()}". r is empty and b = "()". The answer is max(0, 1) = 1.
In the second example it's optimal to make s = "\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}". r = b = "()" and the answer is 1.
In the third example we can make s = "\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}". r = "()()" and b = "(()())" and the answer is 2. | def gns():
return [int(x)for x in input().split()]
# n=int(input())
# ns=gns()
n=int(input())
s=input()
d=0
for c in s:
if c=='(':
d+=1
print(d%2,end='')
else:
print(d%2,end='')
d-=1
print()
| {
"input": [
"2\n()\n",
"4\n(())\n",
"10\n((()())())\n"
],
"output": [
"00\n",
"0110\n",
"0100001110\n"
]
} |
2,263 | 10 | The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 β€ l β€ r β€ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} β¦ s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} β¦ t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, β¦, i_k such that i_1 < i_2 < β¦ < i_k and p_{i_1} β€ p_{i_2} β€ β¦ β€ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 10^5.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one. | import sys
input = sys.stdin.readline
def solve():
i = 0
s = list(input().strip())
st = []
for c in s:
if c == '1':
st.append(i)
elif len(st) > 0:
st.pop()
i += 1
for i in st:
s[i] = '0'
print(''.join(s))
solve()
| {
"input": [
"110\n",
"0001111\n",
"010\n",
"0111001100111011101000\n"
],
"output": [
"010",
"0000000",
"010",
"0011001100001011101000"
]
} |
2,264 | 9 | You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.
So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.
You are a coach at a very large university and you know that c of your students are coders, m are mathematicians and x have no specialization.
What is the maximum number of full perfect teams you can distribute them into?
Note that some students can be left without a team and each student can be a part of no more than one team.
You are also asked to answer q independent queries.
Input
The first line contains a single integer q (1 β€ q β€ 10^4) β the number of queries.
Each of the next q lines contains three integers c, m and x (0 β€ c, m, x β€ 10^8) β the number of coders, mathematicians and students without any specialization in the university, respectively.
Note that the no student is both coder and mathematician at the same time.
Output
Print q integers β the i-th of them should be the answer to the i query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.
Example
Input
6
1 1 1
3 6 0
0 0 0
0 1 1
10 1 10
4 4 1
Output
1
3
0
0
1
3
Note
In the first example here are how teams are formed:
1. the only team of 1 coder, 1 mathematician and 1 without specialization;
2. all three teams consist of 1 coder and 2 mathematicians;
3. no teams can be formed;
4. no teams can be formed;
5. one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team;
6. one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians. | def ans(c,m,x):
print(min(c,m,(c+m+x)//3))
n=int(input())
for _ in range(n):
c,m,x=map(int,input().split())
ans(c,m,x) | {
"input": [
"6\n1 1 1\n3 6 0\n0 0 0\n0 1 1\n10 1 10\n4 4 1\n"
],
"output": [
"1\n3\n0\n0\n1\n3\n"
]
} |
2,265 | 10 | There are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) denote the debt of a towards b, or 0 if there is no such debt.
Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money.
When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:
1. Let d(a,b) > 0 and d(c,d) > 0 such that a β c or b β d. We can decrease the d(a,b) and d(c,d) by z and increase d(c,b) and d(a,d) by z, where 0 < z β€ min(d(a,b),d(c,d)).
2. Let d(a,a) > 0. We can set d(a,a) to 0.
The total debt is defined as the sum of all debts:
$$$\Sigma_d = β_{a,b} d(a,b)$$$
Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.
Input
The first line contains two space separated integers n (1 β€ n β€ 10^5) and m (0 β€ m β€ 3β
10^5), representing the number of people and the number of debts, respectively.
m lines follow, each of which contains three space separated integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), d_i (1 β€ d_i β€ 10^9), meaning that the person u_i borrowed d_i burles from person v_i.
Output
On the first line print an integer m' (0 β€ m' β€ 3β
10^5), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint.
After that print m' lines, i-th of which contains three space separated integers u_i, v_i, d_i, meaning that the person u_i owes the person v_i exactly d_i burles. The output must satisfy 1 β€ u_i, v_i β€ n, u_i β v_i and 0 < d_i β€ 10^{18}.
For each pair i β j, it should hold that u_i β u_j or v_i β v_j. In other words, each pair of people can be included at most once in the output.
Examples
Input
3 2
1 2 10
2 3 5
Output
2
1 2 5
1 3 5
Input
3 3
1 2 10
2 3 15
3 1 10
Output
1
2 3 5
Input
4 2
1 2 12
3 4 8
Output
2
1 2 12
3 4 8
Input
3 4
2 3 1
2 3 2
2 3 4
2 3 8
Output
1
2 3 15
Note
In the first example the optimal sequence of operations can be the following:
1. Perform an operation of the first type with a = 1, b = 2, c = 2, d = 3 and z = 5. The resulting debts are: d(1, 2) = 5, d(2, 2) = 5, d(1, 3) = 5, all other debts are 0;
2. Perform an operation of the second type with a = 2. The resulting debts are: d(1, 2) = 5, d(1, 3) = 5, all other debts are 0.
In the second example the optimal sequence of operations can be the following:
1. Perform an operation of the first type with a = 1, b = 2, c = 3, d = 1 and z = 10. The resulting debts are: d(3, 2) = 10, d(2, 3) = 15, d(1, 1) = 10, all other debts are 0;
2. Perform an operation of the first type with a = 2, b = 3, c = 3, d = 2 and z = 10. The resulting debts are: d(2, 2) = 10, d(3, 3) = 10, d(2, 3) = 5, d(1, 1) = 10, all other debts are 0;
3. Perform an operation of the second type with a = 2. The resulting debts are: d(3, 3) = 10, d(2, 3) = 5, d(1, 1) = 10, all other debts are 0;
4. Perform an operation of the second type with a = 3. The resulting debts are: d(2, 3) = 5, d(1, 1) = 10, all other debts are 0;
5. Perform an operation of the second type with a = 1. The resulting debts are: d(2, 3) = 5, all other debts are 0. |
import sys
import collections
import heapq
import math
import bisect
input = sys.stdin.readline
def rints(): return map(int, input().strip().split())
def rstr(): return input().strip()
def rint(): return int(input().strip())
def rintas(): return [int(i) for i in input().strip().split()]
def gcd(a, b):
if (b == 0):
return a
return gcd(b, a%b)
n, m = rints()
d = [0 for i in range(n)]
for _ in range(m):
u, v, k = rints()
d[u-1] += k
d[v-1] -= k
ans = []
j = 0
for i in range(n):
while d[i] > 0:
while j < n and d[j] >= 0:
j += 1
loan = min(d[i], -d[j])
ans.append((i+1,j+1,loan))
d[i] -= loan
d[j] += loan
print(len(ans))
for i in ans:
print(i[0], i[1], i[2])
| {
"input": [
"3 2\n1 2 10\n2 3 5\n",
"3 3\n1 2 10\n2 3 15\n3 1 10\n",
"3 4\n2 3 1\n2 3 2\n2 3 4\n2 3 8\n",
"4 2\n1 2 12\n3 4 8\n"
],
"output": [
"2\n1 2 5\n1 3 5\n",
"1\n2 3 5\n",
"1\n2 3 15\n",
"2\n1 2 12\n3 4 8\n"
]
} |
2,266 | 8 | There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
She nearly ran out of rhymes.
Input
The input contains a single integer a (4 β€ a β€ 998). Not every integer in the range is a valid input for the problem; you are guaranteed that the input will be a valid integer.
Output
Output a single number.
Examples
Input
35
Output
57
Input
57
Output
319
Input
391
Output
1723 | n=int(input())
def a(n):
for i in range(2,n):
if(n%i==0):
return i
return 1
print(str(a(n))+""+str(n//a(n))) | {
"input": [
"391\n",
"57\n",
"35\n"
],
"output": [
"1723",
"319",
"57"
]
} |
2,267 | 8 | A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 β€ k β€ r, and set k days as the number of days in a week.
Alice is going to paint some n consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.
She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.
Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.
For example, in the picture, a week has 4 days and Alice paints 5 consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.
<image>
Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive n days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases. Next t lines contain descriptions of test cases.
For each test case, the only line contains two integers n, r (1 β€ n β€ 10^9, 1 β€ r β€ 10^9).
Output
For each test case, print a single integer β the answer to the problem.
Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language.
Example
Input
5
3 4
3 2
3 1
13 7
1010000 9999999
Output
4
3
1
28
510049495001
Note
In the first test case, Alice can set 1,2,3 or 4 days as the number of days in a week.
There are 6 possible paintings shown in the picture, but there are only 4 different shapes. So, the answer is 4. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides.
<image>
In the last test case, be careful with the overflow issue, described in the output format. | def solve():
n, r = map(int, input().split())
k = min(r, n - 1)
print(k * (k + 1) // 2 + (r >= n))
for i in range(int(input())):
solve()
| {
"input": [
"5\n3 4\n3 2\n3 1\n13 7\n1010000 9999999\n"
],
"output": [
"4\n3\n1\n28\n510049495001\n"
]
} |
2,268 | 10 | Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates.
Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different x coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some x and move all piles from x to x+1 or x-1 using his broom. Note that he can't choose how many piles he will move.
Also, there are two types of queries:
* 0 x β remove a pile of trash from the coordinate x. It is guaranteed that there is a pile in the coordinate x at this moment.
* 1 x β add a pile of trash to the coordinate x. It is guaranteed that there is no pile in the coordinate x at this moment.
Note that it is possible that there are zero piles of trash in the room at some moment.
Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.
For better understanding, please read the Notes section below to see an explanation for the first example.
Input
The first line of the input contains two integers n and q (1 β€ n, q β€ 10^5) β the number of piles in the room before all queries and the number of queries, respectively.
The second line of the input contains n distinct integers p_1, p_2, ..., p_n (1 β€ p_i β€ 10^9), where p_i is the coordinate of the i-th pile.
The next q lines describe queries. The i-th query is described with two integers t_i and x_i (0 β€ t_i β€ 1; 1 β€ x_i β€ 10^9), where t_i is 0 if you need to remove a pile from the coordinate x_i and is 1 if you need to add a pile to the coordinate x_i. It is guaranteed that for t_i = 0 there is such pile in the current set of piles and for t_i = 1 there is no such pile in the current set of piles.
Output
Print q+1 integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of q queries.
Examples
Input
5 6
1 2 6 8 10
1 4
1 9
0 6
0 10
1 100
1 50
Output
5
7
7
5
4
8
49
Input
5 8
5 1 2 4 3
0 1
0 2
0 3
0 4
0 5
1 1000000000
1 1
1 500000000
Output
3
2
1
0
0
0
0
0
499999999
Note
Consider the first example.
Initially, the set of piles is [1, 2, 6, 8, 10]. The answer before the first query is 5 because you can move all piles from 1 to 2 with one move, all piles from 10 to 8 with 2 moves and all piles from 6 to 8 with 2 moves.
After the first query, the set becomes [1, 2, 4, 6, 8, 10]. Then the answer is 7 because you can move all piles from 6 to 4 with 2 moves, all piles from 4 to 2 with 2 moves, all piles from 2 to 1 with 1 move and all piles from 10 to 8 with 2 moves.
After the second query, the set of piles becomes [1, 2, 4, 6, 8, 9, 10] and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).
After the third query, the set of piles becomes [1, 2, 4, 8, 9, 10] and the answer is 5 because you can move all piles from 1 to 2 with 1 move, all piles from 2 to 4 with 2 moves, all piles from 10 to 9 with 1 move and all piles from 9 to 8 with 1 move.
After the fourth query, the set becomes [1, 2, 4, 8, 9] and the answer is almost the same (the previous sequence of moves can be applied without moving piles from 10).
After the fifth query, the set becomes [1, 2, 4, 8, 9, 100]. You can move all piles from 1 and further to 9 and keep 100 at its place. So the answer is 8.
After the sixth query, the set becomes [1, 2, 4, 8, 9, 50, 100]. The answer is 49 and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from 50 to 9 too. | def get(t, l, r):
l += len(t)//2
r += len(t)//2
res = -1
while l <= r:
if l % 2 == 1:
res = max(res, t[l])
if r % 2 == 0:
res = max(res, t[r])
l = (l + 1) // 2
r = (r - 1) // 2
return res
def change(t, x, v):
x += len(t)//2
t[x] = v
while x > 1:
x //= 2
t[x] = max(t[x*2],t[x*2+1])
def build(t):
for x in range(len(t)//2 - 1, 0, -1):
t[x] = max(t[x*2],t[x*2+1])
def solve():
n, q = map(int,input().split())
p = list(map(int,input().split()))
all_x = p[::]
qe = [None]*q
for i in range(q):
t, x = map(int,input().split())
qe[i] = (t,x)
all_x.append(x)
all_x.append(0)
all_x.append(int(1e9)+1)
all_x.sort()
id_x = dict()
allx = []
idn = 0
for i in all_x:
if i not in id_x:
id_x[i] = idn
idn += 1
allx.append(i)
#print(allx)
#print(id_x)
m = idn
nnext = [-1]*m
pprev = [-1]*m
z = [0]*m
nnext[0] = m-1
pprev[m-1] = 0
have = [-1]*(m*2)
have[m-1] = m-1
cnt = [0]*(m*2)
build(have)
change(have, 0, 0)
build(cnt)
for x in set(p):
# add
xi = id_x[x]
pr = get(have, 0, xi)
nz = x - allx[pr]
change(cnt, pr, nz)
change(have, xi, xi)
ne = nnext[pr]
change(cnt, xi, allx[ne] - x)
nnext[pr] = xi
nnext[xi] = ne
pprev[xi] = pr
pprev[ne] = xi
#print(cnt[m:2*m])
#print(have[m:2*m])
#print(nnext)
#print('===')
if nnext[0] == m-1:
print(0) # 0 piles
else:
ne = nnext[0]
pr = pprev[m-1]
if ne == pr:
print(0) # single pile
else:
#print(ne,pr,get(cnt,ne,pr-1))
print(allx[pr]-allx[ne]-get(cnt,ne,pr-1))
for t, x in qe:
xi = id_x[x]
if t == 0:
# remove
ne = nnext[xi]
pr = pprev[xi]
change(have, xi, -1)
change(cnt, xi, 0)
change(cnt, pr, allx[ne]-allx[pr])
nnext[pr] = ne
pprev[ne] = pr
else:
# add
pr = get(have, 0, xi)
nz = x - allx[pr]
change(cnt, pr, nz)
change(have, xi, xi)
ne = nnext[pr]
change(cnt, xi, allx[ne] - x)
nnext[pr] = xi
nnext[xi] = ne
pprev[xi] = pr
pprev[ne] = xi
#print(cnt[m:2*m])
#print(have[m:2*m])
#print(nnext)
#print('===')
if nnext[0] == m-1:
print(0) # 0 piles
else:
ne = nnext[0]
pr = pprev[m-1]
if ne == pr:
print(0) # single pile
else:
#print(ne,pr,get(cnt,ne,pr-1))
print(allx[pr]-allx[ne]-get(cnt,ne,pr-1))
solve() | {
"input": [
"5 8\n5 1 2 4 3\n0 1\n0 2\n0 3\n0 4\n0 5\n1 1000000000\n1 1\n1 500000000\n",
"5 6\n1 2 6 8 10\n1 4\n1 9\n0 6\n0 10\n1 100\n1 50\n"
],
"output": [
"3\n2\n1\n0\n0\n0\n0\n0\n499999999\n",
"5\n7\n7\n5\n4\n8\n49\n"
]
} |
2,269 | 9 | Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows:
<image>
Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).
Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x!
Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order.
Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7.
Input
The only line of input contains integers n, x and pos (1 β€ x β€ n β€ 1000, 0 β€ pos β€ n - 1) β the required length of the permutation, the number to search, and the required position of that number, respectively.
Output
Print a single number β the remainder of the division of the number of valid permutations by 10^9+7.
Examples
Input
4 1 2
Output
6
Input
123 42 24
Output
824071958
Note
All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). |
def binarysearch(n,pos ,x):
left = 0
right = n
ans=1
l=0
r=0
while left <right :
middle =(left+right)//2
if middle < pos :
r+=1
left = middle+1
elif middle == pos :
left = middle+1
else:
right = middle
l+=1
for i in range(l):
ans*=(n-x-i)
for i in range(r):
ans*=(x-i-1)
for i in range(1,n-l-r):
ans*=i
return ans%((10**9)+7)
n,x,pos = map(int,input().split())
print(binarysearch(n,pos,x))
| {
"input": [
"4 1 2\n",
"123 42 24\n"
],
"output": [
"6",
"824071958"
]
} |
2,270 | 7 | One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules:
* the string may only contain characters 'a', 'b', or 'c';
* the maximum length of a substring of this string that is a palindrome does not exceed k.
<image>
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. For example, strings "a", "bc", "abc" are substrings of a string "abc", while strings "ac", "ba", "cba" are not.
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings "abccba", "abbba", "aba", "abacaba", "a", and "bacab" are palindromes, while strings "abcbba", "abb", and "ab" are not.
Now Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 10).
The only line of each test case contains two integers n and k (1 β€ k β€ n β€ 1 000) β the required string length and the maximum length of a palindrome substring, respectively.
Output
For each test case, print any string that satisfies the conditions from the problem statement. If there are multiple correct answers, you can print any one of them. It can be proven that the answer always exists under the given constraints.
Example
Input
2
3 2
4 1
Output
aab
acba
Note
In the first test case of the example, the palindrome substring with the maximum length is "aa". Its length does not exceed 2, so it fits.
In the second test case all palindrome substrings have the length one. | def answer():
return 'a'*k + 'bca'*((n-k)//3) + 'bca'[:(n-k)%3]
for T in range(int(input())):
n,k=map(int,input().split())
print(answer())
| {
"input": [
"2\n3 2\n4 1\n"
],
"output": [
"\naab\nacba\n"
]
} |
2,271 | 8 | You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|, where |x| is the absolute value of x.
Input
First line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 1000). Next n lines describe the positions of the houses (x_i, y_i) (0 β€ x_i, y_i β€ 10^9).
It's guaranteed that the sum of all n does not exceed 1000.
Output
For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.
Example
Input
6
3
0 0
2 0
1 2
4
1 0
0 2
2 3
3 1
4
0 0
0 1
1 0
1 1
2
0 0
1 1
2
0 0
2 0
2
0 0
0 0
Output
1
4
4
4
3
1
Note
Here are the images for the example test cases. Blue dots stand for the houses, green β possible positions for the exhibition.
<image>
First test case.
<image>
Second test case. <image>
Third test case. <image>
Fourth test case. <image>
Fifth test case. <image>
Sixth test case. Here both houses are located at (0, 0). | def solve(arr):
arr.sort()
n = len(arr)
return arr[n//2] - arr[(n-1)//2] + 1
for _ in range(int(input())):
n = int(input())
x , y = [0]*n , [0]*n
for i in range(n):
x[i] , y[i] = map(int,input().split())
print(solve(x)*solve(y))
| {
"input": [
"6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0\n"
],
"output": [
"\n1\n4\n4\n4\n3\n1\n"
]
} |
2,272 | 10 | Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, β¦, a_{2k-1}, is the array b with elements b_1, b_2, β¦, b_{k} such that b_i is equal to the median of a_1, a_2, β¦, a_{2i-1} for all i. Omkar has found an array b of size n (1 β€ n β€ 2 β
10^5, -10^9 β€ b_i β€ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray?
The median of a set of numbers a_1, a_2, β¦, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, β¦, c_{2i-1} represents a_1, a_2, β¦, a_{2i-1} sorted in nondecreasing order.
Input
Each test contains multiple test cases. The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases. Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 2 β
10^5) β the length of the array b.
The second line contains n integers b_1, b_2, β¦, b_n (-10^9 β€ b_i β€ 10^9) β the elements of b.
It is guaranteed the sum of n across all test cases does not exceed 2 β
10^5.
Output
For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).
Examples
Input
5
4
6 2 1 3
1
4
5
4 -8 5 6 -7
2
3 3
4
2 1 2 3
Output
NO
YES
NO
YES
YES
Input
5
8
-8 2 -6 -5 -4 3 3 2
7
1 1 3 1 0 -2 -1
7
6 12 8 6 2 6 10
6
5 1 2 3 6 7
5
1 3 4 3 0
Output
NO
YES
NO
NO
NO
Note
In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4.
In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3.
In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as
* the median of 2 is 2
* the median of 0, 1, 2 is 1
* the median of 0, 1, 2, 3, 4 is 2
* and the median of 0, 1, 2, 3, 3, 4, 4 is 3.
In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as
* the median of 1 is 1
* the median of 0, 1, 4 is 1
* the median of 0, 1, 3, 4, 5 is 3
* the median of -2, -2, 0, 1, 3, 4, 5 is 1
* the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0
* the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2
* and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1
For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a. | def solve(n, a):
prev = a[0]
r = [10 ** 9]
l = [-r[0]]
for i in range(1, n):
if a[i] < prev:
if a[i] < l[-1]:
return False
elif a[i] == l[-1]:
l.pop()
r.append(prev)
elif a[i] > prev:
if a[i] > r[-1]:
return False
elif a[i] == r[-1]:
r.pop()
l.append(prev)
prev = a[i]
return True
t = int(input())
for w in range(t):
n = int(input())
a = list(map(int, input().split()))
if solve(n, a):
print("YES")
else:
print("NO")
| {
"input": [
"5\n8\n-8 2 -6 -5 -4 3 3 2\n7\n1 1 3 1 0 -2 -1\n7\n6 12 8 6 2 6 10\n6\n5 1 2 3 6 7\n5\n1 3 4 3 0\n",
"5\n4\n6 2 1 3\n1\n4\n5\n4 -8 5 6 -7\n2\n3 3\n4\n2 1 2 3\n"
],
"output": [
"\nNO\nYES\nNO\nNO\nNO\n",
"\nNO\nYES\nNO\nYES\nYES\n"
]
} |
2,273 | 10 | It is well known that Berland has n cities, which form the Silver ring β cities i and i + 1 (1 β€ i < n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).
Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?
Input
The first line contains two integers n and m (4 β€ n β€ 100, 1 β€ m β€ 100). Each of the following m lines contains two integers ai and bi (1 β€ ai, bi β€ n, ai β bi). No two cities will be connected by more than one road in the list. The list will not contain the roads which exist in the Silver ring.
Output
If it is impossible to build the roads in such a way that no two roads intersect, output Impossible. Otherwise print m characters. i-th character should be i, if the road should be inside the ring, and o if the road should be outside the ring. If there are several solutions, output any of them.
Examples
Input
4 2
1 3
2 4
Output
io
Input
6 3
1 3
3 5
5 1
Output
ooo | def intersect(l1, r1, l2, r2):
if l1 <= l2 and r1 >= r2 or l2 <= l1 and r2 >= r1:
return False
if r2 <= r1 and l1 <= l2 and r2 <= l2:
return False
if l1 >= r2 and l1 >= l2 or r1 <= l2 and r1 <= r2:
return False
return True
def ans():
print(''.join(['i' if i == 0 else 'o' for i in color]))
def dfs(v, clr):
if color[v] != -1 and color[v] != clr:
print('Impossible')
exit(0)
if color[v] != -1:
return
color[v] = clr
for u in graph[v]:
dfs(u, 1 - clr)
n, m = map(int, input().split())
graph = [[] for i in range(m)]
vedge = []
color = [-1] * m
for i in range(m):
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
for j, v in enumerate(vedge):
if intersect(a, b, v[0], v[1]):
graph[i].append(j)
graph[j].append(i)
vedge.append((a, b))
for i in range(m):
if color[i] == -1:
dfs(i, 0)
ans()
| {
"input": [
"4 2\n1 3\n2 4\n",
"6 3\n1 3\n3 5\n5 1\n"
],
"output": [
"io\n",
"iii\n"
]
} |
2,274 | 8 | Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k β₯ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 β€ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 β€ n β€ 105) β the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen β the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 β€ ai β€ n) β the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k β the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk β the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | #!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
t = (-1,) + readln()
v = (0,) + readln()
cnt = [0] * (n + 1)
for i in range(1, n + 1):
cnt[v[i]] += 1
ans = []
for i in range(1, n + 1):
if t[i] == 1:
j = i
tmp = [i]
while(t[v[j]] == 0) and cnt[v[j]] == 1:
j = v[j]
tmp.append(j)
if(len(tmp) > len(ans)):
ans = tmp
print(len(ans))
print(*tuple(reversed(ans)))
| {
"input": [
"5\n0 0 1 0 1\n0 1 2 2 4\n",
"5\n0 0 0 0 1\n0 1 2 3 4\n",
"4\n1 0 0 0\n2 3 4 2\n"
],
"output": [
"2\n4 5\n",
"5\n1 2 3 4 5\n",
"1\n1\n"
]
} |
2,275 | 9 | Inna and Dima bought a table of size n Γ m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".
Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:
1. initially, Inna chooses some cell of the table where letter "D" is written;
2. then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name;
3. Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D".
Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 103).
Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A".
Note that it is not guaranteed that the table contains at least one letter "D".
Output
If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer β the maximum number of times Inna can go through name DIMA.
Examples
Input
1 2
DI
Output
Poor Dima!
Input
2 2
MA
ID
Output
Poor Inna!
Input
5 5
DIMAD
DIMAI
DIMAM
DDMAA
AAMID
Output
4
Note
Notes to the samples:
In the first test sample, Inna cannot go through name DIMA a single time.
In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.
In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times. | import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,6)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
n, m = L()
m += 1
q = {'I': 0, 'M': 1, 'A': 2, 'D': 3}
t = []
for i in range(n):
t += map(q.get, input())
t.append(-7)
t += [-7] * m
# print(t)
p = [[] for q in t]
c = [0] * len(t)
for a in range(n * m):
for b in (a - m, a + m, a - 1, a + 1):
if abs(t[b] - t[a] + 1) == 2:
p[a].append(b)
c[b] += 1
s = [i for i, q in enumerate(c) if not q]
while s:
a = s.pop()
for b in p[a]:
t[b] = max(t[b], t[a] + 1)
c[b] -= 1
if c[b] == 0: s.append(b)
k = max(t) - 2 >> 2
print('Poor Inna!' if any(c) else k if k > 0 else 'Poor Dima!')
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
| {
"input": [
"5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID\n",
"1 2\nDI\n",
"2 2\nMA\nID\n"
],
"output": [
"4",
"Poor Dima!\n",
"Poor Inna!\n"
]
} |
2,276 | 7 | The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the Β«translationΒ». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output
If the word t is a word s, written reversely, print YES, otherwise print NO.
Examples
Input
code
edoc
Output
YES
Input
abb
aba
Output
NO
Input
code
code
Output
NO | def main():
x = input()
y = input()
print("YES") if x == y[-1::-1] else print("NO")
main()
| {
"input": [
"code\nedoc\n",
"abb\naba\n",
"code\ncode\n"
],
"output": [
"YES\n",
"NO\n",
"NO\n"
]
} |
2,277 | 7 | Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of disks on the combination lock.
The second line contains a string of n digits β the original state of the disks.
The third line contains a string of n digits β Scrooge McDuck's combination that opens the lock.
Output
Print a single integer β the minimum number of moves Scrooge McDuck needs to open the lock.
Examples
Input
5
82195
64723
Output
13
Note
In the sample he needs 13 moves:
* 1 disk: <image>
* 2 disk: <image>
* 3 disk: <image>
* 4 disk: <image>
* 5 disk: <image> | def m(a, b):
k = abs(a - b)
return min(k, 10 - k)
input()
print(sum(m(int(d1), int(d2)) for d1, d2 in zip(input(), input()))) | {
"input": [
"5\n82195\n64723\n"
],
"output": [
"13\n"
]
} |
2,278 | 8 | Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set Ο of pairs (a, b) of elements of some set A is called a binary relation on set A. For two elements a and b of the set A we say that they are in relation Ο, if pair <image>, in this case we use a notation <image>.
Binary relation is equivalence relation, if:
1. It is reflexive (for any a it is true that <image>);
2. It is symmetric (for any a, b it is true that if <image>, then <image>);
3. It is transitive (if <image> and <image>, than <image>).
Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof":
Take any two elements, a and b. If <image>, then <image> (according to property (2)), which means <image> (according to property (3)).
It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong.
Here's your task: count the number of binary relations over a set of size n such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).
Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 109 + 7.
Input
A single line contains a single integer n (1 β€ n β€ 4000).
Output
In a single line print the answer to the problem modulo 109 + 7.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
10
Note
If n = 1 there is only one such relation β an empty one, i.e. <image>. In other words, for a single element x of set A the following is hold: <image>.
If n = 2 there are three such relations. Let's assume that set A consists of two elements, x and y. Then the valid relations are <image>, Ο = {(x, x)}, Ο = {(y, y)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations. | def main():
mod = 10 ** 9 + 7
n = int(input())
a = [[0] * (n + 1) for i in range(n + 1)]
a[0][0] = 1
for i in range(1, n + 1):
a[i][0] = a[i - 1][i - 1]
for j in range(1, i + 1):
a[i][j] = (a[i][j - 1] + a[i - 1][j - 1]) % mod
print(a[n][n - 1])
main() | {
"input": [
"2\n",
"3\n",
"1\n"
],
"output": [
"3\n",
"10\n",
"1\n"
]
} |
2,279 | 8 | The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system β 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?
Assume that all positive integers are always written without leading zeros.
Input
The only line of the input contains two integers a and b (1 β€ a β€ b β€ 1018) β the first year and the last year in Limak's interval respectively.
Output
Print one integer β the number of years Limak will count in his chosen interval.
Examples
Input
5 10
Output
2
Input
2015 2015
Output
1
Input
100 105
Output
0
Input
72057594000000000 72057595000000000
Output
26
Note
In the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and 1010 = 10102. Two of them (1012 and 1102) have the described property. | def z(n):
n = bin(n)[2:]
k = len(n) - 1
r = n.find("0")
s = k * (k-1) // 2 + (n.count("0") == 1)
s += k if r == -1 else r-1
return s;
a, b = map(int, input().split());
print (z(b) - z(a - 1)) | {
"input": [
"72057594000000000 72057595000000000\n",
"100 105\n",
"5 10\n",
"2015 2015\n"
],
"output": [
"26\n",
"0\n",
"2\n",
"1\n"
]
} |
2,280 | 8 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.
So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.
Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.
Input
The first input line contains an integer n (1 β€ n β€ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 β€ yi β€ 9999).
Output
Print n numbers z1, z2, ..., zn (1000 β€ zi β€ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).
Examples
Input
3
1875
1936
1721
Output
1835
1836
1921
Input
4
9999
2000
3000
3011
Output
1999
2000
2000
2011
Input
3
1999
5055
2000
Output
No solution | def f(t, s):
r = '2012'
x, y = '1' + t[1: ], '2' + t[1: ]
if x >= s: r = x
elif r > y >= s: r = y
if t[0] > '2': return r
for i in range(1, 4):
a, b = t[: i], t[i + 1: ]
x, y = a + '0' + b, a + '9' + b
if y >= s and x < r:
if x < s:
x = a + s[i] + b
if x < s: x = a + str(int(s[i]) + 1) + b
r = x
return r
n = int(input())
t = ['2012'] * n
t[0] = f(input(), '1000')
for i in range(1, n):
t[i] = f(input(), t[i - 1])
if t[i] == '2012': break
if t[n - 1] == '2012': print('No solution')
else: print('\n'.join(t))
| {
"input": [
"3\n1999\n5055\n2000\n",
"4\n9999\n2000\n3000\n3011\n",
"3\n1875\n1936\n1721\n"
],
"output": [
"No solution",
"1999\n2000\n2000\n2011\n",
"1075\n1136\n1221\n"
]
} |
2,281 | 8 | Theater stage is a rectangular field of size n Γ m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) β left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
* there is no actor in the cell the spotlight is placed to;
* there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 1000) β the number of rows and the number of columns in the plan.
The next n lines contain m integers, 0 or 1 each β the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
Output
Print one integer β the number of good positions for placing the spotlight.
Examples
Input
2 4
0 1 0 0
1 0 1 0
Output
9
Input
4 4
0 0 0 0
1 0 0 1
0 1 1 0
0 1 0 0
Output
20
Note
In the first example the following positions are good:
1. the (1, 1) cell and right direction;
2. the (1, 1) cell and down direction;
3. the (1, 3) cell and left direction;
4. the (1, 3) cell and down direction;
5. the (1, 4) cell and left direction;
6. the (2, 2) cell and left direction;
7. the (2, 2) cell and up direction;
8. the (2, 2) and right direction;
9. the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example. | def go(s):
l,r=s.find('1'),s.rfind('1')
if l==-1:
return 0
else: return l +len(s)-r-1+2*sum(s[i]=='0' for i in range(l+1,r))
n,m=map(int,input().split())
a=[''.join(input().split()) for i in range(n)]
r=sum(go(s) for s in a)
c=sum(go(''.join(a[i][j] for i in range(n))) for j in range(m))
print(r+c)
| {
"input": [
"2 4\n0 1 0 0\n1 0 1 0\n",
"4 4\n0 0 0 0\n1 0 0 1\n0 1 1 0\n0 1 0 0\n"
],
"output": [
"9",
"20"
]
} |
2,282 | 9 | There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | # Author: Maharshi Gor
from collections import deque
def read(t:type=int):
return t(input())
def read_arr(t=int):
return [t(i) for i in str(input()).split()]
D = deque()
R = deque()
k = read()
S = input()
n = len(S)
for i in range(len(S)):
if S[i] == 'R':
R.append(i)
else:
D.append(i)
while R and D:
r = R.popleft()
d = D.popleft()
if r < d:
R.append(r+n)
else:
D.append(d+n)
if R:
print('R')
else:
print('D')
| {
"input": [
"5\nDDRRR\n",
"6\nDDRRRR\n"
],
"output": [
"D\n",
"R\n"
]
} |
2,283 | 8 | You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
Input
The first line has one integer n (4 β€ n β€ 1 000) β the number of vertices.
The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 β€ xi, yi β€ 109) β the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
Output
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4
0 0
0 1
1 1
1 0
Output
0.3535533906
Input
6
5 0
10 0
12 -4
10 -8
5 -8
3 -4
Output
1.0000000000
Note
Here is a picture of the first sample
<image>
Here is an example of making the polygon non-convex.
<image>
This is not an optimal solution, since the maximum distance we moved one point is β 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most β 0.3535533906. | n = int(input())
P = []
def h(p1, p2, m):
return abs(((p2[0] - p1[0])*(m[1] - p1[1])-(p2[1] - p1[1])*(m[0] - p1[0]))\
/((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1])**2) ** 0.5)
for i in range(n):
P.append(list(map(int, input().split())))
answer = float("inf")
for i in range(n):
cw = P[(i + 1) % n]
ucw = P[i - 1]
answer = min(answer, h(cw, ucw, P[i])/2)
print(answer)
| {
"input": [
"4\n0 0\n0 1\n1 1\n1 0\n",
"6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4\n"
],
"output": [
"0.353553391",
"1.000000000"
]
} |
2,284 | 8 | You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
You should write a program which finds sum of the best subsequence.
Input
The first line contains integer number n (1 β€ n β€ 105).
The second line contains n integer numbers a1, a2, ..., an ( - 104 β€ ai β€ 104). The sequence contains at least one subsequence with odd sum.
Output
Print sum of resulting subseqeuence.
Examples
Input
4
-2 2 -3 1
Output
3
Input
3
2 -5 -3
Output
-1
Note
In the first example sum of the second and the fourth elements is 3. | def odd_sum(lst):
k, m = 0, 10 ** 9
for elem in lst:
if elem >= 0:
k += elem
if k % 2:
return k
for elem in lst:
if elem % 2:
m = min(m, abs(elem))
return k - m
n = int(input())
a = [int(i) for i in input().split()]
print(odd_sum(a))
| {
"input": [
"3\n2 -5 -3\n",
"4\n-2 2 -3 1\n"
],
"output": [
"-1\n",
"3\n"
]
} |
2,285 | 10 | You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array:
* [1] (from index 1 to index 1), imbalance value is 0;
* [1, 4] (from index 1 to index 2), imbalance value is 3;
* [1, 4, 1] (from index 1 to index 3), imbalance value is 3;
* [4] (from index 2 to index 2), imbalance value is 0;
* [4, 1] (from index 2 to index 3), imbalance value is 3;
* [1] (from index 3 to index 3), imbalance value is 0;
You have to determine the imbalance value of the array a.
Input
The first line contains one integer n (1 β€ n β€ 106) β size of the array a.
The second line contains n integers a1, a2... an (1 β€ ai β€ 106) β elements of the array.
Output
Print one integer β the imbalance value of a.
Example
Input
3
1 4 1
Output
9 |
#taken from https://stackoverflow.com/questions/30698441/optimal-way-to-find-sums-of-all-contiguous-sub-arrays-max-difference
def max_sums(d):
stack = [(-1, float('inf'))]
sum_ = 0
for i, x in enumerate(d):
while x > stack[-1][1]:
prev_i, prev_x = stack.pop()
prev_prev_i, prev_prev_x = stack[-1]
sum_ += prev_x * (i - prev_i) * (prev_i - prev_prev_i)
stack.append((i, x))
while len(stack) > 1:
prev_i, prev_x = stack.pop()
prev_prev_i, prev_prev_x = stack[-1]
sum_ += prev_x * (len(d) - prev_i) * (prev_i - prev_prev_i)
return sum_
def max_differences_sum(d):
return max_sums(d) + max_sums([-x for x in d])
n=int(input())
l=list(map(int,input().split()))
print(max_differences_sum(l)) | {
"input": [
"3\n1 4 1\n"
],
"output": [
"9\n"
]
} |
2,286 | 10 | Today at the lesson Vitya learned a very interesting function β mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.
Vitya quickly understood all tasks of the teacher, but can you do the same?
You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps:
* Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x.
* Find mex of the resulting array.
Note that after each query the array changes.
Input
First line contains two integer numbers n and m (1 β€ n, m β€ 3Β·105) β number of elements in array and number of queries.
Next line contains n integer numbers ai (0 β€ ai β€ 3Β·105) β elements of then array.
Each of next m lines contains query β one integer number x (0 β€ x β€ 3Β·105).
Output
For each query print the answer on a separate line.
Examples
Input
2 2
1 3
1
3
Output
1
0
Input
4 3
0 1 5 6
1
2
4
Output
2
0
0
Input
5 4
0 1 5 6 7
1
1
4
5
Output
2
2
0
2 | # ------------------- 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 --------------------
class Trie:
class Node:
def __init__(self, char: bool = False):
self.char = char
self.children = []
self.counter = 1
def __init__(self):
self.root = Trie.Node()
def add(self, word):
node = self.root
for char in word:
found_in_child = False
for child in node.children:
if child.char == char:
child.counter += 1
node = child
found_in_child = True
break
if not found_in_child:
new_node = Trie.Node(char)
node.children.append(new_node)
node = new_node
def query(self, prefix, root=None):
if not root: root = self.root
node = root
if not root.children:
return 0
prefix = [prefix]
for char in prefix:
char_not_found = True
for child in node.children:
if child.char == char:
char_not_found = False
node = child
break
if char_not_found:
return 0
return node
n, m = map(int, input().split())
a = list(map(int, input().split()))
tr = Trie()
st = set()
for i in a:
if i in st:continue
else:st.add(i)
x = bin(i)[2:]
x = "0"*(20 - len(x)) + x
x = [True if k == "1" else False for k in x]
tr.add(x)
def f(x):
x = bin(x)[2:]
x = "0" * (20 - len(x)) + x
x = [True if k == "1" else False for k in x]
node = tr.root
ans = 0
for i in range(20):
cur = x[i]
next = tr.query(cur, node)
if next and next.counter == 2**(19-i):
node = tr.query(not cur, node)
ans += 2**(19-i)
else:
node = next
return ans
cur = -1
for _ in range(m):
if cur == -1:
cur = int(input())
else:
cur = cur ^ int(input())
print(f(cur)) | {
"input": [
"2 2\n1 3\n1\n3\n",
"5 4\n0 1 5 6 7\n1\n1\n4\n5\n",
"4 3\n0 1 5 6\n1\n2\n4\n"
],
"output": [
"1\n0\n",
"2\n2\n0\n2\n",
"2\n0\n0\n"
]
} |
2,287 | 10 | You are given an array a of size n, and q queries to it. There are queries of two types:
* 1 li ri β perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li β€ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari;
* 2 li ri β reverse the segment [li, ri].
There are m important indices in the array b1, b2, ..., bm. For each i such that 1 β€ i β€ m you have to output the number that will have index bi in the array after all queries are performed.
Input
The first line contains three integer numbers n, q and m (1 β€ n, q β€ 2Β·105, 1 β€ m β€ 100).
The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 109).
Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li, ri] is the segment where this query is performed (1 β€ ti β€ 2, 1 β€ li β€ ri β€ n).
The last line contains m integer numbers b1, b2, ..., bm (1 β€ bi β€ n) β important indices of the array.
Output
Print m numbers, i-th of which is equal to the number at index bi after all queries are done.
Example
Input
6 3 5
1 2 3 4 5 6
2 1 3
2 3 6
1 1 6
2 2 1 5 3
Output
3 3 1 5 2 | import sys
import math
from collections import defaultdict,deque
def get(ind ,arr):
n = len(arr)
for i in range(n):
t,l,r = arr[i]
if t == 1:
if l <= ind <= r:
if ind == l:
ind = r
else:
ind -= 1
continue
if t == 2:
if l <=ind <= r:
ind = (r - ind + l)
continue
return ind
n,q,m = map(int,sys.stdin.readline().split())
arr = list(map(int,sys.stdin.readline().split()))
l = []
for i in range(q):
a,b,c = map(int,sys.stdin.readline().split())
l.append([a,b,c])
l.reverse()
b = list(map(int,sys.stdin.readline().split()))
ans = []
for i in range(m):
x = get(b[i],l)
ans.append(arr[x -1])
print(*ans) | {
"input": [
"6 3 5\n1 2 3 4 5 6\n2 1 3\n2 3 6\n1 1 6\n2 2 1 5 3\n"
],
"output": [
"3 3 1 5 2 "
]
} |
2,288 | 7 | A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:
* If Petya has visited this room before, he writes down the minute he was in this room last time;
* Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β then number of notes in Petya's logbook.
The second line contains n non-negative integers t1, t2, ..., tn (0 β€ ti < i) β notes in the logbook.
Output
In the only line print a single integer β the minimum possible number of rooms in Paris catacombs.
Examples
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
Note
In the first sample, sequence of rooms Petya visited could be, for example 1 β 1 β 2, 1 β 2 β 1 or 1 β 2 β 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 β 2 β 3 β 1 β 2 β 1. | def main():
n, pool, res = int(input()), {0}, 1
for i, t in enumerate(map(int, input().split()), 1):
if t in pool:
pool.remove(t)
else:
res += 1
pool.add(i)
print(res)
if __name__ == '__main__':
main()
| {
"input": [
"2\n0 0\n",
"5\n0 1 0 1 3\n"
],
"output": [
"2\n",
"3\n"
]
} |
2,289 | 12 | You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps:
1. choose two leaves;
2. add the length of the simple path between them to the answer;
3. remove one of the chosen leaves from the tree.
Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex.
Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!
Input
The first line contains one integer number n (2 β€ n β€ 2Β·105) β the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form ai, bi (1 β€ ai, bi β€ n, ai β bi). It is guaranteed that given graph is a tree.
Output
In the first line print one integer number β maximal possible answer.
In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β pair of the leaves that are chosen in the current operation (1 β€ ai, bi β€ n), ci (1 β€ ci β€ n, ci = ai or ci = bi) β choosen leaf that is removed from the tree in the current operation.
See the examples for better understanding.
Examples
Input
3
1 2
1 3
Output
3
2 3 3
2 1 1
Input
5
1 2
1 3
2 4
2 5
Output
9
3 5 5
4 3 3
4 1 1
4 2 2 | import sys
n = int(sys.stdin.buffer.readline().decode('utf-8'))
adj = [[] for _ in range(n)]
deg = [0]*n
for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
deg[u-1] += 1
deg[v-1] += 1
def get_dia(st):
stack = [(st, 0)]
prev = [-1]*n
prev[st] = -2
dia, t = 0, -1
while stack:
v, steps = stack.pop()
if dia < steps:
dia, t = steps, v
for dest in adj[v]:
if prev[dest] != -1:
continue
prev[dest] = v
stack.append((dest, steps+1))
return t, prev
def get_dist(st, dist):
dist[st] = 0
stack = [st]
while stack:
v = stack.pop()
for dest in adj[v]:
if dist[dest] != -1:
continue
dist[dest] = dist[v] + 1
stack.append(dest)
edge1, _ = get_dia(0)
edge2, prev = get_dia(edge1)
dia_path = [0]*n
x = edge2
while x != edge1:
dia_path[x] = 1
x = prev[x]
dia_path[x] = 1
dist1, dist2 = [-1]*n, [-1]*n
get_dist(edge1, dist1)
get_dist(edge2, dist2)
ans = []
score = 0
stack = [i for i in range(n) if deg[i] == 1 and dia_path[i] == 0]
while stack:
v = stack.pop()
deg[v] = 0
if dist1[v] > dist2[v]:
score += dist1[v]
ans.append(f'{edge1+1} {v+1} {v+1}')
else:
score += dist2[v]
ans.append(f'{edge2+1} {v+1} {v+1}')
for dest in adj[v]:
if dia_path[dest] == 0 and deg[dest] > 0:
deg[dest] -= 1
if deg[dest] <= 1:
stack.append(dest)
x = edge2
while x != edge1:
score += dist1[x]
ans.append(f'{edge1+1} {x+1} {x+1}')
x = prev[x]
sys.stdout.buffer.write(
(str(score) + '\n' + '\n'.join(ans)).encode('utf-8')
)
| {
"input": [
"5\n1 2\n1 3\n2 4\n2 5\n",
"3\n1 2\n1 3\n"
],
"output": [
"9\n3 5 5\n4 3 3\n4 1 1\n4 2 2\n",
"3\n2 3 3\n2 1 1\n"
]
} |
2,290 | 7 | A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.
You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
Input
The first and only line consists of a string S ( 1 β€ |S| β€ 5 000 ). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
Output
Print "YES" or "NO", according to the condition.
Examples
Input
aaabccc
Output
YES
Input
bbacc
Output
NO
Input
aabc
Output
YES
Note
Consider first example: the number of 'c' is equal to the number of 'a'.
Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.
Consider third example: the number of 'c' is equal to the number of 'b'. | import re
def sv():
S = input()
if not re.match(r'^a+b+c+$', S):
return False
chrs = {'a':0,'b':0,'c':0}
for c in S:
chrs[c] += 1
return chrs['c'] == chrs['a'] or chrs['c'] == chrs['b']
print('YES' if sv() else 'NO')
| {
"input": [
"aabc\n",
"aaabccc\n",
"bbacc\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
2,291 | 7 | Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurrence of 1 in the array a with 2;
* Replace each occurrence of 2 in the array a with 1;
* Replace each occurrence of 3 in the array a with 4;
* Replace each occurrence of 4 in the array a with 3;
* Replace each occurrence of 5 in the array a with 6;
* Replace each occurrence of 6 in the array a with 5;
* ...
* Replace each occurrence of 10^9 - 1 in the array a with 10^9;
* Replace each occurrence of 10^9 in the array a with 10^9 - 1.
Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers (2i - 1, 2i) for each i β\{1, 2, β¦, 5 β
10^8\} as described above.
For example, for the array a = [1, 2, 4, 5, 10], the following sequence of arrays represents the algorithm:
[1, 2, 4, 5, 10] β (replace all occurrences of 1 with 2) β [2, 2, 4, 5, 10] β (replace all occurrences of 2 with 1) β [1, 1, 4, 5, 10] β (replace all occurrences of 3 with 4) β [1, 1, 4, 5, 10] β (replace all occurrences of 4 with 3) β [1, 1, 3, 5, 10] β (replace all occurrences of 5 with 6) β [1, 1, 3, 6, 10] β (replace all occurrences of 6 with 5) β [1, 1, 3, 5, 10] β ... β [1, 1, 3, 5, 10] β (replace all occurrences of 10 with 9) β [1, 1, 3, 5, 9]. The later steps of the algorithm do not change the array.
Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.
Input
The first line of the input contains one integer number n (1 β€ n β€ 1000) β the number of elements in Mishka's birthday present (surprisingly, an array).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print n integers β b_1, b_2, ..., b_n, where b_i is the final value of the i-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array a. Note that you cannot change the order of elements in the array.
Examples
Input
5
1 2 4 5 10
Output
1 1 3 5 9
Input
10
10000 10 50605065 1 5 89 5 999999999 60506056 1000000000
Output
9999 9 50605065 1 5 89 5 999999999 60506055 999999999
Note
The first example is described in the problem statement. | def m(n):
return int(n)-(int(n)-1)%2
n= int(input())
print(*list(map(m,input().split())))
| {
"input": [
"5\n1 2 4 5 10\n",
"10\n10000 10 50605065 1 5 89 5 999999999 60506056 1000000000\n"
],
"output": [
"1 1 3 5 9 ",
"9999 9 50605065 1 5 89 5 999999999 60506055 999999999 "
]
} |
2,292 | 12 | There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly a red tiles and exactly b blue tiles across the board.
Vova wants to color such a set of tiles that:
* they would form a rectangle, consisting of exactly a+b colored tiles;
* all tiles of at least one color would also form a rectangle.
Here are some examples of correct colorings:
<image>
Here are some examples of incorrect colorings:
<image>
Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?
It is guaranteed that there exists at least one correct coloring.
Input
A single line contains two integers a and b (1 β€ a, b β€ 10^{14}) β the number of tiles red marker should color and the number of tiles blue marker should color, respectively.
Output
Print a single integer β the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly a tiles red and exactly b tiles blue.
It is guaranteed that there exists at least one correct coloring.
Examples
Input
4 4
Output
12
Input
3 9
Output
14
Input
9 3
Output
14
Input
3 6
Output
12
Input
506 2708
Output
3218
Note
The first four examples correspond to the first picture of the statement.
Note that for there exist multiple correct colorings for all of the examples.
In the first example you can also make a rectangle with sides 1 and 8, though its perimeter will be 18 which is greater than 8.
In the second example you can make the same resulting rectangle with sides 3 and 4, but red tiles will form the rectangle with sides 1 and 3 and blue tiles will form the rectangle with sides 3 and 3. | from math import sqrt
lens = [0 for _ in range(1000000)]
def solve(a, b):
k = 0
for i in range(1, int(sqrt(b)) + 2):
if b % i == 0:
lens[k] = i
k += 1
ans = 2 * (a + b) + 2
x = a + b
l = 0
for i in range(1, int(sqrt(x)) + 2):
if x % i == 0:
while l + 1 < k and lens[l + 1] <= i:
l += 1
if b * i <= x * lens[l]:
ans = min(ans, (i + x // i) * 2)
return ans
a, b = map(int, input().split())
print(min(solve(a, b), solve(b, a)))
| {
"input": [
"3 9\n",
"4 4\n",
"506 2708\n",
"3 6\n",
"9 3\n"
],
"output": [
"14\n",
"12\n",
"3218\n",
"12\n",
"14\n"
]
} |
2,293 | 7 | You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and only if there is no letter to appear strictly more than \frac n 2 times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.
Your task is to find any diverse substring of string s or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the length of string s.
The second line is the string s, consisting of exactly n lowercase Latin letters.
Output
Print "NO" if there is no diverse substring in the string s.
Otherwise the first line should contain "YES". The second line should contain any diverse substring of string s.
Examples
Input
10
codeforces
Output
YES
code
Input
5
aaaaa
Output
NO
Note
The first example has lots of correct answers.
Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer. | def solve():
_ = int(input())
s = input()
for i in range(len(s) - 1):
if s[i] != s[i + 1]:
print("YES")
print(s[i : i + 2])
return
print("NO")
solve()
| {
"input": [
"5\naaaaa\n",
"10\ncodeforces\n"
],
"output": [
"NO\n",
"YES\nco\n"
]
} |
2,294 | 7 | Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
* he writes down s_m m times.
For example, if s="bab" the process is: "b" β "baa" β "baabbb". So the encrypted s="bab" is "baabbb".
Given string t β the result of encryption of some string s. Your task is to decrypt it, i. e. find the string s.
Input
The first line contains integer n (1 β€ n β€ 55) β the length of the encrypted string. The second line of the input contains t β the result of encryption of some string s. It contains only lowercase Latin letters. The length of t is exactly n.
It is guaranteed that the answer to the test exists.
Output
Print such string s that after encryption it equals t.
Examples
Input
6
baabbb
Output
bab
Input
10
ooopppssss
Output
oops
Input
1
z
Output
z | def f():
n=int(input())
s=input()
t,i=0,1
g=""
while(t<n):
g=g+s[t]
t=t+i
i=i+1
print(g)
f() | {
"input": [
"6\nbaabbb\n",
"10\nooopppssss\n",
"1\nz\n"
],
"output": [
"bab",
"oops",
"z"
]
} |
2,295 | 8 | An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, β¦, a_r for some l, r.
Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example:
* For array x = [4, 3, 1, 5, 2] and m = 3, the 3 largest elements of x are 5, 4 and 3, so the beauty of x is 5 + 4 + 3 = 12.
* For array x = [10, 10, 10] and m = 2, the beauty of x is 10 + 10 = 20.
You are given an array a_1, a_2, β¦, a_n, the value of the said constant m and an integer k. Your need to split the array a into exactly k subarrays such that:
* Each element from a belongs to exactly one subarray.
* Each subarray has at least m elements.
* The sum of all beauties of k subarrays is maximum possible.
Input
The first line contains three integers n, m and k (2 β€ n β€ 2 β
10^5, 1 β€ m, 2 β€ k, m β
k β€ n) β the number of elements in a, the constant m in the definition of beauty and the number of subarrays to split to.
The second line contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
Output
In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition.
In the second line, print k-1 integers p_1, p_2, β¦, p_{k-1} (1 β€ p_1 < p_2 < β¦ < p_{k-1} < n) representing the partition of the array, in which:
* All elements with indices from 1 to p_1 belong to the first subarray.
* All elements with indices from p_1 + 1 to p_2 belong to the second subarray.
* β¦.
* All elements with indices from p_{k-1} + 1 to n belong to the last, k-th subarray.
If there are several optimal partitions, print any of them.
Examples
Input
9 2 3
5 2 5 2 4 1 1 3 2
Output
21
3 5
Input
6 1 4
4 1 3 2 2 3
Output
12
1 3 5
Input
2 1 2
-1000000000 1000000000
Output
0
1
Note
In the first example, one of the optimal partitions is [5, 2, 5], [2, 4], [1, 1, 3, 2].
* The beauty of the subarray [5, 2, 5] is 5 + 5 = 10.
* The beauty of the subarray [2, 4] is 2 + 4 = 6.
* The beauty of the subarray [1, 1, 3, 2] is 3 + 2 = 5.
The sum of their beauties is 10 + 6 + 5 = 21.
In the second example, one optimal partition is [4], [1, 3], [2, 2], [3]. | def get():
return list(map(int,input().split()))
n,m,k=get()
a=get()
b=sorted(a)
c=b[-(m*k):]
f=c.count(c[0])
r=0
s=sum(b[-(m*k):])
l=[]
for i in range(n):
if a[i]>c[0] or (a[i]==c[0] and f>0):
if a[i]==c[0]:
f-=1
r+=1
if r==m:
r=0
l+=[i+1]
print(s)
print(*l[:k-1]) | {
"input": [
"2 1 2\n-1000000000 1000000000\n",
"9 2 3\n5 2 5 2 4 1 1 3 2\n",
"6 1 4\n4 1 3 2 2 3\n"
],
"output": [
"0\n1 ",
"21\n2 4 ",
"12\n1 3 4 "
]
} |
2,296 | 9 | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an U-shaped parabola through each pair of the points that have different x coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.
The internal area of an U-shaped parabola is the part of the plane that lies strictly above the parabola when the y axis is directed upwards.
Input
The first line contains a single integer n (1 β€ n β€ 100 000) β the number of points.
The next n lines describe the points, the i-th of them contains two integers x_i and y_i β the coordinates of the i-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed 10^6 by absolute value.
Output
In the only line print a single integer β the number of U-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).
Examples
Input
3
-1 0
0 2
1 0
Output
2
Input
5
1 0
1 -1
0 -1
-1 0
-1 -1
Output
1
Note
On the pictures below all U-shaped parabolas that pass through at least two given points are drawn for each of the examples. The U-shaped parabolas that do not have any given point inside their internal area are drawn in red.
<image> The first example. <image> The second example. | import sys
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
N = int(input())
A = [None]*N
for i in range(N):
x, y = map(int, sys.stdin.readline().split())
A[i] = (x, y-x*x)
A.sort()
upper = []
for p in reversed(A):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
while len(upper) >= 2 and upper[-1][0] == upper[-2][0]:
upper.pop()
print(len(upper) - 1)
| {
"input": [
"3\n-1 0\n0 2\n1 0\n",
"5\n1 0\n1 -1\n0 -1\n-1 0\n-1 -1\n"
],
"output": [
"2\n",
"1\n"
]
} |
2,297 | 11 | Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stones from each of the chosen piles. They can remove a different number of stones from the piles in a single turn. The first player unable to make a move loses (when there are less than n/2 nonempty piles).
Given the starting configuration, determine who will win the game.
Input
The first line contains one integer n (2 β€ n β€ 50) β the number of piles. It is guaranteed that n is an even number.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 50) β the number of stones in the piles.
Output
Print a single string "Alice" if Alice wins; otherwise, print "Bob" (without double quotes).
Examples
Input
2
8 8
Output
Bob
Input
4
3 1 4 1
Output
Alice
Note
In the first example, each player can only remove stones from one pile (2/2=1). Alice loses, since Bob can copy whatever Alice does on the other pile, so Alice will run out of moves first.
In the second example, Alice can remove 2 stones from the first pile and 3 stones from the third pile on her first move to guarantee a win. | def getn():
return int(input())
def getns():
return [int(x)for x in input().split()]
# n=getn()
# ns=getns()
n=getn()
ns=getns()
mm=min(ns)
ans=0
for c in ns:
if c==mm:
ans+=1
if ans<=n//2:
print('Alice')
else:
print('Bob')
| {
"input": [
"4\n3 1 4 1\n",
"2\n8 8\n"
],
"output": [
"Alice\n",
"Bob\n"
]
} |
2,298 | 10 | This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 β€ a_i β€ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type 1 and two candies of type 2 is bad).
It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.
Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.
You have to answer q independent queries.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer q (1 β€ q β€ 2 β
10^5) β the number of queries. Each query is represented by two lines.
The first line of each query contains one integer n (1 β€ n β€ 2 β
10^5) β the number of candies.
The second line of each query contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the type of the i-th candy in the box.
It is guaranteed that the sum of n over all queries does not exceed 2 β
10^5.
Output
For each query print one integer β the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.
Example
Input
3
8
1 4 8 4 5 6 3 8
16
2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1
9
2 2 4 4 4 7 7 7 7
Output
3
10
9
Note
In the first query, you can prepare a gift with two candies of type 8 and one candy of type 5, totalling to 3 candies.
Note that this is not the only possible solution β taking two candies of type 4 and one candy of type 6 is also valid. | import sys, collections
def candy_box(a):
counter = []
for value in sorted(collections.Counter(a).values(), reverse = True): counter += [max(min(value, counter[-1] - 1), 0) if counter else value]
return sum(counter)
#sys.stdin = open('temp.txt', 'r')
input_ = sys.stdin.read().split('\n')[1:-1]
for i in range(1, len(input_), 2):
a = map(int, input_[i].split(' '))
print(candy_box(a)) | {
"input": [
"3\n8\n1 4 8 4 5 6 3 8\n16\n2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1\n9\n2 2 4 4 4 7 7 7 7\n"
],
"output": [
"3\n10\n9\n"
]
} |
2,299 | 11 | Amugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".
Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
Input
The first line contains an integer n (1 β€ n β€ 10^5), the number of the words in Amugae's sentence.
The second line contains n words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed 10^6.
Output
In the only line output the compressed word after the merging process ends as described in the problem.
Examples
Input
5
I want to order pizza
Output
Iwantorderpizza
Input
5
sample please ease in out
Output
sampleaseinout | def partial(s):
g, pi = 0, [0] * len(s)
for i in range(1, len(s)):
while g and (s[g] != s[i]):
g = pi[g - 1]
pi[i] = g = g + (s[g] == s[i])
return pi[-1]
n = int(input())
s = input().split()
ans = [*s[0]]
for i in s[1:]:
c = [*i] + ['$'] + ans[-min(len(i), len(ans)):]
j = partial(c)
for _ in range(j):
ans.pop()
ans.extend([*i])
print(''.join(ans)) | {
"input": [
"5\nsample please ease in out\n",
"5\nI want to order pizza\n"
],
"output": [
"sampleaseinout\n",
"Iwantorderpizza\n"
]
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.