import heapq
from collections import defaultdict
import sys
import bisect
input = sys.stdin.readline

n = int(input())
#####単位元######
ide_ele = -1
#ide_ele = 10**9+1

#num:n以上の最小の2のべき乗
num =2**(n-1).bit_length())
seg=[ide_ele]*(2*num)

def init(init_val):
    #set_val
    for i in range(n):
        seg[i+num-1]=init_val[i]
    #built
    for i in range(num-2,-1,-1) :
        seg[i]=max(seg[2*i+1],seg[2*i+2])

def update(k,x):
    k += num-1
    seg[k] = x
    while k+1:
        k = (k-1)//2
        seg[k] = max(seg[k*2+1],seg[k*2+2])

def query(p,q):
    if q<=p:
        return ide_ele
    p += num-1
    q += num-2
    res=ide_ele
    while q-p>1:
        if p&1 == 0:
            res = max(res,seg[p])
        if q&1 == 1:
            res = max(res,seg[q])
            q -= 1
        p = p//2
        q = (q-1)//2
    if p == q:
        res = max(res,seg[p])
    else:
        res = max(max(res,seg[p]),seg[q])
    return res

def main():
    used = defaultdict(int)
    aa = [int(input()) for i in range(n)]
    b = sorted(aa)
    for i in range(n):
        aa[i] = bisect.bisect_left(b,aa[i])

    a0 = aa[0]
    tank = [a0]
    used[a0] = 1
    update(a0,a0)

    for i in range(1,n):
        a = aa[i]
        while True:
            if used[tank[0]] > 0:
                break
            else:
                heapq.heappop(tank)
        #塗り替え
        if tank[0] < a:
            ma = query(0,a+1)

            used[ma] -= 1
            heapq.heappush(tank,a)
            used[a] += 1
            if used[ma] == 0:
                update(ma,-1)
        else:
            heapq.heappush(tank,a)
            used[a] += 1
        update(a,a)

    res = 0
    for e in tank:
        if used[e] > 0:
            res += 1
    print(res)

if __name__ == '__main__':
    main()


def li():
    return list(map(int, input().split()))

if __name__ == "__main__":
    n = int(input())
    a_list = [int(input()) for _ in range(n)]

    color_list = []

    for a in a_list:
        # 既存の色でぬれるかチェック
        can_draw = False
        # 増分が一番小さいものを選ぶ
        best_diff = 10 ** 9 + 1
        best_index = -1
        for index, color in enumerate(color_list):
            if color < a:
                can_draw = True
                diff = a - color
                if diff < best_diff:
                    best_diff = diff
                    best_index = index
        if can_draw:
            color_list[best_index] = a
        else:
            color_list.append(a)
        # print(color_list)
    # print()
    # print(color_list)
    print(len(color_list))

# a1から順番に塗っていく
# 色ごとに、今まで塗った最大値を記録する
# 既存の色でぬれる場合は、なるべく最大値の増分が少なくなるように色を選ぶ
# 既存の色でぬれない場合は新しい色を作って最大値を記録する

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.


# -*- coding:utf-8 -*-
# /usr/bin/python3

from collections import defaultdict

