index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
3,300 | 7 | It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
Input
The single line contains integer y (1000 β€ y β€ 9000) β the year number.
Output
Print a single integer β the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
Examples
Input
1987
Output
2013
Input
2013
Output
2014 | def f(x):
y=len(set(list(str(x))))
return y
x=int(input())+1
while f(x)<4:
x+=1
print(x)
| {
"input": [
"1987\n",
"2013\n"
],
"output": [
"2013\n",
"2014\n"
]
} |
3,301 | 9 | There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on.
He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7).
Input
The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 β€ n β€ 1000, 1 β€ m β€ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.
Output
In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7).
Examples
Input
3 1
1
Output
1
Input
4 2
1 4
Output
2
Input
11 2
4 8
Output
6720 | def f(n):
if n == 0:
return 1
ans = 1
for i in range(2, n + 1):
ans *= i
return ans
n, m = map(int, input().split())
a = list(map(int, input().split()))
a = sorted(a)
ans = f(n - m) // f(a[0] - 1)
for i in range(1, m):
ans //= f(a[i] - a[i - 1] - 1)
if a[i] - a[i - 1] != 1:
ans *= 2 ** (a[i] - a[i - 1] - 2)
ans //= f(n - a[m - 1])
print(ans % 1000000007)
| {
"input": [
"11 2\n4 8\n",
"4 2\n1 4\n",
"3 1\n1\n"
],
"output": [
"6720",
"2",
"1"
]
} |
3,302 | 7 | Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.
Input
The only line of input contains integers n and k (1 β€ k β€ n β€ 1012).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print the number that will stand at the position number k after Volodya's manipulations.
Examples
Input
10 3
Output
5
Input
7 7
Output
6
Note
In the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 5. | def fun(n,k):
if k<= n//2 + n%2 :
print(2*k-1)
else:
print(2*(k- (n//2 + n%2)))
n,k=map(int,input().split())
fun(n,k) | {
"input": [
"7 7\n",
"10 3\n"
],
"output": [
"6\n",
"5\n"
]
} |
3,303 | 7 | Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:
* a < b < c;
* a divides b, b divides c.
Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has <image> groups of three.
Help Xenia, find the required partition or else say that it doesn't exist.
Input
The first line contains integer n (3 β€ n β€ 99999) β the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7.
It is guaranteed that n is divisible by 3.
Output
If the required partition exists, print <image> groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them.
If there is no solution, print -1.
Examples
Input
6
1 1 1 2 2 2
Output
-1
Input
6
2 2 1 1 4 6
Output
1 2 4
1 2 6 | def f():
n = int(input()) // 3
t = input()
if '5' in t: return -1
a = t.count('1')
if a != n: return -1
b = t.count('2')
c = t.count('3')
if b + c != n: return -1
d = t.count('4')
if d > b: return -1
f = t.count('6')
if f < c: return -1
return '1 2 4\n' * d + '1 3 6\n' * c + '1 2 6\n' * (n - d - c)
print(f()) | {
"input": [
"6\n2 2 1 1 4 6\n",
"6\n1 1 1 2 2 2\n"
],
"output": [
"1 2 4\n1 2 6\n",
"-1\n"
]
} |
3,304 | 9 | You have a string of decimal digits s. Let's define bij = siΒ·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.
A rectangle in a matrix is a group of four integers (x, y, z, t) (x β€ y, z β€ t). The elements of the rectangle are all cells (i, j) such that x β€ i β€ y, z β€ j β€ t.
Input
The first line contains integer a (0 β€ a β€ 109), the second line contains a string of decimal integers s (1 β€ |s| β€ 4000).
Output
Print a single integer β the answer to a problem.
Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
10
12345
Output
6
Input
16
439873893693495623498263984765
Output
40 | import math
def main(arr,a):
f=[]
for i in range(1,int(math.sqrt(a))+1):
f1=i
f2=a/i
if f2==int(f2):
f.append(f1)
if f2!=f1:
f.append(int(f2))
f.sort()
prefix=[0]
for i in range(len(arr)):
prefix.append(prefix[-1]+arr[i])
diff={}
for i in range(len(prefix)):
for j in range(0,i):
val= prefix[i]-prefix[j]
if val not in diff:
diff[val]=0
diff[val]+=1
if a==0:
for e in diff:
f.append(e)
f.append(0)
f.sort()
ans=0
i=0
j=len(f)-1
while i<=j:
f1=f[i]
f2=f[j]
if f1 in diff and f2 in diff:
if f1==f2:
ans+=diff[f1]*diff[f2]
else:
ans+=2*(diff[f1]*diff[f2])
i+=1
j-=1
return ans
a=int(input())
arr=[int(c) for c in input()]
print(main(arr,a)) | {
"input": [
"10\n12345\n",
"16\n439873893693495623498263984765\n"
],
"output": [
"6\n",
"40\n"
]
} |
3,305 | 8 | Fox Ciel has a board with n rows and n columns. So, the board consists of n Γ n cells. Each cell contains either a symbol '.', or a symbol '#'.
A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.
<image>
Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.
Please, tell Ciel if she can draw the crosses in the described way.
Input
The first line contains an integer n (3 β€ n β€ 100) β the size of the board.
Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.
Output
Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".
Examples
Input
5
.#...
####.
.####
...#.
.....
Output
YES
Input
4
####
####
####
####
Output
NO
Input
6
.#....
####..
.####.
.#.##.
######
.#..#.
Output
YES
Input
6
.#..#.
######
.####.
.####.
######
.#..#.
Output
NO
Input
3
...
...
...
Output
YES
Note
In example 1, you can draw two crosses. The picture below shows what they look like.
<image>
In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all. | n = int(input())
s = [list(input()) for _ in range(n)]
def TryCross(i, j):
if 0 <= i < n - 2 and 0 < j < n - 1:
c = [(i, j), (i + 1, j - 1), (i + 1, j), (i + 1, j + 1), (i + 2, j)]
if not all(s[x][y] == "#" for x, y in c):
return False
for x, y in c:
s[x][y] = "."
return True
return False
for i in range(n):
for j in range(n):
if s[i][j] == "#" and not TryCross(i, j):
print("NO")
exit()
print("YES") | {
"input": [
"6\n.#....\n####..\n.####.\n.#.##.\n######\n.#..#.\n",
"5\n.#...\n####.\n.####\n...#.\n.....\n",
"4\n####\n####\n####\n####\n",
"6\n.#..#.\n######\n.####.\n.####.\n######\n.#..#.\n",
"3\n...\n...\n...\n"
],
"output": [
"YES",
"YES",
"NO",
"NO",
"YES"
]
} |
3,306 | 11 | <image>
Input
The input contains a single floating-point number x with exactly 6 decimal places (0 < x < 5).
Output
Output two integers separated by a single space. Each integer should be between 1 and 10, inclusive. If several solutions exist, output any of them. Solution will exist for all tests.
Examples
Input
1.200000
Output
3 2
Input
2.572479
Output
10 3
Input
4.024922
Output
9 9 | import math
def getR(a,h):
return math.sin(math.atan2(h,0.5*a))*0.5*a
r = float(input())
bestR=1e100
for a in range(1,11):
for h in range(1,11):
d = abs(r-getR(a,h))
if d < bestR:
bestR = d
bestA = a
bestH = h
print(bestA, bestH)
| {
"input": [
"4.024922\n",
"2.572479\n",
"1.200000\n"
],
"output": [
"9 9\n",
"6 5\n",
"3 2\n"
]
} |
3,307 | 7 | Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn.
Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.
Input
The single line of the input contains two space-separated positive integers n, k (1 β€ k < n β€ 105).
Output
Print n integers forming the permutation. If there are multiple answers, print any of them.
Examples
Input
3 2
Output
1 3 2
Input
3 1
Output
1 2 3
Input
5 2
Output
1 3 2 4 5
Note
By |x| we denote the absolute value of number x. | def getLine():
return list(map(int,input().split()))
n,k = getLine()
l = [0]*n
for i in range(n):
if i%2 == 0:l[i] = i//2+1
else : l[i] = n - l[i-1]+1
ans=l
for i in range(k,n):
if k%2 == 0:l[i] = l[i-1]-1
else : l[i] = l[i-1]+1
for i in ans:
print(i,end=" ") | {
"input": [
"5 2\n",
"3 2\n",
"3 1\n"
],
"output": [
"1 3 2 4 5\n",
"1 3 2 ",
"1 2 3 "
]
} |
3,308 | 11 | ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 β€ n β€ 5000, 1 β€ k β€ 20).
The next line contains n space-separated integers ai (1 β€ ai β€ 107) β the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 β€ q β€ 20) β the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 β€ xi β€ 2Β·108) β the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1 | f = lambda: map(int, input().split())
n, k = f()
t = list(f())
u = [{i * q for q in t} for i in range(1, k + 1)]
def g(d):
v = [{d - q for q in p} for p in u]
for j in range(1, k + 1):
if d in u[j - 1]: return j
for i in range(j // 2):
if u[i].intersection(v[j - i - 2]): return j
return -1
for i in range(int(input())): print(g(int(input())))
| {
"input": [
"6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950\n",
"5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15\n"
],
"output": [
"6\n20\n19\n20\n-1\n3\n-1\n-1\n",
"1\n1\n1\n2\n2\n2\n2\n-1\n"
]
} |
3,309 | 8 | Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 β€ i β€ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li β€ x β€ ri, li + 1 β€ y β€ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 β€ n β€ 2Β·105) and m (1 β€ m β€ 2Β·105) β the number of islands and bridges.
Next n lines each contain two integers li and ri (1 β€ li β€ ri β€ 1018) β the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 β€ ai β€ 1018) β the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist. | # Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = " ".join([str(n) for n in self.result])
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 20000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate()) | {
"input": [
"2 1\n1 1\n1000000000000000000 1000000000000000000\n999999999999999999\n",
"4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8\n",
"2 2\n11 14\n17 18\n2 9\n"
],
"output": [
"Yes\n1 \n",
"Yes\n2 3 1 \n",
"No\n"
]
} |
3,310 | 7 | One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 β€ a, b β€ 100) β the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers β the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day. | def hipster(a, b):
return min(a, b), abs(a-b) // 2
print(*hipster(*map(int, input().split()))) | {
"input": [
"2 3\n",
"3 1\n",
"7 3\n"
],
"output": [
"2 0\n",
"1 1\n",
"3 2\n"
]
} |
3,311 | 9 | People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n Γ n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n Γ n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 500, 1 β€ k β€ n) β the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13 | def mp():
return map(int,input().split())
def lt():
return list(map(int,input().split()))
def pt(x):
print(x)
n,k = mp()
pt(((n**2-n+k+(k-1)*n+1)*n)//2)
for i in range(n):
L1 = [(k-1)*i+r for r in range(1,k)]
L2 = [(n-k+1)*i+(k-1)*n+r for r in range(1,n-k+2)]
print(' '.join([str(s) for s in L1]+[str(t) for t in L2]))
| {
"input": [
"5 3\n",
"4 1\n"
],
"output": [
"85\n1 2 11 12 13 \n3 4 14 15 16 \n5 6 17 18 19 \n7 8 20 21 22 \n9 10 23 24 25 \n",
"28\n1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 16 \n"
]
} |
3,312 | 8 | A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 β€ i β€ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 β€ n, k β€ 100, 0 β€ t β€ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0 | def s():
[n,k,t] = list(map(int,input().split()))
a = n*t//100
b = n*t%100*k//100
c = n - a - 1
print(*[k for _ in range(a)],end='')
if n > a:
print(' 'if a>0 else '',b,end='',sep='')
if c > 0:
print('',*[0 for _ in range(c)])
s()
| {
"input": [
"11 13 37\n",
"10 10 54\n"
],
"output": [
"13 13 13 13 0 0 0 0 0 0 0\n",
"10 10 10 10 10 4 0 0 0 0\n"
]
} |
3,313 | 9 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 β€ n β€ 105) β the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 β€ u, v β€ n, u β v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 β€ ci β€ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO | def main():
n = int(input())
pairs = []
for i in range(n-1):
a, b = list(map(int, input().split()))
pairs.append([a-1, b-1])
colors = list(map(int, input().split()))
bad_pairs_count = 0
bad_points_counts = {0:0}
for a,b in pairs:
if colors[a] != colors[b]:
bad_pairs_count += 1
def add(x):
if x not in bad_points_counts:
bad_points_counts[x] = 0
bad_points_counts[x] += 1
add(a)
add(b)
for k, v in bad_points_counts.items():
if v == bad_pairs_count:
print("YES")
print(k+1)
return
print("NO")
main()
| {
"input": [
"4\n1 2\n2 3\n3 4\n1 2 1 2\n",
"4\n1 2\n2 3\n3 4\n1 2 1 1\n",
"3\n1 2\n2 3\n1 2 3\n"
],
"output": [
"NO\n",
"YES\n2",
"YES\n2"
]
} |
3,314 | 9 | Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 β€ ci β€ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 β€ ti β€ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
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")
#-------------------game starts now-----------------------------------------------------
from heapq import heappush, heappop, heapify
n, k = map(int, input().split())
a = list(map(int, input().split()))
q = [(-a[i], i) for i in range(k)]
heapify(q)
res, s = [0] * n, 0
for i in range(k, n):
heappush(q, (-a[i], i))
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
for i in range(n, n+k):
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
print(s)
print(*res) | {
"input": [
"5 2\n4 2 1 10 2\n"
],
"output": [
"20\n3 6 7 4 5 \n"
]
} |
3,315 | 7 | It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n β number of doctors (1 β€ n β€ 1000).
Next n lines contain two numbers si and di (1 β€ si, di β€ 1000).
Output
Output a single integer β the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11. | def main():
n = int(input())
day = 0
for i in range(n):
s, d = map(int,input().split())
if s > day:
day = s
else:
day = ((day -s)//d +1)*d +s
print(day)
main()
| {
"input": [
"2\n10 1\n6 5\n",
"3\n2 2\n1 2\n2 2\n"
],
"output": [
"11\n",
"4\n"
]
} |
3,316 | 9 | Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 β€ h β€ 105) β the height of the tree.
The second line contains h + 1 integers β the sequence a0, a1, ..., ah (1 β€ ai β€ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image> | def do_amb(v, n, sum):
print("ambiguous")
diff = []
for i in v:
temp = len(diff)
diff.extend((temp for j in range(i)))
print(" ".join(str(i) for i in diff))
diff[sum+1] = sum-1
print(" ".join(str(i) for i in diff))
n = int(input())
v = [int(i) for i in input().split()]
ans = []
ind = -1
sum = 0
for i in v:
if i != 1 and v[ind] != 1:
do_amb(v, ind, sum)
exit()
sum+=i
ind+=1
print("perfect") | {
"input": [
"2\n1 1 1\n",
"2\n1 2 2\n"
],
"output": [
"perfect",
"ambiguous\n0 1 1 3 3 \n0 1 1 2 3 "
]
} |
3,317 | 10 | This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1 / n). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
Input
The first line contains a single integer n from the problem's statement (1 β€ n β€ 10000).
Output
Print the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.
Examples
Input
2
Output
1/1
Input
3
Output
8/3
Input
4
Output
2/1 | from math import gcd
def PRINT(a, b) :
print(str(int(a)) + "/" + str(int(b)))
def solve(n) :
pre = 0
while(n > 1 and (n % 2 == 0)) :
pre = pre + 1
n = n // 2
if(n == 1) :
PRINT(pre, 1)
return
arr = []
rem = 1
while(True) :
rem = rem * 2
arr.append(int(rem // n))
rem = rem % n
if(rem == 1) :
break
k = len(arr)
ans = 0
for i in range(0, k) :
if(arr[i] == 1) :
ans = ans + (2 ** (k-1-i)) * (i+1)
ans = ans * n + k
A = ans
B = 2**k - 1
G = gcd(A, B)
A = A // G
B = B // G
PRINT(A + B * pre, B)
n = int(input())
solve(n)
| {
"input": [
"3\n",
"2\n",
"4\n"
],
"output": [
"8/3\n",
"1/1\n",
"2/1\n"
]
} |
3,318 | 11 | Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c β the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a β b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 β€ n β€ 5 β
10^5, 1 β€ k β€ 10^9).
The second line contains a string s (|s| = n) β the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) β the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number β maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8. | def solve(n, k, start, end):
tot = 0
lvl = 1
for i in range(n):
lvl += lvl - int(start[i] == 'b') - int(end[i] == 'a')
if lvl >= k:
tot += k * (n-i)
break
else:
tot += lvl
return tot
n, k = map(int, input().split())
start = input()
end = input()
print(solve(n, k, start, end))
| {
"input": [
"2 4\naa\nbb\n",
"4 5\nabbb\nbaaa\n",
"3 3\naba\nbba\n"
],
"output": [
"6\n",
"8\n",
"8\n"
]
} |
3,319 | 8 | Two people are playing a game with a string s, consisting of lowercase latin letters.
On a player's turn, he should choose two consecutive equal letters in the string and delete them.
For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.
Your task is to determine which player will win if both play optimally.
Input
The only line contains the string s, consisting of lowercase latin letters (1 β€ |s| β€ 100 000), where |s| means the length of a string s.
Output
If the first player wins, print "Yes". If the second player wins, print "No".
Examples
Input
abacaba
Output
No
Input
iiq
Output
Yes
Input
abba
Output
No
Note
In the first example the first player is unable to make a turn, so he loses.
In the second example first player turns the string into "q", then second player is unable to move, so he loses. | def f(s):
n=len(s)
l=[s[0]]
c=0
for i in range(1,n):
if l!=[]:
if s[i]==l[-1]:
l.pop()
c+=1
else:
l.append(s[i])
else:
l.append(s[i])
if c%2==1:
print('Yes')
else:
print('No')
s=input()
f(s)
| {
"input": [
"iiq\n",
"abba\n",
"abacaba\n"
],
"output": [
"Yes\n",
"No\n",
"No\n"
]
} |
3,320 | 9 | Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.
Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs to choose the smallest one.
Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?
Input
The only line contains two integers a and b (1 β€ a, b β€ 10^9).
Output
Print the smallest non-negative integer k (k β₯ 0) such that the lowest common multiple of a+k and b+k is the smallest possible.
If there are many possible integers k giving the same value of the least common multiple, print the smallest one.
Examples
Input
6 10
Output
2
Input
21 31
Output
9
Input
5 10
Output
0
Note
In the first test, one should choose k = 2, as the least common multiple of 6 + 2 and 10 + 2 is 24, which is the smallest least common multiple possible. | import math
n,m=map(int,input().split())
def lcm(i):
return (n+i)*(m+i)//math.gcd(n+i,m+i)
t=abs(n-m)
p=set([])
i=1
while (i**2 <=t):
if(t)%i==0:
p.add(i)
p.add(t//i)
i+=1
p=sorted(list(p))
g=10**20
key=0
for i in p:
index = (i-n%i)%i
l=lcm(index)
if(l<g):
g=l
key=index
print(key)
| {
"input": [
"6 10\n",
"5 10\n",
"21 31\n"
],
"output": [
"2\n",
"0\n",
"9\n"
]
} |
3,321 | 7 | You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements?
Input
The first line contains an integer n (1 β€ n β€ 1000), where 2n is the number of elements in the array a.
The second line contains 2n space-separated integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^6) β the elements of the array a.
Output
If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing 2n space-separated integers. They must form a reordering of a. You are allowed to not change the order.
Examples
Input
3
1 2 2 1 3 1
Output
2 1 3 1 1 2
Input
1
1 1
Output
-1
Note
In the first example, the first n elements have sum 2+1+3=6 while the last n elements have sum 1+1+2=4. The sums aren't equal.
In the second example, there's no solution. | n=int(input())
m=input().split()
def r(x):
return len(x),x
if len(set(m))==1:
print(-1)
else:
m.sort(key=r)
print(' '.join(m))
| {
"input": [
"3\n1 2 2 1 3 1\n",
"1\n1 1\n"
],
"output": [
"1 1 1 2 2 3\n",
"-1\n"
]
} |
3,322 | 12 | There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.
The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be any real numbers satisfying that l < r. The upper side of the area is boundless, which you can regard as a line parallel to the x-axis at infinity. The following figure shows a strange rectangular area.
<image>
A point (x_i, y_i) is in the strange rectangular area if and only if l < x_i < r and y_i > a. For example, in the above figure, p_1 is in the area while p_2 is not.
Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.
Input
The first line contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the number of points on the plane.
The i-th of the next n lines contains two integers x_i, y_i (1 β€ x_i, y_i β€ 10^9) β the coordinates of the i-th point.
All points are distinct.
Output
Print a single integer β the number of different non-empty sets of points she can obtain.
Examples
Input
3
1 1
1 2
1 3
Output
3
Input
3
1 1
2 1
3 1
Output
6
Input
4
2 1
2 2
3 1
3 2
Output
6
Note
For the first example, there is exactly one set having k points for k = 1, 2, 3, so the total number is 3.
For the second example, the numbers of sets having k points for k = 1, 2, 3 are 3, 2, 1 respectively, and their sum is 6.
For the third example, as the following figure shows, there are
* 2 sets having one point;
* 3 sets having two points;
* 1 set having four points.
Therefore, the number of different non-empty sets in this example is 2 + 3 + 0 + 1 = 6.
<image> | from sys import stdin, stdout
from collections import defaultdict
n = int(input())
pts = []
for i in range(n):
x, y = map(int, stdin.readline().split())
pts.append((x, y))
pts.sort()
cts = [0]*(n+1)
x_map = {}
ctr = 0
for p in pts:
if p[0] not in x_map:
ctr += 1
x_map[p[0]] = ctr
cts[ctr] += 1
pts = [(x_map[p[0]], p[1]) for p in pts]
collected = defaultdict(list)
for p in pts:
collected[p[1]].append(p)
bit = [0]*(n+1)
# sum from 1 to i, inclusive
# 1-indexed array!
def query(i):
ans = 0
while i > 0:
ans += bit[i]
i -= i & (-i)
return ans
# 1-indexed! Passing 0 is infinite loop
def update(i, x):
while i <= n:
bit[i] += x
i += i & (-i)
for i in range(1,ctr+1):
update(i, 1)
ans = 0
for y, y_pts in sorted(collected.items()):
total = query(n)
# print(y, y_pts, total)
ans += total*(total+1) // 2
prev_x = 0
for p in y_pts:
local = query(p[0]) - (query(prev_x) if prev_x else 0) - 1
ans -= local*(local+1)//2
prev_x = p[0]
local = total - query(prev_x)
ans -= local*(local + 1)//2
for p in y_pts:
cts[p[0]] -= 1
if cts[p[0]] == 0:
update(p[0], -1)
print(ans)
| {
"input": [
"3\n1 1\n1 2\n1 3\n",
"4\n2 1\n2 2\n3 1\n3 2\n",
"3\n1 1\n2 1\n3 1\n"
],
"output": [
"3",
"6",
"6"
]
} |
3,323 | 9 | Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 β€ a β€ b β€ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 β€ n β€ 7, 0 β€ m β€ (nβ
(n-1))/(2)) β the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 β€ a, b β€ n, a β b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots. | n, m = map(int, input().split())
a = [[*map(int, input().split())] for i in range(m)]
from itertools import combinations
s = []
ans = 0
def do():
global ans
if len(s) == n:
t = set()
for j in a:
y, z = s[j[0] - 1], s[j[1] - 1]
if y > z:
y, z = z, y
t.add((y, z))
ans = max(ans, len(t))
return
for i in range(6):
s.append(i)
do()
del s[-1]
do()
print(ans) | {
"input": [
"7 21\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n2 3\n2 4\n2 5\n2 6\n2 7\n3 4\n3 5\n3 6\n3 7\n4 5\n4 6\n4 7\n5 6\n5 7\n6 7\n",
"7 0\n",
"4 4\n1 2\n2 3\n3 4\n4 1\n",
"3 1\n1 3\n"
],
"output": [
"16\n",
"0\n",
"4\n",
"1\n"
]
} |
3,324 | 11 | At first, let's define function f(x) as follows: $$$ \begin{matrix} f(x) & = & \left\{ \begin{matrix} x/2 & \mbox{if } x is even \\\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} $$$
We can see that if we choose some value v and will apply function f to it, then apply f to f(v), and so on, we'll eventually get 1. Let's write down all values we get in this process in a list and denote this list as path(v). For example, path(1) = [1], path(15) = [15, 14, 7, 6, 3, 2, 1], path(32) = [32, 16, 8, 4, 2, 1].
Let's write all lists path(x) for every x from 1 to n. The question is next: what is the maximum value y such that y is contained in at least k different lists path(x)?
Formally speaking, you need to find maximum y such that \left| \{ x ~|~ 1 β€ x β€ n, y β path(x) \} \right| β₯ k.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 10^{18}).
Output
Print the only integer β the maximum value that is contained in at least k paths.
Examples
Input
11 3
Output
5
Input
11 6
Output
4
Input
20 20
Output
1
Input
14 5
Output
6
Input
1000000 100
Output
31248
Note
In the first example, the answer is 5, since 5 occurs in path(5), path(10) and path(11).
In the second example, the answer is 4, since 4 occurs in path(4), path(5), path(8), path(9), path(10) and path(11).
In the third example n = k, so the answer is 1, since 1 is the only number occuring in all paths for integers from 1 to 20. | def gg(n,lol):
ans = 0
cur = 1
lol2 = lol
while(2*lol+1<=n):
cur *= 2
ans += cur
lol = 2*lol+1
lol2 *= 2
if lol2*2 <= n:
ans += n-lol2*2+1
return ans
n,k = map(int,input().split())
low = 1
high = n//2
res = 1
while low <= high:
mid = (low+high)//2
if gg(n,mid) >= k:
res = mid
low = mid+1
else:
high = mid-1
if n == k:
print(1)
elif(gg(n,res)-1-gg(n,res*2) >= k):
print(res*2+1)
else:
print(res*2)
| {
"input": [
"11 3\n",
"1000000 100\n",
"20 20\n",
"11 6\n",
"14 5\n"
],
"output": [
"5\n",
"31248\n",
"1\n",
"4\n",
"6\n"
]
} |
3,325 | 12 | You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 β€ a_i, b_i β€ n, a_i β b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res β the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 β€ a, b, c β€ n and a β , b β c, a β c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | from collections import deque
import sys
ans = 0
input = sys.stdin.readline
n = int(input())
def put():
return map(int, input().split())
def bfs(l):
dis = [0]*n
for i in l:
dis[i]=1
q.append(i)
i = -1
while q:
i = q.popleft()
for j in tree[i]:
if dis[j]==0:
parent[j]=i
q.append(j)
dis[j]=dis[i]+1
return i,dis[i]
parent = [-1]*n
tree = [[] for _ in range(n)]
for _ in range(n-1):
x,y = put()
tree[x-1].append(y-1)
tree[y-1].append(x-1)
q = deque()
far, _ = bfs([0])
end, dis = bfs([far])
parent[far]=-1
curr = end
l = []
while curr!=-1:
l.append(curr)
curr = parent[curr]
third, dis2 = bfs(l)
if third in [far, end]:
x=0
while x in [far, end]:
x+=1
third = x
print(dis+dis2-2)
print(far+1, end+1, third+1)
| {
"input": [
"8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\n"
],
"output": [
"5\n5 1 6\n"
]
} |
3,326 | 8 | Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.
<image>
The dragon has a hit point of x initially. When its hit point goes to 0 or under 0, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.
* Void Absorption
Assume that the dragon's current hit point is h, after casting this spell its hit point will become \leftβ h/2 \rightβ + 10. Here \leftβ h/2 \rightβ denotes h divided by two, rounded down.
* Lightning Strike
This spell will decrease the dragon's hit point by 10. Assume that the dragon's current hit point is h, after casting this spell its hit point will be lowered to h-10.
Due to some reasons Kana can only cast no more than n Void Absorptions and m Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. For each test case the only line contains three integers x, n, m (1β€ x β€ 10^5, 0β€ n,mβ€30) β the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.
Output
If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
7
100 3 4
189 3 4
64 2 3
63 2 3
30 27 7
10 9 1
69117 21 2
Output
YES
NO
NO
YES
YES
YES
YES
Note
One possible casting sequence of the first test case is shown below:
* Void Absorption \leftβ 100/2 \rightβ + 10=60.
* Lightning Strike 60-10=50.
* Void Absorption \leftβ 50/2 \rightβ + 10=35.
* Void Absorption \leftβ 35/2 \rightβ + 10=27.
* Lightning Strike 27-10=17.
* Lightning Strike 17-10=7.
* Lightning Strike 7-10=-3. | def solv():
x,n,m=map(int,input().split())
while (x>m*10)and(n>0)and(x>20): x=x//2 + 10; n-=1
print('YES' if x<=m*10 else 'NO')
t=int(input())
for i in range(t): solv()
| {
"input": [
"7\n100 3 4\n189 3 4\n64 2 3\n63 2 3\n30 27 7\n10 9 1\n69117 21 2\n"
],
"output": [
"Yes\nNo\nNo\nYes\nYes\nYes\nYes\n"
]
} |
3,327 | 7 | Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
Input
The only line of the input data contains a non-empty string consisting of letters "Π‘" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "Π‘", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.
Output
Print the only number β the minimum number of times Polycarpus has to visit the closet.
Examples
Input
CPCPCPC
Output
7
Input
CCCCCCPPPPPP
Output
4
Input
CCCCCCPPCPPPPPPPPPP
Output
6
Input
CCCCCCCCCC
Output
2
Note
In the first sample Polycarpus needs to take one item to the closet 7 times.
In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.
In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.
In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). | def count_times(row):
res = int(row != '')
hand = 0
n = len(row)
for i in range(1, n):
hand += 1
if hand == 5 or row[i] != row[i - 1]:
hand = 0
res += 1
return res
row = input()
print(count_times(row)) | {
"input": [
"CPCPCPC\n",
"CCCCCCCCCC\n",
"CCCCCCPPCPPPPPPPPPP\n",
"CCCCCCPPPPPP\n"
],
"output": [
"7\n",
"2\n",
"6\n",
"4\n"
]
} |
3,328 | 7 | Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.
Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
Input
Input contains one integer number A (3 β€ A β€ 1000).
Output
Output should contain required average value in format Β«X/YΒ», where X is the numerator and Y is the denominator.
Examples
Input
5
Output
7/3
Input
3
Output
2/1
Note
In the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | from math import gcd
def f(i,n):
c=0
while n>0:
c+=n%i
n=n//i
return c
n=int(input())
c=0
for i in range(2,n):
c+=f(i,n)
a=c
b=n-2
x=gcd(a,b)
a=a//x
b=b//x
print(str(a)+"/"+str(b)) | {
"input": [
"3\n",
"5\n"
],
"output": [
"2/1\n",
"7/3\n"
]
} |
3,329 | 9 | Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from n different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:
* the dish will be delivered by a courier from the restaurant i, in this case the courier will arrive in a_i minutes,
* Petya goes to the restaurant i on his own and picks up the dish, he will spend b_i minutes on this.
Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.
For example, if Petya wants to order n = 4 dishes and a = [3, 7, 4, 5], and b = [2, 1, 2, 4], then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in 3 minutes, the courier of the fourth restaurant will bring the order in 5 minutes, and Petya will pick up the remaining dishes in 1 + 2 = 3 minutes. Thus, in 5 minutes all the dishes will be at Petya's house.
Find the minimum time after which all the dishes can be at Petya's home.
Input
The first line contains one positive integer t (1 β€ t β€ 2 β
10^5) β the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 β€ n β€ 2 β
10^5) β the number of dishes that Petya wants to order.
The second line of each test case contains n integers a_1 β¦ a_n (1 β€ a_i β€ 10^9) β the time of courier delivery of the dish with the number i.
The third line of each test case contains n integers b_1 β¦ b_n (1 β€ b_i β€ 10^9) β the time during which Petya will pick up the dish with the number i.
The sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case output one integer β the minimum time after which all dishes can be at Petya's home.
Example
Input
4
4
3 7 4 5
2 1 2 4
4
1 2 3 4
3 3 3 3
2
1 2
10 10
2
10 10
1 2
Output
5
3
2
3 | def helper(m):
s = 0
for i in range(len(a)):
if a[i] > m:
s += b[i]
return s <= m
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
l, r = 1, 10**9
while l < r:
mid = l + (r-l)//2
temp = helper(mid)
if temp:
r = mid
else:
l = mid+1
print(l)
| {
"input": [
"4\n4\n3 7 4 5\n2 1 2 4\n4\n1 2 3 4\n3 3 3 3\n2\n1 2\n10 10\n2\n10 10\n1 2\n"
],
"output": [
"5\n3\n2\n3\n"
]
} |
3,330 | 12 | This is an interactive problem.
There exists a matrix a of size n Γ m (n rows and m columns), you know only numbers n and m. The rows of the matrix are numbered from 1 to n from top to bottom, and columns of the matrix are numbered from 1 to m from left to right. The cell on the intersection of the x-th row and the y-th column is denoted as (x, y).
You are asked to find the number of pairs (r, c) (1 β€ r β€ n, 1 β€ c β€ m, r is a divisor of n, c is a divisor of m) such that if we split the matrix into rectangles of size r Γ c (of height r rows and of width c columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal.
You can use queries of the following type:
* ? h w i_1 j_1 i_2 j_2 (1 β€ h β€ n, 1 β€ w β€ m, 1 β€ i_1, i_2 β€ n, 1 β€ j_1, j_2 β€ m) β to check if non-overlapping subrectangles of height h rows and of width w columns of matrix a are equal or not. The upper left corner of the first rectangle is (i_1, j_1). The upper left corner of the second rectangle is (i_2, j_2). Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect.
You can use at most 3 β
\left β{ log_2{(n+m)} } \right β queries. All elements of the matrix a are fixed before the start of your program and do not depend on your queries.
Input
The first line contains two integers n and m (1 β€ n, m β€ 1000) β the number of rows and columns, respectively.
Output
When ready, print a line with an exclamation mark ('!') and then the answer β the number of suitable pairs (r, c). After that your program should terminate.
Interaction
To make a query, print a line with the format "? h w i_1 j_1 i_2 j_2 ", where the integers are the height and width and the coordinates of upper left corners of non-overlapping rectangles, about which you want to know if they are equal or not.
After each query read a single integer t (t is 0 or 1): if the subrectangles are equal, t=1, otherwise t=0.
In case your query is of incorrect format or you asked more than 3 β
\left β{ log_2{(n+m)} } \right β queries, you will receive the Wrong Answer verdict.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
It is guaranteed that the matrix a is fixed and won't change during the interaction process.
Hacks format
For hacks use the following format.
The first line contains two integers n and m (1 β€ n, m β€ 1000) β the number of rows and columns in the matrix, respectively.
Each of the next n lines contains m integers β the elements of matrix a. All the elements of the matrix must be integers between 1 and n β
m, inclusive.
Example
Input
3 4
1
1
1
0
Output
? 1 2 1 1 1 3
? 1 2 2 1 2 3
? 1 2 3 1 3 3
? 1 1 1 1 1 2
! 2
Note
In the example test the matrix a of size 3 Γ 4 is equal to:
1 2 1 2
3 3 3 3
2 1 2 1
| import sys
input = sys.stdin.readline
flush = sys.stdout.flush
from collections import Counter
from math import sqrt
def query(h, w, i1, j1, i2, j2):
print("? {} {} {} {} {} {}".format(h, w, i1, j1, i2, j2))
flush()
return int(input())
def fac(x):
cnt = Counter()
if not x % 2:
while not x % 2:
x //= 2
cnt[2] += 1
for i in range(3, int(sqrt(x)) + 1, 2):
if not x % i:
while not x % i:
x //= i
cnt[i] += 1
if x > 1: cnt[x] += 1
return cnt
def check(a, b, flag):
mid = (a // 2) * b
if a == 2:
if flag: return query(mid, n, 1, 1, mid + 1, 1)
else: return query(m, mid, 1, 1, 1, mid + 1)
if a == 3:
if flag: return query(mid, n, 1, 1, mid + 1, 1) and query(mid, n, 1, 1, mid + b + 1, 1)
else: return query(m, mid, 1, 1, 1, mid + 1) and query(m, mid, 1, 1, 1, mid + b + 1)
if flag: return query(mid, n, 1, 1, mid + 1, 1) and query(mid, n, 1, 1, mid + b + 1, 1) and query(mid, n, b + 1, 1, mid + b + 1, 1)
else: return query(m, mid, 1, 1, 1, mid + 1) and query(m, mid, 1, 1, 1, mid + b + 1) and query(m, mid, 1, b + 1, 1, mid + b + 1)
m, n = map(int, input().split())
m0, n0 = m, n
fm, fn = fac(m0), fac(n0)
for k, v in fm.items():
for _ in range(v):
if check(k, m0 // k, 1): m0 //= k
for k, v in fn.items():
for _ in range(v):
if check(k, n0 // k, 0): n0 //= k
ans0, ans1 = 0, 0
m0, n0 = m // m0, n // n0
for i in range(1, m + 1):
if not m0 % i: ans0 += 1
for j in range(1, n + 1):
if not n0 % j: ans1 += 1
print("! {}".format(ans0 * ans1)) | {
"input": [
"3 4\n1\n1\n1\n0"
],
"output": [
"\n? 1 2 1 1 1 3\n? 1 2 2 1 2 3\n? 1 2 3 1 3 3\n? 1 1 1 1 1 2\n! 2"
]
} |
3,331 | 9 | Baby Ehab was toying around with arrays. He has an array a of length n. He defines an array to be good if there's no way to partition it into 2 subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in a so that it becomes a good array. Can you help him?
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero or all) elements. A partitioning of an array is a way to divide it into 2 subsequences such that every element belongs to exactly one subsequence, so you must use all the elements, and you can't share any elements.
Input
The first line contains an integer n (2 β€ n β€ 100) β the length of the array a.
The second line contains n integers a_1, a_2, β¦, a_{n} (1 β€ a_i β€ 2000) β the elements of the array a.
Output
The first line should contain the minimum number of elements you need to remove.
The second line should contain the indices of the elements you're removing, separated by spaces.
We can show that an answer always exists. If there are multiple solutions, you can print any.
Examples
Input
4
6 3 9 12
Output
1
2
Input
2
1 2
Output
0
Note
In the first example, you can partition the array into [6,9] and [3,12], so you must remove at least 1 element. Removing 3 is sufficient.
In the second example, the array is already good, so you don't need to remove any elements. | def possible(nums,target):
reach = {0}
for num in nums:
reach |= {i+num for i in reach if i+num <= target}
if target in reach:
return True
return False
n = int(input())
arr = list(map(int,input().split()))
s = sum(arr)
if s%2==1 or not possible(arr,s//2):
print(0)
else:
print(1)
mi = 100
res = -1
for i in range(n):
A = arr[i] & (-arr[i])
cnt = 0
while A :
cnt += 1
A >>= 1
if cnt < mi:
mi = cnt
res = i+1
print(res)
| {
"input": [
"4\n6 3 9 12\n",
"2\n1 2\n"
],
"output": [
"\n1\n2",
"\n0"
]
} |
3,332 | 10 | This is the easy version of the problem. The only difference is that here k=2. You can make hacks only if both the versions of the problem are solved.
This is an interactive problem.
Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR of two k-its a and b as (a + b)mod k.
The k-itwise XOR of two base k numbers is equal to the new number formed by taking the k-itwise XOR of their corresponding k-its. The k-itwise XOR of two decimal numbers a and b is denoted by aβ_{k} b and is equal to the decimal representation of the k-itwise XOR of the base k representations of a and b. All further numbers used in the statement below are in decimal unless specified. When k = 2 (it is always true in this version), the k-itwise XOR is the same as the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between 0 and n-1 inclusive. So, you have decided to guess it. Luckily, you can try at most n times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was x, and you guess a different number y, then the system changes the password to a number z such that xβ_{k} z=y. Guess the password and break into the system.
Input
The first line of input contains a single integer t (1β€ tβ€ 10 000) denoting the number of test cases. t test cases follow.
The first line of each test case contains two integers n (1β€ nβ€ 2β
10^5) and k (k=2).
It is guaranteed that the sum of n over all test cases does not exceed 2β
10^5.
Interaction
For each test case, first read two integers n and k. Then you may ask up to n queries.
For each query, print a single integer y (0β€ yβ€ 2β
10^7). Let the current password be x. After that, read an integer r.
If x=y, you will read r=1 and the test case is solved. You must then continue solving the remaining test cases.
Else, you will read r=0. At this moment the password is changed to a number z such that xβ_{k} z=y.
After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get the Idleness limit exceeded verdict.
To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If you ask an invalid query or exceed n queries, you will read r=-1 and you will receive the Wrong Answer verdict. Make sure to exit immediately to avoid unexpected verdicts.
Note that the interactor is adaptive. That is, the original password is not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial password such that all the answers to the queries are consistent.
Hacks:
To use hacks, use the following format of tests:
The first line should contain a single integer t (1β€ tβ€ 10 000) β the number of test cases.
The first and only line of each test case should contain two integers n (1β€ nβ€ 2β
10^5) and k (k=2) denoting the number of queries and the base respectively. The optimal original password is automatically decided by the adaptive interactor.
You must ensure that the sum of n over all test cases does not exceed 2β
10^5.
Example
Input
1
5 2
0
0
1
Output
3
4
5
Note
In the example test case, the hidden password is 2.
The first query is 3. It is not equal to the current password. So, 0 is returned, and the password is changed to 1 since 2β_2 1=3.
The second query is 4. It is not equal to the current password. So, 0 is returned, and the password is changed to 5 since 1β_2 5=4.
The third query is 5. It is equal to the current password. So, 1 is returned, and the job is done.
Note that this initial password is taken just for the sake of explanation. When you submit, the interactor might behave differently because it is adaptive. | try:
import sys
def solve():
n,k = map(int,input().split())
print(0)
sys.stdout.flush()
glad = int(input())
if(glad == 1):
return
for i in range(1 , n):
print(i^(i-1))
sys.stdout.flush()
glad = int(input())
if (glad == 1):
break
for _ in range(int(input())):
solve()
except EOFError:
print(" ") | {
"input": [
"1\n5 2\n\n0\n\n0\n\n1\n"
],
"output": [
"0\n1\n3\n"
]
} |
3,333 | 11 | You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language.
Input
This program has only one test, and it's empty (it doesn't give your program anything to read).
Output
Output the name of the mysterious language.
Examples | #!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def inpu(): return int(inp())
# -----------------------------------------------------------------
def regularbracket(t):
p = 0
for i in t:
if i == "(":
p += 1
else:
p -= 1
if p < 0:
return False
else:
if p > 0:
return False
else:
return True
# -------------------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# ------------------------------reverse string(pallindrome)
def reverse1(string):
pp = ""
for i in string[::-1]:
pp += i
if pp == string:
return True
return False
# --------------------------------reverse list(paindrome)
def reverse2(list1):
l = []
for i in list1[::-1]:
l.append(i)
if l == list1:
return True
return False
def mex(list1):
# list1 = sorted(list1)
p = max(list1) + 1
for i in range(len(list1)):
if list1[i] != i:
p = i
break
return p
def sumofdigits(n):
n = str(n)
s1 = 0
for i in n:
s1 += int(i)
return s1
def perfect_square(n):
s = math.sqrt(n)
if s == int(s):
return True
return False
# -----------------------------roman
def roman_number(x):
if x > 15999:
return
value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
roman = ""
i = 0
while x > 0:
div = x // value[i]
x = x % value[i]
while div:
roman += symbol[i]
div -= 1
i += 1
return roman
def soretd(s):
for i in range(1, len(s)):
if s[i - 1] > s[i]:
return False
return True
# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
ct = 0
for i in range(2, h + 1, 2):
for j in range(2, w + 1, 2):
ct += (h - i + 1) * (w - j + 1)
return ct
def countrhombi2(h, w):
return ((h * h) // 4) * ((w * w) // 4)
# ---------------------------------
def binpow(a, b):
if b == 0:
return 1
else:
res = binpow(a, b // 2)
if b % 2 != 0:
return res * res * a
else:
return res * res
# -------------------------------------------------------
def binpowmodulus(a, b, m):
a %= m
res = 1
while (b > 0):
if (b & 1):
res = res * a % m
a = a * a % m
b >>= 1
return res
# -------------------------------------------------------------
def coprime_to_n(n):
result = n
i = 2
while (i * i <= n):
if (n % i == 0):
while (n % i == 0):
n //= i
result -= result // i
i += 1
if (n > 1):
result -= result // n
return result
# -------------------prime
def prime(x):
if x == 1:
return False
else:
for i in range(2, int(math.sqrt(x)) + 1):
if (x % i == 0):
return False
else:
return True
def luckynumwithequalnumberoffourandseven(x, n, a):
if x >= n and str(x).count("4") == str(x).count("7"):
a.append(x)
else:
if x < 1e12:
luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a)
luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a)
return a
def luckynuber(x, n, a):
p = set(str(x))
if len(p) <= 2:
a.append(x)
if x < n:
luckynuber(x + 1, n, a)
return a
#------------------------------------------------------interactive problems
def interact(type, x):
if type == "r":
inp = input()
return inp.strip()
else:
print(x, flush=True)
#------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
# Initialize result
count = 0
# Keep dividing n by
# 5 & update Count
while (n >= 5):
n //= 5
count += n
return count
#-----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
#-----------------------------------------------lucky number with two lucky any digits
res = set()
def solve(p, l, a, b,n):#given number
if p > n or l > 10:
return
if p > 0:
res.add(p)
solve(p * 10 + a, l + 1, a, b,n)
solve(p * 10 + b, l + 1, a, b,n)
# problem
"""
n = int(input())
for a in range(0, 10):
for b in range(0, a):
solve(0, 0)
print(len(res))
"""
#-----------------------------------------------
# endregion------------------------------
"""
def main():
n = inpu()
cnt=0
c = n
if n % 7 == 0:
print("7" * (n // 7))
else:
while(c>0):
c-=4
cnt+=1
if c%7==0 and c>=0:
#print(n,n%4)
print("4"*(cnt)+"7"*(c//7))
break
else:
if n % 4 == 0:
print("4" * (n // 4))
else:
print(-1)
if __name__ == '__main__':
main()
"""
"""
def main():
n,t = sep()
arr = lis()
i=0
cnt=0
min1 = min(arr)
while(True):
if t>=arr[i]:
cnt+=1
t-=arr[i]
i+=1
else:
i+=1
if i==n:
i=0
if t<min1:
break
print(cnt)
if __name__ == '__main__':
main()
"""
# Python3 program to find all subsets
# by backtracking.
# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index,d):
print(*subset)
s = sum(subset)
d.append(s)
for i in range(index, len(A)):
# include the A[i] in subset.
subset.append(A[i])
# move onto the next element.
subsetsUtil(A, subset, i + 1,d)
# exclude the A[i] from subset and
# triggers backtracking.
subset.pop(-1)
return d
def subsetSums(arr, l, r,d, sum=0):
if l > r:
d.append(sum)
return
subsetSums(arr, l + 1, r,d, sum + arr[l])
# Subset excluding arr[l]
subsetSums(arr, l + 1, r,d, sum)
return d
"""
def main():
t = inpu()
for _ in range(t):
n = inpu()
arr=[]
subset=[]
i=0
l=[]
for j in range(26):
arr.append(3**j)
if __name__ == '__main__':
main()
"""
"""
def main():
n = int(input())
cnt=1
if n==1:
print(1)
else:
for i in range(1,n):
cnt+=i*12
print(cnt)
if __name__ == '__main__':
main()
"""
def main():
print("INTERCAL")
if __name__ == '__main__':
main()
| {
"input": [],
"output": []
} |
3,334 | 9 | They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost).
But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.
A simple path is the path which goes through every Berland city not more than once.
The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.
Note how the fools' paths are given in the input.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the number of cities.
Each of the next n - 1 lines contains two space-separated integers ui, vi (1 β€ ui, vi β€ n, ui β vi), that means that there is a road connecting cities ui and vi.
The next line contains integer k (0 β€ k β€ 105) β the number of pairs of fools who visit each other.
Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 β€ ai, bi β€ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.
Output
Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.
Examples
Input
5
1 2
1 3
2 4
2 5
2
1 4
3 5
Output
2 1 1 1
Input
5
3 4
4 5
1 4
2 4
3
2 3
1 3
3 5
Output
3 1 1 1
Note
In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.
In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1. | # solved using sparse table
from math import log2
def construct(root):
stack = [root]
while stack:
u = stack.pop()
for v in edges[u]:
if v != parents[u]:
parents[v] = u
levels[v] = levels[u] + 1
stack.append(v)
table.append(parents)
k = 1
while (1 << k) < n:
new_row = [0] * n
for i in range(n):
new_row[i] = table[k-1][table[k-1][i]]
table.append(new_row)
k += 1
def getlca(a, b): # range MINIMUM query
depth_gap = levels[b] - levels[a]
if depth_gap < 0: # make sure node b is at a deeper level than node a
a, b = b, a
depth_gap = -depth_gap
if depth_gap != 0: ## traverse upward from a so that both a and b are at the same level
k = int(log2(depth_gap))
while depth_gap:
if (depth_gap) >= (2**k):
b = table[k][b]
depth_gap = levels[b] - levels[a]
k -= 1
if b == a:
return a
for k in range(logn, -1, -1):
if table[k][a] != table[k][b]:
a, b = table[k][a], table[k][b]
return table[0][a]
def travel(a, b):
lca = getlca(a, b)
tally[a] += 1
tally[b] += 1
tally[lca] -= 2
def sum_subtree(root):
stack = []
for v in edges[root]:
stack.append([v, 0])
while stack:
u, i = stack[-1]
if i == len(edges[u]):
tally[parents[u]] += tally[u]
stack.pop()
else:
v = edges[u][i]
stack[-1][1] += 1
if v != parents[u]:
stack.append([v, 0])
def count_fools(u, v):
if levels[u] > levels[v]:
return tally[u]
else:
return tally[v]
n = int(input())
logn = int(log2(n))
edges = [[] for _ in range(n)]
edges_list = []
for i in range(n-1):
u, v = map(int, input().split())
u, v = u-1, v-1 # adjusting index convention for convenience
edges[u].append(v)
edges[v].append(u)
edges_list.append((u, v))
parents = [0] * n
levels = [0] * n
table = []
root = 0
construct(root//2)
tally = [0] * n
k = int(input())
for _ in range(k):
a, b = map(int, input().split())
travel(a-1, b-1)
sum_subtree(root)
for u, v in edges_list:
print(count_fools(u, v), end=' ')
print()
| {
"input": [
"5\n1 2\n1 3\n2 4\n2 5\n2\n1 4\n3 5\n",
"5\n3 4\n4 5\n1 4\n2 4\n3\n2 3\n1 3\n3 5\n"
],
"output": [
"2 1 1 1\n",
"3 1 1 1\n"
]
} |
3,335 | 9 | There is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i, j).
A group of six numbers (a, b, c, d, x0, y0), where 0 β€ a, b, c, d, is a cross, and there is a set of cells that are assigned to it. Cell (x, y) belongs to this set if at least one of two conditions are fulfilled:
* |x0 - x| β€ a and |y0 - y| β€ b
* |x0 - x| β€ c and |y0 - y| β€ d
<image> The picture shows the cross (0, 1, 1, 0, 2, 3) on the grid 3 Γ 4.
Your task is to find the number of different groups of six numbers, (a, b, c, d, x0, y0) that determine the crosses of an area equal to s, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (x, y) of the cross 1 β€ x β€ n; 1 β€ y β€ m holds). The area of the cross is the number of cells it has.
Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.
Input
The input consists of a single line containing three integers n, m and s (1 β€ n, m β€ 500, 1 β€ s β€ nΒ·m). The integers are separated by a space.
Output
Print a single integer β the number of distinct groups of six integers that denote crosses with area s and that are fully placed on the n Γ m grid.
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 2 1
Output
4
Input
3 4 5
Output
4
Note
In the first sample the sought groups of six numbers are: (0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 2, 1), (0, 0, 0, 0, 2, 2).
In the second sample the sought groups of six numbers are: (0, 1, 1, 0, 2, 2), (0, 1, 1, 0, 2, 3), (1, 0, 0, 1, 2, 2), (1, 0, 0, 1, 2, 3). | from sys import stdin
def read(): return map(int, stdin.readline().split())
def ways(h,w,area):
if area == h*w:
return 2 * ( (h+1)//2 * (w+1)//2 ) - 1
if area > h*w: return 0
if area < h+w-1: return 0
area = h*w - area
if area % 4 != 0: return 0
area //= 4
ans = 0
h //= 2
w //= 2
for a in range(1,h+1):
if area%a == 0 and area//a <= w:
ans += 1
return ans*2
n, m, s = read()
ans = 0
for h in range(1,n+1,2):
for w in range(1,m+1,2):
ans += ways(h,w,s) * (n-h+1) * (m-w+1)
print(ans)
| {
"input": [
"2 2 1\n",
"3 4 5\n"
],
"output": [
" 4\n",
" 4\n"
]
} |
3,336 | 9 | A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 β€ l β€ r β€ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.
The expression <image> means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β as "xor".
In this problem you are asked to compute the number of sequences made of n integers from 0 to 2m - 1 that are not a wool sequence. You should print this number modulo 1000000009 (109 + 9).
Input
The only line of input contains two space-separated integers n and m (1 β€ n, m β€ 105).
Output
Print the required number of sequences modulo 1000000009 (109 + 9) on the only line of output.
Examples
Input
3 2
Output
6
Note
Sequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (3, 2, 3). | MOD = int(1e9+9)
def fast_power(b, e):
res = 1
while e:
if e % 2 == 1:
res = res * b % MOD
b = b * b % MOD
e >>= 1
return res
n, m = map(int, input().split())
a = fast_power(2, m) - 1
a = (a + MOD) % MOD
b = a - 1
b = (b + MOD) % MOD
for i in range(1, n):
a = a * b % MOD
b = (b - 1 + MOD) % MOD
print(a)
| {
"input": [
"3 2\n"
],
"output": [
"6\n"
]
} |
3,337 | 7 | Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].
You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.
Input
The input consists of only one line. The only line contains the string s (1 β€ |s| β€ 106). Each character in s will be either "l" or "r".
Output
Output n lines β on the i-th line you should print the i-th stone's number from the left.
Examples
Input
llrlr
Output
3
5
4
2
1
Input
rrlll
Output
1
2
5
4
3
Input
lrlrr
Output
2
4
5
3
1
Note
In the first example, the positions of stones 1, 2, 3, 4, 5 will be <image>, respectively. So you should print the sequence: 3, 5, 4, 2, 1. | def escape(s):
for i in range(len(s)):
if s[i]=="r":
print(i+1)
for i in range(len(s)-1,-1,-1):
if s[i]=="l":
print(i+1)
return ""
print(escape(input())) | {
"input": [
"llrlr\n",
"lrlrr\n",
"rrlll\n"
],
"output": [
"3\n5\n4\n2\n1\n",
"2\n4\n5\n3\n1\n",
"1\n2\n5\n4\n3\n"
]
} |
3,338 | 7 | Little penguin Polo adores strings. But most of all he adores strings of length n.
One day he wanted to find a string that meets the following conditions:
1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
2. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si β si + 1(1 β€ i < n).
3. Among all strings that meet points 1 and 2, the required string is lexicographically smallest.
Help him find such string or state that such string doesn't exist.
String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.
Input
A single line contains two positive integers n and k (1 β€ n β€ 106, 1 β€ k β€ 26) β the string's length and the number of distinct letters.
Output
In a single line print the required string. If there isn't such string, print "-1" (without the quotes).
Examples
Input
7 4
Output
ababacd
Input
4 7
Output
-1 | def polo(n,k):
if k==1 and n>1:
return -1
if k==1 and n==1:
return "a"
if k>n:
return -1
base="ab"*(n)
k-=2
n-=k
ans=base[:n]
l="cdefghijklmnopqrstuvwxyz"
ans+=l[:k]
return ans
a,b=map(int,input().strip().split())
print(polo(a,b)) | {
"input": [
"4 7\n",
"7 4\n"
],
"output": [
"-1\n",
"ababacd"
]
} |
3,339 | 7 | Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.
Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.
Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
Input
The single line contains integer n (10 β€ |n| β€ 109) β the state of Ilya's bank account.
Output
In a single line print an integer β the maximum state of the bank account that Ilya can get.
Examples
Input
2230
Output
2230
Input
-10
Output
0
Input
-100003
Output
-10000
Note
In the first test sample Ilya doesn't profit from using the present.
In the second test sample you can delete digit 1 and get the state of the account equal to 0. | def mb(ns):
n=int(ns)
if n>=0:
return n
return max(int(ns[:-1]),int(ns[:-2]+ns[-1]))
print(mb(input())) | {
"input": [
"2230\n",
"-100003\n",
"-10\n"
],
"output": [
"2230\n",
"-10000\n",
"0\n"
]
} |
3,340 | 10 | Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.
Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?
Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.
Help Inna maximize the total joy the hares radiate. :)
Input
The first line of the input contains integer n (1 β€ n β€ 3000) β the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 β€ ai, bi, ci β€ 105.
Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number Ρi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
Output
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
Examples
Input
4
1 2 3 4
4 3 2 1
0 1 1 0
Output
13
Input
7
8 5 7 6 1 8 9
2 7 9 5 4 3 1
2 3 3 4 1 1 3
Output
44
Input
3
1 1 1
1 2 1
1 1 1
Output
4 | def main():
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
c = list(map(int, input().split(' ')))
d0 = [0]*n
d0[n-1] = a[n-1]
d1 = [0]*n
d1[n-1] = b[n-1]
for i in range(n-2, -1, -1):
d0[i] = max(a[i]+d1[i+1], b[i]+d0[i+1])
d1[i] = max(b[i]+d1[i+1], c[i]+d0[i+1])
print(d0[0])
if __name__ == "__main__":
main()
| {
"input": [
"7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3\n",
"4\n1 2 3 4\n4 3 2 1\n0 1 1 0\n",
"3\n1 1 1\n1 2 1\n1 1 1\n"
],
"output": [
"44\n",
"13\n",
"4\n"
]
} |
3,341 | 9 | Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times).
A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
Input
The first line contains integer m (1 β€ m β€ 105) β the number of stages to build a sequence.
Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1 β€ xi β€ 105) β the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li, ci (1 β€ li β€ 105, 1 β€ ci β€ 104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence.
The next line contains integer n (1 β€ n β€ 105) β the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.
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 the elements that Sereja is interested in, in the order in which their numbers occur in the input.
Examples
Input
6
1 1
1 2
2 2 1
1 3
2 5 2
1 4
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output
1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4 | from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
if not i in F:
k = bisect_left(t, i)
F[i] = s[k] if type(s[k]) == str else f((i - t[k] - 1) % s[k] + 1)
return F[i]
print(' '.join(f(i) for i in map(int, input().split())))
# Made By Mostafa_Khaled | {
"input": [
"6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n"
],
"output": [
"1\n2\n1\n2\n3\n1\n2\n1\n2\n3\n1\n2\n1\n2\n3\n4\n"
]
} |
3,342 | 8 | The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 β€ i β€ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 β€ i < n), ai + 1 - ai = k, where k is the number the Queen chose.
Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?
Input
The first line contains two space-separated integers: n, k (1 β€ n, k β€ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 1000) β the heights of the trees in the row.
Output
In the first line print a single integer p β the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.
If the gardener needs to increase the height of the j-th (1 β€ j β€ n) tree from the left by x (x β₯ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 β€ j β€ n) tree from the left by x (x β₯ 1) meters, print on the corresponding line "- j x".
If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.
Examples
Input
4 1
1 2 1 5
Output
2
+ 3 2
- 4 1
Input
4 1
1 2 3 4
Output
0 | n, k = list(map(int,input().split(" ")))
ts = list(map(int,input().split(" ")))
aps = dict()
for i in range(n):
f = ts[i] - k*i
if f > 0:
aps[f] = aps.get(f,0) + 1
af = max([i for i in aps.keys()], key=lambda x:aps[x])
print(len([1 for i in range(n) if ts[i] != af + k*i]))
def action(af, i, ts, k):
if ts[i] > af+k*i:
return "- %i %i" % (i+1, ts[i] - (af+k*i))
elif ts[i] < af+k*i:
return "+ " + str(i+1) + " " + str(af+(k*i) - ts[i])
else:
return None
acts = [action(af, i, ts, k) for i in range(n)]
acts = [act for act in acts if act]
print("\n".join(acts))
| {
"input": [
"4 1\n1 2 1 5\n",
"4 1\n1 2 3 4\n"
],
"output": [
"2\n+ 3 2\n- 4 1\n",
"0\n"
]
} |
3,343 | 9 | Right now you are to solve a very, very simple problem β to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both by one; you may choose two adjacent even numbers and divide both by two. Nothing else. Crack the safe!
Input
The single line of the input contains four space-separated integer positive numbers not greater than 109 each β four numbers on the circle in consecutive order.
Output
The output should contain "-1" (quotes for clarity) if the safe is secure, that is it's impossible to crack it. Otherwise, output should contain the sequence of operations (one operations per line) leading to unlocking the safe. You don't have to minimize the number of operations, but it should not exceed 1000. To make things clear, assume numbers stand on positions 1 through 4. Each operation is encoded by two symbols. If the following operation is dividing then first symbol is '/'; otherwise it's '+' (addition). The second symbol is the position of the first number in pair in consecutive order. (see samples for clarification).
If there are several solutions, output any of them.
Examples
Input
1 1 1 1
Output
Input
1 2 4 2
Output
/2
/3
Input
3 3 1 1
Output
+1
/1
/1
Input
2 1 2 4
Output
/3
/4 | ring = list(map(int, input().split()))
n = len(ring)
record = []
def halve(pos):
a, b = pos % n, (pos + 1) % n
ring[a] //= 2
ring[b] //= 2
record.append('/%d' % (a + 1))
def increment(pos):
a, b = pos % n, (pos + 1) % n
ring[a] += 1
ring[b] += 1
record.append('+%d' % (a + 1))
while True:
modified = False
for a in range(n):
b = (a + 1) % n
while ring[a] + ring[b] > 3:
if ring[a] % 2 == 1 and ring[b] % 2 == 1:
increment(a)
elif ring[a] % 2 == 1:
increment(a - 1)
elif ring[b] % 2 == 1:
increment(b)
halve(a)
modified = True
if not modified:
break
while 2 in ring:
pos = ring.index(2)
increment(pos - 1)
increment(pos)
halve(pos - 1)
halve(pos)
if len(record) > 0:
print('\n'.join(record))
#print(len(record), ring)
| {
"input": [
"3 3 1 1\n",
"2 1 2 4\n",
"1 2 4 2\n",
"1 1 1 1\n"
],
"output": [
"+1\n/1\n/1\n",
"/3\n/4\n",
"/2\n/3\n",
"\n"
]
} |
3,344 | 7 | You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.
You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.
Input
First line contains an integer n (6 β€ n β€ 8) β the length of the string.
Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword).
Output
Print a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter).
Examples
Input
7
j......
Output
jolteon
Input
7
...feon
Output
leafeon
Input
7
.l.r.o.
Output
flareon
Note
Here's a set of names in a form you can paste into your solution:
["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]
{"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"} | def match(p, s):
return len(p) == len(s) and all(d in ('.', c) for d, c in zip(p, s))
l = ['vaporeon', 'jolteon', 'flareon', 'espeon',
'umbreon', 'leafeon', 'glaceon', 'sylveon']
input()
p = input()
print(next(s for s in l if match(p, s)))
| {
"input": [
"7\nj......\n",
"7\n...feon\n",
"7\n.l.r.o.\n"
],
"output": [
"jolteon\n",
"leafeon\n",
"flareon\n"
]
} |
3,345 | 11 | You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.
You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route β the chain of junctions, consecutively connected by roads. Routes must meet the following conditions:
* all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same);
* to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes);
* no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit).
Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2Β·105) β the number of intersections and roads, respectively.
The following m lines contain two integers β the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself.
Please note that it is not guaranteed that you can get from any junction to any other one by using the roads.
Output
If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement.
If it is impossible to make the routes in accordance with the requirements, print NO.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
NO
Input
5 6
1 2
1 3
1 4
2 5
3 5
4 5
Output
YES
3 5 4 1
3 5 3 1
3 5 2 1 | from typing import List
import sys
n, m = [int(a) for a in input().split(' ')]
adj: List[List[int]] = [[]] + [[] for _ in range(n)]
visited: List[bool] = [False] * (n + 1)
parent: List[int] = [0] * (n + 1)
depth: List[int] = [0] * (n + 1)
low: List[int] = [0] * (n + 1)
cx: List[int] = [0] * (n + 1)
cy: List[int] = [0] * (n + 1)
qi: List[int] = [0] * (n + 1)
for i in range(m):
u, v = [int(a) for a in input().split(' ')]
adj[u].append(v)
adj[v].append(u)
def solve():
for i in range(1, n + 1):
if not visited[i]:
# dfs(i)
dfs2(i)
print('NO')
def lca(a, b):
while depth[a] > depth[b]:
a = parent[a]
while depth[b] > depth[a]:
b = parent[b]
while a != b:
a = parent[a]
b = parent[b]
return a
def parent_path(a, b):
p = []
while a != b:
p.append(str(a))
a = parent[a]
p.append(str(b))
return p
def gett(a, b, u, v, e):
if depth[b] > depth[v]:
a, b, u, v = u, v, a, b
# e = lca(a, u)
print('YES')
c1 = parent_path(e, v)
print(' '.join([str(len(c1))] + c1))
c2 = list(reversed(parent_path(a, e))) + list(reversed(parent_path(v, b)))
print(' '.join([str(len(c2))] + c2))
c3 = list(reversed(parent_path(u, e))) + [str(v)]
print(' '.join([str(len(c3))] + c3))
exit(0)
def dfs(i):
visited[i] = True
depth[i] = depth[parent[i]] + 1
for ni in adj[i]:
if parent[i] != ni:
if not visited[ni]:
parent[ni] = i
dfs(ni)
elif depth[ni] < depth[i]:
x = i
while x != ni:
if cx[x] and cy[x]:
gett(cx[x], cy[x], i, ni)
else:
cx[x] = i
cy[x] = ni
x = parent[x]
def dfs2(i):
visited[i] = True
q = list()
q.append(i)
while len(q) > 0:
u = q[-1]
if qi[u] >= len(adj[u]):
q.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
depth[v] = depth[u] + 1
visited[v] = True
q.append(v)
elif depth[v] < depth[u]:
x = u
while x != v:
if cx[x] and cy[x]:
gett(cx[x], cy[x], u, v, x)
else:
cx[x] = u
cy[x] = v
x = parent[x]
solve() | {
"input": [
"5 6\n1 2\n1 3\n1 4\n2 5\n3 5\n4 5\n",
"4 4\n1 2\n2 3\n3 4\n4 1\n"
],
"output": [
"YES\n3 5 2 1 \n3 5 3 1 \n3 5 4 1 \n",
"NO\n"
]
} |
3,346 | 8 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.
Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.
You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of employees of company Looksery.
Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1.
The last line contains n space-separated integers: a1, a2, ..., an (0 β€ ai β€ n), where ai represents the number of messages that the i-th employee should get according to Igor.
Output
In the first line print a single integer m β the number of employees who should come to the party so that Igor loses the dispute.
In the second line print m space-separated integers β the numbers of these employees in an arbitrary order.
If Igor wins the dispute in any case, print -1.
If there are multiple possible solutions, print any of them.
Examples
Input
3
101
010
001
0 1 2
Output
1
1
Input
1
1
1
Output
0
Input
4
1111
0101
1110
0001
1 0 1 0
Output
4
1 2 3 4
Note
In the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.
In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.
In the third sample the first employee will receive 2 messages, the second β 3, the third β 2, the fourth β 3. | import sys
input = sys.stdin.readline
def solve():
n = int(input())
b = [input() for i in range(n)]
a = list(map(int,input().split()))
c = [None]*n
w = [False]*n
h = [0]*n
for i in range(n):
c[i] = (a[i], i)
c.sort()
r = []
for i in range(n):
while True:
ok = False
for j in range(i+1):
v = c[j][1]
if h[v] == a[v]:
ok = True
if w[v]:
raise Exception('wut')
else:
w[v] = True
r.append(v)
for k in range(n):
if b[v][k] == '1':
h[k] += 1
if not ok:
break
print(len(r))
for i in r:
print(i+1)
#print(h)
solve()
| {
"input": [
"3\n101\n010\n001\n0 1 2\n",
"4\n1111\n0101\n1110\n0001\n1 0 1 0\n",
"1\n1\n1\n"
],
"output": [
"1\n1 ",
"1\n2 ",
"0\n"
]
} |
3,347 | 10 | There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert β Tablecityβs Chief of Police. Albert does not know where the thief is located, but he does know how he moves.
Tablecity can be represented as 1000 Γ 2 grid, where every cell represents one district. Each district has its own unique name β(X, Y)β, where X and Y are the coordinates of the district in the grid. The thiefβs movement is as
Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity.
Below is an example of thiefβs possible movements if he is located in district (7,1):
<image>
Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.
Input
There is no input for this problem.
Output
The first line of output contains integer N β duration of police search in hours. Each of the following N lines contains exactly 4 integers Xi1, Yi1, Xi2, Yi2 separated by spaces, that represent 2 districts (Xi1, Yi1), (Xi2, Yi2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thiefβs initial position and movement.
* N β€ 2015
* 1 β€ X β€ 1000
* 1 β€ Y β€ 2
Examples
Input
Π ΡΡΠΎΠΉ Π·Π°Π΄Π°ΡΠ΅ Π½Π΅Ρ ΠΏΡΠΈΠΌΠ΅ΡΠΎΠ² Π²Π²ΠΎΠ΄Π°-Π²ΡΠ²ΠΎΠ΄Π°.
This problem doesn't have sample input and output.
Output
Π‘ΠΌΠΎΡΡΠΈΡΠ΅ Π·Π°ΠΌΠ΅ΡΠ°Π½ΠΈΠ΅ Π½ΠΈΠΆΠ΅.
See the note below.
Note
Let's consider the following output:
2
5 1 50 2
8 1 80 2
This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.
Consider the following initial position and thiefβs movement:
In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.
At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.
Since there is no further investigation by the police, the thief escaped! | def main():
print(2001)
for i in range(1, 1001):
print(i, 1, i, 2)
print(1, 1, 1, 1)
for i in range(1, 1001):
print(i, 1, i, 2)
main()
| {
"input": [
"Π ΡΡΠΎΠΉ Π·Π°Π΄Π°ΡΠ΅ Π½Π΅Ρ ΠΏΡΠΈΠΌΠ΅ΡΠΎΠ² Π²Π²ΠΎΠ΄Π°-Π²ΡΠ²ΠΎΠ΄Π°.\nThis problem doesn't have sample input and output."
],
"output": [
"2000\n1 1 1 2\n2 1 2 2\n3 1 3 2\n4 1 4 2\n5 1 5 2\n6 1 6 2\n7 1 7 2\n8 1 8 2\n9 1 9 2\n10 1 10 2\n11 1 11 2\n12 1 12 2\n13 1 13 2\n14 1 14 2\n15 1 15 2\n16 1 16 2\n17 1 17 2\n18 1 18 2\n19 1 19 2\n20 1 20 2\n21 1 21 2\n22 1 22 2\n23 1 23 2\n24 1 24 2\n25 1 25 2\n26 1 26 2\n27 1 27 2\n28 1 28 2\n29 1 29 2\n30 1 30 2\n31 1 31 2\n32 1 32 2\n33 1 33 2\n34 1 34 2\n35 1 35 2\n36 1 36 2\n37 1 37 2\n38 1 38 2\n39 1 39 2\n40 1 40 2\n41 1 41 2\n42 1 42 2\n43 1 43 2\n44 1 44 2\n45 1 45 2\n46 1 46 2\n47 1 47 2\n48 1 48 2\n49 1 49 2\n50 1 50 2\n51 1 51 2\n52 1 52 2\n53 1 53 2\n54 1 54 2\n55 1 55 2\n56 1 56 2\n57 1 57 2\n58 1 58 2\n59 1 59 2\n60 1 60 2\n61 1 61 2\n62 1 62 2\n63 1 63 2\n64 1 64 2\n65 1 65 2\n66 1 66 2\n67 1 67 2\n68 1 68 2\n69 1 69 2\n70 1 70 2\n71 1 71 2\n72 1 72 2\n73 1 73 2\n74 1 74 2\n75 1 75 2\n76 1 76 2\n77 1 77 2\n78 1 78 2\n79 1 79 2\n80 1 80 2\n81 1 81 2\n82 1 82 2\n83 1 83 2\n84 1 84 2\n85 1 85 2\n86 1 86 2\n87 1 87 2\n88 1 88 2\n89 1 89 2\n90 1 90 2\n91 1 91 2\n92 1 92 2\n93 1 93 2\n94 1 94 2\n95 1 95 2\n96 1 96 2\n97 1 97 2\n98 1 98 2\n99 1 99 2\n100 1 100 2\n101 1 101 2\n102 1 102 2\n103 1 103 2\n104 1 104 2\n105 1 105 2\n106 1 106 2\n107 1 107 2\n108 1 108 2\n109 1 109 2\n110 1 110 2\n111 1 111 2\n112 1 112 2\n113 1 113 2\n114 1 114 2\n115 1 115 2\n116 1 116 2\n117 1 117 2\n118 1 118 2\n119 1 119 2\n120 1 120 2\n121 1 121 2\n122 1 122 2\n123 1 123 2\n124 1 124 2\n125 1 125 2\n126 1 126 2\n127 1 127 2\n128 1 128 2\n129 1 129 2\n130 1 130 2\n131 1 131 2\n132 1 132 2\n133 1 133 2\n134 1 134 2\n135 1 135 2\n136 1 136 2\n137 1 137 2\n138 1 138 2\n139 1 139 2\n140 1 140 2\n141 1 141 2\n142 1 142 2\n143 1 143 2\n144 1 144 2\n145 1 145 2\n146 1 146 2\n147 1 147 2\n148 1 148 2\n149 1 149 2\n150 1 150 2\n151 1 151 2\n152 1 152 2\n153 1 153 2\n154 1 154 2\n155 1 155 2\n156 1 156 2\n157 1 157 2\n158 1 158 2\n159 1 159 2\n160 1 160 2\n161 1 161 2\n162 1 162 2\n163 1 163 2\n164 1 164 2\n165 1 165 2\n166 1 166 2\n167 1 167 2\n168 1 168 2\n169 1 169 2\n170 1 170 2\n171 1 171 2\n172 1 172 2\n173 1 173 2\n174 1 174 2\n175 1 175 2\n176 1 176 2\n177 1 177 2\n178 1 178 2\n179 1 179 2\n180 1 180 2\n181 1 181 2\n182 1 182 2\n183 1 183 2\n184 1 184 2\n185 1 185 2\n186 1 186 2\n187 1 187 2\n188 1 188 2\n189 1 189 2\n190 1 190 2\n191 1 191 2\n192 1 192 2\n193 1 193 2\n194 1 194 2\n195 1 195 2\n196 1 196 2\n197 1 197 2\n198 1 198 2\n199 1 199 2\n200 1 200 2\n201 1 201 2\n202 1 202 2\n203 1 203 2\n204 1 204 2\n205 1 205 2\n206 1 206 2\n207 1 207 2\n208 1 208 2\n209 1 209 2\n210 1 210 2\n211 1 211 2\n212 1 212 2\n213 1 213 2\n214 1 214 2\n215 1 215 2\n216 1 216 2\n217 1 217 2\n218 1 218 2\n219 1 219 2\n220 1 220 2\n221 1 221 2\n222 1 222 2\n223 1 223 2\n224 1 224 2\n225 1 225 2\n226 1 226 2\n227 1 227 2\n228 1 228 2\n229 1 229 2\n230 1 230 2\n231 1 231 2\n232 1 232 2\n233 1 233 2\n234 1 234 2\n235 1 235 2\n236 1 236 2\n237 1 237 2\n238 1 238 2\n239 1 239 2\n240 1 240 2\n241 1 241 2\n242 1 242 2\n243 1 243 2\n244 1 244 2\n245 1 245 2\n246 1 246 2\n247 1 247 2\n248 1 248 2\n249 1 249 2\n250 1 250 2\n251 1 251 2\n252 1 252 2\n253 1 253 2\n254 1 254 2\n255 1 255 2\n256 1 256 2\n257 1 257 2\n258 1 258 2\n259 1 259 2\n260 1 260 2\n261 1 261 2\n262 1 262 2\n263 1 263 2\n264 1 264 2\n265 1 265 2\n266 1 266 2\n267 1 267 2\n268 1 268 2\n269 1 269 2\n270 1 270 2\n271 1 271 2\n272 1 272 2\n273 1 273 2\n274 1 274 2\n275 1 275 2\n276 1 276 2\n277 1 277 2\n278 1 278 2\n279 1 279 2\n280 1 280 2\n281 1 281 2\n282 1 282 2\n283 1 283 2\n284 1 284 2\n285 1 285 2\n286 1 286 2\n287 1 287 2\n288 1 288 2\n289 1 289 2\n290 1 290 2\n291 1 291 2\n292 1 292 2\n293 1 293 2\n294 1 294 2\n295 1 295 2\n296 1 296 2\n297 1 297 2\n298 1 298 2\n299 1 299 2\n300 1 300 2\n301 1 301 2\n302 1 302 2\n303 1 303 2\n304 1 304 2\n305 1 305 2\n306 1 306 2\n307 1 307 2\n308 1 308 2\n309 1 309 2\n310 1 310 2\n311 1 311 2\n312 1 312 2\n313 1 313 2\n314 1 314 2\n315 1 315 2\n316 1 316 2\n317 1 317 2\n318 1 318 2\n319 1 319 2\n320 1 320 2\n321 1 321 2\n322 1 322 2\n323 1 323 2\n324 1 324 2\n325 1 325 2\n326 1 326 2\n327 1 327 2\n328 1 328 2\n329 1 329 2\n330 1 330 2\n331 1 331 2\n332 1 332 2\n333 1 333 2\n334 1 334 2\n335 1 335 2\n336 1 336 2\n337 1 337 2\n338 1 338 2\n339 1 339 2\n340 1 340 2\n341 1 341 2\n342 1 342 2\n343 1 343 2\n344 1 344 2\n345 1 345 2\n346 1 346 2\n347 1 347 2\n348 1 348 2\n349 1 349 2\n350 1 350 2\n351 1 351 2\n352 1 352 2\n353 1 353 2\n354 1 354 2\n355 1 355 2\n356 1 356 2\n357 1 357 2\n358 1 358 2\n359 1 359 2\n360 1 360 2\n361 1 361 2\n362 1 362 2\n363 1 363 2\n364 1 364 2\n365 1 365 2\n366 1 366 2\n367 1 367 2\n368 1 368 2\n369 1 369 2\n370 1 370 2\n371 1 371 2\n372 1 372 2\n373 1 373 2\n374 1 374 2\n375 1 375 2\n376 1 376 2\n377 1 377 2\n378 1 378 2\n379 1 379 2\n380 1 380 2\n381 1 381 2\n382 1 382 2\n383 1 383 2\n384 1 384 2\n385 1 385 2\n386 1 386 2\n387 1 387 2\n388 1 388 2\n389 1 389 2\n390 1 390 2\n391 1 391 2\n392 1 392 2\n393 1 393 2\n394 1 394 2\n395 1 395 2\n396 1 396 2\n397 1 397 2\n398 1 398 2\n399 1 399 2\n400 1 400 2\n401 1 401 2\n402 1 402 2\n403 1 403 2\n404 1 404 2\n405 1 405 2\n406 1 406 2\n407 1 407 2\n408 1 408 2\n409 1 409 2\n410 1 410 2\n411 1 411 2\n412 1 412 2\n413 1 413 2\n414 1 414 2\n415 1 415 2\n416 1 416 2\n417 1 417 2\n418 1 418 2\n419 1 419 2\n420 1 420 2\n421 1 421 2\n422 1 422 2\n423 1 423 2\n424 1 424 2\n425 1 425 2\n426 1 426 2\n427 1 427 2\n428 1 428 2\n429 1 429 2\n430 1 430 2\n431 1 431 2\n432 1 432 2\n433 1 433 2\n434 1 434 2\n435 1 435 2\n436 1 436 2\n437 1 437 2\n438 1 438 2\n439 1 439 2\n440 1 440 2\n441 1 441 2\n442 1 442 2\n443 1 443 2\n444 1 444 2\n445 1 445 2\n446 1 446 2\n447 1 447 2\n448 1 448 2\n449 1 449 2\n450 1 450 2\n451 1 451 2\n452 1 452 2\n453 1 453 2\n454 1 454 2\n455 1 455 2\n456 1 456 2\n457 1 457 2\n458 1 458 2\n459 1 459 2\n460 1 460 2\n461 1 461 2\n462 1 462 2\n463 1 463 2\n464 1 464 2\n465 1 465 2\n466 1 466 2\n467 1 467 2\n468 1 468 2\n469 1 469 2\n470 1 470 2\n471 1 471 2\n472 1 472 2\n473 1 473 2\n474 1 474 2\n475 1 475 2\n476 1 476 2\n477 1 477 2\n478 1 478 2\n479 1 479 2\n480 1 480 2\n481 1 481 2\n482 1 482 2\n483 1 483 2\n484 1 484 2\n485 1 485 2\n486 1 486 2\n487 1 487 2\n488 1 488 2\n489 1 489 2\n490 1 490 2\n491 1 491 2\n492 1 492 2\n493 1 493 2\n494 1 494 2\n495 1 495 2\n496 1 496 2\n497 1 497 2\n498 1 498 2\n499 1 499 2\n500 1 500 2\n501 1 501 2\n502 1 502 2\n503 1 503 2\n504 1 504 2\n505 1 505 2\n506 1 506 2\n507 1 507 2\n508 1 508 2\n509 1 509 2\n510 1 510 2\n511 1 511 2\n512 1 512 2\n513 1 513 2\n514 1 514 2\n515 1 515 2\n516 1 516 2\n517 1 517 2\n518 1 518 2\n519 1 519 2\n520 1 520 2\n521 1 521 2\n522 1 522 2\n523 1 523 2\n524 1 524 2\n525 1 525 2\n526 1 526 2\n527 1 527 2\n528 1 528 2\n529 1 529 2\n530 1 530 2\n531 1 531 2\n532 1 532 2\n533 1 533 2\n534 1 534 2\n535 1 535 2\n536 1 536 2\n537 1 537 2\n538 1 538 2\n539 1 539 2\n540 1 540 2\n541 1 541 2\n542 1 542 2\n543 1 543 2\n544 1 544 2\n545 1 545 2\n546 1 546 2\n547 1 547 2\n548 1 548 2\n549 1 549 2\n550 1 550 2\n551 1 551 2\n552 1 552 2\n553 1 553 2\n554 1 554 2\n555 1 555 2\n556 1 556 2\n557 1 557 2\n558 1 558 2\n559 1 559 2\n560 1 560 2\n561 1 561 2\n562 1 562 2\n563 1 563 2\n564 1 564 2\n565 1 565 2\n566 1 566 2\n567 1 567 2\n568 1 568 2\n569 1 569 2\n570 1 570 2\n571 1 571 2\n572 1 572 2\n573 1 573 2\n574 1 574 2\n575 1 575 2\n576 1 576 2\n577 1 577 2\n578 1 578 2\n579 1 579 2\n580 1 580 2\n581 1 581 2\n582 1 582 2\n583 1 583 2\n584 1 584 2\n585 1 585 2\n586 1 586 2\n587 1 587 2\n588 1 588 2\n589 1 589 2\n590 1 590 2\n591 1 591 2\n592 1 592 2\n593 1 593 2\n594 1 594 2\n595 1 595 2\n596 1 596 2\n597 1 597 2\n598 1 598 2\n599 1 599 2\n600 1 600 2\n601 1 601 2\n602 1 602 2\n603 1 603 2\n604 1 604 2\n605 1 605 2\n606 1 606 2\n607 1 607 2\n608 1 608 2\n609 1 609 2\n610 1 610 2\n611 1 611 2\n612 1 612 2\n613 1 613 2\n614 1 614 2\n615 1 615 2\n616 1 616 2\n617 1 617 2\n618 1 618 2\n619 1 619 2\n620 1 620 2\n621 1 621 2\n622 1 622 2\n623 1 623 2\n624 1 624 2\n625 1 625 2\n626 1 626 2\n627 1 627 2\n628 1 628 2\n629 1 629 2\n630 1 630 2\n631 1 631 2\n632 1 632 2\n633 1 633 2\n634 1 634 2\n635 1 635 2\n636 1 636 2\n637 1 637 2\n638 1 638 2\n639 1 639 2\n640 1 640 2\n641 1 641 2\n642 1 642 2\n643 1 643 2\n644 1 644 2\n645 1 645 2\n646 1 646 2\n647 1 647 2\n648 1 648 2\n649 1 649 2\n650 1 650 2\n651 1 651 2\n652 1 652 2\n653 1 653 2\n654 1 654 2\n655 1 655 2\n656 1 656 2\n657 1 657 2\n658 1 658 2\n659 1 659 2\n660 1 660 2\n661 1 661 2\n662 1 662 2\n663 1 663 2\n664 1 664 2\n665 1 665 2\n666 1 666 2\n667 1 667 2\n668 1 668 2\n669 1 669 2\n670 1 670 2\n671 1 671 2\n672 1 672 2\n673 1 673 2\n674 1 674 2\n675 1 675 2\n676 1 676 2\n677 1 677 2\n678 1 678 2\n679 1 679 2\n680 1 680 2\n681 1 681 2\n682 1 682 2\n683 1 683 2\n684 1 684 2\n685 1 685 2\n686 1 686 2\n687 1 687 2\n688 1 688 2\n689 1 689 2\n690 1 690 2\n691 1 691 2\n692 1 692 2\n693 1 693 2\n694 1 694 2\n695 1 695 2\n696 1 696 2\n697 1 697 2\n698 1 698 2\n699 1 699 2\n700 1 700 2\n701 1 701 2\n702 1 702 2\n703 1 703 2\n704 1 704 2\n705 1 705 2\n706 1 706 2\n707 1 707 2\n708 1 708 2\n709 1 709 2\n710 1 710 2\n711 1 711 2\n712 1 712 2\n713 1 713 2\n714 1 714 2\n715 1 715 2\n716 1 716 2\n717 1 717 2\n718 1 718 2\n719 1 719 2\n720 1 720 2\n721 1 721 2\n722 1 722 2\n723 1 723 2\n724 1 724 2\n725 1 725 2\n726 1 726 2\n727 1 727 2\n728 1 728 2\n729 1 729 2\n730 1 730 2\n731 1 731 2\n732 1 732 2\n733 1 733 2\n734 1 734 2\n735 1 735 2\n736 1 736 2\n737 1 737 2\n738 1 738 2\n739 1 739 2\n740 1 740 2\n741 1 741 2\n742 1 742 2\n743 1 743 2\n744 1 744 2\n745 1 745 2\n746 1 746 2\n747 1 747 2\n748 1 748 2\n749 1 749 2\n750 1 750 2\n751 1 751 2\n752 1 752 2\n753 1 753 2\n754 1 754 2\n755 1 755 2\n756 1 756 2\n757 1 757 2\n758 1 758 2\n759 1 759 2\n760 1 760 2\n761 1 761 2\n762 1 762 2\n763 1 763 2\n764 1 764 2\n765 1 765 2\n766 1 766 2\n767 1 767 2\n768 1 768 2\n769 1 769 2\n770 1 770 2\n771 1 771 2\n772 1 772 2\n773 1 773 2\n774 1 774 2\n775 1 775 2\n776 1 776 2\n777 1 777 2\n778 1 778 2\n779 1 779 2\n780 1 780 2\n781 1 781 2\n782 1 782 2\n783 1 783 2\n784 1 784 2\n785 1 785 2\n786 1 786 2\n787 1 787 2\n788 1 788 2\n789 1 789 2\n790 1 790 2\n791 1 791 2\n792 1 792 2\n793 1 793 2\n794 1 794 2\n795 1 795 2\n796 1 796 2\n797 1 797 2\n798 1 798 2\n799 1 799 2\n800 1 800 2\n801 1 801 2\n802 1 802 2\n803 1 803 2\n804 1 804 2\n805 1 805 2\n806 1 806 2\n807 1 807 2\n808 1 808 2\n809 1 809 2\n810 1 810 2\n811 1 811 2\n812 1 812 2\n813 1 813 2\n814 1 814 2\n815 1 815 2\n816 1 816 2\n817 1 817 2\n818 1 818 2\n819 1 819 2\n820 1 820 2\n821 1 821 2\n822 1 822 2\n823 1 823 2\n824 1 824 2\n825 1 825 2\n826 1 826 2\n827 1 827 2\n828 1 828 2\n829 1 829 2\n830 1 830 2\n831 1 831 2\n832 1 832 2\n833 1 833 2\n834 1 834 2\n835 1 835 2\n836 1 836 2\n837 1 837 2\n838 1 838 2\n839 1 839 2\n840 1 840 2\n841 1 841 2\n842 1 842 2\n843 1 843 2\n844 1 844 2\n845 1 845 2\n846 1 846 2\n847 1 847 2\n848 1 848 2\n849 1 849 2\n850 1 850 2\n851 1 851 2\n852 1 852 2\n853 1 853 2\n854 1 854 2\n855 1 855 2\n856 1 856 2\n857 1 857 2\n858 1 858 2\n859 1 859 2\n860 1 860 2\n861 1 861 2\n862 1 862 2\n863 1 863 2\n864 1 864 2\n865 1 865 2\n866 1 866 2\n867 1 867 2\n868 1 868 2\n869 1 869 2\n870 1 870 2\n871 1 871 2\n872 1 872 2\n873 1 873 2\n874 1 874 2\n875 1 875 2\n876 1 876 2\n877 1 877 2\n878 1 878 2\n879 1 879 2\n880 1 880 2\n881 1 881 2\n882 1 882 2\n883 1 883 2\n884 1 884 2\n885 1 885 2\n886 1 886 2\n887 1 887 2\n888 1 888 2\n889 1 889 2\n890 1 890 2\n891 1 891 2\n892 1 892 2\n893 1 893 2\n894 1 894 2\n895 1 895 2\n896 1 896 2\n897 1 897 2\n898 1 898 2\n899 1 899 2\n900 1 900 2\n901 1 901 2\n902 1 902 2\n903 1 903 2\n904 1 904 2\n905 1 905 2\n906 1 906 2\n907 1 907 2\n908 1 908 2\n909 1 909 2\n910 1 910 2\n911 1 911 2\n912 1 912 2\n913 1 913 2\n914 1 914 2\n915 1 915 2\n916 1 916 2\n917 1 917 2\n918 1 918 2\n919 1 919 2\n920 1 920 2\n921 1 921 2\n922 1 922 2\n923 1 923 2\n924 1 924 2\n925 1 925 2\n926 1 926 2\n927 1 927 2\n928 1 928 2\n929 1 929 2\n930 1 930 2\n931 1 931 2\n932 1 932 2\n933 1 933 2\n934 1 934 2\n935 1 935 2\n936 1 936 2\n937 1 937 2\n938 1 938 2\n939 1 939 2\n940 1 940 2\n941 1 941 2\n942 1 942 2\n943 1 943 2\n944 1 944 2\n945 1 945 2\n946 1 946 2\n947 1 947 2\n948 1 948 2\n949 1 949 2\n950 1 950 2\n951 1 951 2\n952 1 952 2\n953 1 953 2\n954 1 954 2\n955 1 955 2\n956 1 956 2\n957 1 957 2\n958 1 958 2\n959 1 959 2\n960 1 960 2\n961 1 961 2\n962 1 962 2\n963 1 963 2\n964 1 964 2\n965 1 965 2\n966 1 966 2\n967 1 967 2\n968 1 968 2\n969 1 969 2\n970 1 970 2\n971 1 971 2\n972 1 972 2\n973 1 973 2\n974 1 974 2\n975 1 975 2\n976 1 976 2\n977 1 977 2\n978 1 978 2\n979 1 979 2\n980 1 980 2\n981 1 981 2\n982 1 982 2\n983 1 983 2\n984 1 984 2\n985 1 985 2\n986 1 986 2\n987 1 987 2\n988 1 988 2\n989 1 989 2\n990 1 990 2\n991 1 991 2\n992 1 992 2\n993 1 993 2\n994 1 994 2\n995 1 995 2\n996 1 996 2\n997 1 997 2\n998 1 998 2\n999 1 999 2\n1000 1 1000 2\n1000 1 1000 2\n999 1 999 2\n998 1 998 2\n997 1 997 2\n996 1 996 2\n995 1 995 2\n994 1 994 2\n993 1 993 2\n992 1 992 2\n991 1 991 2\n990 1 990 2\n989 1 989 2\n988 1 988 2\n987 1 987 2\n986 1 986 2\n985 1 985 2\n984 1 984 2\n983 1 983 2\n982 1 982 2\n981 1 981 2\n980 1 980 2\n979 1 979 2\n978 1 978 2\n977 1 977 2\n976 1 976 2\n975 1 975 2\n974 1 974 2\n973 1 973 2\n972 1 972 2\n971 1 971 2\n970 1 970 2\n969 1 969 2\n968 1 968 2\n967 1 967 2\n966 1 966 2\n965 1 965 2\n964 1 964 2\n963 1 963 2\n962 1 962 2\n961 1 961 2\n960 1 960 2\n959 1 959 2\n958 1 958 2\n957 1 957 2\n956 1 956 2\n955 1 955 2\n954 1 954 2\n953 1 953 2\n952 1 952 2\n951 1 951 2\n950 1 950 2\n949 1 949 2\n948 1 948 2\n947 1 947 2\n946 1 946 2\n945 1 945 2\n944 1 944 2\n943 1 943 2\n942 1 942 2\n941 1 941 2\n940 1 940 2\n939 1 939 2\n938 1 938 2\n937 1 937 2\n936 1 936 2\n935 1 935 2\n934 1 934 2\n933 1 933 2\n932 1 932 2\n931 1 931 2\n930 1 930 2\n929 1 929 2\n928 1 928 2\n927 1 927 2\n926 1 926 2\n925 1 925 2\n924 1 924 2\n923 1 923 2\n922 1 922 2\n921 1 921 2\n920 1 920 2\n919 1 919 2\n918 1 918 2\n917 1 917 2\n916 1 916 2\n915 1 915 2\n914 1 914 2\n913 1 913 2\n912 1 912 2\n911 1 911 2\n910 1 910 2\n909 1 909 2\n908 1 908 2\n907 1 907 2\n906 1 906 2\n905 1 905 2\n904 1 904 2\n903 1 903 2\n902 1 902 2\n901 1 901 2\n900 1 900 2\n899 1 899 2\n898 1 898 2\n897 1 897 2\n896 1 896 2\n895 1 895 2\n894 1 894 2\n893 1 893 2\n892 1 892 2\n891 1 891 2\n890 1 890 2\n889 1 889 2\n888 1 888 2\n887 1 887 2\n886 1 886 2\n885 1 885 2\n884 1 884 2\n883 1 883 2\n882 1 882 2\n881 1 881 2\n880 1 880 2\n879 1 879 2\n878 1 878 2\n877 1 877 2\n876 1 876 2\n875 1 875 2\n874 1 874 2\n873 1 873 2\n872 1 872 2\n871 1 871 2\n870 1 870 2\n869 1 869 2\n868 1 868 2\n867 1 867 2\n866 1 866 2\n865 1 865 2\n864 1 864 2\n863 1 863 2\n862 1 862 2\n861 1 861 2\n860 1 860 2\n859 1 859 2\n858 1 858 2\n857 1 857 2\n856 1 856 2\n855 1 855 2\n854 1 854 2\n853 1 853 2\n852 1 852 2\n851 1 851 2\n850 1 850 2\n849 1 849 2\n848 1 848 2\n847 1 847 2\n846 1 846 2\n845 1 845 2\n844 1 844 2\n843 1 843 2\n842 1 842 2\n841 1 841 2\n840 1 840 2\n839 1 839 2\n838 1 838 2\n837 1 837 2\n836 1 836 2\n835 1 835 2\n834 1 834 2\n833 1 833 2\n832 1 832 2\n831 1 831 2\n830 1 830 2\n829 1 829 2\n828 1 828 2\n827 1 827 2\n826 1 826 2\n825 1 825 2\n824 1 824 2\n823 1 823 2\n822 1 822 2\n821 1 821 2\n820 1 820 2\n819 1 819 2\n818 1 818 2\n817 1 817 2\n816 1 816 2\n815 1 815 2\n814 1 814 2\n813 1 813 2\n812 1 812 2\n811 1 811 2\n810 1 810 2\n809 1 809 2\n808 1 808 2\n807 1 807 2\n806 1 806 2\n805 1 805 2\n804 1 804 2\n803 1 803 2\n802 1 802 2\n801 1 801 2\n800 1 800 2\n799 1 799 2\n798 1 798 2\n797 1 797 2\n796 1 796 2\n795 1 795 2\n794 1 794 2\n793 1 793 2\n792 1 792 2\n791 1 791 2\n790 1 790 2\n789 1 789 2\n788 1 788 2\n787 1 787 2\n786 1 786 2\n785 1 785 2\n784 1 784 2\n783 1 783 2\n782 1 782 2\n781 1 781 2\n780 1 780 2\n779 1 779 2\n778 1 778 2\n777 1 777 2\n776 1 776 2\n775 1 775 2\n774 1 774 2\n773 1 773 2\n772 1 772 2\n771 1 771 2\n770 1 770 2\n769 1 769 2\n768 1 768 2\n767 1 767 2\n766 1 766 2\n765 1 765 2\n764 1 764 2\n763 1 763 2\n762 1 762 2\n761 1 761 2\n760 1 760 2\n759 1 759 2\n758 1 758 2\n757 1 757 2\n756 1 756 2\n755 1 755 2\n754 1 754 2\n753 1 753 2\n752 1 752 2\n751 1 751 2\n750 1 750 2\n749 1 749 2\n748 1 748 2\n747 1 747 2\n746 1 746 2\n745 1 745 2\n744 1 744 2\n743 1 743 2\n742 1 742 2\n741 1 741 2\n740 1 740 2\n739 1 739 2\n738 1 738 2\n737 1 737 2\n736 1 736 2\n735 1 735 2\n734 1 734 2\n733 1 733 2\n732 1 732 2\n731 1 731 2\n730 1 730 2\n729 1 729 2\n728 1 728 2\n727 1 727 2\n726 1 726 2\n725 1 725 2\n724 1 724 2\n723 1 723 2\n722 1 722 2\n721 1 721 2\n720 1 720 2\n719 1 719 2\n718 1 718 2\n717 1 717 2\n716 1 716 2\n715 1 715 2\n714 1 714 2\n713 1 713 2\n712 1 712 2\n711 1 711 2\n710 1 710 2\n709 1 709 2\n708 1 708 2\n707 1 707 2\n706 1 706 2\n705 1 705 2\n704 1 704 2\n703 1 703 2\n702 1 702 2\n701 1 701 2\n700 1 700 2\n699 1 699 2\n698 1 698 2\n697 1 697 2\n696 1 696 2\n695 1 695 2\n694 1 694 2\n693 1 693 2\n692 1 692 2\n691 1 691 2\n690 1 690 2\n689 1 689 2\n688 1 688 2\n687 1 687 2\n686 1 686 2\n685 1 685 2\n684 1 684 2\n683 1 683 2\n682 1 682 2\n681 1 681 2\n680 1 680 2\n679 1 679 2\n678 1 678 2\n677 1 677 2\n676 1 676 2\n675 1 675 2\n674 1 674 2\n673 1 673 2\n672 1 672 2\n671 1 671 2\n670 1 670 2\n669 1 669 2\n668 1 668 2\n667 1 667 2\n666 1 666 2\n665 1 665 2\n664 1 664 2\n663 1 663 2\n662 1 662 2\n661 1 661 2\n660 1 660 2\n659 1 659 2\n658 1 658 2\n657 1 657 2\n656 1 656 2\n655 1 655 2\n654 1 654 2\n653 1 653 2\n652 1 652 2\n651 1 651 2\n650 1 650 2\n649 1 649 2\n648 1 648 2\n647 1 647 2\n646 1 646 2\n645 1 645 2\n644 1 644 2\n643 1 643 2\n642 1 642 2\n641 1 641 2\n640 1 640 2\n639 1 639 2\n638 1 638 2\n637 1 637 2\n636 1 636 2\n635 1 635 2\n634 1 634 2\n633 1 633 2\n632 1 632 2\n631 1 631 2\n630 1 630 2\n629 1 629 2\n628 1 628 2\n627 1 627 2\n626 1 626 2\n625 1 625 2\n624 1 624 2\n623 1 623 2\n622 1 622 2\n621 1 621 2\n620 1 620 2\n619 1 619 2\n618 1 618 2\n617 1 617 2\n616 1 616 2\n615 1 615 2\n614 1 614 2\n613 1 613 2\n612 1 612 2\n611 1 611 2\n610 1 610 2\n609 1 609 2\n608 1 608 2\n607 1 607 2\n606 1 606 2\n605 1 605 2\n604 1 604 2\n603 1 603 2\n602 1 602 2\n601 1 601 2\n600 1 600 2\n599 1 599 2\n598 1 598 2\n597 1 597 2\n596 1 596 2\n595 1 595 2\n594 1 594 2\n593 1 593 2\n592 1 592 2\n591 1 591 2\n590 1 590 2\n589 1 589 2\n588 1 588 2\n587 1 587 2\n586 1 586 2\n585 1 585 2\n584 1 584 2\n583 1 583 2\n582 1 582 2\n581 1 581 2\n580 1 580 2\n579 1 579 2\n578 1 578 2\n577 1 577 2\n576 1 576 2\n575 1 575 2\n574 1 574 2\n573 1 573 2\n572 1 572 2\n571 1 571 2\n570 1 570 2\n569 1 569 2\n568 1 568 2\n567 1 567 2\n566 1 566 2\n565 1 565 2\n564 1 564 2\n563 1 563 2\n562 1 562 2\n561 1 561 2\n560 1 560 2\n559 1 559 2\n558 1 558 2\n557 1 557 2\n556 1 556 2\n555 1 555 2\n554 1 554 2\n553 1 553 2\n552 1 552 2\n551 1 551 2\n550 1 550 2\n549 1 549 2\n548 1 548 2\n547 1 547 2\n546 1 546 2\n545 1 545 2\n544 1 544 2\n543 1 543 2\n542 1 542 2\n541 1 541 2\n540 1 540 2\n539 1 539 2\n538 1 538 2\n537 1 537 2\n536 1 536 2\n535 1 535 2\n534 1 534 2\n533 1 533 2\n532 1 532 2\n531 1 531 2\n530 1 530 2\n529 1 529 2\n528 1 528 2\n527 1 527 2\n526 1 526 2\n525 1 525 2\n524 1 524 2\n523 1 523 2\n522 1 522 2\n521 1 521 2\n520 1 520 2\n519 1 519 2\n518 1 518 2\n517 1 517 2\n516 1 516 2\n515 1 515 2\n514 1 514 2\n513 1 513 2\n512 1 512 2\n511 1 511 2\n510 1 510 2\n509 1 509 2\n508 1 508 2\n507 1 507 2\n506 1 506 2\n505 1 505 2\n504 1 504 2\n503 1 503 2\n502 1 502 2\n501 1 501 2\n500 1 500 2\n499 1 499 2\n498 1 498 2\n497 1 497 2\n496 1 496 2\n495 1 495 2\n494 1 494 2\n493 1 493 2\n492 1 492 2\n491 1 491 2\n490 1 490 2\n489 1 489 2\n488 1 488 2\n487 1 487 2\n486 1 486 2\n485 1 485 2\n484 1 484 2\n483 1 483 2\n482 1 482 2\n481 1 481 2\n480 1 480 2\n479 1 479 2\n478 1 478 2\n477 1 477 2\n476 1 476 2\n475 1 475 2\n474 1 474 2\n473 1 473 2\n472 1 472 2\n471 1 471 2\n470 1 470 2\n469 1 469 2\n468 1 468 2\n467 1 467 2\n466 1 466 2\n465 1 465 2\n464 1 464 2\n463 1 463 2\n462 1 462 2\n461 1 461 2\n460 1 460 2\n459 1 459 2\n458 1 458 2\n457 1 457 2\n456 1 456 2\n455 1 455 2\n454 1 454 2\n453 1 453 2\n452 1 452 2\n451 1 451 2\n450 1 450 2\n449 1 449 2\n448 1 448 2\n447 1 447 2\n446 1 446 2\n445 1 445 2\n444 1 444 2\n443 1 443 2\n442 1 442 2\n441 1 441 2\n440 1 440 2\n439 1 439 2\n438 1 438 2\n437 1 437 2\n436 1 436 2\n435 1 435 2\n434 1 434 2\n433 1 433 2\n432 1 432 2\n431 1 431 2\n430 1 430 2\n429 1 429 2\n428 1 428 2\n427 1 427 2\n426 1 426 2\n425 1 425 2\n424 1 424 2\n423 1 423 2\n422 1 422 2\n421 1 421 2\n420 1 420 2\n419 1 419 2\n418 1 418 2\n417 1 417 2\n416 1 416 2\n415 1 415 2\n414 1 414 2\n413 1 413 2\n412 1 412 2\n411 1 411 2\n410 1 410 2\n409 1 409 2\n408 1 408 2\n407 1 407 2\n406 1 406 2\n405 1 405 2\n404 1 404 2\n403 1 403 2\n402 1 402 2\n401 1 401 2\n400 1 400 2\n399 1 399 2\n398 1 398 2\n397 1 397 2\n396 1 396 2\n395 1 395 2\n394 1 394 2\n393 1 393 2\n392 1 392 2\n391 1 391 2\n390 1 390 2\n389 1 389 2\n388 1 388 2\n387 1 387 2\n386 1 386 2\n385 1 385 2\n384 1 384 2\n383 1 383 2\n382 1 382 2\n381 1 381 2\n380 1 380 2\n379 1 379 2\n378 1 378 2\n377 1 377 2\n376 1 376 2\n375 1 375 2\n374 1 374 2\n373 1 373 2\n372 1 372 2\n371 1 371 2\n370 1 370 2\n369 1 369 2\n368 1 368 2\n367 1 367 2\n366 1 366 2\n365 1 365 2\n364 1 364 2\n363 1 363 2\n362 1 362 2\n361 1 361 2\n360 1 360 2\n359 1 359 2\n358 1 358 2\n357 1 357 2\n356 1 356 2\n355 1 355 2\n354 1 354 2\n353 1 353 2\n352 1 352 2\n351 1 351 2\n350 1 350 2\n349 1 349 2\n348 1 348 2\n347 1 347 2\n346 1 346 2\n345 1 345 2\n344 1 344 2\n343 1 343 2\n342 1 342 2\n341 1 341 2\n340 1 340 2\n339 1 339 2\n338 1 338 2\n337 1 337 2\n336 1 336 2\n335 1 335 2\n334 1 334 2\n333 1 333 2\n332 1 332 2\n331 1 331 2\n330 1 330 2\n329 1 329 2\n328 1 328 2\n327 1 327 2\n326 1 326 2\n325 1 325 2\n324 1 324 2\n323 1 323 2\n322 1 322 2\n321 1 321 2\n320 1 320 2\n319 1 319 2\n318 1 318 2\n317 1 317 2\n316 1 316 2\n315 1 315 2\n314 1 314 2\n313 1 313 2\n312 1 312 2\n311 1 311 2\n310 1 310 2\n309 1 309 2\n308 1 308 2\n307 1 307 2\n306 1 306 2\n305 1 305 2\n304 1 304 2\n303 1 303 2\n302 1 302 2\n301 1 301 2\n300 1 300 2\n299 1 299 2\n298 1 298 2\n297 1 297 2\n296 1 296 2\n295 1 295 2\n294 1 294 2\n293 1 293 2\n292 1 292 2\n291 1 291 2\n290 1 290 2\n289 1 289 2\n288 1 288 2\n287 1 287 2\n286 1 286 2\n285 1 285 2\n284 1 284 2\n283 1 283 2\n282 1 282 2\n281 1 281 2\n280 1 280 2\n279 1 279 2\n278 1 278 2\n277 1 277 2\n276 1 276 2\n275 1 275 2\n274 1 274 2\n273 1 273 2\n272 1 272 2\n271 1 271 2\n270 1 270 2\n269 1 269 2\n268 1 268 2\n267 1 267 2\n266 1 266 2\n265 1 265 2\n264 1 264 2\n263 1 263 2\n262 1 262 2\n261 1 261 2\n260 1 260 2\n259 1 259 2\n258 1 258 2\n257 1 257 2\n256 1 256 2\n255 1 255 2\n254 1 254 2\n253 1 253 2\n252 1 252 2\n251 1 251 2\n250 1 250 2\n249 1 249 2\n248 1 248 2\n247 1 247 2\n246 1 246 2\n245 1 245 2\n244 1 244 2\n243 1 243 2\n242 1 242 2\n241 1 241 2\n240 1 240 2\n239 1 239 2\n238 1 238 2\n237 1 237 2\n236 1 236 2\n235 1 235 2\n234 1 234 2\n233 1 233 2\n232 1 232 2\n231 1 231 2\n230 1 230 2\n229 1 229 2\n228 1 228 2\n227 1 227 2\n226 1 226 2\n225 1 225 2\n224 1 224 2\n223 1 223 2\n222 1 222 2\n221 1 221 2\n220 1 220 2\n219 1 219 2\n218 1 218 2\n217 1 217 2\n216 1 216 2\n215 1 215 2\n214 1 214 2\n213 1 213 2\n212 1 212 2\n211 1 211 2\n210 1 210 2\n209 1 209 2\n208 1 208 2\n207 1 207 2\n206 1 206 2\n205 1 205 2\n204 1 204 2\n203 1 203 2\n202 1 202 2\n201 1 201 2\n200 1 200 2\n199 1 199 2\n198 1 198 2\n197 1 197 2\n196 1 196 2\n195 1 195 2\n194 1 194 2\n193 1 193 2\n192 1 192 2\n191 1 191 2\n190 1 190 2\n189 1 189 2\n188 1 188 2\n187 1 187 2\n186 1 186 2\n185 1 185 2\n184 1 184 2\n183 1 183 2\n182 1 182 2\n181 1 181 2\n180 1 180 2\n179 1 179 2\n178 1 178 2\n177 1 177 2\n176 1 176 2\n175 1 175 2\n174 1 174 2\n173 1 173 2\n172 1 172 2\n171 1 171 2\n170 1 170 2\n169 1 169 2\n168 1 168 2\n167 1 167 2\n166 1 166 2\n165 1 165 2\n164 1 164 2\n163 1 163 2\n162 1 162 2\n161 1 161 2\n160 1 160 2\n159 1 159 2\n158 1 158 2\n157 1 157 2\n156 1 156 2\n155 1 155 2\n154 1 154 2\n153 1 153 2\n152 1 152 2\n151 1 151 2\n150 1 150 2\n149 1 149 2\n148 1 148 2\n147 1 147 2\n146 1 146 2\n145 1 145 2\n144 1 144 2\n143 1 143 2\n142 1 142 2\n141 1 141 2\n140 1 140 2\n139 1 139 2\n138 1 138 2\n137 1 137 2\n136 1 136 2\n135 1 135 2\n134 1 134 2\n133 1 133 2\n132 1 132 2\n131 1 131 2\n130 1 130 2\n129 1 129 2\n128 1 128 2\n127 1 127 2\n126 1 126 2\n125 1 125 2\n124 1 124 2\n123 1 123 2\n122 1 122 2\n121 1 121 2\n120 1 120 2\n119 1 119 2\n118 1 118 2\n117 1 117 2\n116 1 116 2\n115 1 115 2\n114 1 114 2\n113 1 113 2\n112 1 112 2\n111 1 111 2\n110 1 110 2\n109 1 109 2\n108 1 108 2\n107 1 107 2\n106 1 106 2\n105 1 105 2\n104 1 104 2\n103 1 103 2\n102 1 102 2\n101 1 101 2\n100 1 100 2\n99 1 99 2\n98 1 98 2\n97 1 97 2\n96 1 96 2\n95 1 95 2\n94 1 94 2\n93 1 93 2\n92 1 92 2\n91 1 91 2\n90 1 90 2\n89 1 89 2\n88 1 88 2\n87 1 87 2\n86 1 86 2\n85 1 85 2\n84 1 84 2\n83 1 83 2\n82 1 82 2\n81 1 81 2\n80 1 80 2\n79 1 79 2\n78 1 78 2\n77 1 77 2\n76 1 76 2\n75 1 75 2\n74 1 74 2\n73 1 73 2\n72 1 72 2\n71 1 71 2\n70 1 70 2\n69 1 69 2\n68 1 68 2\n67 1 67 2\n66 1 66 2\n65 1 65 2\n64 1 64 2\n63 1 63 2\n62 1 62 2\n61 1 61 2\n60 1 60 2\n59 1 59 2\n58 1 58 2\n57 1 57 2\n56 1 56 2\n55 1 55 2\n54 1 54 2\n53 1 53 2\n52 1 52 2\n51 1 51 2\n50 1 50 2\n49 1 49 2\n48 1 48 2\n47 1 47 2\n46 1 46 2\n45 1 45 2\n44 1 44 2\n43 1 43 2\n42 1 42 2\n41 1 41 2\n40 1 40 2\n39 1 39 2\n38 1 38 2\n37 1 37 2\n36 1 36 2\n35 1 35 2\n34 1 34 2\n33 1 33 2\n32 1 32 2\n31 1 31 2\n30 1 30 2\n29 1 29 2\n28 1 28 2\n27 1 27 2\n26 1 26 2\n25 1 25 2\n24 1 24 2\n23 1 23 2\n22 1 22 2\n21 1 21 2\n20 1 20 2\n19 1 19 2\n18 1 18 2\n17 1 17 2\n16 1 16 2\n15 1 15 2\n14 1 14 2\n13 1 13 2\n12 1 12 2\n11 1 11 2\n10 1 10 2\n9 1 9 2\n8 1 8 2\n7 1 7 2\n6 1 6 2\n5 1 5 2\n4 1 4 2\n3 1 3 2\n2 1 2 2\n1 1 1 2\n"
]
} |
3,348 | 8 | A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values β the start time li and the finish time ri (li β€ ri).
Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?
No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.
Input
The first line contains integer number n (1 β€ n β€ 5Β·105) β number of orders. The following n lines contain integer values li and ri each (1 β€ li β€ ri β€ 109).
Output
Print the maximal number of orders that can be accepted.
Examples
Input
2
7 11
4 7
Output
1
Input
5
1 2
2 3
3 4
4 5
5 6
Output
3
Input
6
4 8
1 5
4 7
2 5
1 3
6 8
Output
2 | def snd(lst):
return lst[1]
n = int(input())
l = []
for i in range(0, n):
l.append([int(i) for i in input().split()])
l.sort(key=snd)
e = 0
ans = 0
for p in l:
if (p[0] > e):
ans+=1
e = p[1]
print(ans)
| {
"input": [
"6\n4 8\n1 5\n4 7\n2 5\n1 3\n6 8\n",
"5\n1 2\n2 3\n3 4\n4 5\n5 6\n",
"2\n7 11\n4 7\n"
],
"output": [
"2\n",
"3\n",
"1\n"
]
} |
3,349 | 8 | A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree β he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree β in this case print "-1".
Input
The first line contains three integers n, d and h (2 β€ n β€ 100 000, 1 β€ h β€ d β€ n - 1) β the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers β indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | def main():
n, d, h = map(int, input().split())
if h * 2 < d or d < 2 < n or h > d:
print(-1)
return
res, f = [], ' '.join
for e in (2, h + 2), (h + 2, d + 2):
a = "1"
for b in map(str, range(*e)):
res.append((f((a, b))))
a = b
a = "1 %d" if h < d else "2 %d"
res.extend(a % i for i in range(d + 2, n + 1))
print('\n'.join(res))
if __name__ == '__main__':
main()
| {
"input": [
"8 4 2\n",
"8 5 2\n",
"5 3 2\n"
],
"output": [
"1 2\n2 3\n1 4\n4 5\n1 6\n1 7\n1 8\n",
"-1\n",
"1 2\n2 3\n1 4\n1 5\n"
]
} |
3,350 | 7 | Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the N attendees love to play a very risky game...
Every zombie gets a number ni (1 β€ ni β€ N) written on his forehead. Although no zombie can see his own number, he can see the numbers written on the foreheads of all N - 1 fellows. Note that not all numbers have to be unique (they can even all be the same). From this point on, no more communication between zombies is allowed. Observation is the only key to success. When the cuckoo clock strikes midnight, all attendees have to simultaneously guess the number on their own forehead. If at least one of them guesses his number correctly, all zombies survive and go home happily. On the other hand, if not a single attendee manages to guess his number correctly, all of them are doomed to die!
Zombies aren't very bright creatures though, and Heidi has to act fast if she does not want to jeopardize her life. She has one single option: by performing some quick surgery on the brain she managed to get from the chest, she has the ability to remotely reprogram the decision-making strategy of all attendees for their upcoming midnight game! Can you suggest a sound strategy to Heidi which, given the rules of the game, ensures that at least one attendee will guess his own number correctly, for any possible sequence of numbers on the foreheads?
Given a zombie's rank R and the N - 1 numbers ni on the other attendees' foreheads, your program will have to return the number that the zombie of rank R shall guess. Those answers define your strategy, and we will check if it is flawless or not.
Input
The first line of input contains a single integer T (1 β€ T β€ 50000): the number of scenarios for which you have to make a guess.
The T scenarios follow, described on two lines each:
* The first line holds two integers, N (2 β€ N β€ 6), the number of attendees, and R (1 β€ R β€ N), the rank of the zombie who has to make the guess.
* The second line lists N - 1 integers: the numbers on the foreheads of all other attendees, listed in increasing order of the attendees' rank. (Every zombie knows the rank of every other zombie.)
Output
For every scenario, output a single integer: the number that the zombie of rank R shall guess, based on the numbers ni on his N - 1 fellows' foreheads.
Examples
Input
4
2 1
1
2 2
1
2 1
2
2 2
2
Output
1
2
2
1
Input
2
5 2
2 2 2 2
6 4
3 2 6 1 2
Output
5
2
Note
For instance, if there were N = 2 two attendees, a successful strategy could be:
* The zombie of rank 1 always guesses the number he sees on the forehead of the zombie of rank 2.
* The zombie of rank 2 always guesses the opposite of the number he sees on the forehead of the zombie of rank 1. | def main():
T = int(input())
for _ in range(T):
n, r = readints()
nums = readints()
print(sol(nums, r, n))
def readints():
return [int(fld) for fld in input().strip().split()]
def sol(nums, r, n):
ans = 1 + (r - sum(nums)) % n
return ans
main() | {
"input": [
"4\n2 1\n1\n2 2\n1\n2 1\n2\n2 2\n2\n",
"2\n5 2\n2 2 2 2\n6 4\n3 2 6 1 2\n"
],
"output": [
"1\n2\n2\n1\n",
"4\n2\n"
]
} |
3,351 | 7 | Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000. | from sys import stdin
def main():
cnt = [0] * 2 ** 18
t = str.maketrans("0123456789", "0101010101")
input()
for sign, s in map(str.split, stdin):
if sign == '?':
print(cnt[int(s, 2)])
else:
cnt[int(s.translate(t), 2)] += 1 if sign == '+' else -1
if __name__ == '__main__':
main()
| {
"input": [
"4\n+ 200\n+ 200\n- 200\n? 0\n",
"12\n+ 1\n+ 241\n? 1\n+ 361\n- 241\n? 0101\n+ 101\n? 101\n- 101\n? 101\n+ 4000\n? 0\n"
],
"output": [
"1\n",
"2\n1\n2\n1\n1\n"
]
} |
3,352 | 9 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.
Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.
Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.
Input
In the first line there are two positive integer numbers n and k (1 β€ n β€ 2Β·105, 0 β€ k β€ n) β total number of items to buy and minimal number of items Igor wants to by right now.
The second line contains sequence of integers a1, a2, ..., an (1 β€ ai β€ 104) β prices of items during discounts (i.e. right now).
The third line contains sequence of integers b1, b2, ..., bn (1 β€ bi β€ 104) β prices of items after discounts (i.e. after a week).
Output
Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.
Examples
Input
3 1
5 4 6
3 1 5
Output
10
Input
5 3
3 4 7 10 3
4 5 5 12 5
Output
25
Note
In the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.
In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | #!/usr/bin/env python3
def ri():
return map(int, input().split())
n, k = ri()
a = list(ri())
b = list(ri())
c = [a[i]-b[i] for i in range(n)]
d = list(zip(c, a,b))
d.sort()
ans = 0
for i in range(k):
ans+=d[i][1]
for i in range(k, n):
ans+=min(d[i][1], d[i][2])
print(ans)
| {
"input": [
"5 3\n3 4 7 10 3\n4 5 5 12 5\n",
"3 1\n5 4 6\n3 1 5\n"
],
"output": [
"25\n",
"10\n"
]
} |
3,353 | 9 | You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
Input
The first line contains single integer q (1 β€ q β€ 105) β the number of queries.
q lines follow. The (i + 1)-th line contains single integer ni (1 β€ ni β€ 109) β the i-th query.
Output
For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.
Examples
Input
1
12
Output
3
Input
2
6
8
Output
1
2
Input
3
1
2
3
Output
-1
-1
-1
Note
12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.
8 = 4 + 4, 6 can't be split into several composite summands.
1, 2, 3 are less than any composite number, so they do not have valid splittings. | def max_sum(n):
if n in [1, 2, 3, 5, 7, 11]:
return -1
return n // 4 - n % 2
n = int(input())
[print(max_sum(int(input()))) for i in range(n)]
| {
"input": [
"3\n1\n2\n3\n",
"1\n12\n",
"2\n6\n8\n"
],
"output": [
"-1\n-1\n-1\n",
"3\n",
"1\n2\n"
]
} |
3,354 | 8 | β Thanks a lot for today.
β I experienced so many great things.
β You gave me memories like dreams... But I have to leave now...
β One last request, can you...
β Help me solve a Codeforces problem?
β ......
β What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.
Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!
Input
The first line contains two integers k and p (1 β€ k β€ 105, 1 β€ p β€ 109).
Output
Output single integer β answer to the problem.
Examples
Input
2 100
Output
33
Input
5 30
Output
15
Note
In the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.
In the second example, <image>. | def zcy(n):
s = str(n)
return int(s + ''.join(reversed(s)))
k, p = [int(i) for i in input().split()]
print(sum(zcy(i) for i in range(1, k+1)) % p)
| {
"input": [
"2 100\n",
"5 30\n"
],
"output": [
"33\n",
"15\n"
]
} |
3,355 | 9 | And where the are the phone numbers?
You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.
It's guaranteed that the answer exists.
Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.
String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.
Input
The first line of input contains two space separated integers n and k (1 β€ n, k β€ 100 000) β the length of s and the required length of t.
The second line of input contains the string s consisting of n lowercase English letters.
Output
Output the string t conforming to the requirements above.
It's guaranteed that the answer exists.
Examples
Input
3 3
abc
Output
aca
Input
3 2
abc
Output
ac
Input
3 3
ayy
Output
yaa
Input
2 3
ba
Output
baa
Note
In the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca. | def phone(a, b, s):
s1 = sorted(set(s))
if b > a:
return s + s1[0] * (b - a)
i = b - 1
while s[i] >= s1[-1] and i > - 1:
i -= 1
ind = s1.index(s[i])
return s[:i] + s1[ind + 1] + s1[0] * (b - i - 1)
x, y = [int(j) for j in input().split()]
t = input()
print(phone(x, y, t))
| {
"input": [
"3 3\nabc\n",
"2 3\nba\n",
"3 2\nabc\n",
"3 3\nayy\n"
],
"output": [
"aca\n",
"baa\n",
"ac\n",
"yaa\n"
]
} |
3,356 | 9 | Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days [l_a; r_a] are lucky, then there are some unlucky days: [r_a + 1; l_a + t_a - 1], and then there are lucky days again: [l_a + t_a; r_a + t_a] and so on. In other words, the day is lucky for Alice if it lies in the segment [l_a + k t_a; r_a + k t_a] for some non-negative integer k.
The Bob's lucky day have similar structure, however the parameters of his sequence are different: l_b, r_b, t_b. So a day is a lucky for Bob if it lies in a segment [l_b + k t_b; r_b + k t_b], for some non-negative integer k.
Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.
Input
The first line contains three integers l_a, r_a, t_a (0 β€ l_a β€ r_a β€ t_a - 1, 2 β€ t_a β€ 10^9) and describes Alice's lucky days.
The second line contains three integers l_b, r_b, t_b (0 β€ l_b β€ r_b β€ t_b - 1, 2 β€ t_b β€ 10^9) and describes Bob's lucky days.
It is guaranteed that both Alice and Bob have some unlucky days.
Output
Print one integer: the maximum number of days in the row that are lucky for both Alice and Bob.
Examples
Input
0 2 5
1 3 5
Output
2
Input
0 1 3
2 3 6
Output
1
Note
The graphs below correspond to the two sample tests and show the lucky and unlucky days of Alice and Bob as well as the possible solutions for these tests.
<image>
<image> | import math
la, ra, ta = map(int, input().split())
lb, rb, tb = map(int, input().split())
def f(la, ra, ta, lb, rb, tb):
d = la - lb
x = math.gcd(ta, tb)
d = ((d % x) + x) % x
return min(ra, rb - d)
ra = ra - la + 1
rb = rb - lb + 1
print(max([0, f(la, ra, ta, lb, rb, tb), f(lb, rb, tb, la, ra, ta)])) | {
"input": [
"0 2 5\n1 3 5\n",
"0 1 3\n2 3 6\n"
],
"output": [
"2\n",
"1\n"
]
} |
3,357 | 10 | You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find such element in s, then you cannot cut out one more copy of t. The both arrays can contain duplicate elements.
For example, if s = [1, 2, 3, 2, 4, 3, 1] and k = 3 then one of the possible answers is t = [1, 2, 3]. This array t can be cut out 2 times.
* To cut out the first copy of t you can use the elements [1, \underline{2}, 3, 2, 4, \underline{3}, \underline{1}] (use the highlighted elements). After cutting out the first copy of t the array s can look like [1, 3, 2, 4].
* To cut out the second copy of t you can use the elements [\underline{1}, \underline{3}, \underline{2}, 4]. After cutting out the second copy of t the array s will be [4].
Your task is to find such array t that you can cut out the copy of t from s maximum number of times. If there are multiple answers, you may choose any of them.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in s and the desired number of elements in t, respectively.
The second line of the input contains exactly n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 2 β
10^5).
Output
Print k integers β the elements of array t such that you can cut out maximum possible number of copies of this array from s. If there are multiple answers, print any of them. The required array t can contain duplicate elements. All the elements of t (t_1, t_2, ..., t_k) should satisfy the following condition: 1 β€ t_i β€ 2 β
10^5.
Examples
Input
7 3
1 2 3 2 4 3 1
Output
1 2 3
Input
10 4
1 3 1 3 10 3 7 7 12 3
Output
7 3 1 3
Input
15 2
1 2 1 1 1 2 1 1 2 1 2 1 1 1 1
Output
1 1
Note
The first example is described in the problem statement.
In the second example the only answer is [7, 3, 1, 3] and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to 2.
In the third example the array t can be cut out 5 times. | def read_input():
return list(map(int,input().split()))
from collections import Counter
n, k = read_input()
c = Counter(read_input())
l = []
for a,b in c.items():
for i in range(1,b+1):
l.append((b//i,a))
l.sort(reverse=True)
print(' '.join(str(b) for a,b in l[:k])) | {
"input": [
"7 3\n1 2 3 2 4 3 1\n",
"15 2\n1 2 1 1 1 2 1 1 2 1 2 1 1 1 1\n",
"10 4\n1 3 1 3 10 3 7 7 12 3\n"
],
"output": [
"1 2 3\n",
"1 1\n",
"1 3 3 7 "
]
} |
3,358 | 9 | Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!
Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1.
Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4.
<image>
The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible.
Input
The only input line contains two integers n and s β the number of vertices in the tree and the desired sum of the subtree sizes (2 β€ n β€ 10^5; 1 β€ s β€ 10^{10}).
Output
If the required tree does not exist, output Β«NoΒ». Otherwise output Β«YesΒ» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i.
Examples
Input
3 5
Output
Yes
1 1
Input
4 42
Output
No
Input
6 15
Output
Yes
1 2 3 1 5
Note
Below one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2.
<image>
Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2.
<image> | n, s = map(int, input().split())
if not 2*n - 1 <= s <= n * (n+1) // 2:
print('No')
exit()
print('Yes')
def ok(d):
dep, cur, sum, m = 2, 1, 1, 0
while cur + m < n:
m += cur
cur = min(n - m, cur * d)
sum += cur * dep
dep += 1
return sum <= s
l, r = 1, n
while l < r:
mid = (l+r) // 2
if ok(mid):
r = mid
else:
l = mid + 1
a, me = [l-1] * (n+1), [_ for _ in range(n+1)]
sum, low = n * (n+1) // 2, 2
while n > low and sum > s:
dest = min(sum-s, n-low)
sum -= dest
me[n] -= dest
a[me[n]+1] += l
a[me[n]] -= 1
if not a[low]: low += 1
n -= 1
me, l, dg = sorted(me[1:]), 0, 0
for i in me[1:]:
while me[l] < i-1 or dg == r:
dg = 0
l += 1
print(l+1, end=' ')
dg += 1
| {
"input": [
"6 15\n",
"3 5\n",
"4 42\n"
],
"output": [
"Yes\n1 1 2 2 4 \n",
"Yes\n1 1 \n",
"No\n"
]
} |
3,359 | 10 | Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.
In return, the fleas made a bigger ukulele for her: it has n strings, and each string has (10^{18} + 1) frets numerated from 0 to 10^{18}. The fleas use the array s_1, s_2, β¦, s_n to describe the ukulele's tuning, that is, the pitch of the j-th fret on the i-th string is the integer s_i + j.
Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.
Each question is in the form of: "How many different pitches are there, if we consider frets between l and r (inclusive) on all strings?"
Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!
Formally, you are given a matrix with n rows and (10^{18}+1) columns, where the cell in the i-th row and j-th column (0 β€ j β€ 10^{18}) contains the integer s_i + j. You are to answer q queries, in the k-th query you have to answer the number of distinct integers in the matrix from the l_k-th to the r_k-th columns, inclusive.
Input
The first line contains an integer n (1 β€ n β€ 100 000) β the number of strings.
The second line contains n integers s_1, s_2, β¦, s_n (0 β€ s_i β€ 10^{18}) β the tuning of the ukulele.
The third line contains an integer q (1 β€ q β€ 100 000) β the number of questions.
The k-th among the following q lines contains two integers l_kοΌr_k (0 β€ l_k β€ r_k β€ 10^{18}) β a question from the fleas.
Output
Output one number for each question, separated by spaces β the number of different pitches.
Examples
Input
6
3 1 4 1 5 9
3
7 7
0 2
8 17
Output
5 10 18
Input
2
1 500000000000000000
2
1000000000000000000 1000000000000000000
0 1000000000000000000
Output
2 1500000000000000000
Note
For the first example, the pitches on the 6 strings are as follows.
$$$ \begin{matrix} Fret & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & β¦ \\\ s_1: & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & ... \\\ s_2: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & ... \\\ s_3: & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & ... \\\ s_4: & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & ... \\\ s_5: & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & ... \\\ s_6: & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & ... \end{matrix} $$$
There are 5 different pitches on fret 7 β 8, 10, 11, 12, 16.
There are 10 different pitches on frets 0, 1, 2 β 1, 2, 3, 4, 5, 6, 7, 9, 10, 11. | def main():
from bisect import bisect
from itertools import accumulate, chain
from sys import stdin, stdout
input = stdin.readline
input()
s = sorted(set(map(int, input().split())))
n = len(s)
inp = sorted((a - b for (a, b) in zip(s[1:], s)))
acc = tuple(chain(accumulate(inp), (0,)))
for _ in range(int(input())):
l_, r = map(int, input().split())
d = r + 1 - l_
i = bisect(inp, d)
stdout.write(f'{acc[i - 1] + (n - i) * d} ')
main()
| {
"input": [
"6\n3 1 4 1 5 9\n3\n7 7\n0 2\n8 17\n",
"2\n1 500000000000000000\n2\n1000000000000000000 1000000000000000000\n0 1000000000000000000\n"
],
"output": [
"5 10 18\n",
"2 1500000000000000000\n"
]
} |
3,360 | 7 | Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.
Alice can erase some characters from her string s. She would like to know what is the longest string remaining after erasing some characters (possibly zero) to get a good string. It is guaranteed that the string has at least one "a" in it, so the answer always exists.
Input
The first line contains a string s (1 β€ |s| β€ 50) consisting of lowercase English letters. It is guaranteed that there is at least one "a" in s.
Output
Print a single integer, the length of the longest good string that Alice can get after erasing some characters from s.
Examples
Input
xaxxxxa
Output
3
Input
aaabaa
Output
6
Note
In the first example, it's enough to erase any four of the "x"s. The answer is 3 since that is the maximum number of characters that can remain.
In the second example, we don't need to erase any characters. | def main():
s = input()
x = s.count('a')
print(min(len(s), 2*x-1))
main() | {
"input": [
"aaabaa\n",
"xaxxxxa\n"
],
"output": [
"6\n",
"3\n"
]
} |
3,361 | 7 | A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.
You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number.
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 100) β the length of string s.
The second line of each test case contains the string s (|s| = n) consisting of digits.
Output
For each test print one line.
If there is a sequence of operations, after which s becomes a telephone number, print YES.
Otherwise, print NO.
Example
Input
2
13
7818005553535
11
31415926535
Output
YES
NO
Note
In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535. | def is_number(s):
return len(s[s.find('8'):]) >= 11
n = int(input())
for _ in range(n):
input()
print(("NO", "YES")[is_number(input())])
| {
"input": [
"2\n13\n7818005553535\n11\n31415926535\n"
],
"output": [
"YES\nNO\n"
]
} |
3,362 | 10 | A sequence a_1, a_2, ..., a_k is called an arithmetic progression if for each i from 1 to k elements satisfy the condition a_i = a_1 + c β
(i - 1) for some fixed c.
For example, these five sequences are arithmetic progressions: [5, 7, 9, 11], [101], [101, 100, 99], [13, 97] and [5, 5, 5, 5, 5]. And these four sequences aren't arithmetic progressions: [3, 1, 2], [1, 2, 4, 8], [1, -1, 1, -1] and [1, 2, 3, 3, 3].
You are given a sequence of integers b_1, b_2, ..., b_n. Find any index j (1 β€ j β€ n), such that if you delete b_j from the sequence, you can reorder the remaining n-1 elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.
Input
The first line of the input contains one integer n (2 β€ n β€ 2β
10^5) β length of the sequence b. The second line contains n integers b_1, b_2, ..., b_n (-10^9 β€ b_i β€ 10^9) β elements of the sequence b.
Output
Print such index j (1 β€ j β€ n), so that if you delete the j-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.
Examples
Input
5
2 6 8 7 4
Output
4
Input
8
1 2 3 4 5 6 7 8
Output
1
Input
4
1 2 4 8
Output
-1
Note
Note to the first example. If you delete the 4-th element, you can get the arithmetic progression [2, 4, 6, 8].
Note to the second example. The original sequence is already arithmetic progression, so you can delete 1-st or last element and you will get an arithmetical progression again. | from sys import exit
def isg(a):
d=a[1][0]-a[0][0]
for i in range(2,len(a)):
if a[i][0]-a[i-1][0]!=d:return False
return True
n=int(input())
if n<=3:print(1);exit()
a=sorted([[int(e),i]for i,e in enumerate(input().split())])
if isg(a[1:]):print(a[0][1]+1);exit()
if isg([a[0]]+a[2:]):print(a[1][1]+1);exit()
m=a[1][0]-a[0][0]
for i in range(2,n):
if a[i][0]-a[i-1][0]!=m:
if isg(a[:i]+a[i+1:]):print(a[i][1]+1)
else:print(-1)
break
| {
"input": [
"8\n1 2 3 4 5 6 7 8\n",
"5\n2 6 8 7 4\n",
"4\n1 2 4 8\n"
],
"output": [
"1\n",
"4\n",
"-1\n"
]
} |
3,363 | 8 | Mislove had an array a_1, a_2, β
β
β
, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(2) in the array.
For example, if n=5, l=2, r=3 then an array could be [1,2,2,4,4] or [1,1,1,1,2]; but it couldn't be [1,2,2,4,8] because this array contains 4 different numbers; it couldn't be [1,2,2,3,3] because 3 is odd and isn't equal to 1; and it couldn't be [1,1,2,2,16] because there is a number 16 in the array but there isn't a number 16/2 = 8.
According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.
Input
The only input line contains three integers n, l and r (1 β€ n β€ 1 000, 1 β€ l β€ r β€ min(n, 20)) β an array's size, the minimal number and the maximal number of distinct elements in an array.
Output
Output two numbers β the minimal and the maximal possible sums of all elements in an array.
Examples
Input
4 2 2
Output
5 7
Input
5 1 5
Output
5 31
Note
In the first example, an array could be the one of the following: [1,1,1,2], [1,1,2,2] or [1,2,2,2]. In the first case the minimal sum is reached and in the last case the maximal sum is reached.
In the second example, the minimal sum is reached at the array [1,1,1,1,1], and the maximal one is reached at the array [1,2,4,8,16]. | def f(l):
n,l,r = l
return [2**l-1+(n-l),2**r-1+(n-r)*2**(r-1)]
l = list(map(int,input().split()))
print(*f(l))
| {
"input": [
"4 2 2\n",
"5 1 5\n"
],
"output": [
"5 7\n",
"5 31\n"
]
} |
3,364 | 7 | Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red.
"Oh, I just spent x_i hours solving problems", said the i-th of them.
Bob wants to train his math skills, so for each answer he wrote down the number of minutes (60 β
x_i), thanked the grandmasters and went home. Bob could write numbers with leading zeroes β for example, if some grandmaster answered that he had spent 2 hours, Bob could write 000120 instead of 120.
Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:
* rearranged its digits, or
* wrote a random number.
This way, Alice generated n numbers, denoted y_1, ..., y_n.
For each of the numbers, help Bob determine whether y_i can be a permutation of a number divisible by 60 (possibly with leading zeroes).
Input
The first line contains a single integer n (1 β€ n β€ 418) β the number of grandmasters Bob asked.
Then n lines follow, the i-th of which contains a single integer y_i β the number that Alice wrote down.
Each of these numbers has between 2 and 100 digits '0' through '9'. They can contain leading zeroes.
Output
Output n lines.
For each i, output the following. If it is possible to rearrange the digits of y_i such that the resulting number is divisible by 60, output "red" (quotes for clarity). Otherwise, output "cyan".
Example
Input
6
603
006
205
228
1053
0000000000000000000000000000000000000000000000
Output
red
red
cyan
cyan
cyan
red
Note
In the first example, there is one rearrangement that yields a number divisible by 60, and that is 360.
In the second example, there are two solutions. One is 060 and the second is 600.
In the third example, there are 6 possible rearrangments: 025, 052, 205, 250, 502, 520. None of these numbers is divisible by 60.
In the fourth example, there are 3 rearrangements: 228, 282, 822.
In the fifth example, none of the 24 rearrangements result in a number divisible by 60.
In the sixth example, note that 000...0 is a valid solution. | def get(n):
for i in n:
if not i&1 and i:
return True
return False
for _ in range(int(input())):
n=list(map(int,list(input())))
c=n.count(0)
if c and not sum(n)%3:
col= ("red" if get(n) else "cyan") if c==1 else "red"
else:
col="cyan"
print(col) | {
"input": [
"6\n603\n006\n205\n228\n1053\n0000000000000000000000000000000000000000000000\n"
],
"output": [
"red\nred\ncyan\ncyan\ncyan\nred\n"
]
} |
3,365 | 9 | Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.
<image>
Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 2). For example, the complexity of 1 4 2 3 5 is 2 and the complexity of 1 3 5 7 6 4 2 is 1.
No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of light bulbs on the garland.
The second line contains n integers p_1,\ p_2,\ β¦,\ p_n (0 β€ p_i β€ n) β the number on the i-th bulb, or 0 if it was removed.
Output
Output a single number β the minimum complexity of the garland.
Examples
Input
5
0 5 0 2 3
Output
2
Input
7
1 0 0 5 0 0 2
Output
1
Note
In the first example, one should place light bulbs as 1 5 4 2 3. In that case, the complexity would be equal to 2, because only (5, 4) and (2, 3) are the pairs of adjacent bulbs that have different parity.
In the second case, one of the correct answers is 1 7 3 5 6 4 2. | def solve(bulbs, i, ec, oc, prev, memo={}):
if i == len(bulbs):
if min(ec, oc) != 0:
return float('inf')
return 0
if bulbs[i] != 0:
return (prev != bulbs[i]%2) + solve(bulbs,i+1, ec, oc, bulbs[i]%2, memo)
if (i, ec, oc, prev) not in memo:
eit = (prev == 1) + solve(bulbs,i+1, ec-1, oc, 0, memo)
oit = (prev == 0) + solve(bulbs,i+1, ec, oc-1, 1, memo)
memo[(i, ec, oc, prev)] = min(eit, oit)
return memo[(i, ec, oc, prev)]
n = int(input())
bulbs = list(map(int, input().split()))
bulbSet = set(bulbs)
ec, oc = 0,0
for i in range(1,n+1):
if i not in bulbSet:
if i%2 == 0:
ec += 1
else:
oc += 1
memo = {}
print(min(solve(bulbs,0, ec, oc, 0, memo), solve(bulbs,0, ec, oc, 1, memo))) | {
"input": [
"7\n1 0 0 5 0 0 2\n",
"5\n0 5 0 2 3\n"
],
"output": [
"1\n",
"2\n"
]
} |
3,366 | 9 | Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.
The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!
For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6.
Input
The first line contains a string s of lowercase Latin letters (1 β€ |s| β€ 10^5) β the text that Bessie intercepted.
Output
Output a single integer β the number of occurrences of the secret message.
Examples
Input
aaabb
Output
6
Input
usaco
Output
1
Input
lol
Output
2
Note
In the first example, these are all the hidden strings and their indice sets:
* a occurs at (1), (2), (3)
* b occurs at (4), (5)
* ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5)
* aa occurs at (1,2), (1,3), (2,3)
* bb occurs at (4,5)
* aab occurs at (1,3,5), (2,3,4)
* aaa occurs at (1,2,3)
* abb occurs at (3,4,5)
* aaab occurs at (1,2,3,4)
* aabb occurs at (2,3,4,5)
* aaabb occurs at (1,2,3,4,5)
Note that all the sets of indices are arithmetic progressions.
In the second example, no hidden string occurs more than once.
In the third example, the hidden string is the letter l. | def solve(s, a, b):
cnt = 0
res = 0
for ch in s:
if ch == b:
res += cnt
if ch == a:
cnt += 1
return res
s = input()
res = 0
for i in range(26):
res = max(res, len([x for x in s if x == chr(i + 97)]))
for j in range(26):
res = max(res, solve(s, chr(97 + i), chr(97 + j)))
print(res)
| {
"input": [
"aaabb\n",
"lol\n",
"usaco\n"
],
"output": [
"6\n",
"2\n",
"1\n"
]
} |
3,367 | 9 | Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.
Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints.
Input
The first line contains two integers n,m (1 β€ m β€ n β€ 100 000).
The second line contains m integers l_1, l_2, β¦, l_m (1 β€ l_i β€ n).
Output
If it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes).
Otherwise, print m integers p_1, p_2, β¦, p_m (1 β€ p_i β€ n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored.
If there are several possible solutions, you can print any.
Examples
Input
5 3
3 2 2
Output
2 4 1
Input
10 1
1
Output
-1 | def f(n, m, l):
if sum(l) < n:
return [-1]
for i in range(m):
if n-l[i] < i:
return [-1]
c = 0
r = list(range(1, m+1))
for i in range(1, m+1):
c += l[-i]
if n-c <= m-i:
break
r[-i] = n-c+1
r[-i] = m+1-i
return r
n, m = map(int, input().split())
l = [*map(int, input().split())]
print(*f(n, m, l))
| {
"input": [
"10 1\n1\n",
"5 3\n3 2 2\n"
],
"output": [
"-1\n",
"1 2 4 \n"
]
} |
3,368 | 9 | For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integers from s.
For example, \gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6 and lcm(\{4,6\})=12. Note that for any positive integer x, \gcd(\\{x\})=lcm(\\{x\})=x.
Orac has a sequence a with length n. He come up with the multiset t=\{lcm(\\{a_i,a_j\})\ |\ i<j\}, and asked you to find the value of \gcd(t) for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.
Input
The first line contains one integer n\ (2β€ nβ€ 100 000).
The second line contains n integers, a_1, a_2, β¦, a_n (1 β€ a_i β€ 200 000).
Output
Print one integer: \gcd(\{lcm(\\{a_i,a_j\})\ |\ i<j\}).
Examples
Input
2
1 1
Output
1
Input
4
10 24 40 80
Output
40
Input
10
540 648 810 648 720 540 594 864 972 648
Output
54
Note
For the first example, t=\{lcm(\{1,1\})\}=\{1\}, so \gcd(t)=1.
For the second example, t=\{120,40,80,120,240,80\}, and it's not hard to see that \gcd(t)=40. | from math import gcd
def lcm(a, b):
return (a * b) // gcd(a, b)
n = int(input())
a = list(map(int, input().split()))
s = []
g = 0
for i in a:
s.append(lcm(i, g))
g = gcd(g, i)
f = 0
for i in s:
f = gcd(f, i)
print(f)
| {
"input": [
"10\n540 648 810 648 720 540 594 864 972 648\n",
"4\n10 24 40 80\n",
"2\n1 1\n"
],
"output": [
"54\n",
"40\n",
"1\n"
]
} |
3,369 | 8 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).
Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has n planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:
* + x: the storehouse received a plank with length x
* - x: one plank with length x was removed from the storehouse (it is guaranteed that the storehouse had some planks with length x).
Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!
We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.
Input
The first line contains a single integer n (1 β€ n β€ 10^5): the initial amount of planks at the company's storehouse, the second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^5): the lengths of the planks.
The third line contains a single integer q (1 β€ q β€ 10^5): the number of events in the company. Each of the next q lines contains a description of the events in a given format: the type of the event (a symbol + or -) is given first, then goes the integer x (1 β€ x β€ 10^5).
Output
After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).
Example
Input
6
1 1 1 2 1 1
6
+ 2
+ 1
- 1
+ 2
- 1
+ 2
Output
NO
YES
NO
NO
NO
YES
Note
After the second event Applejack can build a rectangular storage using planks with lengths 1, 2, 1, 2 and a square storage using planks with lengths 1, 1, 1, 1.
After the sixth event Applejack can build a rectangular storage using planks with lengths 2, 2, 2, 2 and a square storage using planks with lengths 1, 1, 1, 1. | def f(t,d=''):global x,y;t=int(t);x-=c[t]>3;y-=c[t]//2;c[t]+=int(d+'1');x+=c[t]>3;y+=c[t]//2
_,a,_,*o=open(0);x,y,*c=[0]*9**6;[*map(f,a.split())]
for q in o:f(q[2:],q[0]);print("YNEOS"[x<1 or y<4::2]) | {
"input": [
"6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2\n"
],
"output": [
"NO\nYES\nNO\nNO\nNO\nYES\n"
]
} |
3,370 | 7 | You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade offers:
* exchange 1 stick for x sticks (you lose 1 stick and gain x sticks).
* exchange y sticks for 1 coal (you lose y sticks and gain 1 coal).
During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.
Your task is to find the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.
You have to answer t independent test cases.
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 only line of the test case contains three integers x, y and k (2 β€ x β€ 10^9; 1 β€ y, k β€ 10^9) β the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.
Output
For each test case, print the answer: the minimum number of trades you need to craft at least k torches. The answer always exists under the given constraints.
Example
Input
5
2 1 5
42 13 24
12 11 12
1000000000 1000000000 1000000000
2 1000000000 1000000000
Output
14
33
25
2000000003
1000000001999999999 | def f(a,s):return -(-a//s)
for i in range(int(input())):
x,y,k=map(int,input().split())
#yk+k
print(f(y*k+k-1,x-1)+k) | {
"input": [
"5\n2 1 5\n42 13 24\n12 11 12\n1000000000 1000000000 1000000000\n2 1000000000 1000000000\n"
],
"output": [
"14\n33\n25\n2000000003\n1000000001999999999\n"
]
} |
3,371 | 9 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has sequence a consisting of n integers.
The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.
Two sequences are considered different if index sets of numbers included in them are different. That is, the values βof the elements βdo not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).
A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).
Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7).
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 105). The next line contains n integers ai (1 β€ ai β€ 109) β the sequence a.
Output
On the single line print the single number β the answer to the problem modulo prime number 1000000007 (109 + 7).
Examples
Input
3 2
10 10 10
Output
3
Input
4 2
4 4 7 7
Output
4
Note
In the first sample all 3 subsequences of the needed length are considered lucky.
In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}. | MOD = 10 ** 9 + 7
def is_lucky(n):
n = str(n)
return n.count('4') + n.count('7') == len(n)
def get_inv(n):
return pow(n, MOD - 2, MOD)
def c(n, k):
if n < k or k < 0:
return 0
global fact, rfact
return (fact[n] * rfact[k] * rfact[n - k]) % MOD
fact = [1]
rfact = [1]
for i in range(1, 100500):
fact.append((i * fact[-1]) % MOD)
rfact.append((get_inv(i) * rfact[-1]) % MOD)
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = dict()
for x in a:
if is_lucky(x):
d[x] = d.get(x, 0) + 1
dp = [0 for i in range(len(d) + 2)]
dp[0] = 1
for x in d:
for i in range(len(dp) - 1, 0, -1):
dp[i] += dp[i - 1] * d[x]
dp[i] %= MOD
unlucky = n - sum(d.values())
ret = 0
for i in range(len(dp)):
if k >= i:
ret += dp[i] * c(unlucky, k - i)
print(ret % MOD)
| {
"input": [
"3 2\n10 10 10\n",
"4 2\n4 4 7 7\n"
],
"output": [
"3\n",
"4\n"
]
} |
3,372 | 11 | You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root.
Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree 1 are leaves. If vertices s and f are connected by an edge and the distance of f from the root is greater than the distance of s from the root, then f is called a child of s.
Initially, there are a red coin and a blue coin on the vertex 1. Let r be the vertex where the red coin is and let b be the vertex where the blue coin is. You should make d moves. A move consists of three steps:
* Move the red coin to any child of r.
* Move the blue coin to any vertex b' such that dist(1, b') = dist(1, b) + 1. Here dist(x, y) indicates the length of the simple path between x and y. Note that b and b' are not necessarily connected by an edge.
* You can optionally swap the two coins (or skip this step).
Note that r and b can be equal at any time, and there is no number written on the root.
After each move, you gain |a_r - a_b| points. What's the maximum number of points you can gain after d moves?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The second line of each test case contains n-1 integers v_2, v_3, ..., v_n (1 β€ v_i β€ n, v_i β i) β the i-th of them indicates that there is an edge between vertices i and v_i. It is guaranteed, that these edges form a tree.
The third line of each test case contains n-1 integers a_2, ..., a_n (1 β€ a_i β€ 10^9) β the numbers written on the vertices.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, print a single integer: the maximum number of points you can gain after d moves.
Example
Input
4
14
1 1 1 2 3 4 4 5 5 6 7 8 8
2 3 7 7 6 9 5 9 7 3 6 6 5
6
1 2 2 3 4
32 78 69 5 41
15
1 15 1 10 4 9 11 2 4 1 8 6 10 11
62 13 12 43 39 65 42 86 25 38 19 19 43 62
15
11 2 7 6 9 8 10 1 1 1 5 3 15 2
50 19 30 35 9 45 13 24 8 44 16 26 10 40
Output
14
45
163
123
Note
In the first test case, an optimal solution is to:
* move 1: r = 4, b = 2; no swap;
* move 2: r = 7, b = 6; swap (after it r = 6, b = 7);
* move 3: r = 11, b = 9; no swap.
The total number of points is |7 - 2| + |6 - 9| + |3 - 9| = 14.
<image>
In the second test case, an optimal solution is to:
* move 1: r = 2, b = 2; no swap;
* move 2: r = 3, b = 4; no swap;
* move 3: r = 5, b = 6; no swap.
The total number of points is |32 - 32| + |78 - 69| + |5 - 41| = 45. | import sys, io, os
from collections import defaultdict
if os.environ['USERNAME']=='kissz':
inp=open('in1.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
# SCRIPT STARTS HERE
for _ in range(int(inp())):
n=int(inp())
parents=[0,0]+[*map(int,inp().split())]
depth=[-1]*(n+1)
depth[1]=0
layers=defaultdict(list)
children=defaultdict(list)
for i in range(2,n+1):
children[parents[i]].append(i)
val=[0,0]+[*map(int,inp().split())]
layer_mins=[1<<30]*(n+1)
layer_maxs=[0]*(n+1)
maxdepth=0
Q=children[1]
while Q:
i=Q.pop()
p=parents[i]
d=depth[p]+1
depth[i]=d
maxdepth=max(maxdepth,d)
layer_mins[d]=min(layer_mins[d],val[i])
layer_maxs[d]=max(layer_maxs[d],val[i])
layers[depth[i]].append(i)
Q+=children[i]
best=[0]*(n+1)
for d in range(1,maxdepth+1):
best_sub=max(best[parents[i]]-val[i] for i in layers[d])
best_add=max(best[parents[i]]+val[i] for i in layers[d])
for i in layers[d]:
best[i]=max(best[parents[i]]+layer_maxs[d]-val[i],
best[parents[i]]+val[i]-layer_mins[d],
val[i]+best_sub,
best_add-val[i])
#debug(i,best[parents[i]]+layer_maxs[d]-val[i],
# best[parents[i]]+val[i]-layer_mins[d],
# val[i]+best_sub,
# best_add-val[i])
print(max(best))
| {
"input": [
"4\n14\n1 1 1 2 3 4 4 5 5 6 7 8 8\n2 3 7 7 6 9 5 9 7 3 6 6 5\n6\n1 2 2 3 4\n32 78 69 5 41\n15\n1 15 1 10 4 9 11 2 4 1 8 6 10 11\n62 13 12 43 39 65 42 86 25 38 19 19 43 62\n15\n11 2 7 6 9 8 10 1 1 1 5 3 15 2\n50 19 30 35 9 45 13 24 8 44 16 26 10 40\n"
],
"output": [
"\n14\n45\n163\n123\n"
]
} |
3,373 | 7 | Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array a = [a_1, a_2, β¦, a_n] of n distinct integers. An array b = [b_1, b_2, β¦, b_k] is called nice if for any two distinct elements b_i, b_j of b, |b_i-b_j| appears in b at least once. In addition, all elements in b must be distinct. Can you add several (maybe, 0) integers to a to create a nice array b of size at most 300? If a is already nice, you don't have to add any elements.
For example, array [3, 6, 9] is nice, as |6-3|=|9-6| = 3, which appears in the array, and |9-3| = 6, which appears in the array, while array [4, 2, 0, 6, 9] is not nice, as |9-4| = 5 is not present in the array.
For integers x and y, |x-y| = x-y if x > y and |x-y| = y-x otherwise.
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 50), the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer n (2 β€ n β€ 100) β the length of the array a.
The second line of each test case contains n distinct integers a_1, a_2, β
β
β
, a_n (-100 β€ a_i β€ 100) β the elements of the array a.
Output
For each test case, output one line containing YES if Omkar can create a nice array b by adding elements to a and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted.
If the first line is YES, output a second line containing a single integer k (n β€ k β€ 300).
Then output one line containing k distinct integers b_1, b_2, β
β
β
, b_k (-10^9 β€ b_i β€ 10^9), the elements of the nice array b. b_1, b_2, β
β
β
, b_k can be in any order. For each a_i in a, a_i must appear at least once in b.
It can be proved that if Omkar can create such an array b, then he can also do so in a way that satisfies the above constraints.
If multiple solutions exist, you can print any.
Example
Input
4
3
3 0 9
2
3 4
5
-7 3 13 -2 8
4
4 8 12 6
Output
yes
4
6 0 3 9
yEs
5
5 3 1 2 4
NO
Yes
6
8 12 6 2 4 10
Note
For the first case, you can add integers to a to receive the array b = [6, 0, 3, 9]. Note that |6-3| = |9-6| = |3-0| = 3 and 3 is in b, |6-0| = |9-3| = 6 and 6 is in b, and |9-0| = 9 is in b, so b is nice.
For the second case, you can add integers to a to receive the array b = [5, 3, 1, 2, 4]. We have that |2-1| = |3-2| = |4-3| = |5-4| = 1 is in b, |3-1| = |4-2| = |5-3| = 2 is in b, |4-1| = |5-2| = 3 is in b, and |5-1| = 4 is in b, so b is nice.
For the fourth case, you can add integers to a to receive the array b = [8, 12, 6, 2, 4, 10]. We have that |4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2 is in b, |6-2| = |8-4| = |10-6| = |12-8| = 4 is in b, |8-2| = |10-4| = |12-6| = 6 is in b, |10-2| = |12-4| = 8 is in b, and |12-2| = 10 is in b, so b is nice.
It can be proven that for all other test cases it is impossible to create a nice array b. | def sol():
n = int(input())
arr = [int(x) for x in input().split()]
for el in arr:
if el < 0:
print('NO')
return
print('YES')
print(101)
print(*[i for i in range(0,101)])
return
def main():
for i in range(int(input())):
sol()
main()
| {
"input": [
"4\n3\n3 0 9\n2\n3 4\n5\n-7 3 13 -2 8\n4\n4 8 12 6\n"
],
"output": [
"\nyes\n4\n6 0 3 9\nyEs\n5\n5 3 1 2 4\nNO\nYes\n6\n8 12 6 2 4 10\n"
]
} |
3,374 | 7 | Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.
The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) β "R", to point (x, y - 1) β "D", to point (x, y + 1) β "U".
The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".
You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β the number of the car's movements from the headquarters to the stall.
Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".
All movements are given in chronological order.
Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.
Output
Print a single integer β the number of different possible locations of the gang's headquarters.
Examples
Input
3
UR
UL
ULDR
Output
9
Input
2
DR
DL
Output
4
Note
The figure below shows the nine possible positions of the gang headquarters from the first sample:
<image>
For example, the following movements can get the car from point (1, 0) to point (0, 0):
<image> | def main():
a = b = 1
for _ in range(int(input())):
s = input()
if s in ("UL", "DR"):
a += 1
elif s in ("UR", "DL"):
b += 1
elif s == "ULDR":
a += 1
b += 1
print(a * b)
if __name__ == '__main__':
main()
| {
"input": [
"2\nDR\nDL\n",
"3\nUR\nUL\nULDR\n"
],
"output": [
"4\n",
"9\n"
]
} |
3,375 | 8 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not.
Input
The first line contains a single positive integer, n (1 β€ n β€ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 β€ xi β€ 1012).
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is advised to use the cin, cout streams or the %I64d specifier.
Output
Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Π’-prime, and "NO" (without the quotes), if it isn't.
Examples
Input
3
4 5 6
Output
YES
NO
NO
Note
The given test has three numbers. The first number 4 has exactly three divisors β 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | def I(): return(list(map(int,input().split())))
def sieve(n):
a=[1]*n
for i in range(2,n):
if a[i]:
for j in range(i*i,n,i):
a[j]=0
r.add(i*i)
return a
n=2**20
r=set()
sieve(n)
input()
for a in I() :
print (['NO','YES'][a in r]) | {
"input": [
"3\n4 5 6\n"
],
"output": [
"YES\nNO\nNO\n"
]
} |
3,376 | 7 | Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:
* a1 = p, where p is some integer;
* ai = ai - 1 + ( - 1)i + 1Β·q (i > 1), where q is some integer.
Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.
Sequence s1, s2, ..., sk is a subsequence of sequence b1, b2, ..., bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1 β€ i1 < i2 < ... < ik β€ n), that bij = sj. In other words, sequence s can be obtained from b by crossing out some elements.
Input
The first line contains integer n (1 β€ n β€ 4000). The next line contains n integers b1, b2, ..., bn (1 β€ bi β€ 106).
Output
Print a single integer β the length of the required longest subsequence.
Examples
Input
2
3 5
Output
2
Input
4
10 20 10 30
Output
3
Note
In the first test the sequence actually is the suitable subsequence.
In the second test the following subsequence fits: 10, 20, 10. | def ap(arr):
if len(arr)==1:
return 1
dp=[[1]*len(arr) for i in range(len(arr))]
cnst=0
dct={}
for i in set(arr):
dct[i]=cnst
cnst+=1
for i in range(len(arr)):
arr[i]=dct[arr[i]]
ans=0
for i in range(len(dp)):
for j in range(i):
dp[i][arr[j]]=max(dp[j][arr[i]]+1,dp[i][arr[j]])
ans=max(ans,dp[i][arr[j]])
return ans
a=input()
lst=list(map(int,input().strip().split()))
print(ap(lst)) | {
"input": [
"2\n3 5\n",
"4\n10 20 10 30\n"
],
"output": [
"2",
"3"
]
} |
3,377 | 7 | Β«PolygonΒ» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.
You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
Input
The first line contains one integer n (1 β€ n β€ 3000) β the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ 3000) β indexes of these tests.
Output
Output the required default value for the next test index.
Examples
Input
3
1 7 2
Output
3 | n=int(input())
a=sorted(list(map(int, input().split())))
def fn(a,n):
for i in range(n):
if a[i]!=i+1:return i+1
if i==n-1:return i+2
print(fn(a,n))
| {
"input": [
"3\n1 7 2\n"
],
"output": [
"3\n"
]
} |
3,378 | 7 | You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n Γ n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The cleaning of all evil will awaken the door!
Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.
The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.
You would like to purify all n Γ n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.
Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.
Input
The first line will contain a single integer n (1 β€ n β€ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.
Output
If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.
Examples
Input
3
.E.
E.E
.E.
Output
1 1
2 2
3 3
Input
3
EEE
E..
E.E
Output
-1
Input
5
EE.EE
E.EE.
E...E
.EE.E
EE.EE
Output
3 3
1 3
2 2
4 4
5 3
Note
The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.
<image>
In the second example, it is impossible to purify the cell located at row 1 and column 1.
For the third example:
<image> | n = int(input())
maze = [input().strip() for _ in range(n)]
def go(by_row):
global maze
maze = list(zip(*maze))
can = True
for i in range(n):
if '.' not in maze[i]:
can = False
if can:
for i in range(n):
for j in range(n):
if maze[i][j] == '.':
print(i + 1, j + 1) if by_row else print(j + 1, i + 1)
break
return can
if not go(0) and not go(1):
print(-1) | {
"input": [
"3\nEEE\nE..\nE.E\n",
"3\n.E.\nE.E\n.E.\n",
"5\nEE.EE\nE.EE.\nE...E\n.EE.E\nEE.EE\n"
],
"output": [
"-1\n",
"1 1\n2 2\n3 1\n",
"1 3\n2 2\n3 2\n4 1\n5 3\n"
]
} |
3,379 | 10 | There are n cities in Berland. Each city has its index β an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi β index of the last city on the way from the capital to i.
Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.
Input
The first line contains three space-separated integers n, r1, r2 (2 β€ n β€ 5Β·104, 1 β€ r1 β r2 β€ n) β amount of cities in Berland, index of the old capital and index of the new one, correspondingly.
The following line contains n - 1 space-separated integers β the old representation of the road map. For each city, apart from r1, there is given integer pi β index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.
Output
Output n - 1 numbers β new representation of the road map in the same format.
Examples
Input
3 2 3
2 2
Output
2 3
Input
6 2 4
6 1 2 4 2
Output
6 4 1 4 2 | n, r1, r2 = map(int, input().split())
def dfs(u):
x = None
while x != r1:
tmp = prev[u]
prev[u] = x
x = u
u = tmp
prev = [0] + list(map(int, input().split()))
prev.insert(r1, None)
dfs(r2)
prev.remove(0)
prev.remove(None)
print(*prev)
| {
"input": [
"3 2 3\n2 2\n",
"6 2 4\n6 1 2 4 2\n"
],
"output": [
"2 3\n",
"6 4 1 4 2\n"
]
} |
3,380 | 8 | Let's assume that
* v(n) is the largest prime number, that does not exceed n;
* u(n) is the smallest prime number strictly greater than n.
Find <image>.
Input
The first line contains integer t (1 β€ t β€ 500) β the number of testscases.
Each of the following t lines of the input contains integer n (2 β€ n β€ 109).
Output
Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q > 0.
Examples
Input
2
2
3
Output
1/6
7/30 | def prime(n):
m = int(n ** 0.5) + 1
t = [1] * (n + 1)
for i in range(3, m):
if t[i]: t[i * i :: 2 * i] = [0] * ((n - i * i) // (2 * i) + 1)
return [2] + [i for i in range(3, n + 1, 2) if t[i]]
def gcd(a, b):
c = a % b
return gcd(b, c) if c else b
p = prime(31650)
def g(n):
m = int(n ** 0.5)
for j in p:
if n % j == 0: return True
if j > m: return False
def f(n):
a, b = n, n + 1
while g(a): a -= 1
while g(b): b += 1
p, q = (b - 2) * a + 2 * (n - b + 1), 2 * a * b
d = gcd(p, q)
print(str(p // d) + '/' + str(q // d))
for i in range(int(input())): f(int(input())) | {
"input": [
"2\n2\n3\n"
],
"output": [
"1/6\n7/30\n"
]
} |
3,381 | 9 | While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n Γ m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.
Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.
Input
The first line contains two integers n and m (1 β€ n, m β€ 100) β the size of the table.
Output
Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.
Examples
Input
1 1
Output
1
Input
1 2
Output
3 4 | """
Codeforces Round 241 Div 1 Problem E
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
res = inputs[:]
inputs[:] = []
while n > len(inputs):
inputs.extend(input().split(" "))
if n > 0:
res = inputs[:n]
inputs[:n] = []
return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput
############################## SOLUTION ##############################
n,m = [int(x) for x in g()]
def sqr(n):
if n == 1:
return [1]
if n == 2:
return [4,3]
if n % 2:
return [(n+1)//2, 2] + [1] * (n-2)
return [(n-2)//2] + [1] * (n-1)
a = sqr(n)
b = sqr(m)
for i in range(n):
res = [str(a[i]*x) for x in b]
print(" ".join(res)) | {
"input": [
"1 1\n",
"1 2\n"
],
"output": [
"1 \n",
"3 4 \n"
]
} |
3,382 | 7 | DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 100).
Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.
Output
Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.
If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.
Examples
Input
1 1
.
Output
B
Input
2 2
..
..
Output
BW
WB
Input
3 3
.-.
---
--.
Output
B-B
---
--B
Note
In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.
In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.
In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are. | def main():
n, m = [int(i) for i in input().split()]
table = [input() for i in range(n)]
for i in range(n):
for j in range(m):
if table[i][j] == '-': print('-', end='')
elif (i + j) % 2 == 0: print('B', end='')
else: print('W', end='')
print()
main()
| {
"input": [
"3 3\n.-.\n---\n--.",
"1 1\n.\n",
"2 2\n..\n..\n"
],
"output": [
"B-B\n---\n--B\n",
"B\n",
"BW\nWB\n"
]
} |
3,383 | 8 | After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».
The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type.
Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.
Input
The first line contains three integers n, m, k (1 β€ k β€ n β€ 20; 1 β€ m β€ 1000).
The i-th of the next (m + 1) lines contains a single integer xi (1 β€ xi β€ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.
Output
Print a single integer β the number of Fedor's potential friends.
Examples
Input
7 3 1
8
5
111
17
Output
0
Input
3 3 3
1
2
3
4
Output
3 | n,m,k = [int(x) for x in input().split()]
arr = [int(input()) for i in range(m+1)]
def calc(x):
return bin(x^arr[-1]).count('1')<=k
print(sum(map(calc,arr[:-1]))) | {
"input": [
"7 3 1\n8\n5\n111\n17\n",
"3 3 3\n1\n2\n3\n4\n"
],
"output": [
"0\n",
"3\n"
]
} |
3,384 | 9 | Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.
Input
The single line contains a number n (1 β€ n β€ 104) which is the number of mounds.
Output
Print n integers pi (1 β€ pi β€ n) which are the frog's route plan.
* All the pi's should be mutually different.
* All the |piβpi + 1|'s should be mutually different (1 β€ i β€ n - 1).
If there are several solutions, output any.
Examples
Input
2
Output
1 2
Input
3
Output
1 3 2 |
def main():
n = int(input())
xx = int(n/2)
for i in range(1,xx+1):
print(i,n-i+1)
if(n%2==1) :
print(int(n/2)+1)
main()
| {
"input": [
"3\n",
"2\n"
],
"output": [
"1 3 2",
"1 2 "
]
} |
3,385 | 11 | Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s β t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.
Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.
The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.
Input
The first lines contain four integers n, m, s and t (2 β€ n β€ 105; 1 β€ m β€ 105; 1 β€ s, t β€ n) β the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s β t).
Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 β€ ai, bi β€ n; ai β bi; 1 β€ li β€ 106) β the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi.
The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.
Output
Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input).
If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes).
Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing.
If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes).
Examples
Input
6 7 1 6
1 2 2
1 3 10
2 3 7
2 4 8
3 5 3
4 5 2
5 6 1
Output
YES
CAN 2
CAN 1
CAN 1
CAN 1
CAN 1
YES
Input
3 3 1 3
1 2 10
2 3 10
1 3 100
Output
YES
YES
CAN 81
Input
2 2 1 2
1 2 1
1 2 2
Output
YES
NO
Note
The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.
In the first sample president initially may choose one of the two following ways for a ride: 1 β 2 β 4 β 5 β 6 or 1 β 2 β 3 β 5 β 6. | from heapq import *
from collections import defaultdict
def D(v,g):
h,p,o=[],defaultdict(lambda:1e99),[]
heappush(h,(0,v))
while h:
l,w=heappop(h)
if w in p:continue
p[w]=l
o.append(w)
for u,L in g[w]:
heappush(h,(L+l,u))
return p,o
n,m,s,t=map(int,input().split())
r=[]
g={i+1:[] for i in range(n)}
G={i+1:[] for i in range(n)}
for _ in range(m):
a,b,l=map(int,input().split())
r.append((a,b,l))
g[a].append((b,l))
G[b].append((a,l))
S,o=D(s,g)
T,_=D(t,G)
L=S[t]
H={v:[w for w,l in e if S[v]+T[w]+l==L] for v,e in g.items()}
B,A=set(),{s}
for v in o:
if not H[v]:continue
if 1==len(A)==len(H[v]):B.add(v)
A.update(H[v])
A.remove(v)
print('\n'.join("YES" if a in B and S[a]+T[b]+l==L else "CAN "+str(S[a]+T[b]+l-L+1) if S[a]+T[b]+1<L else "NO" for a,b,l in r))
| {
"input": [
"3 3 1 3\n1 2 10\n2 3 10\n1 3 100\n",
"2 2 1 2\n1 2 1\n1 2 2\n",
"6 7 1 6\n1 2 2\n1 3 10\n2 3 7\n2 4 8\n3 5 3\n4 5 2\n5 6 1\n"
],
"output": [
"YES\nYES\nCAN 81\n",
"YES\nNO\n",
"YES\nCAN 2\nCAN 1\nCAN 1\nCAN 1\nCAN 1\nYES\n"
]
} |
3,386 | 10 | Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.
Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of segments drawn by Vika.
Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 β€ x1, y1, x2, y2 β€ 109) β the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.
Output
Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.
Examples
Input
3
0 1 2 1
1 4 1 2
0 3 2 3
Output
8
Input
4
-2 -1 2 -1
2 1 -2 1
-1 -2 -1 2
1 2 1 -2
Output
16
Note
In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3). | from sys import stdin
from itertools import repeat
from collections import defaultdict
def main():
n = int(stdin.readline())
h = defaultdict(list)
w = defaultdict(list)
for i in range(n):
a, b, c, d = map(int, input().split())
if a > c:
a, c = c, a
if b > d:
b, d = d, b
if a == c:
h[a].append((b, d))
else:
w[b].append((a, c))
ans = 0
ys = set()
es = defaultdict(list)
qs = defaultdict(list)
for t, l in h.items():
l.sort()
l.append((1001001001, 1001001001))
nl = []
p = r = l[0][0]
for a, b in l:
if a > r:
nl.append((p, r))
ans += r - p + 1
es[p].append((1, t))
es[r+1].append((-1, t))
p = r = a
if r < b:
r = b
l = nl
ys.add(t)
for t, l in w.items():
l.sort()
l.append((1001001001, 1001001001))
nl = []
p = r = l[0][0]
for a, b in l:
if a > r:
nl.append((p, r))
ys.add(p)
ys.add(r)
es[t].append((2, p, r))
ans += r - p + 1
p = r = a
if r < b:
r = b
l = nl
ys = [-1001001001] + list(ys)
ys.sort()
d = {v: i for i, v in enumerate(ys)}
l = len(ys)
bs = [0] * l
for x in sorted(es.keys()):
for q in sorted(es[x]):
if q[0] <= 1:
a, b = q[0], d[q[1]]
while b < l:
bs[b] += a
b += b - (b & (b - 1))
else:
a, b = d[q[1]] - 1, d[q[2]]
while b > 0:
ans -= bs[b]
b = b & (b - 1)
while a > 0:
ans += bs[a]
a = a & (a - 1)
print (ans)
main() | {
"input": [
"3\n0 1 2 1\n1 4 1 2\n0 3 2 3\n",
"4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2\n"
],
"output": [
"8",
"16"
]
} |
3,387 | 9 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.
Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex β root.
Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?
Input
In the first line of the input integer n (1 β€ n β€ 105) is given β the number of vertices in the tree.
In the second line the sequence of n integers a1, a2, ..., an (1 β€ ai β€ 109) is given, where ai is the number written on vertex i.
The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 β€ pi β€ n, - 109 β€ ci β€ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.
Output
Print the only integer β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.
Example
Input
9
88 22 83 14 95 91 98 53 11
3 24
7 -8
1 67
1 64
9 65
5 12
6 -80
3 8
Output
5
Note
The following image represents possible process of removing leaves from the tree:
<image> | """
Author : Arif Ahmad
Date : 18-06-16
Algo : DFS
Difficulty : Medium
"""
def main():
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
g = [[] for x in range(n+1)]
cost = {}
for i in range(2, n+1):
p, c = map(int, input().split())
g[p].append((i, c))
stack = [(1, 0, False)]
ans = 0
while stack:
u, dist, sad = stack.pop()
sad = sad or dist > a[u]
if sad: ans += 1
for v, c in g[u]:
stack.append((v, max(0, dist+c), sad))
print(ans)
if __name__ == '__main__':
main()
| {
"input": [
"9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8\n"
],
"output": [
"5"
]
} |
3,388 | 8 | Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.
Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 β€ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).
Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins?
Peter is pretty good at math, but now he asks you to help.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of tests Peter is about to make.
The second line contains n space separated integers a1, a2, ..., an (1 β€ ai β€ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.
Output
Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.
Examples
Input
3
1 2 3
Output
2
1
1
Input
5
1 1 5 1 1
Output
2
2
2
2
2
Note
In the first sample test:
In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.
In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.
In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.
In the second sample test:
Having cycles of size 1 is like not having them (because no one can make a move on them).
In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.
* If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.
* If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins.
So, either way first player loses. | def s():
n = int(input())
su = 1
for i in map(int,input().split()):
su += i-1
print(su%2+1)
s() | {
"input": [
"5\n1 1 5 1 1\n",
"3\n1 2 3\n"
],
"output": [
"2 2 2 2 2\n",
"2 1 1\n"
]
} |
3,389 | 7 | Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values x and y written on it. These values define four moves which can be performed using the potion:
* <image>
* <image>
* <image>
* <image>
Map shows that the position of Captain Bill the Hummingbird is (x1, y1) and the position of the treasure is (x2, y2).
You task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output "YES", otherwise "NO" (without quotes).
The potion can be used infinite amount of times.
Input
The first line contains four integer numbers x1, y1, x2, y2 ( - 105 β€ x1, y1, x2, y2 β€ 105) β positions of Captain Bill the Hummingbird and treasure respectively.
The second line contains two integer numbers x, y (1 β€ x, y β€ 105) β values on the potion bottle.
Output
Print "YES" if it is possible for Captain to reach the treasure using the potion, otherwise print "NO" (without quotes).
Examples
Input
0 0 0 6
2 3
Output
YES
Input
1 1 3 6
1 5
Output
NO
Note
In the first example there exists such sequence of moves:
1. <image> β the first type of move
2. <image> β the third type of move | def main():
x1, y1, x2, y2 = map(int, input().split())
a, b = map(int, input().split())
x1 -= x2
y1 -= y2
print(("NO", "YES")[x1 % a == 0 == y1 % b and x1 % (2 * a) * b == y1 % (2 * b) * a])
if __name__ == '__main__':
main()
| {
"input": [
"1 1 3 6\n1 5\n",
"0 0 0 6\n2 3\n"
],
"output": [
"No\n",
"Yes\n"
]
} |
3,390 | 7 | Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers β amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers a and b such that l β€ a β€ r and x β€ b β€ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)Β·(y - x + 1) potions).
Kirill wants to buy a potion which has efficiency k. Will he be able to do this?
Input
First string contains five integer numbers l, r, x, y, k (1 β€ l β€ r β€ 107, 1 β€ x β€ y β€ 107, 1 β€ k β€ 107).
Output
Print "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise.
You can output each of the letters in any register.
Examples
Input
1 10 1 10 1
Output
YES
Input
1 5 6 10 1
Output
NO | def foo():
x,y,l,r,k = [int(x) for x in input().split()]
for i in range(l, r+1):
if x <= k*i <= y:
return 'YES'
return 'NO'
print(foo()) | {
"input": [
"1 10 1 10 1\n",
"1 5 6 10 1\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
3,391 | 7 | Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String t is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.
You are given some integer number x. Check if it's a quasi-palindromic number.
Input
The first line contains one integer number x (1 β€ x β€ 109). This number is given without any leading zeroes.
Output
Print "YES" if number x is quasi-palindromic. Otherwise, print "NO" (without quotes).
Examples
Input
131
Output
YES
Input
320
Output
NO
Input
2010200
Output
YES | def main():
s = input().rstrip('0')
print(('NO', 'YES')[s == s[::-1]])
if __name__ == '__main__':
main()
| {
"input": [
"2010200\n",
"320\n",
"131\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n"
]
} |
3,392 | 11 | You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 β€ b1 < b2 < ... < bk β€ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty.
Print the maximum possible value of <image>.
Input
The first line contains two integers n and m (1 β€ n β€ 35, 1 β€ m β€ 109).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print the maximum possible value of <image>.
Examples
Input
4 4
5 2 4 1
Output
3
Input
3 20
199 41 299
Output
19
Note
In the first example you can choose a sequence b = {1, 2}, so the sum <image> is equal to 7 (and that's 3 after taking it modulo 4).
In the second example you can choose a sequence b = {3}. | n,m=map(int,input().split())
a=[int(i) for i in input().split()]
x,y=set(),set()
def f(x,n,i,s=0):
if i==n:x.add(s%m)
else:
f(x,n,i+1,s+a[i])
f(x,n,i+1,s)
h=n//2
f(x,h,0)
f(y,n,h)
y=sorted(y)
import bisect
k=0
print(max(i+y[bisect.bisect_left(y,m-i)-1]for i in x)) | {
"input": [
"3 20\n199 41 299\n",
"4 4\n5 2 4 1\n"
],
"output": [
"19",
"3"
]
} |
3,393 | 9 | Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state β sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th second, then it is lit only during seconds x, x + ki, x + 2ki, x + 3ki and so on.
Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers x1, x2 and x3 (not necessarily distinct) so that he will switch on the first garland during x1-th second, the second one β during x2-th second, and the third one β during x3-th second, respectively, and during each second starting from max(x1, x2, x3) at least one garland will be lit.
Help Mishka by telling him if it is possible to do this!
Input
The first line contains three integers k1, k2 and k3 (1 β€ ki β€ 1500) β time intervals of the garlands.
Output
If Mishka can choose moments of time to switch on the garlands in such a way that each second after switching the garlands on at least one garland will be lit, print YES.
Otherwise, print NO.
Examples
Input
2 2 3
Output
YES
Input
4 2 3
Output
NO
Note
In the first example Mishka can choose x1 = 1, x2 = 2, x3 = 1. The first garland will be lit during seconds 1, 3, 5, 7, ..., the second β 2, 4, 6, 8, ..., which already cover all the seconds after the 2-nd one. It doesn't even matter what x3 is chosen. Our choice will lead third to be lit during seconds 1, 4, 7, 10, ..., though.
In the second example there is no way to choose such moments of time, there always be some seconds when no garland is lit. | from collections import Counter
def main():
c = Counter(map(int, input().split()))
if c[1] >= 1 or c[2] >= 2 or c[3] >= 3 or (c[4] == 2 and c[2] == 1):
print('YES')
else:
print('NO')
main()
| {
"input": [
"2 2 3\n",
"4 2 3\n"
],
"output": [
"YES",
"NO"
]
} |
3,394 | 7 | A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.
Little Tommy is among them. He would like to choose an interval [l, r] (1 β€ l β€ r β€ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.
A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 β€ ap2 β€ ... β€ apk. The length of the subsequence is k.
Input
The first line contains an integer n (1 β€ n β€ 2000), denoting the length of the original sequence.
The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 β€ ai β€ 2, i = 1, 2, ..., n).
Output
Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.
Examples
Input
4
1 2 1 2
Output
4
Input
10
1 1 2 2 2 1 1 2 2 1
Output
9
Note
In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.
In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | def solve(lst):
a = b = c = d = 0
for i in range(len(lst)):
if lst[i] == 1:
a += 1
c = max(b, c) + 1
else:
b = max(a, b) + 1
d = max(c, d) + 1
return max(a, b, c, d)
n = input()
lst = list(map(int, input().split()))
print(solve(lst))
| {
"input": [
"4\n1 2 1 2\n",
"10\n1 1 2 2 2 1 1 2 2 1\n"
],
"output": [
"4\n",
"9\n"
]
} |
3,395 | 9 | Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.
Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.
At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium.
Input
The first line contains two integers n and m (1 β€ n β€ 1000, 0 β€ m β€ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 β€ x, y β€ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 β€ ui, vi β€ n, 1 β€ wi β€ 109) β they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 β€ ti, ci β€ 109), which describe the taxi driver that waits at the i-th junction β the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character.
Output
If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
4 4
1 3
1 2 3
1 4 1
2 4 1
2 3 5
2 7
7 2
1 2
7 7
Output
9
Note
An optimal way β ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles. | from sys import stdin
import heapq
n,m = [int(x) for x in stdin.readline().split()]
start,end = [int(x)-1 for x in stdin.readline().split()]
graph = [{} for x in range(n)]
taxis = []
for road in range(m):
l,r,d = [int(x) for x in stdin.readline().split()]
l -= 1
r -= 1
if not r in graph[l]:
graph[l][r] = d
graph[r][l] = d
else:
graph[l][r] = min(graph[l][r], d)
graph[r][l] = min(graph[r][l], d)
for junc in range(n):
d,c = [int(x) for x in stdin.readline().split()]
taxis.append((d,c))
def canGo(l,die):
q = []
dists = [float('inf') for x in range(n)]
visited = [False for x in range(n)]
dists[l] = 0
heapq.heappush(q,(0,l))
while q:
d,nxt = heapq.heappop(q)
if not visited[nxt]:
visited[nxt] = True
for x in graph[nxt]:
if not visited[x]:
if d+graph[nxt][x] < dists[x]:
dists[x] = d+graph[nxt][x]
heapq.heappush(q,(dists[x], x))
out = []
for x in range(n):
if dists[x] <= die:
out.append(x)
#print(l,die,dists)
return out
q = []
dists = [float('inf') for x in range(n)]
visited = [False for x in range(n)]
dists[start] = 0
heapq.heappush(q,(0,start))
while q:
d,nxt = heapq.heappop(q)
if not visited[nxt]:
visited[nxt] = True
for x in canGo(nxt,taxis[nxt][0]):
if not visited[x]:
if d+taxis[nxt][1] < dists[x]:
dists[x] = d+taxis[nxt][1]
heapq.heappush(q,(dists[x], x))
if dists[end] != float('inf'):
print(dists[end])
else:
print(-1)
| {
"input": [
"4 4\n1 3\n1 2 3\n1 4 1\n2 4 1\n2 3 5\n2 7\n7 2\n1 2\n7 7\n"
],
"output": [
"9\n"
]
} |
3,396 | 7 | You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.
Input
In the first line of input there is one integer n (0 β€ n β€ 6) β the number of Gems in Infinity Gauntlet.
In next n lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.
Output
In the first line output one integer m (0 β€ m β€ 6) β the number of absent Gems.
Then in m lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.
Examples
Input
4
red
purple
yellow
orange
Output
2
Space
Time
Input
0
Output
6
Time
Mind
Soul
Power
Reality
Space
Note
In the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.
In the second sample Thanos doesn't have any Gems, so he needs all six. | def Thanos():
powers = {"purple":"Power", "green":"Time", "blue":"Space", "orange":"Soul", "red":"Reality", "yellow":"Mind"}
n = int(input())
for i in range(n):
powers.pop(input())
print(len(powers))
for key, val in powers.items():
print(val)
Thanos() | {
"input": [
"0\n",
"4\nred\npurple\nyellow\norange\n"
],
"output": [
"6\nPower\nTime\nSpace\nSoul\nReality\nMind\n",
"2\nTime\nSpace\n"
]
} |
3,397 | 10 | There are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1.
You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house x to the house y, the total distance you walked increases by |x-y| units of distance, where |a| is the absolute value of a. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).
Your goal is to walk exactly s units of distance in total.
If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly k moves.
Input
The first line of the input contains three integers n, k, s (2 β€ n β€ 10^9, 1 β€ k β€ 2 β
10^5, 1 β€ s β€ 10^{18}) β the number of houses, the number of moves and the total distance you want to walk.
Output
If you cannot perform k moves with total walking distance equal to s, print "NO".
Otherwise print "YES" on the first line and then print exactly k integers h_i (1 β€ h_i β€ n) on the second line, where h_i is the house you visit on the i-th move.
For each j from 1 to k-1 the following condition should be satisfied: h_j β h_{j + 1}. Also h_1 β 1 should be satisfied.
Examples
Input
10 2 15
Output
YES
10 4
Input
10 9 45
Output
YES
10 1 10 1 2 1 2 1 6
Input
10 9 81
Output
YES
10 1 10 1 10 1 10 1 10
Input
10 9 82
Output
NO | import sys
input=sys.stdin.readline
def read():return list(map(int,input().split()))
n,k,s=read()
if (n-1)*k<s or k>s:
print('NO')
quit()
print('YES')
cur=1
while k > 0:
l = min(n-1,s-k+1)
if cur-l>0:
cur -= l
else:
cur += l
print(cur, end=" ")
s -= l
k -= 1
print() | {
"input": [
"10 2 15\n",
"10 9 82\n",
"10 9 81\n",
"10 9 45\n"
],
"output": [
"YES\n10 4 ",
"NO",
"YES\n10 1 10 1 10 1 10 1 10 ",
"YES\n6 1 6 1 6 1 6 1 6\n"
]
} |
3,398 | 8 | This is an interactive problem.
In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.
The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.
To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l β€ r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that max(1, x - k) β€ y β€ min(n, x + k).
Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.
After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure.
Can you find the station with the train using no more than 4500 applications of the gadgets?
Input
The first line contains two integers n and k (1 β€ n β€ 10^{18}, 0 β€ k β€ 10) β the number of stations and the maximum number of stations the train can move between two applications of the gadget.
Interaction
You can apply the gadget at most 4500 times. In order to apply the gadget you need to print two space-separated integers l and r (1 β€ l β€ r β€ n). You will then receive either string "Yes", if the train is between stations l and r, inclusive, or string "No" otherwise. If l = r and you received "Yes", then you found the train successfully, and your program must halt immediately.
Answer "Bad" instead of "Yes" or "No" means that you made an invalid query or made too many queries. Exit immediately after receiving "Bad" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hacks
In order to hack, you should present a test in the following format.
The first line should contain three integers n, k and p (1 β€ n β€ 10^{18}, 0 β€ k β€ 10, 1 β€ p β€ n) β the number of stations, the maximum number of stations the train can move between two applications of the gadget and the initial position of the train, respectively.
Each of the next 4500 lines should contain a single integer x (1 β€ x β€ n) β the positions of the train after each query. Two consecutive positions (including the initial one) should not differ by more than k.
For example, the following lines are the first lines of the sample test.
10 2 5
5
3
5
7
7
...
Example
Input
10 2
Yes
No
Yes
Yes
Output
3 5
3 3
3 4
5 5
Note
In the first sample, the train was initially at the station 5, after the first application of the gadget it did not move, after the second application it moved to the station 3, and after the third application moved again to the station 5. | import random, sys
n,k=map(int,input().split(' '))
def ask(l, r):
print(l,r)
sys.stdout.flush()
ans=input()
if ans=="Bad":
sys.exit(0)
return ans=="Yes"
def f(l, r):
while r-l>5*max(1,k):
mid=(l+r)//2
if ask(l,mid):
l=max(1,l-k)
r=min(n,mid+k)
else:
l=max(1,mid+1-k)
r=min(n,r+k)
return (l,r)
l,r=f(1,n)
while 1:
i=random.randint(l,r)
if ask(i,i):
break
else:
l,r=f(max(1,l-k),min(n,r+k)) | {
"input": [
"10 2\n\nYes\n\nNo\n\nYes\n\nYes\n"
],
"output": [
"10 10\n"
]
} |
3,399 | 10 | There are n TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The i-th of the shows is going from l_i-th to r_i-th minute, both ends inclusive.
You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments [l_i, r_i] and [l_j, r_j] intersect, then shows i and j can't be watched simultaneously on one TV.
Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.
There is a TV Rental shop near you. It rents a TV for x rupees, and charges y (y < x) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes [a; b] you will need to pay x + y β
(b - a).
You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo 10^9 + 7.
Input
The first line contains integers n, x and y (1 β€ n β€ 10^5, 1 β€ y < x β€ 10^9) β the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute.
Each of the next n lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9) denoting the start and the end minute of the i-th TV show.
Output
Print exactly one integer β the minimum cost to view all the shows taken modulo 10^9 + 7.
Examples
Input
5 4 3
1 2
4 10
2 4
10 11
5 9
Output
60
Input
6 3 2
8 20
6 22
4 15
20 28
17 25
20 27
Output
142
Input
2 1000000000 2
1 2
2 3
Output
999999997
Note
In the first example, the optimal strategy would be to rent 3 TVs to watch:
* Show [1, 2] on the first TV,
* Show [4, 10] on the second TV,
* Shows [2, 4], [5, 9], [10, 11] on the third TV.
This way the cost for the first TV is 4 + 3 β
(2 - 1) = 7, for the second is 4 + 3 β
(10 - 4) = 22 and for the third is 4 + 3 β
(11 - 2) = 31, which gives 60 int total.
In the second example, it is optimal watch each show on a new TV.
In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo 10^9 + 7. | 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")
##########################################################
#q.sort(key=lambda x:((x[1]-x[0]),-x[0]))
#from collections import Counter
#from fractions import Fraction
#s=iter(input())
# for _ in range(int(input())):
#from collections import deque
# n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
#ls=list(map(int,input().split()))
#for in range(m):
from bisect import bisect_right
n, x, y = map(int, input().split(' '))
s=[0]*n
e=[0]*n
v=[0]*n
c=0
for i in range(n):
s[i],e[i]=map(int, input().split(' '))
c+=x+(e[i]-s[i])*y
s.sort()
e.sort()
for i in range(n-2,-1,-1):
k=bisect_right(s,e[i])
while (k < n) and (v[k]==1) and (s[k]-e[i]) * y < x :
k+=1
if k==n:
continue
if (s[k]-e[i]) * y < x :
v[k] = 1
c+=(s[k]-e[i])*y-x
print(c%(10**9+7)) | {
"input": [
"6 3 2\n8 20\n6 22\n4 15\n20 28\n17 25\n20 27\n",
"5 4 3\n1 2\n4 10\n2 4\n10 11\n5 9\n",
"2 1000000000 2\n1 2\n2 3\n"
],
"output": [
"142\n",
"60\n",
"999999997\n"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.