I found an interesting problem on https://atcoder.jp/contests/abc116/tasks/abc116_c:
In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq  k \leq N), by repeating the following "watering" operation:
 - Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.
Find the minimum number of watering operations required to satisfy the condition.

-----Constraints-----
 - 1 \leq N  \leq 100
 - 0 \leq h_i \leq 100
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
h_1 h_2 h_3 ...... h_N

-----Output-----
Print the minimum number of watering operations required to satisfy the condition.

-----Sample Input-----
4
1 2 2 1

-----Sample Output-----
2

The minimum number of watering operations required is 2.
One way to achieve it is:
 - Perform the operation with (l,r)=(1,3).
 - Perform the operation with (l,r)=(2,4).

I tried it in Python, but could not do it. Can you solve it?

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 00:43:39 2020

@author: liang
"""

N = int(input())
H = [int(x) for x in input().split()]

ans = 0
for i in range(max(H)):
    count = 0
    flag = False
    for j in range(N):
        if i < H[j]:
            if flag == False:
                count += 1
            flag = True
        else:
            flag = False
    ans += count
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc116/tasks/abc116_d:
There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:
 - The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".
 - The base total deliciousness is the sum of the deliciousness of the pieces you eat.
 - The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.
You want to have as much satisfaction as possible.
Find this maximum satisfaction.

-----Constraints-----
 - 1 \leq K \leq N  \leq 10^5
 - 1 \leq t_i \leq N
 - 1 \leq d_i \leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

-----Output-----
Print the maximum satisfaction that you can obtain.

-----Sample Input-----
5 3
1 9
1 7
2 6
2 5
3 1

-----Sample Output-----
26

If you eat Sushi 1,2 and 3:
 - The base total deliciousness is 9+7+6=22.
 - The variety bonus is 2*2=4.
Thus, your satisfaction will be 26, which is optimal.

I tried it in Python, but could not do it. Can you solve it?

n, k = list(map(int, input().split()))
sushi = []
for i in range(n):
    sushi.append(list(map(int, input().split())))
point = 0
sushi_kind = set()
duplication = []
sushi.sort(key=lambda x: x[1],reverse = True)
for i in range(k):
    point += sushi[i][1]
    if sushi[i][0] in sushi_kind:
        duplication.append(sushi[i])
    else:
        sushi_kind.add(sushi[i][0])
ans = point + pow(len(sushi_kind),2)
dup_index = len(duplication) - 1
for i in range(k,n):
    if sushi[i][0] in sushi_kind:
        continue
    else:
        if dup_index >= 0:
            point -= duplication[dup_index][1]
            dup_index -= 1
            point += sushi[i][1]
            sushi_kind.add(sushi[i][0])
    ans = max(ans, point + pow(len(sushi_kind),2))
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc117/tasks/abc117_a:
In order to pass the entrance examination tomorrow, Taro has to study for T more hours.
Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).
While (X \times t) hours pass in World B, t hours pass in World A.
How many hours will pass in World A while Taro studies for T hours in World B?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq T \leq 100
 - 1 \leq X \leq 100

-----Input-----
Input is given from Standard Input in the following format:
T X

-----Output-----
Print the number of hours that will pass in World A.
The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

-----Sample Input-----
8 3

-----Sample Output-----
2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.
Note that an absolute or relative error of at most 10^{-3} is allowed.

I tried it in Python, but could not do it. Can you solve it?

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


I found an interesting problem on https://atcoder.jp/contests/abc117/tasks/abc117_b:
Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.
You can use the following theorem:
Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

-----Constraints-----
 - All values in input are integers.
 - 3 \leq N \leq 10
 - 1 \leq L_i \leq 100

-----Input-----
Input is given from Standard Input in the following format:
N
L_1 L_2 ... L_N

-----Output-----
If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

-----Sample Input-----
4
3 8 5 1

-----Sample Output-----
Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
list01 = input().split()
list02 = sorted([int(s) for s in list01])
a = sum(list02) - list02[-1]
if list02[-1] < a:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc117/tasks/abc117_c:
We will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.
Note that the coordinates where we initially place the pieces are already regarded as visited.
Find the minimum number of moves required to achieve the objective.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - -10^5 \leq X_i \leq 10^5
 - X_1, X_2, ..., X_M are all different.

-----Input-----
Input is given from Standard Input in the following format:
N M
X_1 X_2 ... X_M

-----Output-----
Find the minimum number of moves required to achieve the objective.

-----Sample Input-----
2 5
10 12 1 2 14

-----Sample Output-----
5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.
 - Initially, put the two pieces at coordinates 1 and 10.
 - Move the piece at coordinate 1 to 2.
 - Move the piece at coordinate 10 to 11.
 - Move the piece at coordinate 11 to 12.
 - Move the piece at coordinate 12 to 13.
 - Move the piece at coordinate 13 to 14.

I tried it in Python, but could not do it. Can you solve it?

n, m = list(map(int, input().split()))
x = sorted(list(map(int, input().split())))
y = []
if n > m :
    print((0))
    return
for i in range(m-1):
    diff = x[i+1] - x[i]
    y.append(diff)
y.sort(reverse = True)
res = x[-1] - x[0]
for i in range(n-1):
    res -= y[i]
print(res)


I found an interesting problem on https://atcoder.jp/contests/abc117/tasks/abc117_d:
You are given N non-negative integers A_1, A_2, ..., A_N and another non-negative integer K.
For a integer X between 0 and K (inclusive), let f(X) = (X XOR A_1) + (X XOR A_2) + ... + (X XOR A_N).
Here, for non-negative integers a and b, a XOR b denotes the bitwise exclusive OR of a and b.
Find the maximum value of f.
What is XOR?
The bitwise exclusive OR of a and b, X, is defined as follows:
 - When X is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if, when written in base two, exactly one of A and B has 1 in the 2^k's place, and 0 otherwise.
For example, 3 XOR 5 = 6. (When written in base two: 011 XOR 101 = 110.)

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 0 \leq K \leq 10^{12}
 - 0 \leq A_i \leq 10^{12}

-----Input-----
Input is given from Standard Input in the following format:
N K
A_1 A_2 ... A_N

-----Output-----
Print the maximum value of f.

-----Sample Input-----
3 7
1 6 3

-----Sample Output-----
14

The maximum value is: f(4) = (4 XOR 1) + (4 XOR 6) + (4 XOR 3) = 5 + 2 + 7 = 14.

I tried it in Python, but could not do it. Can you solve it?

import numpy as np

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

L = len(f'{10**12:b}')
res = 0
for i in range(-1, L):
    if i != -1 and not (k >> i) & 1:
        continue
    val = 0
    for j in range(L):
        d = np.count_nonzero((a >> j) & 1)
        if i < j:
            if (k >> j) & 1:
                val += (n-d) * 2**j
            else:
                val += d * 2**j
        elif i == j:
            val += d * 2**j
        else:
            val += max(d, n-d) * 2**j
    res = max(res, val)
print(res)


I found an interesting problem on https://atcoder.jp/contests/abc118/tasks/abc118_a:
You are given positive integers A and B.
If A is a divisor of B, print A + B; otherwise, print B - A.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A \leq B \leq 20

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
If A is a divisor of B, print A + B; otherwise, print B - A.

-----Sample Input-----
4 12

-----Sample Output-----
16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

I tried it in Python, but could not do it. Can you solve it?

A, B = input().split()

if (int(B)%int(A)) == 0:
    print(int(A)+int(B))
else:
    print(int(B)-int(A))


I found an interesting problem on https://atcoder.jp/contests/abc118/tasks/abc118_b:
Katsusando loves omelette rice.
Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.
To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.
The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.
Find the number of the foods liked by all the N people.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N, M \leq 30
 - 1 \leq K_i \leq M
 - 1 \leq A_{ij} \leq M
 - For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

-----Constraints-----
Input is given from Standard Input in the following format:
N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

-----Output-----
Print the number of the foods liked by all the N people.

-----Sample Input-----
3 4
2 1 3
3 1 2 3
2 3 2

-----Sample Output-----
1

As only the third food is liked by all the three people, 1 should be printed.

I tried it in Python, but could not do it. Can you solve it?

n, m = list(map(int, input().split()))
like = [0] * m

for i in range(n):
    a = list(map(int, input().split()))[1:]
    for j in a:  like[j-1] += 1

print((sum(i==n for i in like)))


I found an interesting problem on https://atcoder.jp/contests/abc118/tasks/abc118_c:
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
 - A random alive monster attacks another random alive monster.
 - As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 1 \leq A_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N

-----Output-----
Print the minimum possible final health of the last monster alive.

-----Sample Input-----
4
2 10 8 40

-----Sample Output-----
2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

I tried it in Python, but could not do it. Can you solve it?

import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

def gcd_list(numbers):
    return reduce(math.gcd, numbers)

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

def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

n = int(input())
a = [int(i) for i in input().split()]
if 1 in a:
    ans = 1
else:
    ans = gcd_list(a)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc118/tasks/abc118_d:
Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:
 - Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).
 - The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^4
 - 1 \leq M \leq 9
 - 1 \leq A_i \leq 9
 - A_i are all different.
 - There exists an integer that can be formed by exactly N matchsticks under the conditions.

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 A_2 ... A_M

-----Output-----
Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

-----Sample Input-----
20 4
3 7 8 4

-----Sample Output-----
777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

I tried it in Python, but could not do it. Can you solve it?

N, M = map(int, input().split())
A = list(map(int, input().split()))
weight = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
dp = [-1]*(N+1)
dp[0] = 0
for i in range(N+1):
    for a in A:
        if i + weight[a]<=N:
            dp[i+weight[a]] = max(dp[i+weight[a]],dp[i]*10+a)
print(dp[N])


I found an interesting problem on https://atcoder.jp/contests/abc119/tasks/abc119_a:
You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)
Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

-----Constraints-----
 - S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

-----Sample Input-----
2019/04/30

-----Sample Output-----
Heisei

I tried it in Python, but could not do it. Can you solve it?

s = input()

if s > '2019/04/30':
  print('TBD')
else:
  print('Heisei')


I found an interesting problem on https://atcoder.jp/contests/abc119/tasks/abc119_b:
Takahashi received otoshidama (New Year's money gifts) from N of his relatives.
You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.
For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.
If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

-----Constraints-----
 - 2 \leq N \leq 10
 - u_i = JPY or BTC.
 - If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.
 - If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 u_1
x_2 u_2
:
x_N u_N

-----Output-----
If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).
Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.

-----Sample Input-----
2
10000 JPY
0.10000000 BTC

-----Sample Output-----
48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.
Outputs such as 48000 and 48000.1 will also be judged correct.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
num = 0
for i in range(n):
    x1,v1 = map(str, input().split())
    if v1 == 'JPY':
        num += int(x1)
    else:
        num += float(x1)*380000
print(num)


I found an interesting problem on https://atcoder.jp/contests/abc119/tasks/abc119_c:
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.
Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:
 - Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.
 - Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.
 - Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)
At least how much MP is needed to achieve the objective?

-----Constraints-----
 - 3 \leq N \leq 8
 - 1 \leq C < B < A \leq 1000
 - 1 \leq l_i \leq 1000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N A B C
l_1
l_2
:
l_N

-----Output-----
Print the minimum amount of MP needed to achieve the objective.

-----Sample Input-----
5 100 90 80
98
40
30
21
80

-----Sample Output-----
23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.
 - Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)
 - Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)
 - Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)
 - Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

I tried it in Python, but could not do it. Can you solve it?

import itertools
N,A,B,C=map(int, input().split())
l=[int(input()) for _ in range(N)]
pattern=["a","b","c","N"]

lcombi=itertools.product(pattern,repeat=N)

ans=(1000)**3
for lc in list(lcombi):
	Alen=0
	Blen=0
	Clen=0
	Acost=0
	Bcost=0
	Ccost=0

	if ("a" not in lc) or("b" not in lc) or("c" not in lc):
		continue
	else:
		for i in range(N):
			if lc[i]=="a":
				if Alen==0:Alen+=l[i]
				else:
					Alen+=l[i]
					Acost+=10
			elif lc[i]=="b":
				if Blen==0:Blen+=l[i]
				else:
					Blen+=l[i]
					Bcost+=10
			elif lc[i]=="c":
				if Clen==0:Clen+=l[i]
				else:
					Clen+=l[i]
					Ccost+=10
		Acost+=abs(Alen-A)
		Bcost+=abs(Blen-B)
		Ccost+=abs(Clen-C)
		ans=min(ans,Acost+Bcost+Ccost)

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc119/tasks/abc119_d:
Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.
Answer the following Q queries:
 - Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

-----Constraints-----
 - 1 \leq A, B \leq 10^5
 - 1 \leq Q \leq 10^5
 - 1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}
 - 1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}
 - 1 \leq x_i \leq 10^{10}
 - s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

-----Output-----
Print Q lines. The i-th line should contain the answer to the i-th query.

-----Sample Input-----
2 3 4
100
600
400
900
1000
150
2000
899
799

-----Sample Output-----
350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.
 - Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.
 - Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.
 - Query 3: If we start from a point at a distance of 899 meters from the west end of the...

I tried it in Python, but could not do it. Can you solve it?

from bisect import bisect_right
a, b, q = map(int, input().split())
s = [-float("inf")] + [int(input()) for i in range(a)] + [float("inf")]
t = [-float("inf")] + [int(input()) for i in range(b)] + [float("inf")]
x = [int(input()) for i in range(q)]
for i in range(q):
    X = x[i]
    l, r = bisect_right(s, X), bisect_right(t, X)
    ans = float("inf")
    ans = min(ans, abs(s[l - 1] - X) + abs(t[r - 1] - s[l - 1]), abs(t[r - 1] - X) + abs(s[l - 1] - t[r - 1]))
    ans = min(ans, abs(s[l - 1] - X) + abs(t[r] - s[l - 1]), abs(t[r] - X) + abs(s[l - 1] - t[r]))
    ans = min(ans, abs(s[l] - X) + abs(t[r - 1] - s[l]), abs(t[r - 1] - X) + abs(s[l] - t[r - 1]))
    ans = min(ans, abs(s[l] - X) + abs(t[r] - s[l]), abs(t[r] - X) + abs(s[l] - t[r]))
    print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc120/tasks/abc120_a:
Takahashi likes the sound when he buys a drink from a vending machine.
That sound can be heard by spending A yen (the currency of Japan) each time.
Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.
How many times will he hear the sound?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A, B, C \leq 100

-----Input-----
Input is given from Standard Input in the following format:
A B C

-----Output-----
Print the number of times Takahashi will hear his favorite sound.

-----Sample Input-----
2 11 4

-----Sample Output-----
4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

I tried it in Python, but could not do it. Can you solve it?

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

i = B // A
if i > C:
    print(C)
else:
    print(i)


I found an interesting problem on https://atcoder.jp/contests/abc120/tasks/abc120_b:
You are given positive integers A and B.
Find the K-th largest positive integer that divides both A and B.
The input guarantees that there exists such a number.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A, B \leq 100
 - The K-th largest positive integer that divides both A and B exists.
 - K \geq 1

-----Input-----
Input is given from Standard Input in the following format:
A B K

-----Output-----
Print the K-th largest positive integer that divides both A and B.

-----Sample Input-----
8 12 2

-----Sample Output-----
2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

I tried it in Python, but could not do it. Can you solve it?

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

divid_number = []
for X in range(1,100+1):
    if A % X ==0 and B % X == 0:
        divid_number.append(X)

divid_number.reverse()
print((divid_number[K-1]))


I found an interesting problem on https://atcoder.jp/contests/abc120/tasks/abc120_c:
There are N cubes stacked vertically on a desk.
You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.
You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.
At most how many cubes can be removed?

-----Constraints-----
 - 1 \leq N \leq 10^5
 - |S| = N
 - Each character in S is 0 or 1.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print the maximum number of cubes that can be removed.

-----Sample Input-----
0011

-----Sample Output-----
4

All four cubes can be removed, by performing the operation as follows:
 - Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.
 - Remove the first and second cubes from the bottom.

I tried it in Python, but could not do it. Can you solve it?

a=list(input())
temp1=0
temp0=0

for i in range(len(a)):
    if a[i]=="0":
        temp0+=1
    else:
        temp1+=1
print((min(temp0,temp1)*2))


I found an interesting problem on https://atcoder.jp/contests/abc120/tasks/abc120_d:
There are N islands and M bridges.
The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.
Initially, we can travel between any two islands using some of these bridges.
However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.
Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.
For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - 1 \leq A_i < B_i \leq N
 - All pairs (A_i, B_i) are distinct.
 - The inconvenience is initially 0.

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

-----Output-----
In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

-----Sample Input-----
4 5
1 2
3 4
1 3
2 3
1 4

-----Sample Output-----
0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

I tried it in Python, but could not do it. Can you solve it?

import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7

class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        """
        親が同じか判別する
        """
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        """
        yをxの根に繋ぐ
        """
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def same(self, x, y):
        """
        xとyが同じ連結成分か判別する
        """
        return self.find(x) == self.find(y)

    def size(self, x):
        """
        xの連結成分の大きさを返す
        """
        return -self.parents[self.find(x)]

    def kruskal(self, edge):
        """
        :param edge: edge = [(コスト, 頂点1, 頂点2),...]の形で重み付き隣接リストを渡して下さい
        :return: 最小全域木のコストの和
        """
        edge.sort()
        cost_sum = 0
        for cost, node1, node2 in edge:
            if not self.same(node1, node2):
                cost_sum += cost
                self.union(node1, node2)
        return cost_sum

def resolve():
    n, m = map(int, input().split())
    edge = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(m)]
    uf = UnionFind(n)
    res = [(n - 1) * n // 2]
    for i in reversed(range(1, m)):
        a, b = edge[i]
        if not uf.same(a, b):
            res.append(res[-1] - uf.size(a) * uf.size(b))
            uf.union(a, b)
        else:
            res.append(res[-1])
    print(*res[::-1], sep="\n")

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc121/tasks/abc121_a:
There are H rows and W columns of white square cells.
You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.
How many white cells will remain?
It can be proved that this count does not depend on what rows and columns are chosen.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq H, W \leq 20
 - 1 \leq h \leq H
 - 1 \leq w \leq W

-----Input-----
Input is given from Standard Input in the following format:
H W
h w

-----Output-----
Print the number of white cells that will remain.

-----Sample Input-----
3 2
2 1

-----Sample Output-----
1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

I tried it in Python, but could not do it. Can you solve it?

a,b = map(int,input().split())
c,d = map(int,input().split())
print((a-c)*(b-d))


I found an interesting problem on https://atcoder.jp/contests/abc121/tasks/abc121_b:
There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.
Additionally, you are given integers B_1, B_2, ..., B_M and C.
The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.
Among the N codes, find the number of codes that correctly solve this problem.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N, M \leq 20
 - -100 \leq A_{ij} \leq 100
 - -100 \leq B_i \leq 100
 - -100 \leq C \leq 100

-----Input-----
Input is given from Standard Input in the following format:
N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

-----Output-----
Print the number of codes among the given N codes that correctly solve this problem.

-----Sample Input-----
2 3 -10
1 2 3
3 2 1
1 2 2

-----Sample Output-----
1

Only the second code correctly solves this problem, as follows:
 - Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.
 - 1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

I tried it in Python, but could not do it. Can you solve it?

n,m,c=list(map(int, input().split()))
b=[int(i) for i in input().split()]

count=0
for i in range(n):
    a=[int(i) for i in input().split()]
    sum=c
    for j in range(m):
        sum+=a[j]*b[j]

    if sum>0:
        count+=1

print(count)


I found an interesting problem on https://atcoder.jp/contests/abc121/tasks/abc121_c:
Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.
There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.
What is the minimum amount of money with which he can buy M cans of energy drinks?
It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N, M \leq 10^5
 - 1 \leq A_i \leq 10^9
 - 1 \leq B_i \leq 10^5
 - B_1 + ... + B_N \geq M

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

-----Output-----
Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

-----Sample Input-----
2 5
4 9
2 4

-----Sample Output-----
12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

I tried it in Python, but could not do it. Can you solve it?

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

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

l.sort(key=lambda x: x[0])

r = m
i = 0
cnt = 0
while((r-l[i][1])>0):
    r -= l[i][1]
    cnt += (l[i][0]*l[i][1])
    i += 1

cnt += (r*l[i][0])

print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc121/tasks/abc121_d:
Let f(A, B) be the exclusive OR of A, A+1, ..., B. Find f(A, B).
What is exclusive OR?
The bitwise exclusive OR of integers c_1, c_2, ..., c_n (let us call it y) is defined as follows:
 - When y is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if, the number of integers among c_1, c_2, ...c_m whose binary representations have 1 in the 2^k's place, is odd, and 0 if that count is even.
For example, the exclusive OR of 3 and 5 is 6. (When written in base two: the exclusive OR of 011 and 101 is 110.)

-----Constraints-----
 - All values in input are integers.
 - 0 \leq A \leq B \leq 10^{12}

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Compute f(A, B) and print it.

-----Sample Input-----
2 4

-----Sample Output-----
5

2, 3, 4 are 010, 011, 100 in base two, respectively.
The exclusive OR of these is 101, which is 5 in base ten.

I tried it in Python, but could not do it. Can you solve it?

a, b = map(int, input().split())
aq, bq = a % 4, b % 4

ans = 0
for i in range(a, a + (4 - aq)):
    ans ^= i

for i in range(b - bq, b + 1):
    ans ^= i

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_a:
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-----
A

-----Sample Output-----
T

I tried it in Python, but could not do it. Can you solve it?

AT = ['A', 'T']
CG = ['C', 'G']
b = input()

if b in AT:
    AT.remove(b)
    print((*AT))
else:
    CG.remove(b)
    print((*CG))


I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_b:
You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.
Here, a ACGT string is a string that contains no characters other than A, C, G and T.

-----Notes-----
A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.
For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

-----Constraints-----
 - S is a string of length between 1 and 10 (inclusive).
 - Each character in S is an uppercase English letter.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print the length of the longest ACGT string that is a substring of S.

-----Sample Input-----
ATCODER

-----Sample Output-----
3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

I tried it in Python, but could not do it. Can you solve it?

import re
s = input()
res = re.findall(r'[ATGC]+',s)
ans = 0

for e in res:
  ans = max(ans,len(e))

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_c:
You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:
 - Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

-----Notes-----
A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.
For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq Q \leq 10^5
 - S is a string of length N.
 - Each character in S is A, C, G or T.
 - 1 \leq l_i < r_i \leq N

-----Input-----
Input is given from Standard Input in the following format:
N Q
S
l_1 r_1
:
l_Q r_Q

-----Output-----
Print Q lines. The i-th line should contain the answer to the i-th query.

-----Sample Input-----
8 3
ACACTACG
3 7
2 3
1 8

-----Sample Output-----
2
0
3

 - Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.
 - Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.
 - Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.

I tried it in Python, but could not do it. Can you solve it?

n, q = map(int, input().split())
S = input()
flag = False
L = [0 for _ in range(n)]
cnt = 0
for i, s in enumerate(S):
    if flag:
        if s == "C":
            cnt += 1
        flag = False
    if s == "A":
        flag = True
    L[i] = cnt

for _ in range(q):
    l, r = map(lambda x: int(x) - 1, input().split())
    print(L[r] - L[l])


I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_d:
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
 - The string does not contain characters other than A, C, G and T.
 - The string does not contain AGC as a substring.
 - The condition above cannot be violated by swapping two adjacent characters once.

-----Notes-----
A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.
For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

-----Constraints-----
 - 3 \leq N \leq 100

-----Input-----
Input is given from Standard Input in the following format:
N

-----Output-----
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

-----Sample Input-----
3

-----Sample Output-----
61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

I tried it in Python, but could not do it. Can you solve it?

import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def resolve():
    N = int(input())

    # dp[i文字目][3文字前][2文字前][1文字前]
    dp = [[[[0] * 5 for _ in range(5)] for _ in range(5)] for _ in range(N + 1)]
    dp[0][0][0][0] = 1

    # _,A,G,C,T = 0,1,2,3,4
    for n in range(N):
        # 3文字前
        for i in range(5):
            # 2文字前
            for j in range(5):
                # 1文字前
                for k in range(5):
                    # 最後の文字
                    for l in range(1, 5):
                        # AG*C
                        if i == 1 and j == 2 and l == 3: continue
                        # A*GC
                        if i == 1 and k == 2 and l == 3: continue
                        # *AGC
                        if j == 1 and k == 2 and l == 3: continue
                        # *GAC
                        if j == 2 and k == 1 and l == 3: continue
                        # *ACG
                        if j == 1 and k == 3 and l == 2: continue
                        dp[n + 1][j][k][l] += dp[n][i][j][k]
                        dp[n + 1][j][k][l] %= mod
    res = 0
    for i in range(5):
        for j in range(5):
            for k in range(5):
                res += dp[-1][i][j][k]
                res %= mod
    print(res)

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc123/tasks/abc123_a:
In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

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

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

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

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

-----Input-----
Input is given from Standard Input in the following format:
a
b
c
d
e
k

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

-----Sample Input-----
1
2
4
8
9
15

-----Sample Output-----
Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:
 - the distance between A and B is 2 - 1 = 1
 - the distance between A and C is 4 - 1 = 3
 - the distance between A and D is 8 - 1 = 7
 - the distance between A and E is 9 - 1 = 8
 - the distance between B and C is 4 - 2 = 2
 - the distance between B and D is 8 - 2 = 6
 - the distance between B and E is 9 - 2 = 7
 - the distance between C and D is 8 - 4 = 4
 - the distance between C and E is 9 - 4 = 5
 - the distance between D and E is 9 - 8 = 1
and none of them is greater than 15. Thus, the correct output is Yay!.

I tried it in Python, but could not do it. Can you solve it?

a = int(input())
_ = int(input())
_ = int(input())
_ = int(input())
e = int(input())
k = int(input())
print(("Yay!" if e - a <= k else ":("))


I found an interesting problem on https://atcoder.jp/contests/abc123/tasks/abc123_b:
The restaurant AtCoder serves the following five dishes:
 - ABC Don (rice bowl): takes A minutes to serve.
 - ARC Curry: takes B minutes to serve.
 - AGC Pasta: takes C minutes to serve.
 - APC Ramen: takes D minutes to serve.
 - ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
 - An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
 - Only one dish can be ordered at a time.
 - No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

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

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

-----Input-----
Input is given from Standard Input in the following format:
A
B
C
D
E

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

-----Sample Input-----
29
20
7
35
120

-----Sample Output-----
215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:
 - Order ABC Don at time 0, which will be delivered at time 29.
 - Order ARC Curry at time 30, which will be delivered at time 50.
 - Order AGC Pasta at time 50, which will be delivered at time 57.
 - Order ATC Hanbagu at time 60, which will be delivered at time 180.
 - Order APC Ramen at time 180, which will be delivered at time 215.
There is no way to order the dishes in which the last dish will be delivered earlier than this.

I tried it in Python, but could not do it. Can you solve it?

import math

A = input()
B = input()
C = input()
D = input()
E = input()

num = 10
for i in [int(A[-1]), int(B[-1]), int(C[-1]), int(D[-1]), int(E[-1])]:
    if i != 0:
        num = min(num, i)

result = (math.ceil(int(A)/10) + math.ceil(int(B)/10) + math.ceil(int(C)/10) + math.ceil(int(D)/10) + math.ceil(int(E)/10)) * 10
if num != 10:
    result = result - 10 + num

print(result)


I found an interesting problem on https://atcoder.jp/contests/abc123/tasks/abc123_c:
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!
There are five means of transport in this empire:
 - Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.
 - Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.
 - Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.
 - Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.
 - Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.
For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).
There is a group of N people at City 1, and they all want to go to City 6.

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

-----Constraints-----
 - 1 \leq N, A, B, C, D, E \leq 10^{15}
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
A
B
C
D
E

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

-----Sample Input-----
5
3
2
4
3
5

-----Sample Output-----
7

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

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

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

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

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

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

I tried it in Python, but could not do it. Can you solve it?

from math import ceil
n = int(input())
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
print(ceil(n / min(a,b,c,d,e)) + 4)


I found an interesting problem on https://atcoder.jp/contests/abc123/tasks/abc123_d:
The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:
 - The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.
 - The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.
 - The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.
Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

-----Constraints-----
 - 1 \leq X \leq 1 \ 000
 - 1 \leq Y \leq 1 \ 000
 - 1 \leq Z \leq 1 \ 000
 - 1 \leq K \leq \min(3 \ 000, X \times Y \times Z)
 - 1 \leq A_i \leq 10 \ 000 \ 000 \ 000
 - 1 \leq B_i \leq 10 \ 000 \ 000 \ 000
 - 1 \leq C_i \leq 10 \ 000 \ 000 \ 000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

-----Output-----
Print K lines. The i-th line should contain the i-th value stated in the problem statement.

-----Sample Input-----
2 2 2 8
4 6
1 5
3 8

-----Sample Output-----
19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:
 - (A_2, B_2, C_2): 6 + 5 + 8 = 19
 - (A_1, B_2, C_2): 4 + 5 + 8 = 17
 - (A_2, B_1, C_2): 6 + 1 + 8 = 15
 - (A_2, B_2, C_1): 6 + 5 + 3 = 14
 - (A_1, B_1, C_2): 4 + 1 + 8 = 13
 - (A_1, B_2, C_1): 4 + 5 + 3 = 12
 - (A_2, B_1, C_1): 6 + 1 + 3 = 10
 - (A_1, B_1, C_1): 4 + 1 + 3 = 8

I tried it in Python, but could not do it. Can you solve it?

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

import numpy as np
x,y,z,K = list(map(int, input().split()))
a = np.array(list(map(int, input().split())), dtype=np.int64)
b = np.array(list(map(int, input().split())), dtype=np.int64)
c = np.array(list(map(int, input().split())), dtype=np.int64)
ab = (a + b.reshape(-1,1)).reshape(-1)
ab.sort()
c.sort()
abk = ab[-K:]
ck = c[-K:]
l = (abk + ck.reshape(-1,1)).reshape(-1)
l.sort()
l = l[::-1]
write("\n".join(map(str, l[:K])))


I found an interesting problem on https://atcoder.jp/contests/abc124/tasks/abc124_a:
There are two buttons, one of size A and one of size B.
When you press a button of size X, you get X coins and the size of that button decreases by 1.
You will press a button twice. Here, you can press the same button twice, or press both buttons once.
At most how many coins can you get?

-----Constraints-----
 - All values in input are integers.
 - 3 \leq A, B \leq 20

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Print the maximum number of coins you can get.

-----Sample Input-----
5 3

-----Sample Output-----
9

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

I tried it in Python, but could not do it. Can you solve it?

a,b = map(int,input().split())
if a == b:
  print(2*a)
elif a > b:
  print(2*a-1)
else:
  print(2*b-1)


I found an interesting problem on https://atcoder.jp/contests/abc124/tasks/abc124_b:
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-----
4
6 5 6 8

-----Sample Output-----
3

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

I tried it in Python, but could not do it. Can you solve it?

def main():
    sea = 1
    n = int(input())
    h = list(map(int, input().split()))
    mountain = h[0]
    for i in range(1, n):
        if mountain <= h[i]:
            sea += 1
            mountain = h[i]
    print(sea)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc124/tasks/abc124_c:
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-----
000

-----Sample Output-----
1

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

I tried it in Python, but could not do it. Can you solve it?

s=input()

start_0=0
start_1=0

for i,j in enumerate(s):
  if i%2==0 and j=="1":
    start_0+=1
  elif i%2!=0 and j=="0":
    start_0+=1
  elif i%2==0 and j=="0":
    start_1+=1
  elif i%2!=0 and j=="1":
    start_1+=1

print((min(start_0, start_1)))


I found an interesting problem on https://atcoder.jp/contests/abc124/tasks/abc124_d:
N people are arranged in a row from left to right.
You are given a string S of length N consisting of 0 and 1, and a positive integer K.
The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.
You will give the following direction at most K times (possibly zero):
Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.
Find the maximum possible number of consecutive people standing on hands after at most K directions.

-----Constraints-----
 - N is an integer satisfying 1 \leq N \leq 10^5.
 - K is an integer satisfying 1 \leq K \leq 10^5.
 - The length of the string S is N.
 - Each character of the string S is 0 or 1.

-----Input-----
Input is given from Standard Input in the following format:
N K
S

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

-----Sample Input-----
5 1
00010

-----Sample Output-----
4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:
 - Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

I tried it in Python, but could not do it. Can you solve it?

N, K = map(int, input().split())
S = input()

s = []
cnt = 1
for i in range(N-1):
    if S[i] == S[i+1]:
        cnt += 1
    else:
        s.append(cnt)
        cnt = 1
s.append(cnt)

ans = 0
if S[0] == '0':
    s = [0] + s
if S[-1] == '0':
    s = s + [0]

if 2*K + 1 > len(s):
    print(sum(s))
    return

s_cumsum = [s[0]] * len(s)
for i in range(1, len(s)):
    s_cumsum[i] = s_cumsum[i-1] + s[i]

for i in range(0, len(s), 2):
    if i + 2*K >= len(s):
        break
    if i < 1:
        ans = s_cumsum[i+2*K]
    ans = max(ans, s_cumsum[i+2*K]-s_cumsum[i-1])
    #ans = max(ans, sum(s[i:i+2*K+1]))

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc125/tasks/abc125_a:
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-----
3 5 7

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

a,b,t = map(int,input().split())
x = t // a
print(x * b)


I found an interesting problem on https://atcoder.jp/contests/abc125/tasks/abc125_b:
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-----
3
10 2 5
6 3 4

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
v = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
res = 0
for i in range(n):
    if v[i] > c[i]:
        res += v[i] - c[i]
print(res)


I found an interesting problem on https://atcoder.jp/contests/abc125/tasks/abc125_c:
There are N integers, A_1, A_2, ..., A_N, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.
Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 1 \leq A_i \leq 10^9

-----Output-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N

-----Output-----
Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

-----Sample Input-----
3
7 6 8

-----Sample Output-----
2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

I tried it in Python, but could not do it. Can you solve it?

# coding: UTF-8
import sys
import numpy as np
import math

n = int(input())
aList = list(map(int, input().split()))
gcdListLeft = [0 for i in range(n)]
gcdListRight = [0 for i in range(n)]

tmp = aList[0]
for i in range(n):
	tmp = gcdListLeft[i] = math.gcd(tmp, aList[i])

tmp = aList[n-1]
for i in range(n-1, -1, -1):
	tmp = gcdListRight[i] = math.gcd(tmp,aList[i])

ans = gcdListRight[1]
for i in range(1,n-1):
	ans = max(ans, math.gcd(gcdListLeft[i-1], gcdListRight[i+1]))
ans = max(ans, gcdListLeft[n-2])
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc125/tasks/abc125_d:
There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.
You can perform the following operation on this integer sequence any number of times:
Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.
Let B_1, B_2, ..., B_N be the integer sequence after your operations.
Find the maximum possible value of B_1 + B_2 + ... + B_N.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - -10^9 \leq A_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N

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

-----Sample Input-----
3
-10 5 -4

-----Sample Output-----
19

If we perform the operation as follows:
 - Choose 1 as i, which changes the sequence to 10, -5, -4.
 - Choose 2 as i, which changes the sequence to 10, 5, 4.
we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

I tried it in Python, but could not do it. Can you solve it?

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

a.sort()
minus = n
for i in range(n):
  if a[i] >= 0:
    minus = i
    break

a = list(map(abs, a))
a.sort()

if minus % 2 == 0:
  print((sum(a)))
else:
  print((sum(a) - 2 * a[0]))


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_a:
You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

-----Constraints-----
 - 1 ≤ N ≤ 50
 - 1 ≤ K ≤ N
 - S is a string of length N consisting of A, B and C.

-----Input-----
Input is given from Standard Input in the following format:
N K
S

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

-----Sample Input-----
3 1
ABC

-----Sample Output-----
aBC

I tried it in Python, but could not do it. Can you solve it?

n, k = map(int, input().split())
list01 = list(input())
list01[k - 1] = str.lower(list01[k - 1])
a = ''.join(list01)
print(a)


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_b:
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-----
1905

-----Sample Output-----
YYMM

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

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_c:
Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:
 - Throw the die. The current score is the result of the die.
 - As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.
 - The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.
You are given N and K. Find the probability that Snuke wins the game.

-----Constraints-----
 - 1 ≤ N ≤ 10^5
 - 1 ≤ K ≤ 10^5
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K

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

-----Sample Input-----
3 10

-----Sample Output-----
0.145833333333

 - If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.
 - If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.
 - If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.
Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

I tried it in Python, but could not do it. Can you solve it?

N, K = list(map(int, input().split()))
A = 1
ans = 0

while (A <= N):
  count = 0
  T = A
  while (T<K):
    T = T*2
    count += 1
  ans += float((1/N)*(1/2)**count)
  A += 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_d:
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-----
3
1 2 2
2 3 1

-----Sample Output-----
0
0
1

I tried it in Python, but could not do it. Can you solve it?

import sys
sys.setrecursionlimit(1<<30)

N = int(input())
def dfs(x):
    for y in Tree[x]:
        if Parent[x] != y:
            Parent[y] = x
            distance[y] += Web[min(x,y),max(x,y)]+distance[x]
            dfs(y)
Tree = [[] for i in range(N+1)]
Parent = [0]*(N+1)
Web = dict()
for i in range(N-1):
    a,b,w = map(int,input().split())
    Tree[a].append(b)
    Tree[b].append(a)
    Web[(min(a,b),max(a,b))] = w
distance = [0]*(N+1)
dfs(1)
for i in distance[1:]:
    if i%2 == 0:
        print(1)
    else:
        print(0)


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_e:
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.
Let A_i be the integer written on the i-th card.
Your objective is to guess A_1, A_2, ..., A_N correctly.
You know the following facts:
 - For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.
You are a magician and can use the following magic any number of times:
Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.
What is the minimum cost required to determine all of A_1, A_2, ..., A_N?
It is guaranteed that there is no contradiction in given input.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - 1 \leq X_i < Y_i \leq N
 - 1 \leq Z_i \leq 100
 - The pairs (X_i, Y_i) are distinct.
 - There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

-----Input-----
Input is given from Standard Input in the following format:
N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

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

-----Sample Input-----
3 1
1 2 1

-----Sample Output-----
2

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

I tried it in Python, but could not do it. Can you solve it?

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

(n, m), *q = [list(map(int, o.split())) for o in open(0)]
UF = UnionFind(n)
for x, y, _ in q:
    UF.union(x - 1, y - 1)
print(UF.group_count())


I found an interesting problem on https://atcoder.jp/contests/abc126/tasks/abc126_f:
Construct a sequence a = {a_1,\ a_2,\ ...,\ a_{2^{M + 1}}} of length 2^{M + 1} that satisfies the following conditions, if such a sequence exists.
 - Each integer between 0 and 2^M - 1 (inclusive) occurs twice in a.
 - For any i and j (i < j) such that a_i = a_j, the formula a_i \ xor \ a_{i + 1} \ xor \ ... \ xor \ a_j = K holds.
What is xor (bitwise exclusive or)?
The xor of integers c_1, c_2, ..., c_n is defined as follows:
 - When c_1 \ xor \ c_2 \ xor \ ... \ xor \ c_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 c_1, c_2, ...c_m whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.
For example, 3 \ xor \ 5 = 6. (If we write it in base two: 011 xor 101 = 110.)

-----Constraints-----
 - All values in input are integers.
 - 0 \leq M \leq 17
 - 0 \leq K \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
M K

-----Output-----
If there is no sequence a that satisfies the condition, print -1.
If there exists such a sequence a, print the elements of one such sequence a with spaces in between.
If there are multiple sequences that satisfies the condition, any of them will be accepted.

-----Sample Input-----
1 0

-----Sample Output-----
0 0 1 1

For this case, there are multiple sequences that satisfy the condition.
For example, when a = {0, 0, 1, 1}, there are two pairs (i,\ j)\ (i < j) such that a_i = a_j: (1, 2) and (3, 4). Since a_1 \ xor \ a_2 = 0 and a_3 \ xor \ a_4 = 0, this sequence a satisfies the condition.

I tried it in Python, but could not do it. Can you solve it?

import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

def debug(L, k):
    n = len(L)
    used = set()
    for i in range(n):
        if L[i] in used:
            continue
        used.add(L[i])
        t = L[i]
        for j in range(i + 1, n):
            t ^= L[j]
            if L[i] == L[j]:
                break
        if t != k:
            return False
    return True

def resolve():
    m, k = list(map(int, input().split()))

    MAX = pow(2, m)
    if MAX <= k or (m == 1 and k == 1):
        print((-1))
        return

    if m == 1 and k == 0:
        print("0 0 1 1")
        return

    res = []
    for i in range(MAX):
        if i == k:
            continue
        res.append(i)
    res.append(k)
    for i in reversed(list(range(MAX))):
        if i == k:
            continue
        res.append(i)
    res.append(k)
    print((*res))
    # print(debug(res, k))

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_a:
Takahashi, who is A years old, is riding a Ferris wheel.
It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)
Find the cost of the Ferris wheel for Takahashi.

-----Constraints-----
 - 0 ≤ A ≤ 100
 - 2 ≤ B ≤ 1000
 - B is an even number.

-----Input-----
Input is given from Standard Input in the following format:
A B

-----Output-----
Print the cost of the Ferris wheel for Takahashi.

-----Sample Input-----
30 100

-----Sample Output-----
100

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

I tried it in Python, but could not do it. Can you solve it?

rStr = input()

A = int(rStr.split(' ')[0])
B = int(rStr.split(' ')[1])

result = 0

if 13 <= A :
    result = B

elif A <= 5 :
    result = 0

else :
    result = int(B / 2)

print(result)


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_b:
The development of algae in a pond is as follows.
Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:
 - x_{i+1} = rx_i - D
You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

-----Constraints-----
 - 2 ≤ r ≤ 5
 - 1 ≤ D ≤ 100
 - D < x_{2000} ≤ 200
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
r D x_{2000}

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

-----Sample Input-----
2 10 20

-----Sample Output-----
30
50
90
170
330
650
1290
2570
5130
10250

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

I tried it in Python, but could not do it. Can you solve it?

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


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_c:
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-----
4 2
1 3
2 4

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

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

card=[0]*(N+2)
ans=[0]*(N+1)
for i in range(M):
	L,R=map(int, input().split())
	card[L]+=1
	card[R+1]-=1

cnt=0
for h in range(N+1):
	cnt+=card[h]
	ans[h]=str(cnt)

print(ans.count(str(M)))


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_d:
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-----
3 2
5 1 4
2 3
1 5

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

import sys, math
from functools import lru_cache
import datetime
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, M = mi()
    A = list(mi())
    A.sort()
    BC = [list(mi()) for i in range(M)]
    BC.sort(reverse=True, key=lambda x: x[1])

    D = []

    for i in range(M):
        for j in range(BC[i][0]):
            D.append(BC[i][1])
            if len(D) == N:
                break
        if len(D) == N:
            break

    while len(D) < N:
        D.append(0)

    print(sum(max(A[i], D[i]) for i in range(N)))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_e:
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.
If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:
\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)
Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.
We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.

-----Constraints-----
 - 2 \leq N \times M \leq 2 \times 10^5
 - 2 \leq K \leq N \times M
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M K

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

-----Sample Input-----
2 2 2

-----Sample Output-----
8

There are six possible arrangements of the pieces, as follows:
 - ((1,1),(1,2)), with the cost |1-1|+|1-2| = 1
 - ((1,1),(2,1)), with the cost |1-2|+|1-1| = 1
 - ((1,1),(2,2)), with the cost |1-2|+|1-2| = 2
 - ((1,2),(2,1)), with the cost |1-2|+|2-1| = 2
 - ((1,2),(2,2)), with the cost |1-2|+|2-2| = 1
 - ((2,1),(2,2)), with the cost |2-2|+|1-2| = 1
The sum of these costs is 8.

I tried it in Python, but could not do it. Can you solve it?

N, M, K = map(int, input().split())
mod = 10**9+7

def nCk(n, k, mod):
    nu = 1
    de = 1
    for i in range(1, k+1):
        nu *= (n-i+1)
        de *= i
        nu = nu % mod
        de = de % mod
    ans = nu * pow(de, mod-2, mod) % mod
    return ans

ans = nCk(N*M-2, K-2, mod)*N*M*(M+N)*(M*N-1)//6
ans = ans % mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_f:
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
 - An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
 - An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq Q \leq 2 \times 10^5
 - -10^9 \leq a, b \leq 10^9
 - The first query is an update query.

-----Input-----
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

-----Output-----
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

-----Sample Input-----
4
1 4 2
2
1 1 -8
2

-----Sample Output-----
4 2
1 -3

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

I tried it in Python, but could not do it. Can you solve it?

# -*- coding: utf-8 -*-
"""
Created on Tue May 28 22:22:21 2019