def main():
  n, score = map(int, input().strip().split(' '))
  dp = defaultdict(int)
  dp[(0,0,0)] = 1
  for i in range(n):
    for j in range(0, i+1):
      for k in range(0, score+1):
        dp[(i, j, k)] %= (10**9+7)
        dp[(i+1, j+1, k+(j+1))] += dp[(i, j, k)]
        dp[(i+1, j, k+j)] += dp[(i, j ,k)] * (j*2 + 1)
        if j-1 >= 0:
          dp[(i+1, j-1, k+(j-1))] += dp[(i, j, k)] * (j**2)
  if score % 2 == 1:
    print(0)
  else:
    print(dp[(n, 0, score//2)] % (10**9+7))

  pass

if __name__=='__main__':
  main()

Score : 600 points

Problem Statement

Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.

Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Constraints

All values in input are integers.

1 \leq n \leq 50

0 \leq k \leq n^2

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Sample Input 1

3 2

Sample Output 1

2

There are six permutations of {1,\ 2,\ 3}. Among them, two have oddness of 2: {2,\ 1,\ 3} and {1,\ 3,\ 2}.

Sample Input 2

39 14

Sample Output 2

74764168


import math

N = int(input())

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

def xor(x1,x2):
    xdigit = math.ceil(math.log2(max(x1, x2)))
    num = 0
    for i in range(xdigit):
        dig_x1 = x1 // (2**(xdigit-i))
        dig_x2 = x2 // (2**(xdigit-i))

        if dig_x1 != dig_x2:
            num += 2**(xdigit-i)

        if dig_x1 == 1:
            x1 -= 2**(xdigit-i)

        if dig_x2 == 1:
            x2 -= 2**(xdigit-i)
    return num

is_exist = True

for camel in range(1, N-1):
    prev = camel - 1
    furt = camel + 1

    if camel == N-1:
        furt = 0
    if camel == 0:
        prev = N-1

    num_xor = xor(nums[prev], nums[furt])
    if num_xor != nums[camel]:
        is_exist = False
        break

if is_exist == True:
    print("Yes")
else:
    print("No")

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.


from math import log2, floor
from operator import or_
from functools import reduce

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

bl = [0 for _ in range(floor(log2(max(a)))+1)]
for ai in a :
    aj = ai
    for i in range(floor(log2(ai))+1) :
        if aj & 1 == 1 :
            bl[i] += 1
        aj >>= 1

ans = reduce(or_, map(lambda x : x&1, bl))
if ans :
    print("No")
else :
    print("Yes")


import os
import sys
from collections import defaultdict, Counter
from itertools import product, permutations,combinations, accumulate
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from math import ceil, floor, sqrt
from copy import deepcopy

def main():
    n,d = map(int, input().split())
    list_num = []
    for i in range(n):
        list_x = list(map(int, input().split()))
        list_num.append(list_x)

    count = 0
    for i in range(n):
        for j in range(n):
            if i < j:
                ans = 0
                result_num = 0
                for l in range(d):
                    result_num += pow(abs(list_num[i][l] - list_num[j][l]),2)
                ans = sqrt(result_num)

                if ans.is_integer():
                    count += 1
    print(count)

if __name__ == "__main__":
    main()

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


import math
n,d = list(map(int, input().split()))
x = [list(map(int, input().split())) for N in range(n)]

kaijou = 0
cnt = 0

for i in n:
  for j in n:
    for k in d:
      kaijou = kaijou + (x[j][k]-x[i][k])**2
    if math.sqrt(kaioju).is_integer():
      cnt += 1

print(cnt-n)


import math

n,d = map(int,input().split())
x = [[0]*d for _ in range(n)]

for i in range(n):
    x[i] = list( map( int, input().split() ) )

count = 0
for i in range(n):
    for j in range(n):
        if i <= j:
            continue
        dist = 0
        for k in range(d):
            dist += (x[i][k] - x[j][k])**2
        dist = math.sqrt(dist)
        if dist % 1 == 0:
            count += 1

print(count)


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

alpha = (sum(A[:len(A):2])-sum(A[1:len(A)-1:2]))

ans = [alpha]

for i in range(N-1):
    ans.append(2*A[i]-ans[i])

for j in range(N):
    print(ans[j], end = ' ')

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


import numpy as np
n = int(input())
A = [int(i) * 2 for i in input().split()]

L1 = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
    if i + 1 <= n-1:
        L1[i][i] = 1
        L1[i][i+1] = 1
    else:
        L1[i][i] = 1
        L1[i][0] = 1

L1 = np.linalg.inv(L1)
L2 = np.array(A)
ans = list(np.dot(L1, L2))
print(" ".join([str(int(n)) for n in ans]))


S = input()
dic = {}

for  i in range(4):
    if S[i] in dic:
        dic[S[i]] += 1
    else:
        dic[S[i]] = 1

if len(dic) == 2 :
    for i in dic :
        if dic[i] != 2:
            print("No")
            break
    else:
        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())
s.sort()

if s[0]==s[1] and s[2]==s[3] and s[0]!=s[2]:
    print("Yes")
else:
    print("No")


s=input()
ans="Yes"
for i in range(len(s)):
    if s.count(s[i])!=2:
            ans="No"

print(ans)


num = int(input())
# 各行を入力しリストに格納
array = list(map(int, input().split()))
count = 0
for i in range (1,num-1,1):
  if array[i-1] < array[i] and array[i] <array[i+1] or array[i+1] < array[i] and array[i] <array[i-1]:
    count +=1
print(count)

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())
d=list(map(int, input().split()))

import heapq

heapq.heapify(d)

for i in range(n//2-1):
	heapq.heappop(d)

a=heapq.heappop(d)
b=heapq.heappop(d)

print(b-a)

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


n = int(input())
d = sorted(list(map(int, input().split())),reverse=True)
m = n//2

print(-d[m]+d[m-1])


N, K = map(int, input().split())
dp = [[0] * (N + 1) for _ in range(N + 1)]
#dp[i][j]...コンビネーションiCj
mod = 10 ** 9 + 7

for i in range(N + 1):
	for j in range(N + 1):
		if j == 0:
			dp[i][j] = 1
		elif i > 0:
			dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % mod

for i in range(K):
	print((dp[K - 1][i] * dp[N - K + 1][i + 1]) % mod)

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.


from collections import deque
N,M=[int(s) for s in input().split()]
edge = [set() for _ in range(3*N)]
for i in range(M):
  x,y=[int(s) for s in input().split()]
  edge[x-1].add(y-1+N)    #有向グラフなので片方でよい
  edge[x-1+N].add(y-1+2*N)
  edge[x-1+2*N].add(y-1)
S,T=[int(s) for s in input().split()]

#print(edge)

n=0
def dfs(start,goal):
  reach=deque([start])
  distance=[-1 for _ in range(N*3)]
  distance[n]=0
  while reach:
    _from=reach.popleft()
    for _to in edge[_from]:
      if not(_to in reach) and distance[_to]==-1:
        reach.append(_to)
        distance[_to]=distance[_from]+1
  return(distance[goal])

ans=dfs(S-1,T-1)
if ans==-1:
  print(-1)
else:
  print(ans//3)

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

4 4
1 2
2 3
3 4
4 1
1 3

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


import sys
import time
time0=time.time()
input = sys.stdin.readline

N,M=map(int,input().split())
E=[list(map(int,input().split())) for i in range(M)]
S,G=map(int,input().split())

ELIST=[set() for i in range(N+1)]

for x,y in E:
    ELIST[x].add(y)

check=[10**8]*(N+1)
check[S]=0

def three_step_from(S,i):

    ONE=set()

    for s in S:

        ONE=ONE|ELIST[s]

    TWO=set()
    for one in ONE:

        TWO=TWO|ELIST[one]

    THREE=set()
    for two in TWO:
        THREE=THREE|ELIST[two]

    RET=set()

    for three in THREE:
        if check[three]!=10**8:
            continue
        check[three]=i
        RET.add(three)

    return RET

i=1
NOW={S}
while NOW:
    NOW=three_step_from(NOW,i)
    i+=1

    if check[G]!=10**8:
        print(check[G])
        sys.exit()

    if time.time()-time0>1.8:
        print(-1)
        sys.exit()

else:
    print(-1)


if len(list(set(list(input())))) == 4:
  print("Good")
else:
  print("Bad")

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


list = [int(x)for x in input()]
for i in range(3):
  if list[i] == list[i+1]:
    count =1
  else:
    count =0
if count ==0:
  print('Good')
else:
  print('Bad')


s = input()
if s[0] == s[1] or s[1] == s[2] or s[2] == s[3]:
    print("Bad")
else:
    print("Good")


S = input()

for i in range(len(S)-1):
    if S[i] == S[i+1]:
        print('Bad')
        break
    elif i == len(S)-2:
        print('Good')


import sys
readline = sys.stdin.readline
import fractions

def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def main():
    A, B, C, D = map(int, readline().rstrip().split())
    CD = lcm_base(C, D)
    ans = B - (B//C + B//D - B//CD)
    ans -= ((A-1) - ((A-1)//C + (A-1)//D - (A-1)//CD))
    print(ans)

if __name__ == '__main__':
    main()

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


import fractions

A, B, C, D = map(int, input().split())
G = (C * D) // fractions.gcd(C, D)
print(B - A + 1- (B // C - (A - 1) // C) - (B // D - (A - 1) // D) + (B // G - (A - 1) // G))


import sys
inputs = sys.stdin.readlines()

n = int(inputs[0])
AB = []
for s in inputs[1:]:
    a, b = map(int, s.split())
    AB.append((a, b))
AB.sort(key=lambda x: x[1])
s = 0
for a, b in AB:
    s += a
    if s > b:
        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


n = int(input())
l = []
s = 0
for i in range(n):
  a, b = map(int, input().split())
  s += a
  l.append((a, b))

l = sorted(l, key=lambda x: x[1])
for i in range(n):
  if s > l[-1][1]:
    print("No")
    exit()
  else:
    a = l.pop()[0]
    s -= a
print("Yes")


def main():
  values = [list(map(int, input().split())) for _ in range(int(input()))]
  values.sort(key=lambda x: x[1])
  cost = 0

  for c, d in values:
    cost += c

    if d < cost:
      print('No')
      return

  print('Yes')

if __name__ == '__main__':
  main()


from itertools import combinations

n, k = map(int, input().split())
star = []
max_k = (n - 1) * (n - 2) // 2
delta = max_k - k
cnt = 0
if k <= max_k:
    ans = []
    for i in range(2, n + 1):
        star.append((1, i))
        cnt += 1

    if delta > 0:
        kumiawase = list(combinations(range(2, n+1), 2))
        for j in range(delta):
            kumi = kumiawase[j]
            star.append(kumi)
            cnt += 1
    print(cnt)
    for pair in star:
        print(*pair, sep=" ")
else:
    print(-1)

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, k = map(int, input().split())

def main():
    max = (n-1)*(n-2)//2
    if max < k:
        print(-1)
        return 0
    add = max - k
    m = n-1 + add
    print(m)
    for i in range(2,n+1):
        print(1, i)
    for i in range(2, n+1):
        for j in range(i+1, n+1):
            if add <= 0:
                return 0
            print(i, j)
            add -= 1

main()


import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    x,a=map(int,input().split())
    if(x<a):
        print(0)
    else:
        print(10)
resolve()

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.


X , A = map(int,input().split())
if A > X:
  print("0")
else:
  print("10")


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

def main():
    N, X = map(int, input().split())
    L = list(map(int, input().split()))
    L.insert(0, -1)

    D = 0
    count = 1
    for i in range(2, N+2):
        D = D + L[i-1]
        if D > X:
            print(count)
            break
        else:
            count += 1

if __name__ == "__main__":
    main()

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.


w,h,x,y=map(int,input().split())
ans=[w*h/2]
if y*w==x*h or y*h==x*w:
    ans.append(1)
else:ans.append(0)
print(*ans)

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())
ans = []
ans.append(w * h / 2)
if w / 2 == x and h / 2 == y:
    ans.append(1)
else:
    ans.append(0)
print(" ".join(map(str, ans)))


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

if x==w/2 and y==h/2:
    print(1/2*w*h,1)
else:
    print(1/2*w*h,0)


import numpy as np
import sys
input = sys.stdin.readline

MOD = 10**9 + 7
N,M = map(int,input().split())
S = np.array(input().split(), dtype=np.int32)
T = np.array(input().split(), dtype=np.int32)

# (n,m) 以前で作れている列
dp = np.zeros((N+1, M+1), dtype = np.int64)
dp[0] = 1

for n in range(1, N+1):
  same = (T == S[n-1])
  dp[n,1:][same] = dp[n-1,:-1][same] # ちょうど(n,m)で終わる
  dp[n] = (dp[n].cumsum() + dp[n-1]) % MOD # cumsumに直す

answer = dp[N,M]
print(answer)

Score : 500 points

Problem Statement

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

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


def main():
    n=int(input())
    xy = sorted([list(map(int, input().split())) for _ in range(n)])
    xy.sort()
    ans=n
    for i in range(n):
        [x1,y1]=xy[i]
        for j in range(n-1):
            [x2,y2]=xy[j]
            if i!=j:
                [p,q]=[x1-x2,y1-y2]
                cnt=0
                for k in range(n-1):
                    for l in range(k+1,n):
                        [x,y]=[ xy[k][0]-xy[l][0],xy[k][1]-xy[l][1] ]
                        if [x,y]==[p,q] or [x,y]==[-p,-q]:
                            cnt+=1
                ans=min(ans,n-cnt)
    print(ans)

if __name__ == "__main__":
    main()

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

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 minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


N = int(input())
XY = [[int(x) for x in input().split()] for _ in range(N)]

def gcd(a,b):
    a = abs(a)
    b = abs(b)
    while b:
        a,b = b,a%b
    return a

def make_PQ(a,b):
    if a>0:
        return(a//gcd(a,b),b//gcd(a,b))
    elif a<0:
        return(-1*a//gcd(a,b),-1*b//gcd(a,b))
    else:
        print("error")

if N <= 2:
    print(1)
else:
    PQ_list = []
    for i in range(1,N):
        for j in range(i):
            p = XY[j][0] - XY[i][0]
            q = XY[j][1] - XY[i][1]

            if p != 0:
                tmp_p,tmp_q = make_PQ(p,q)
                if not [tmp_p,tmp_q] in PQ_list:
                    PQ_list.append([tmp_p,tmp_q])
    tmp_set = set()
    for x,y in XY:
        tmp_set.add(x)
    ans = len(tmp_set)

    for p,q in PQ_list:
        XY_list = []
        for x1,y1 in XY:
            if XY_list == []:
                XY_list.append([x1,y1])
            else:
                for x2,y2 in XY_list:
                    if x2-x1 == 0:
                        break
                    else:
                        tmp_x,tmp_y = make_PQ(x2-x1,y2-y1)
                        if [tmp_x,tmp_y] == [p,q]:
                            break
                else:
                    XY_list.append([x1,y1])
        ans = min(ans,len(XY_list))

    print(ans)


N = int(input())
A = list(map(int,input().split()))
ans = []
A.sort()
a = A.pop(0)
b = A.pop()
N -= 2
k = 1
for i in range(N):
    y = A.pop()
    if y<0:k=0
    if k:
        ans.append([a,y])
        a -= y
    else:
        ans.append([b,y])
        b -= y
ans.append([b,a])
print(b-a)
for a in ans: print(*a)

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


input_line = input()
P,Q,R = [int(s) for s in input_line.split(' ') if s]
distances = [P+Q,Q+R,R+P]
print(min(distances))

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()))

half=sum(W)//2
left=0
count=0
for i in range(N):
  if left>=half:
    break
  else:
    left+= W[i]
    count+=1
if count>=2:
  left1=W[:count-1]
  right1=W[count-1:]
  ans1=sum(right1)-sum(left1)
  left2=W[:count]
  right2=W[count:]
  ans2=sum(left2)-sum(right2)
  print(min(ans1,ans2))
else:
  left=W[:1]
  right=w[1:]
  print(sum(left)-sum(right))

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


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

from itertools import product

def mat2_mul(X, Y):
    Z = [ [0, 0],
          [0, 0] ]
    for (i,j,k) in product(range(2),range(2),range(2)):
        Z[i][j] += X[i][k] * Y[k][j]
    return Z

def mat2_pow(X, n):
    if n == 0:
        return [ [1, 0],
                 [0, 1] ]
    elif n % 2:
        return mat2_mul(X, mat2_pow(X, n-1))
    else:
        half_pow = mat2_pow(X, n/2)
        return mat2_mul(half_pow, half_pow)

def fb(n):
    if n == 0:
        return 0
    else:
        F = [ [0, 1],
              [1, 1] ]
        return mat2_pow(F, n-1)[1][1]
l=[]
for _ in range(m):
  l.append(int(input()))
ans=fb(l[0])
#print(ans)
for i in range(m-1):
  if l[i]+1==l[i+1]:
    print(0)
    exit()
  elif l[i+1]-l[i]>2:
    ans=ans*(fb(l[i+1]-l[i]-1))
print(ans*fb(n-l[m-1])%1000000007)

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.


n,m = map(int,input().split())
flag = [0]*(n+1)
for i in range(m):
  a = int(input())
  flag[a] = 1
num = 10**9+7
count = [0]*(n+1)
count[0] = 1
count[1] = 1 if 1 not in a else 0
for i in range(2,n+1):
  if flag[i]==0: count[i] = count[i-1] + count[i-2]
  count[i] = count[i]%num
print(count[n])


n,m=map(int,input().split())
a=[int(input()) for i in range(m)]
a=set(a)
MOD=1000000007

dp=[0]*(n+1)
for i in range(1,n+1):
  if i in a:
    dp[i]=0
  else:
    if i==1:
      dp[i]=1
    elif i==2:
      dp[i]=dp[1]+1
    else:
      dp[i]=dp[i-1]+dp[i-2]
print(dp[n]%MOD)


n, m = map(int, input().split())
dp = [0] * (n + 1)
a = []
for i in range(m):
    aa = int(input())
    dp[aa] = -1
    a.append(aa)
for i in range(m - 1):
    if a[i] + 1 == a[i + 1]:
        print(0)
        exit()
mod = 10 ** 9 + 7

dp[0] = 1
if 1 in a:
    dp[1] = 0
else:
    dp[0] = 1
for i in range(1, n):
    if dp[i + 1] == -1:
        dp[i + 1] = 0
    else:
        dp[i + 1] = (dp[i] + dp[i - 1]) % mod
print(dp[n] % mod)


def mulmod(x,y,p):
    return x*y % p

def test(n):
    if n<1:
        return 1
    memo = [0]*(n+1)
    memo[0] = 1
    memo[1] = 1
    for i in range(2,n+1):
        memo[i] = (memo[i-1] + memo[i-2])%1000000007
    return memo[n]

n,m = map(int,input().split())
a =[]
pos = 0
result = 1
last = -1
for i in range(m):
    x = int(input())
    if (last+1) == x:
        print(0)
        exit(0)
    last = x
    a.append(x)

for i in a:
    result = mulmod(test(i-pos-1),result,1000000007)
    pos = i+1

result = mulmod(test(n-pos),result,1000000007)
print(result)


# coding: utf-8
# Your code here!
n,m=map(int,input().split())
key=0
flag=False
a=[int(input()) for i in range(m)]
for i in range(m-1):#answer 0
    if a[i+1]-a[i]==1:
        flag=True

def fb(num):
    """num番目のフィボナッチ数を返す
    """
    a, b = 1, 0
    for _ in range(num+1):
        a, b = a + b, a
    return b

if m!=0:
    key=fb(a[0]-1)

if key==0: key=1

for i in range(m-1):
    key*=fb(a[i+1]-a[i]-2)

if m!=0:
    key*=fb(n-a[len(a)-1]-1)

if m!=0 and flag!=True:
    print(key%1000000007)
elif flag==True:
    print(0)
else: print(fb(n-1))


#初期入力
map1 =[]
H,W = (int(x) for x in input().split())
for i in range(H):
    *s, = input()
    map1.append(s)

#上下左右、ライトが届く距離を配列
u =[[0]*W for _ in range(H)]
d =[[0]*W for _ in range(H)]
r =[[0]*W for _ in range(H)]
l =[[0]*W for _ in range(H)]
ans =[[0]*W for _ in range(H)]

#各方向別にそれぞれの位置でのライトの届く距離
for h in range(H):
    for w in range(W):
        if map1[h][w] ==".":
            if w ==0:
                l[h][w] =1
            else:
                l[h][w] =l[h][w-1] +1
for h in range(H):
    for w in range(W-1,-1,-1):
        if map1[h][w] ==".":
            if w ==W-1:
                r[h][w] =1
            else:
                r[h][w] =r[h][w+1] +1
for w in range(W):
    for h in range(H):
        if map1[h][w] ==".":
            if h ==0:
                u[h][w] =1
            else:
                u[h][w] =u[h-1][w] +1
for w in range(W-1):
    for h in range(H-1,-1,-1):
        if map1[h][w] ==".":
            if h ==H-1:
                d[h][w] =1
            else:
                d[h][w] =d[h+1][w] +1

#それぞれの位置で、各方向を足す。（自分の位置は4方向分足しているからー３）
for h in range(H):
    for w in range(W):
        ans[h][w] =l[h][w] +r[h][w] +u[h][w] +d[h][w] -3
print(max(max(i) for i in ans))

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 sys

def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    n, a, b, c, d = list(map(int, readline().split()))
    s = str(readline().rstrip().decode('utf-8'))
    wrc = 0
    brc = 0
    wc = 0
    bc = 0
    for i in range(n):
        if s[i] == "#":
            bc += 1
            wc = 0
        else:
            bc = 0
            wc += 1
        wrc = max(wrc, wc)
        brc = max(brc, bc)
    if c < d:
        if brc < 2:
            print("Yes")
        else:
            print("No")
    else:
        if brc < 2 and wrc >= 3:
            print("Yes")
        else:
            print("No")

if __name__ == '__main__':
    solve()

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 re

count = 0

def count_inversion(sequence):
    return sum(sum(m>n for m in sequence[i+1:]) for i,n in enumerate(sequence))

s = input()
s = s.replace("BC", "D")
s = re.split(r"[B-C]+", s)

while "" in s:
    s.remove("")
for x in s:
    count += count_inversion(list(x))

print(count)


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


n = int(input())
a = [0]*(n-1)
b = [0]*(n-1)
for i in range(n-1):
    a[i], b[i] = list(map(int, input().split()))
c = list(map(int, input().split()))
c.sort()
x = a
x.extend(b)
y = []
for i in range(n):
    y.append([i,x.count(i+1)])

y.sort(key=lambda x:x[1])

s = 0
z = [0]*n
for i in range(n):
    z[y[i][0]] = c[i]

for i in range(n-1):
    s = s+min(z[a[i]-1],z[b[i]-1])

print(s)
for i in range(n):
  print(z[i], end=" ")

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


A,P = map(int,input().split())
print((A*3+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=input()
b=input()
c=(a*3+b)/2
print(c)


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


a, b = [int(i) for input().split()]
c = (a * 3 + b) // 2
print(c)


n= int(input())
a= []
for i in range(n):
    s,p=input().split()
    a.append([s,int(p),i+1])
tmp = sorted(a,key=lambda a: a[1], reverse=True)
a = sorted(tmp, key=lambda a: a[0])
for i in a:
    print(i[2])

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=int(input())

SP = [list(input().split()) for _ in range(N)]

sp=[]
count=1
for s,p in SP:
    sp.append([s,int(p),count])
    count+=1

#sp.sort(key=lambda x:x[1],reverse=True)
sp.sort(key=lambda x:(x[0],-x[1]))

for i in len(sp):
    print(sp[i][2])


N, K = map(int, input().strip().split())
V = list(map(int, input().strip().split()))
H = []
maxi = 0
if N < K:
    for i in range(N):
        for o in range(i):
            ts = 0
            hand = []
            for p in range(o):
                hand.append(V[p])
            for p in range(N-(i-o), N):
                hand.append(V[p])
            for values in hand:
                ts += values
            if ts > maxi:
                maxi = ts
            if len(hand) > 0:
                hand.sort()
                for j in range(K-i):
                    if len(hand) > 0:
                        if hand[0] < 0:
                            del hand[0]
                        else:
                            break
            ts = 0
            for k in hand:
                ts += k
            if ts > maxi:
                maxi = ts
else:
    for i in range(K):
        for o in range(i):
            ts = 0
            hand = []
            for p in range(o):
                hand.append(V[p])
            for p in range(N-(i-o), N):
                hand.append(V[p])
            for values in hand:
                ts += values
            if ts > maxi:
                maxi = ts
            if len(hand) > 0:
                hand.sort()
                for j in range(K-i):
                    if len(hand) > 0:
                        if hand[0] < 0:
                            del hand[0]
                        else:
                            break
            ts = 0
            for k in hand:
                ts += k
            if ts > maxi:
                maxi = ts
print(maxi)

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.


#!/usr/bin/env python
# -*- coding: utf-8 -*-

def calc_score(hands, push):
  hands.sort()

  for i, v in enumerate(hands):
    if v > 0 or i >= push:
      return sum(hands[i:])

  return 0

def main():
  _, k = map(int, input().split())
  values = list(map(int, input().split()))
  score = 0

  for n in range(1, k + 1):
    if n < len(values):
      for i in range(n):
        score = max(calc_score(values[:i] + values[-n + i:], k - n), score)

      score = max(calc_score(values[:n], k - n), score)

    else:
      score = max(calc_score(values[:], k - n), score)

  print(score)

if __name__ == '__main__':
  main()


import sys
input = sys.stdin.readline

def main():
    N,Q = list(map(int,input().split()))

    road = []
    x_list = []
    for i in range(N):
        s,t,x = list(map(int,input().split()))
        road.append((s-x,x,0))
        road.append((t-x,x,1))
        x_list.append(x)

    for i in range(Q):
        d = int(input())
        road.append((d,i,2))

    road.sort(lambda x:x[2])
    road.sort(lambda x:x[0])

    x_list = list(set(x_list))
    x_list.sort()

    x2i_dict = {}
    for i,x in enumerate(x_list):
        x2i_dict[x]=i

    class BIT:

        def __init__(self, L):
            self.N = len(L)
            self.bit = [0]*self.N
            for i,l in enumerate(L):
                self.add(i,l)

        def add(self, a, w):
            x = a + 1
            for i in range(1000):
                self.bit[x-1] += w
                 x += x & -x
                if x > self.N:
                    break

        def sum(self, a):
            x = a+1
            ret = 0
            for i in range(1000):
                ret += self.bit[x-1]
                x -= x & -x
                if x <= 0:
                    break
           return ret

    bit = BIT([0]*xn)
    bitadd = bit.add
    bitsum = bit.sum
    def bisectR(l,r,bit):
        while r-l>1:
            if bitsum((l+r)//2)>0:
                r = (l+r)//2
            else:
                l = (l+r)//2
        return r

    xn=len(x_list)

    ans = [0]*Q
    for r in road:
        if r[2]==0:
             bitadd(x2i_dict[r[1]],1)
        elif r[2]==1:
            bitadd(x2i_dict[r[1]],-1)
        else:
            if bitsum(xn-1)==0:
               ans[r[1]]=-1
            elif bitsum(0)>0:
                ans[r[1]]=x_list[0]
            else:
                i = bisectR(0,xn-1)
                ans[r[1]] = x_list[r]
    for a in ans:
        print(a)

if __name__ == '__main__':
    main()

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.


def main():
  N, Q = list(map(int, input().split()))
  STX = [list(map(int, input().split())) for _ in range(N)]
  D = [int(input()) for _ in range(Q)]

  STX.sort(key = lambda x: x[2])

  L = [[-1, -1]] * Q
  for s, t, x in STX:
    n = s - x
    ok = Q
    ng = -1
    while abs(ok - ng) > 1:
      mid = abs(ok + ng) // 2
      if D[mid] >= n:
        ok = mid
      else:
        ng = mid
    l = ok

    n = t - x
    ok = Q
    ng = l - 1
    while abs(ok - ng) > 1:
      mid = abs(ok + ng) // 2
      if D[mid] >= n:
        ok = mid
      else:
        ng = mid
    r = ok

    while l < r:
      if L[l][1] == -1:
        L[l] = [x, r]
        l += 1
      else:
        l = L[l][1]

  for i in L:
    print(i[0])

main()


#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import collections
import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

class Node:

    def __init__(self, start, end):
        self.start, self.end, self.mid = start, end, (start + end) // 2
        self.val = float('inf')
        self.left = self.right = None

class NumArray:

    def __init__(self, x):
        x.sort()
        self.x_i = {v: i for i, v in enumerate(x)}

        def createTree(l, r):
            if l >= r:
                return None
            root = Node(l, r)
            if l + 1 == r:
                return root
            mid = root.mid
            root.left = createTree(l, mid)
            root.right = createTree(mid, r)
            return root

        self.root = createTree(0, len(x) - 1)

    def update(self, x1, x2, val):
        def updateVal(root, i, j):
            if root.start == i and root.end == j:
                root.val = min(root.val, val)
            else:
                mid = root.mid
                if i < mid:
                    updateVal(root.left, i, min(mid, j))
                if mid < j:
                    updateVal(root.right, max(mid, i), j)

        return updateVal(self.root, self.x_i[x1], self.x_i[x2])

    def query(self, x):
        def queryVal(root, i):
            if not root or i < root.start or i >= root.end:
                return float('inf')
            else:
                return min(root.val, queryVal(root.left, i), queryVal(root.right, i))

        return queryVal(self.root, self.x_i[x])

def main():
    N, Q = read_int_array()
    updates = []
    for i in range(N):
        S, T, X = read_int_array()
        updates.append((S - X, 1, X))
        updates.append((T - X, -1, X))

    active = []
    to_delete = collections.defaultdict(int)
    import heapq
    heapq.heapify(updates)
    for _ in range(Q):
        x = read_int()
        while updates and updates[0][0] <= x:
            coord, tp, val = heapq.heappop(updates)

            if tp == -1:
                to_delete[val] += 1
            else:
                heapq.heappush(active, val)

            while active and to_delete[active[0]] > 0:
                to_delete[active[0]] -= 1
                heapq.heappop(active)
        print(active[0] if active else -1)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

def read():
    return input()

def read_array(sep=None, maxsplit=-1):
    return read().split(sep, maxsplit)

def read_int():
    return int(read())

def read_int_array(sep=None, maxsplit=-1):
    return [int(a) for a in read_array(sep, maxsplit)]

if __name__ == "__main__":
    main()


N,Q = map(int,input().split())
INF = 10**10
evt = []
for i in range(N):
	s,t,x = map(int,input().split())
	evt.append((s-x,1,x))
	evt.append((t-x,-1,x))
q = []
ans = [0 for i in range(Q)]
for i in range(Q):
	d = int(input())
	evt.append((d, 10, i))
evt.sort()

s = set([INF])
cnt = 0
for e in evt:
	if e[1] == 1:
		s.add(e[2])
	elif e[1] == -1:
		s.remove(e[2])
	elif e[1] == 10:
		ans[e[2]] = min(s)

for a in ans:
	print(a if a != INF else -1)


class Work:
    def __init__(self, time, x, f):
        self.time = time - x
        self.f = f
        self.x = x

def bin_search(lis, x):
    l = 0
    r = len(lis)
    while(True):
        m = (l+r)//2
        if (r-l <= 1):
            break
        elif (lis[m].time <= x.time):
            l = m
        else:
            r = m
    return m

def bin_search_x(lis, x):
    l = 0
    r = len(lis)
    while(True):
        m = (l+r)//2
        if (r-l <= 1):
            break
        elif (lis[m].x <= x.x):
            l = m
        else:
            r = m
    return m

n, q = map(int, input().split())
works = []
for i in range(n):
    s, t, x = map(int, input().split())
    works.add(Work(s, x, True))
    works.add(Work(t, x, False))

works = sorted(works, key = lambda w: w.time)

d = []
for i in range(q):
    d.add(int(input()))

workings = []
x_workings = []

while True:
    if works[0].time < d[0]:
        if works[0].f:
            w = works.pop(0)
            workings.add(workings, w)
            x_workings.insert(bin_search_x(x_workings, w)+1, w)
        else:
            w = works.pop(0)
            workings.pop(bin_search(workings, w))
            x_workings.pop(bin_search_x(x_workings, w))
    else:
        d.pop(0)
        if len(works) == 0:
            print(-1)
        else:
            print(x_workins[0].x)


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

for i in range(m):
  k = list(map(int, input().split()))
  l.append(k[0])
  r.append(k[1])

ans = min(r) - max(l) + 1
print(ans)

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 = map(int,(input().spit()))
L = []
R = []

for i in range(m):
	l,r = map(int(input().spit()))
	L.append(l)
	R.append(r)

ans = min(R) - max(L) + 1

if ans >0:
	print(ans)
else:
	print(0)


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

ll=[]
rr =[]
for i in range(m):
	l,r = map(int,input().split())
	ll.append(l)
	rr.append(r)

an = min(rr)-max(ll)+1
if an >0:
	print(an)
else:
	print(0)


import sys

n=0
m=0
id_list=[]

def calculate(x):
  c = len(list(filter(lambda id_list_index: (x >= id_list[id_list_index][0]) and (x <= id_list[id_list_index][1]) , range(0, m))))
  if m == c:
    return True
  return False

is_arg_ok = False
try:
  n, m  = map(int, input().split())
  for i in range(0, m):
    gate_min, gate_max = map(int, input().split())
    id_list.append([gate_min, gate_max])
  is_arg_ok = True

except:
  print('arg error')
  sys.exit(1)

result = len(list(filter(lambda x: calculate(x), range(1, n + 1))))
print(result)
sys.exit(0)


N, M = map(int, input().split())
A = list(map(int, input().split()))
BC = [map(int, input().split()) for _ in range(M)]
B, C = [list(i) for i in zip(*BC)]

S = A
j = 0

T = 0

while(j<M):
  A = S
  i = 0
  while(i<B[j]):
    if (min(A)<C[j]):
      a = int(A.index(min(A)))
      A[a] = C[j]
    else:
      break
    i += 1
  if(T<=sum(A)):
    T = sum(A)
  j += 1
print(T)

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 = sorted(list(map(int, input().split())))
BC = [list(map(int, input().split())) for _ in range(M)]

# n番目の要素でソートsort
BC = sorted(BC, reverse=True, key=lambda x: x[1])

m = A[0]
D = []
p = 0
for b, c in BC:
    if c > m:
        _ = [D.append(c) for i in range(b)]
        p += 1
        if p > N:
            break
    else:
        continue

D.append(0)

for i, d in enumerate(D):
    if i > N:
        break
    if A[i] < d:
        A[i] = d
    else:
        break

print(sum(A))


N, M = map(int, input().split())
A = [int(i) for i in input().split()]
min_val = sorted(A)[0]
for _ in range(M):
  B, C = map(int, input().split())
  if min_val <= C:
  	A.extend([C]*B)

A = sorted(A, reverse=True)
print(sum(A[:N]))


n, m = map(int, input().split())
a = list(map(int, input().split()))
l = []
for i in range(m):
    l.append(list(map(int, input().split())))
l.sort(reverse=True)
l2 = []
for i in range(m):
  l2 = l2 + [l[i][1] for _ in range(l[i][0])]
  if len(l2) >= n:
    l2 = l2[:n]
    break
a = a + l2
a.sort(reverse=True)
print(sum(a[:n]))


import heapq

N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
heapq.heapify(A)

CB = []
for i in range(M):
  b, c = map(int, input().split())
  CB.append([c, b])

CB.sort()
D = []
for c, b in CB:
  D += [c]*b

for i in range(N):
  d = D.pop()
  g = heapq.heappushpop(A, d)
  if d == g:
    break

print(sum(A))


S = input()

heads = int(S[:2])
tails = int(S[2:])

def is_month(n):
    return n >= 1 and n <= 12

if is_month(heads) and (not is_month(tails)):
    print("MMYY")
elif (not is_month(heads)) and (not is_month(tails)):
    print("NA")
elif (not is_month(heads)) and is_month(tails):
    print("YYMM")
else:
    print("AMBIGUOUS")

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


s = input()

l = int(s[0:2])
r = int(s[2:4])

if (l > 0 and l < 13) and (r > 0 and r < 13):
    ret = 'AMBIGUOUS'
elif (l > 0 and l < 13) and (r == 0 or r >= 13):
    ret = 'MMYY'
elif (l == 0 or l >= 13) and (r > 0 and r < 13):
    ret = 'YYMM'
else:
    ret = 'NA'

print(ret)


S = input()
a, b = int(S[:2]), int(S[2:])

if 1 <= a <= 12:
    if 1 <= b <= 12:
        print("AMBIGUOUS")
    elif b > 12 and b != 0:
        print("MMYY")
    else:
        print("NA")
elif a > 12 and a != 0:
    if 1 <= b <= 12:
        print("YYMM")
    elif b > 12 and b != 0:
        print("AMBIGUOUS")
    else:
        print("NA")
else:
    print("NA")


X = input()

if X[0] == '0' and X[2] != '0':
    print("MMYY")
elif X[0] != '0' and X[2] == '0':
    print("YYMM")
elif X[0] != '0' and X[2] != '0':
    print("NA")
else:
    print("AMBIGUOUS")


S = input()
T = str(S)
A=int(T[0:2])
B=int(T[3:5])
if 1<=A<=12:
  if 1<=B<=12:
    print('AMBIGUOUS')
  else:
    print('MMYY')
elif 1<=B<=12:
  print('YYMM')
else:
  print('NA')


import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()

def solve():
    N = int(single_input())
    edge = [[] for i in range(N)]
    for i in range(N-1):
        u, v, w = map(int, line_input())
        edge[u-1].append((v-1, w))
        edge[v-1].append((u-1, w))

    col = [-1] * N
    que = collections.deque()
    que.append((0, 0))
    while que:
        nownode, nowdist = que.popleft()
        if col[nownode] == -1:
            col[nownode] = nowdist
            for nextnode, weight in edge[nownode]:
                if col[nextnode] == -1:
                    que.append((nextnode, nowdist + weight))
    for i in range(N):
        print(col[i] % 2)

    return 0

if __name__ == "__main__":
    solve()

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


N = int(input())
ss = [input() for _ in range(N)]

contained = sum([s.count('AB') for s in ss])
B_hoge = sum([1 for s in ss if s[0]=='B'])
hoge_A = sum([1 for s in ss if s[-1]=='A'])
B_hoge_A = sum([1 for s in ss if s[0]=='B' and s[-1]=='A'])

B_hoge -= B_hoge_A
hoge_A -= B_hoge_A
gap = abs(B_hoge - hoge_A)
# 差がB_hoge_Aより大きい場合、可能な限り差を埋める
ans = contained
if gap >= B_hoge_A:
    ans += min(B_hoge,hoge_A) + B_hoge_A
#　差がB_hoge_Aより小さい場合、差を埋めた残りでペアを作る
else:
    ans += min(B_hoge,hoge_A)
    if B_hoge_A > 0:
        ans += B_hoge_A - 1
        if B_hoge!=hoge_A:
            ans += 1
print(ans)

# print('-'*20)
# print('contained:',contained)
# print(B_hoge, hoge_A, B_hoge_A)

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 -*-
import sys

#読み込み
n = int(input())

strs = []

for i in range(n):
    strs.append(input())

#文字列の確認
str_in_num = 0
str_both_ab = 0
str_head_a = 0
str_tail_b = 0

for st in strs:
    #文字列中にABを含むもの
    #print(st)
    if len(st) > 2:
        str_in_num += st[0:-1].count('AB')

    #文字列の先頭がBのもの
    if st[-1] == 'A' and st[0] == 'B':
        str_both_ab += 1
    else:
        if st[-1] == 'A':
            str_head_a += 1

        if st[0] == 'B':
            str_tail_b += 1

total = 0

if str_both_ab > 0:
    total += (str_both_ab - 1)

    if str_head_a > 0:
        total += 1
        str_head_a -= 1
    if str_tail_b > 0:
        total += 1
        str_tail_b -= 1

total += str_in_num
total += min(str_head_a, str_tail_b)

print(total)


A,B,T = map(int,input().split())

S=T+0.5

C=S//A

print(int(C*B))

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


n=int(input())
v=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
dif=[]
for i in range(n):
  if v[i]>c[i]:
    dif.append(v[i]-c[i])

ans=0
for i in range(1 << len(dif)):
    sum=0
    for j in range(len(dif)):
        if ((i>>j)&1)==1:
            sum += dif[j]
    ans = max(ans, sum)
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


import numpy as np
n=int(input())
v = np.array(list(map(int,input().split())))
c= np.array(list(map(int,input().split())))
li=v-c
sum=0
for i in li:
    if i > 0:
        sum += i
print(sum)


n = int(input())
value = list(map(int, input().split()))
cost = list(map(int, input().split()))

sum = 0
for i in range(n):
  merit = value[i]-cost[i]
  if merit > 0:
    sum += merit

print(sum)


raw_input()
t=raw_input()
has_black=False
cant=0
for i in t:
  if i=="#": has_black=True
  else:
    if has_black:
      cant+=1
print cant

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


n = int(input())
s = input()

ans = 0
for si in s:
    if si == '#':
        ans += 1

white = [0] * (n+1)
black = [0] * (n+1)

for i in range(n):
    if s[i] == "#":
        white[i+1] = white[i]
        black[i+1] = black[i] + 1
    else:
        white[i+1] = white[i] + 1
        black[i+1] = black[i]

for i in range(n):
    if s[i] == ".":
        continue
    ans = min(ans, black[i] + white[n] - white[i + 1])

print(ans)


Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4

Sample Output 3

563038556


A, B, C = map(int, input().split())

if A < C < B or B < C < A:
    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


a, b, c = map(int,input().split())
if (a-c) * (b-c) < 0:
    print("Yes")
else:
    print("No")


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

T = ''
for i in range(0, N):
    if S[i] != S[K-1]:
        T += '*'
    else:
        T += S[i]
print(T)

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 = input()
cnt_b = 0
cnt_w = 0
Is_Black = False
ans = 0

# ans = S.count("#.")
# print(ans)

for i in range(N):
    if S[i] == "#":
        if Is_Black:
            if cnt_w == 0:
                cnt_b += 1
            elif cnt_b != 0 and cnt_w != 0:
                ans += min(cnt_b, cnt_w)
                cnt_b = 1
                cnt_w = 0
        else:
            Is_Black = True
            cnt_b += 1
    else:
        if Is_Black and cnt_b!=0:
            cnt_w += 1
else:
    if cnt_b != 0 and cnt_w != 0:
                ans += min(cnt_b, cnt_w)
                cnt_b = 1
                cnt_w = 0

print(ans)


N = int(input())
S = str(input())
first_B = S.find('#')
if first_B == -1:
    answer = 0
else:
    S = S[first_B:]
#    print(S)
    answer = S.count('.')
print (answer)


n = int(input())
s = input()

ans = 0
flag = True

if s[0] == '#':
    flag = False
else:
    for i in range(n-1):
        if s[i] == '.' and s[i+1] == '#':
            s = s[i+1:]
            flag = False
            break

if flag == False:
    print(s.count('.'))
else:
    print(0)


_, *hs = map(int, open(0).read().split())
cou=1
hm=hs[0]
for h in hs[1:]:
  if hm<=h:
    cou+=1
    hm=h
print(cou)

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 = int(input())
h = list(map(int, input().split()))
sum = 0
max = 0
for i in range(n):
    if max <= h[i]:
        sum =+ 1
        max = h[i]
print(sum)


Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


s = int(input())

n = len(s)

for i in range(n-1):
  if s[i] == s[i+1]:
    if s[i] == 0:
      s[i+1] = 1
    else:
      [i] = 0

print(s)


s=input()
n=len(s)
c0=0
c1=0
for i in range(n):
    if i%2 >0:
        if s[i]!='1':
            c0+=1
        else:
            c1+=1
    else:
        if s[i]!='0':
            c0+=1
        else:
            c1+=1
print(min(c0,c1))


b = input()

if b == "A":
    print("T")
elif b == "T":
    print("A")
elif b == "C":
    print("G")
else:
    print("C")

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C