N=int(input())
maxi=0
smaxi=0
flag=0
ls=[]
x=0
for i in range(N):
  x=int(input())
  ls.append(x)
  if (maxi<x):
    flag=0
    smaxi=maxi
    maxi=x
  elif (maxi==x):
    flag=1
if(smaxi==0):
  smaxi==maxi
for i in range(N):
  if (ls[i]==maxi):
    if(flag==1):
      print(maxi)
    else:
      print(smaxi)
  else:
    print(maxi)


import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)

INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

MOD = 10 ** 4 + 7

N = int(input())

A = [0] * N
for i in range(N):
    A[i] = int(input())

d = []
for a in A:
    l = -1
    r = len(d)
    while r - l > 1:
        m = l + (r - l) // 2
        if d[m] >= a:
            r = m
        else:
            l = m
    if r == 0:
        d = [a] + d
    else:
        d[r - 1] = a
print(len(d))

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 500 points

Problem Statement

You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If A_i and A_j (i < j) are painted with the same color, A_i < A_j.

Find the minimum number of colors required to satisfy the condition.

Constraints

1 \leq N \leq 10^5

0 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


from collections import Counter
def check():
  N = int(input())
  A = list(map(int, input().split()))
  if N%3 in [1,2]:
    if A!=[0]*N:
      return 'No'
    return 'Yes'
  c = Counter(A)
  if len(c)==1:
    if c[0]==0:
      return 'No'
    return 'Yes'
  if len(c)==2:
    if c[0]!=N//3:
      return 'No'
    return 'Yes'
  if len(c)==3:
    lis = []
    for k,v in c.items():
      if v!=N//3:
        return 'No'
      lis.append(k)
    if lis[0]^lis[1]==lis[2]:
      return 'Yes'
  return 'No'
print(check())

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


import numpy as np
N = int(input())
A = list(map(int, input().split()))
a = np.array(A)
# l = int(((N*N)+1)/2)
b = []
for i in range(N):
    if i%2==0:
        b.append(1)
    else:
        b.append(-1)
c = np.dot(np.array(b),a)
x = [c]
for j in range(1,N):
    x_j = 2*a[j-1] - x[j-1]
    x.append(x_j)
ans = list(map(str, list(map(int, list(x)))))
print(" ".join(ans))

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


s = list(input())
count = int(0)
for i in s:
    for j in s:
        if(i==j):
            count += 1
if(count == 8):
    print("Yes")
else:
    print("No")

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


S = list(input())
A = S[0]
while A in S :
    S.remove(A)
if len(S) == 2 :
    if S[0] == S[1] :
        print("Yes")
    else :
        print("No")
else :
    print("No")


n = int(input())
p = list(map(int, input().split()))

ans = set()
for i in range(1, n-1):
	a = []
	a.append(p[i-1])
	a.append(p[i])
	a.append(p[i+1])
	a.sort()
	if a[0] < a[1] and a[1] < a[2]:
	  ans.add(a[1])

print(len(ans))

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