@author: Yamazaki Kenichi
"""
import heapq

Q = int(input())
Q2 = [input() for i in range(Q)]

ans = []
Al,Ar = [-(-(10**9+1))],[10**9+1]
d, a, b = list(map(int,Q2[0].split()))
heapq.heappush(Al,-a)
B = b

for i in range(1,Q):
    if Q2[i][0] == '1':
#        intput
        d, a, b = list(map(int,Q2[i].split()))
        if len(Al) == len(Ar):
            if a < Ar[0]:
                heapq.heappush(Al,-a)
            else:
                heapq.heappush(Ar,a)
                heapq.heappush(Al,-(heapq.heappop(Ar)))
            C = abs(a - (-Al[0]))
        else:
            C = abs(a - (-Al[0]))
            if a < Ar[0]:
                heapq.heappush(Al,-a)
                heapq.heappush(Ar,-(heapq.heappop(Al)))
            else:
                heapq.heappush(Ar,a)
        B += (b + C)
#        print(Al,Ar,a,B,b)
    else:
#        output
        ans.append([(-Al[0]),B])

for c in ans:
    print((' '.join(map(str,c))))


I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_a:
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 3

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_b:
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-----
6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

N = int(input())

my_list = []

for i in range(N):
    sp = input().split()
    sp[1] = int(sp[1])
    sp.insert(0, i+1)

    my_list.append(sp)

my_list.sort(key = lambda x: x[2], reverse=True)
my_list.sort(key = lambda x: x[1])

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


I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_c:
We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.
Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.
How many combinations of "on" and "off" states of the switches light all the bulbs?

-----Constraints-----
 - 1 \leq N, M \leq 10
 - 1 \leq k_i \leq N
 - 1 \leq s_{ij} \leq N
 - s_{ia} \neq s_{ib} (a \neq b)
 - p_i is 0 or 1.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

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

-----Sample Input-----
2 2
2 1 2
1 2
0 1

-----Sample Output-----
1

 - Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.
 - Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.
There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

I tried it in Python, but could not do it. Can you solve it?

# author:  Taichicchi
# created: 16.09.2020 23:07:07

import sys

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

k = []
s = []

for i in range(M):
    _k, *_s = list(map(int, input().split()))
    k.append(_k)
    s.append(_s)

p = list(map(int, input().split()))
ans = 0

for i in range(2 ** N):
    sw = [0 for _ in range(N)]
    for j in range(N):
        if i >> j & 1:
            sw[j] = 1

    for m in range(M):
        mod = 0
        for switch in s[m]:
            mod += sw[switch - 1]
        if mod % 2 != p[m]:
            break
    else:
        ans += 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_d:
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-----
6 4
-10 8 2 1 2 6

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

n, k = map(int, input().split())
V = list(map(int, input().split()))

ans = - 10 ** 19
# i: Dから取り出す宝石の個数
for i in range(min(k + 1, n + 1)):
  # j: 左からとる個数(i-jが右からとる個数)
  for j in range(i + 1):
    inhands = V[:j] + V[n - i + j:]
    inhands.sort()
    remnum = k - i
    val = 0
    for h in inhands:
      if h < 0 and remnum > 0:
        remnum -= 1
      else:
        val += h
    ans = max(ans, val)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_f:
There is an infinitely large pond, which we consider as a number line.
In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1.
On the lotus at coordinate i, an integer s_i is written.
You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:
 - 1. Choose positive integers A and B. Your score is initially 0.
 - 2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.
 - If y = N-1, the game ends.
 - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.
 - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.
 - 3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.
 - If y = N-1, the game ends.
 - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.
 - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.
 - 4. Go back to step 2.
You want to end the game with as high a score as possible.
What is the score obtained by the optimal choice of A and B?

-----Constraints-----
 - 3 \leq N \leq 10^5
 - -10^9 \leq s_i \leq 10^9
 - s_0=s_{N-1}=0
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
s_0 s_1 ...... s_{N-1}

-----Output-----
Print the score obtained by the optimal choice of A and B.

-----Sample Input-----
5
0 2 5 1 0

-----Sample Output-----
3

If you choose A = 3 and B = 2, the game proceeds as follows:
 - Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1.
 - Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2.
 - Move to coordinate 1 + 3 = 4. The game ends with a score of 3.
There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2...

I tried it in Python, but could not do it. Can you solve it?

def cumsum(itr):
    arr = []
    val = 0
    for x in itr:
        val += x
        arr.append(val)
    return arr

def main(N, scores):
    M = N - 1

    def max_score(d):
        steps = (scores[i] + scores[-i - 1] for i in range(0, M - d, d))
        cum_scores = cumsum(steps)

        if M % d > 0:
            return max(cum_scores)
        else:
            k = M // d + 1
            return max(cum_scores[: k // 2])

    corner_case = scores[0] + scores[M]
    otherwise = max(max_score(d) for d in range(1, M))
    return max(corner_case, otherwise)

N = int(input())
scores = [int(a) for a in input().split()]
result = main(N, scores)

print(result)


I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_a:
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 3 4

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

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

ans = a + b
if a + c < ans:
  ans = a + c
if b + c < ans:
  ans = b + c

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_b:
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-----
3
1 2 3

-----Sample Output-----
0

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

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a = [int(num) for num in input().split()]
min_i = 100000
for i in range(n):
    if abs(sum(a[0:i+1])-sum(a[i+1:n])) < min_i:
        min_i = abs(sum(a[0:i+1])-sum(a[i+1:n]))
print(min_i)


I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_c:
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-----
6 1
3

-----Sample Output-----
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

I tried it in Python, but could not do it. Can you solve it?

#import math
#import itertools
#import numpy as np
#from collections import deque
# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
#INF = 10 ** 9
#PI = 3.14159265358979323846

INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def do():
    n,m=INTM()
    b_sts=[False]*n
    for i in range(m):
        b=INT()
        b-=1
        b_sts[b]=True

    step=[0]*(n+2)
    step[1]=1
    for i in range(n):
        if b_sts[i]:
            continue
        else:
            step[i+2]=(step[i+1]+step[i])%MOD
    print(step[-1]%MOD)

def __starting_point():
    do()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc129/tasks/abc129_d:
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-----
4 6
#..#..
.....#
....#.
#.#...

-----Sample Output-----
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.

I tried it in Python, but could not do it. Can you solve it?

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

H,W = list(map(int,input().split()))
S=np.array([list(input().rstrip("\n")) for _ in range(H)]) == '.'

D = np.zeros((H,W),dtype=int)
U = np.zeros((H,W),dtype=int)
L = np.zeros((H,W),dtype=int)
R = np.zeros((H,W),dtype=int)

# 上下
for i in range(H):
  U[i] = (U[i-1] + 1) * S[i]
  D[-i-1] = (D[-i] + 1) * S[-i-1]

# 左右
for i in range(W):
  L[:,i] = (L[:,i-1] + 1) * S[:,i]
  R[:,-i-1] = (R[:,-i] + 1) * S[:,-i-1]

print((np.max(U+D+L+R)-3))