n = int(input())
a = list(map(int,input().split()))
a.sort()
print(a[n//2]-a[n//2-1])

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685


import sys
sys.setrecursionlimit(1000000)

N,blue = map(int,input().split())
red = N-blue

def cmb(n, r):
    nCr = {}
    if r == 0 or r == n: return 1
    if r == 1: return n
    if (n,r) in nCr: return nCr[(n,r)]
    nCr[(n,r)] = cmb(n-1,r) + cmb(n-1,r-1)
    return nCr[(n,r)]

# 操作回数
max_opr = min(red+1, blue)

for i in range(1,max_opr+1):
    # 青の差し込み箇所（操作回数）
    ins_ptn = cmb(red+1, i)
    # 青の配置方法
    layout_ptn = cmb(blue-1, i-1)
    print(ins_ptn * layout_ptn % (10**9+7))

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


s = input()
if len(set(s)) == 4:
    print('Good')
elif len(set(s)) == 1:
    print('Bad')
elif len(set(s)) == 2:
    if s[0] == s[2] and s.count(s[0]) == 2:
        print('Good')
    else:
        print('Bad')
else:
    if s[0] == s[1] or s[1] == s[2] or s[2] ==s[3]:
        print('Bad')
    else:
        print('Good')

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


n, l = map(int, input().split())

a = []
res = 300
for i in range(n):
  a.append(l+i)
  res = min(res, abs(l+i))
s = sum(a)
if res in a:
  print(s-res)
else:
  print(s+res)

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


N, L = map(int, input().split())

if L > -1:
  N_eat = 1
elif N+L-1 < 1:
  N_eat = N
else:
  N_eat = 1-L

pie = N*(N+1)/2 +N*(L-1) - (L + N_eat-1)
print(pie)


import numpy as np

N,L=map(int, input().split())
taste=0
Apple_taste=[]

for i in range(N):
    taste=L+i
    Apple_taste.append(taste)

Abs=[abs(t) for t in Apple_taste]

i_m=np.argmin(Abs)
del Apple_taste[i_m]

print(sum(Apple_taste))


Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


a,b,c,d = input().split()
a,b,c,d = int(a),int(b),int(c),int(d)
ad = []
for num in range(a,b+1):
    if num%c!=0:
        if num%d!=0:
            ad.append(num)

print(len(ad))


a,b,c,d = map(int, input().split())
count = 0
for i in range(a , b+1):
    e = i % c
    if e != 0:
        f = i % d
        if f != 0:
            count += 1

print(count)


# n = int(sys.stdin.readline())
# a, b = map(int, sys.stdin.readline().split())
# c = list(map(int, sys.stdin.readline().split()))
# s = [list(map(int,list(sys.stdin.readline()))) for i in range(h)]  # 二次元配列入力　二次元マップみたいな入力のとき

# a = 100
# b = 0.987654321
# print('{0:06d}-{1:6f}'.format(a,b))  # 0埋め, 小数点出力桁指定時のときの出力
# 000100-0.987654

import math
import sys
import itertools
import queue
from functools import reduce
from fractions import gcd

def lcm(a, b):
    return a * b / gcd(a, b)

mod = 1000000007

if __name__ == "__main__":
    A, B, C, D = map(int, sys.stdin.readline().split())
    A = A - 1
    c_div = int(B // C)
    d_div = int(B // D)
    cd_div = int(B // lcm(C, D))

    not_div1 = B - (c_div + d_div -cd_div)

    c_div = int(A // C)
    d_div = int(A // D)
    cd_div = int(A // lcm(C, D))

    not_div2 = A - (c_div + d_div -cd_div)

    print(not_div1 - not_div2)


N = int(input())
As, Bs = list(), list()
for i in range(N):
    A, B = map(int, input().split())
    As.append(A)
    Bs.append(B)

Bs_with_index = sorted([(Bs[i], i) for i in range(len(Bs))])
indices = list(map(lambda b: b[1], Bs_with_index))

time = 0
for index in indices:
    time += As[index]
    if time > Bs[index]:
        print('No')
        break

else:
    print('Yes')

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

def LI(): return list(map(int, sys.stdin.readline().split()))

N,K = LI()

if K > (N-1)*(N-2)//2 :
    print("-1")
    exit()
nodes = []
for i in range(1,N):
    nodes.append([1,i+1])
add = (N-1)*(N-2) // 2 - K
for i in range(N-2):
    for j in range(i,N-3):
        add -= 1

        if add < 0:
            break
        nodes.append([i+2,j+3])
    else:
        continue
    break

for node in nodes:
    x,y = node
    print(x,y)

Score: 500 points

Problem Statement

Does there exist an undirected graph with N vertices satisfying the following conditions?

The graph is simple and connected.

The vertices are numbered 1, 2, ..., N.

Let M be the number of edges in the graph. The edges are numbered 1, 2, ..., M, the length of each edge is 1, and Edge i connects Vertex u_i and Vertex v_i.

There are exactly K pairs of vertices (i,\ j)\ (i < j) such that the shortest distance between them is 2.

If there exists such a graph, construct an example.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq K \leq \frac{N(N - 1)}{2}

Input

Input is given from Standard Input in the following format:

N K

Output

If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.

If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):

M
u_1 v_1
:
u_M v_M

If there exist multiple graphs satisfying the conditions, any of them will be accepted.

Sample Input 1

5 3

Sample Output 1

5
4 3
1 2
3 1
4 5
2 3

This graph has three pairs of vertices such that the shortest distance between them is 2: (1,\ 4), (2,\ 4), and (3,\ 5). Thus, the condition is satisfied.

Sample Input 2

5 8

Sample Output 2

-1

There is no graph satisfying the conditions.


N = int(input())

V = 100005
to = [[] for _ in range(V * 2)]
visited = [False for _ in range(V * 2)]
cnt = []

def dfs(v):
  L = [v]
  while len(L) > 0:
    l = L.pop(0)
    if visited[l]:
      continue
    visited[l] = True
    cnt[l // V] += 1
    for u in to[l]:
      L.append(u)

for i in range(N):
  x, y = map(int, input().split())
  y += V
  to[x].append(y)
  to[y].append(x)

ans = 0
for i in range(V * 2):
  if visited[i]:
    continue
  cnt = [0, 0]
  dfs(i)
  ans += cnt[0] * cnt[1]
ans -= N
print(ans)

Score : 600 points

Problem Statement

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq 10^5

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Sample Input 1

3
1 1
5 1
5 5

Sample Output 1

1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

Sample Input 2

2
10 10
20 20

Sample Output 2

0

There are only two dots, so we cannot do the operation at all.

Sample Input 3

9
1 1
2 1
3 1
4 1
5 1
1 2
1 3
1 4
1 5

Sample Output 3

16

We can do the operation for all choices of the form a = 1, b = 1, c = i, d = j (2 \leq i,j \leq 5), and no more. Thus, the maximum number of operations is 16.


x,a=map(int,input().split())
if x<a:
  print(0)
else:
  print(10)

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


import math
import sys

#imgur.com/Pkt7iIf.png

#n, m = map(int, input().split())
#n = int(input())
#d = list(map(int, input().split()))

a, b = map(int, input().split())

print(0) if a < b else print(10)


n,x = map(int, input().split())
l = list(map(int, input().split()))

s = 1
d = 0
for i in range(n):
  d += l[i]
  s += 1
  if d > x:
    break
print(s)

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


N, X = map(int, input().split())
L = list(map(int, input().split()))
check = 0
count = 0
for l in L:
    if check == X:
        print(count+1)
        break
    elif check > X or count == N:
        print(count)
        break
    check = check + l
    count += 1


# -*- coding: utf-8 -*-
N, X = map(int, input().split())
L_list = list(map(int, input().split()))
btimes = 1
longs = 0
for idx, ite in enumerate(L_list):
    longs += ite
    if longs > X:
        break
    btimes += 1
print(btimes)


w,h,x,y = map(int, input().split())

side = (x == 0 or x == w or y == 0 or y == h \
    or y/x == h/w or y == -h/w * x + h \
    or x != w/2 or y != h/2) \
    and not (x == w/2 and y == h/2)
area = w * h

print(area/2, int(not side))

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


W, H, x, y = map(int, input().split())

if W-x < x:
    x = W-x
if H-y < y:
    y = H-y

if x*H > y*W:
    print(y*W, "0")
elif x*H < y*W:
    print(x*H, "0")
else:
    print(x*H, "1")


Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


from collections import deque
N = int(input())
A = deque(sorted(list(map(int, input().split()))))
MAX, MIN = A.pop(), A.popleft()

ans = []
while len(A):
    if A[0] < 0:
        x, y = MAX, A.popleft()
        ans.append([MAX, y])
        MAX = MAX - y
    else:
        x, y = MIN, A.popleft()
        ans.append([x, y])
        MIN = MIN - y

ans.append([MAX, MIN])
print(MAX - MIN)
for x, y in ans:
    print(x, y)

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


N=int(input())
w=list(map(int, input().split()))
S=sum(w)
A=0
ans=10**7
for i in range(N-1):
    A+=w[i]
    if abs(S-A)<=ans:
        ans=abs(S-2*A)

print(ans)

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


def main():
    H, W = map(int, input().split())
    S = [list(input()) for _ in range(H)]

    left = [[-1]*W for _ in range(H)]
    right = [[-1]*W for _ in range(H)]
    up = [[-1]*W for _ in range(H)]
    down = [[-1]*W for _ in range(H)]

    for i in range(H):
        for j in range(W):
            if j == 0:
                left[i][j] = 0
            else:
                left[i][j] = left[i][j-1] + 1

    for i in range(H):
        for j in range(W):
            if j == 0:
                right[-1-i][-1-j] = 0
            else:
                right[-1-i][-1-j] = right[-1-i][-1-(j-1)] + 1

    for i in range(H):
        for j in range(W):
            if i == 0:
                up[i][j] = 0
            else:
                up[i][j] = up[i-1][j] + 1

    for i in range(H):
        for j in range(W):
            if i == 0:
                down[-1-i][-1-j] = 0
            else:
                down[-1-i][-1-j] = down[-1-(i-1)][-1-j] + 1

    ans = 0
    temp = [0] * W
    for i in range(H):
        for j in range(W):
            temp[j] = left[i][j] + right[i][j] + down[i][j] + up[i][j] + 1
        ans = max(ans, max(temp))
    print(ans)

main()

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


import numpy as np
H,W = map(int,input().split())
S = [list(input()) for _ in range(H)]
L = np.zeros((H,W),dtype=np.int)
R = np.zeros((H,W),dtype=np.int)
U = np.zeros((H,W),dtype=np.int)
D = np.zeros((H,W),dtype=np.int)
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            L[i][j] = 0
        else:
            L[i][j] = L[i][j-1]+1
        if S[-i-1][-j-1] == "#":
            R[-i-1][-j-1] = 0
        else:
            R[-i-1][-j-1] = R[-i-1][-j]+1

for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            None
        else:
            U[i][j] = U[i-1][j]+1
        if S[-i-1][-j-1] == "#":
            None
        else:
            D[-i-1][-j-1] = D[-i][-j-1]+1
print(np.max(L+R+U+D)-3)


h, w = map(int, raw_input().split())
S = [raw_input() for i in range(h)]
L = [[0]*w for i in range(h)]
R = [[0]*w for i in range(h)]
U = [[0]*w for i in range(h)]
D = [[0]*w for i in range(h)]

for i in range(h):
    ps = 0
    s = S[i]
    for j in range(w):
        if s[j] == "#":
            ps = 0
        else:
            ps += 1
            L[i][j] = ps

for j in range(w):
    ps = 0
    for i in range(h):
        if S[i][j] == "#":
            ps = 0
        else:
            ps += 1
            U[i][j] = ps

for i in range(h-1, -1, -1):
    ps = 0
    for j in range(w-1, -1, -1):
        if S[i][j] == "#":
            ps = 0
        else:
            ps += 1
            R[i][j] = ps
for j in range(w-1, -1, -1):
    ps = 0
    for i in range(h-1, -1, -1):
        if S[i][j] == "#":
            ps = 0
        else:
            ps += 1
            D[i][j] = ps
maxLight = 0
for i in range(h):
    for j in range(w):
        maxLight = max(maxLight, L[i][j] + R[i][j] + U[i][j] + D[i][j] - 3)
print maxLight


n, a, b, c, d = map(int, input().split())
S = input()
if c < d:
    if "##" in S[a:d-3]:
        print("No")
    else:
        print("Yes")
else:
    f = S[b-2:].find("...")
    if f != -1 and f < (d-1) and f+1 < (c-1) and ("##" not in S[a:d-3]):
        print("Yes")
    else:
        print("No")

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


import sys
input = sys.stdin.readline  # NOQA

def main():
    N, A, B, C, D = map(int, input().split())
    A -= 1
    B -= 1
    C -= 1
    D -= 1
    S = input().rstrip()

    can_jump_R = True  # '##'
    can_jump_B = False  # '...'
    for i in range(A, N - 1):
        if S[i] == S[i+1] == "#":
            if A < i < C or B < i < D:
                can_jump_R = False
        if S[i-1] == S[i] == S[i+1] == ".":
            if B <= i < C:
                can_jump_B = True

    if C < D:
        if can_jump_R:
            ans = "Yes"
        else:
            ans = "No"
    else:
        if can_jump_R and can_jump_B:
            ans = "Yes"
        else:
            ans = "No"
    print(ans)

if __name__ == "__main__":
    main()


N, A, B, C, D = map(int, input().split())
S = input()
p = 0
t = 0
sti = 0
for i in range(A-1, max(C, D) - 1):
  if S[i:i+2] == '##':
    p = 1
for j in range(B-1, min(C, D) - 2):
  if S[j:j+3] == '...':
    if sti == 0:
      sti = j + 1
    t = 1
if S[B] == '.' and S[B-2] == '.':
  t = 1
if (C < D and p == 0) or (C > D and p == 0 and t == 1 and sti <= D-1):
  print('Yes')
else:
  print('No')


Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


a, p = list(map(int,input().split()))
print(int(((3 * a) + p)/2))

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


A, P = map(int, input().split())
print((3 * A + P) // 2)


a, p = map(int, input().split())
print((a * 3 + p) // 2)


A, P = map(int, input().split())
print(int((3*A + P)/2))


N = int(input())
r = []

for i in range(N):
    city, score = input().split()
    r.append((city, int(score), i+1))

r = sorted(r, key = lambda x:(x[0], -x[1]))
for city, score, num in r:
    print(num)

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


n,m = map(int,input().split())
s = [list(map(int,input().split())) for i in range(m)]
p = list(map(int,input().split()))
ans = 0
for i in range(2**n):
  bit = [i>>j & 1 for j in range(n)]
  for k,x in enumerate(s):
    if p[k] != sum([bit[y-1] for y in x[1:]])%2:
      break
  else:
    ans += 1
print(ans)

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


n,m=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
p=list(map(int,input().split()))

b=[]
for k in range(2**n):
  b.append(format(k,'0'+str(n)+'b'))

ans=0
for i in range(2**n):
  cton=0
  for j in range(m):
    ct=0
    for k in range(1,l[j][0]+1):
      if b[i][l[j][k]-1]=='1':ct+=1
    if ct%2==p[j]:cton+=1
  if cton==m:ans+=1
print(ans)


N, K = map(int, input().split())
V = list(map(int, input().split()))

s = 0
for i in range(min(N, K) + 1):
  # res = C + D
  res = K - i

  # i = A + B
  for j in range(i + 1):
    # j: B, k: A
    k = i - j

    # Jewel in hand
    Q = sorted(V[:j] + V[N - k:])

    # Number of negative jewels
    minus = sum([q < 0 for q in Q])

    # Drop some of negative, and sum up
    score = sum(Q[min(minus, res):])

    # Update score
    s = max(s, score)

print(s)

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


import bisect

N, Q = map(int, input().split(" "))
check_points = [list(map(int, input().split(" "))) for _ in range(N)]
querys = [int(input()) for _ in range(Q)]
time = {}
for q in querys:
    time[q] = -1

for s, f, x in check_points:
    start = s-x
    end = f-x
    left = bisect.bisect_left(querys, start)
    for q in querys[left:]:
        if q >= end:
            break
        if time[q] == -1 or time[q] > x:
            time[q] = x

for q in querys:
    print(time[q])

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

1 \leq N, Q \leq 2 \times 10^5

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


n,m = map(int,input().split())
l = []
r = []

for i in range(m):
    a,b = map(int,input().split())
    l.append(a)
    r.append(b)

if min(r) < max(l):
    print(min(r) - max(l) + 1)
else:
    print(0)

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


n, p = map(int, input().split())
if n<6: print(0)
elif 5<n<13: print(p//2)
else: print(p)


a,b = map(int,input().split())
if a < 6:
    b = 0
elif a < 13:
    b /= 2
print(b)


r, d, x = map(int, input().split())
for i in range(10):
  x = r*x-d
  print(x)

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


N, M = map(int, input().split())
L = 1
R = N

for n in range(M):
    l, r = map(int, input().split())
    L = max(l, L)
    R = min(r, R)

print(R - L + 1)

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


n, m = [int(i) for i in input().split()]
lfix = 0
rfix = n + 1
for i in range(m):
    l, r = [int(i) for i in input().split()]
    lfix = max(lfix, l)
    rfix = min(rfix, r)
print(max(rfix - lfix + 1, 0))


n, m = map(int, input().split())

A = list(map(int,  input().split()))

for i in range(m):
    a, b = map(int, input().split())
    for _ in range(a):
        A.append(b)

A = sorted(A)

print(sum(A[-n:]))

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


n,m = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
for _ in range(m):
  b,c = map(int,input().split())
  for i in range(b):
    if a[i] < c:
      a[i] = c
    else:
      break
  a.sort()

print(sum(a))


N, M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
BC = [tuple(int(i) for i in input().split()) for _ in range(M)]

A_ = sorted(A)
BC_ = sorted(BC, key=lambda x: x[1], reverse=True)

D_ = sum(([c] * b for b, c in BC_), [])

for i, (a, c) in enumerate(zip(A_, D_)):
    if a >= c:
        break
else:
    i += 1

print(sum(D_[:i]) + sum(A_[i:]))


N, M = map(int, input().split())
A = list(map(int, input().split()))
counter = {}
for a in A:
    if a in counter:
        counter[a] += 1
    else:
        counter[a] = 1
for _ in range(M):
    B, C = map(int, input().split())
    if C in counter:
        counter[C] += B
    else:
        counter[C] = B
sortedCounter = sorted(counter.items(), reverse=True)
sumResult = 0
for count in sortedCounter:
    if count[1] >= N:
        sumResult += count[0] * N
        break
    else:
        sumResult += count[0] * count[1]
        N -= count[1]
print(sumResult)


Score : 500 points

Problem Statement

We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.

If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:

\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)

Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.

We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.

Constraints

2 \leq N \times M \leq 2 \times 10^5

2 \leq K \leq N \times M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K

Output

Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.

Sample Input 1

2 2 2

Sample Output 1

8

There are six possible arrangements of the pieces, as follows:

((1,1),(1,2)), with the cost |1-1|+|1-2| = 1

((1,1),(2,1)), with the cost |1-2|+|1-1| = 1

((1,1),(2,2)), with the cost |1-2|+|1-2| = 2

((1,2),(2,1)), with the cost |1-2|+|2-1| = 2

((1,2),(2,2)), with the cost |1-2|+|2-2| = 1

((2,1),(2,2)), with the cost |2-2|+|1-2| = 1

The sum of these costs is 8.

Sample Input 2

4 5 4

Sample Output 2

87210

Sample Input 3

100 100 5000

Sample Output 3

817260251

Be sure to print the sum modulo 10^9+7.


BLACK = True
RED = False

class RBNode:
    def __init__(self, value):
        self.value = value
        self.color = RED
        self.duplication = 1
        self.left = None
        self.right = None

def upper_update(upper, child):
    if upper is not None:
        if child.value < upper.value:
            upper.left = child
        else:
            upper.right = child

def ll_rotate(upper, top, middle, bottom):
    # top.left == middle
    # middle.left == bottom

    top.left = middle.right

    upper_update(upper, middle)

    middle.right = top

    bottom.color = BLACK

    return middle

def lr_rotate(upper, top, middle, bottom):
    # top.left == middle
    # middle.right == bottom

    top.left = bottom.right

    middle.right = bottom.left

    bottom.right = top

    bottom.left = middle

    upper_update(upper, bottom)

    middle.color = BLACK

    return bottom

def rl_rotate(upper, top, middle, bottom):
    # top.right == middle
    # middle.left == bottom

    top.right = bottom.left

    middle.left = bottom.right

    bottom.left = top

    bottom.right = middle

    upper_update(upper, bottom)

    middle.color = BLACK

    return bottom

def rr_rotate(upper, top, middle, bottom):
    # top.right == middle
    # middle.right == bottom

    top.right = middle.left

    upper_update(upper, middle)

    middle.left = top

    bottom.color = BLACK

    return middle

class RBTree:
    def __init__(self, value):
        self.root = RBNode(value)
        self.root.color = BLACK
        self.size = 1

    def ordered(self, parent=None):
        if parent is None:
            parent = self.root
        if parent.left is not None:
            yield from self.ordered(parent.left)
        yield parent
        if parent.right is not None:
            yield from self.ordered(parent.right)

    def insert(self, value):
        self.size += 1

        # find
        node = self.root
        stack = [None]
        while True:
            stack.append(node)
            node_value = node.value
            if value == node_value:
                node.duplication += 1
                need_rotation = False
                break
            elif value < node_value:
                if node.left is None:
                    bottom = RBNode(value)
                    node.left = bottom
                    need_rotation = node.color == RED
                    stack.append(bottom)
                    break
                else:
                    node = node.left
                    continue
            else:
                if node.right is None:
                    bottom = RBNode(value)
                    node.right = bottom
                    need_rotation = node.color == RED
                    stack.append(bottom)
                    break
                else:
                    node = node.right
                    continue

        while need_rotation:
            bottom = stack.pop()
            middle = stack.pop()
            top = stack.pop()
            upper = stack[-1]
            if bottom.value < middle.value:
                # Xl
                if middle.value < top.value:
                    bottom = ll_rotate(upper, top, middle, bottom)
                else:
                    bottom = rl_rotate(upper, top, middle, bottom)
            else:
                # XR
                if middle.value < top.value:
                    bottom = lr_rotate(upper, top, middle, bottom)
                else:
                    bottom = rr_rotate(upper, top, middle, bottom)

            if upper is None:
                # root
                bottom.color = BLACK
                need_rotation = False
                self.root = bottom
                break
            else:
                if upper.color == BLACK:
                    need_rotation = False
                    break
                else:
                    stack.append(bottom)
                    continue

        return

    def find(self, value):
        node = self.root
        level = 0
        num_black = 1
        while node.value != value:
            level += 1
            if value < node.value:
                node = node.left
            else:
                node = node.right
            if node is None:
                return False, level, num_black
            if node.color == BLACK:
                num_black += 1
        return node, level, num_black

    def is_leaf(self, value):
        node, level, num_black = self.find(value)
        assert node is not None
        return node.left is None and node.right is None, level, num_black

Q = int(input())
queries = []
for _ in range(Q):
    query = list(map(int, input().split(" ")))
    if len(query) == 1:
        continue
    queries.append(query[1])

tree = RBTree(queries[0])
for q in queries[1:]:
  tree.insert(q)

print("4 2")
print("1 -3")

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

1 \leq Q \leq 2 \times 10^5

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


N, K = map(int, input().split())
S = list(input())
S[K - 1] = S[K - 1].lower()
print("".join(S))

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


N,K=map(int,input().split())
S=input()
S[K-1].lower()
print (S)


N, K = [ int(i) for i in input().split() ]
S = input()

print(S[:K-1] + S[K-1].lower() + S[K:])


N,K = map( int, input().split())
#a = [0 for in range(K)]
l = [0]
win = 0
if N>=K:
  win = N-K+1
  l[0] = N-K+1
now = K-1
cnt = 2
nN = N
while now>=1:
  nx = now // 2
  if N > now:
    a = now-nx
  elif now >= nN > nx:
    a = N - nx
  else:
    a = 0
  l.append(a)
  now = nx
  cnt *= 2
ll = len(l)
pp = 1
for i in range(ll):
  l[ll-i-1] *= pp
  pp *= 2
suml = sum(l)
print( suml/(pp/2))

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


N = int(input())
tree = [list() for _ in range(N)]
for _ in range(N-1):
    u, v, w = map(int, input().split())
    tree[u-1].append((v-1, w))
    tree[v-1].append((u-1, w))
stack = [0]
ans = [0] * N
searched = [False] * N
while stack:
    node = stack.pop()
    searched[node] = True
    for v, w in tree[node]:
        if searched[v]:
            continue
        if w % 2 != 0:
            ans[v] = ans[node] ^ 1
        else:
            ans[v] = ans[node]
        stack.append(v)
print(*ans, sep='\n')

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1


def main():
    import sys
    input=sys.stdin.readline
    n,m=map(int,input().split())
    G=[[] for _ in range(n)]
    for _ in range(m):
        x,y,z=map(int,input().split())
        x-=1
        y-=1
        G[x].append(y)
        G[y].append(x)

    visited=[True]*n
    def dfs(i):
        for e in G[i]:
            if visited[e]:
                visited[e]=False
                dfs(e)

    cnt=0
    for i in range(n):
        if visited[i]:
            cnt+=1
            dfs(i)

    print(cnt)

if __name__=='__main__':
    main()

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

6 5
1 2 1
2 3 2
1 3 3
4 5 4
5 6 5

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


n = int(input())
S = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
ba = 0
for i in range(n):
    cnt += S[i].count("AB")
    if S[i].startswith("B") and S[i].endswith("A"):
        ba += 1
    elif S[i].startswith("B"):
        b += 1
    elif S[i].endswith("A"):
        a += 1
if ba >= 1:
    cnt += ba - 1
    if a >= 1:
        cnt += 1
        a -= 1
    if b >= 1:
        cnt += 1
        b -= 1
    cnt += min(a, b)
elif a >= 1 and b >= 1:
    cnt += min(a, b)
print(cnt)

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


# -*- coding: utf-8 -*-

def main():
    n = int(input())
    s = [input() for _ in range(n)]
    ans = 0
    back_a_count = 0
    front_b_count = 0
    front_b_back_a_count = 0

    for si in s:
        if si[0] == 'B' and si[-1] == 'A':
            front_b_back_a_count += 1
        elif si[0] == 'B':
            front_b_count += 1
        elif si[-1] == 'A':
            back_a_count += 1

        if len(si) >= 3:
            for j in range(len(si) - 1):
                if (si[j] == 'A' and si[j + 1] == 'B'):
                    ans += 1

    if back_a_count >= front_b_count:
        ans += front_b_count
        back_a_count -= front_b_count
        front_b_count = 0
    else:
        ans += back_a_count
        front_b_count -= back_a_count
        back_a_count = 0

    ans += front_b_back_a_count // 2
    front_b_back_a_count %= 2

    if front_b_back_a_count == 1:
        if back_a_count >= 1:
            ans += 1
            back_a_count -= 1
        elif front_b_count >= 1:
            ans += 1
            front_b_count -= 1

    if back_a_count >= 1:
        ans += 1
    elif front_b_count >= 1:
        ans += 1

    print(ans)

if __name__ == '__main__':
    main()


Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


a, b, t = map(int,input().split())

print((t//a)*b)


A, B, T = map(int,input().split())
T += 0.5
print(int(T//A*B))


import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline

n = int(input())
v = list(map(int, input().split()))
c = list(map(int, input().split()))

ans = 0
for bit in range(2**n):
    vsum = 0
    csum = 0
    for i in range(n):
        if (bit & (1 << i)):
            vsum += v[i]
            csum += c[i]
    ans = max(vsum - csum, ans)

print(ans)

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


n = int(input())
v = input().split()
c = input().split()

vc = []
for i in range(n):
  vc.append(int(v[i]) - int(c[i]))

answer = 0
for i in vc:
  if i > 0:
    answer += i

print(answer)


N = int(input())
A = list(map(int,input().split()))
neg_num = 0
max_neg = -float('inf')
sum_abs_A = 0
for a in A:
  sum_abs_A += abs(a)
  if a < 0 :
    neg_num += 0
    max_neg = max(a,max_neg)
print(sum_abs_A if neg_num%2==0 else sum_abs_A + 2*max_neg)

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.


import numpy as np
N = int(input())
a = np.array(list(map(int, input().split())))

tmp = sum(np.abs(a))
if np.count_nonzero(a < 0)%2 == 0:
    print(tmp)
else:
    ind = np.argmin(np.abs(a))
    print(tmp-abs(a[ind])*2)


N = int(input().strip())
A= [int(x) for x in input().strip().split(" ")]

minus_list = filter(lambda x: x<0,A)
minus_cnt = len(list(minus_list))

abs_list = list(map(abs,A))

if minus_cnt % 2 == 0:
    print(sum(abs_list))
else:
    print(sum(abs_list) - 2* min(abs_list))


N = int(input())
A = list(map(int, input().split(" ")))
abs_list = list(map(abs, A))
abs_list.sort()
pos = list(filter(lambda x: x > 0, A))
neg = list(filter(lambda x: x < 0, A))
pos.sort()
neg.sort()

# A has 0
if abs_list[0] == 0:
	print(sum(abs_list))
elif len(neg) % 2 == 0:
	print(sum(abs_list))
elif len(pos) > 0 and abs(pos[0]) < abs(neg[-1]):
	print(sum(abs_list) - 2*pos[0])
else:
	print(sum(abs_list[1:])-abs_list[0])


n = int(input())
#n = 10 ** 5
stones = [0 if x == "." else 1 for x in list(input())]
#stones = [0] + [0 for _ in range(n)] + [1]

bf = 0
af = n - sum(stones)
min_num = bf + af

for i in range(n):
	bf += stones[i]
	af -= 1 - stones[i]
	min_num = min(min_num, bf + af)

print(min_num)

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

1 \leq N \leq 2\times 10^5

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


a, b, c = map(int, input().split())

if a < c < b:
    print('Yes')
else:
    print('No')

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


import sys
import math
N = list(map(int, input().split()))

t = False
if (N[0] < N[1]) == (N[0] < N[2]):
    if abs(N[1] - N[0]) > abs(N[2] - N[0]):
        t = True

print("Yes" if t else "No")


n=int(input())
s=input()
k=int(input())
d=s[k-1]
for a in s:
  if a!=d:
    a='*'
print(s)

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


N = int(input())
S = list(input())

count_list =[]
wc = 0

A=[0]*(N+1)

for i in list(range(N))[::-1]:
    if(S[i] == '#'):
        A[i] = A[i+1] + 1

print(A)
for n in range(N-1):
    if(S[n] == '.'):
        num = n
        count_list.append(A[n+1] + wc)
        wc += 1

if(S[N-1] == '.'):
    count_list.append(wc+1)

count = min(count_list)
print(count)


N=int(input())
S=str(input())

def count_renzoku(S,s):
    renzoku=1
    for i in range(1,len(S)):
        if S[i]==s:
            renzoku+=1
        else:
            break
    return renzoku

if S.count('#')==N or S.count('.')==N:
    print(0)
else:
    a=min(S.count('#'),S.count('.'))
    T=S[::-1]
    if T[0]=='#':
        T=T[count_renzoku(T,'#'):]
        U=T[::-1]
        if U[0]=='.':
            U=U[count_renzoku(U,'.'):]
        b=min(U.count('#'),U.count('.'))
        print(min(a,b))
    elif S[0]=='.':
        S=S[count_renzoku(S,'.'):]
        b=min(S.count('#'),S.count('.'))
        print(min(a,b))
    else:
        print(a)


#!/usr/bin/python
# coding: UTF-8

def exe(n,s,count):
    #print(s)
    for i in range(1,n):
        if s[i-1] == "#" and s[i] == ".":
            return exe(n-2,s[0:i-1]+s[i+1:],count+1)
    return count
N = int(input())
S = input()

print(exe(N,S,0))


N = int(input())
S = input()
blackcnt = 0
whitecnt = 0
whiteflag = False

for i in range(N):
    if S[i] == '#':
        whiteflag = True
        blackcnt += 1
    elif whiteflag and S[i] == '.':
        whitecnt += 1

print(min(blackcnt, whitecnt) if whiteflag else 0)


a = sorted(list(map(int, input().split())))

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


numbers = [int(i) for i in input().split()]

num1 = numbers[0]
num2 = numbers[1]

sum = 0
for i in range (2):

    if num1 >=num2:
        sum += num1
        num1 = num1 -1
    else:
        sum += num2
        num2 = num2-1

print (sum)


a,b = map(int, input().split())

if a == b:
    out = 2*a
else:
    out = max(a, b) * 2 - 1

print(out)


N=int(input())
H=[int(i) for i in input().split()]
result=0
hmax=H[0]
for i in range(N):
    hmax=max(hmax,H[i])
    if H[i]>=hmax:
        result+=1
print(result)

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


N, K = map(int, input().split())
s = "1"+input().strip()+"1"
i = 0
dp = []
while i < len(s):
    l = i
    while i < len(s) and s[i] == '1':
        i += 1
    if l < i:
        dp.append([l, i-1])
    while i < len(s) and s[i] == '0':
        i += 1

if len(dp) <= K:
    print(N)
else:
    ans = 0
    for i in range(0, len(dp)-K):
        t = dp[i+K][1]-dp[i][0]
        if t > ans:
            ans = t
    print(ans)

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


a = [int(input()) for _ in range(5)]
k = int(input())
if(a[4]-a[0]>k):
    print(':(')
else:
    print('Yay!')

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


t = [int(input()) for i in range(6)]
print ("Yay!" if t[4]-t[0] <= t[5] else ":(")


dishes = [int(input()) for i in range(5)]

d = [abs(d % 10 -10) for d in dishes if d % 10 != 0] # select nums which can be divided by 10
d.remove(max(d))
print(sum(dishes) + sum(d))

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


n = int(input())
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
input_list = [a,b,c,d,e]
input_list.sort()
print(n // input_list[0] +5)