I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_c:
We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).
There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

-----Notes-----
For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

-----Constraints-----
 - 2 \leq N \leq 8
 - P and Q are permutations of size N.

-----Input-----
Input is given from Standard Input in the following format:
N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

-----Output-----
Print |a - b|.

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

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

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

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

import itertools
N = int(input())
perm = [ x for x in itertools.permutations(range(1, N + 1)) ]
P = tuple(map(int, input().split(' ')))
Q = tuple(map(int, input().split(' ')))
a = [ idx for idx, val in enumerate(perm) if val == P ][0] + 1
b = [ idx for idx, val in enumerate(perm) if val == Q ][0] + 1
print(abs(a - b))


I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_d:
Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.
Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):
 - There exists a non-negative integer p such that X= a_k \times (p+0.5).
Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq 10^9
 - 2 \leq a_i \leq 10^9
 - a_i is an even number.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
a_1 a_2 ... a_N

-----Output-----
Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

-----Sample Input-----
2 50
6 10

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

 - 15 = 6  \times 2.5
 - 15 = 10 \times 1.5
 - 45 = 6  \times 7.5
 - 45 = 10 \times 4.5
Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

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

import math
from functools import reduce

N,M=list(map(int,input().split()))
A=[int(x)//2 for x in input().split()]

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

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

LCM=lcm(*A)
for a in A:
  if LCM//a%2==0:
    print((0))
    break
else:
  print(((M//LCM+1)//2))


I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_e:
For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows:
 - Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations.
 - Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \times C_i, where D is the number of integers j such that S_j \neq T_j (1 \leq j \leq N) just before this change.
There are 2^N \times (2^N - 1) pairs (S, T) of different sequences of length N consisting of 0 and 1. Compute the sum of f(S, T) over all of those pairs, modulo (10^9+7).

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

-----Input-----
Input is given from Standard Input in the following format:
N
C_1 C_2 \cdots C_N

-----Output-----
Print the sum of f(S, T), modulo (10^9+7).

-----Sample Input-----
1
1000000000

-----Sample Output-----
999999993

There are two pairs (S, T) of different sequences of length 2 consisting of 0 and 1, as follows:
 - S = (0), T = (1): by changing S_1 to 1, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000.
 - S = (1), T = (0): by changing S_1 to 0, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000.
The sum of these is 2000000000, and we should print it modulo (10^9+7), that is, 999999993.

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

def main():
    n=int(input())
    c=sorted(list(map(int,input().split())))
    mod=10**9+7
    ans=0
    for i,j in enumerate(c):
        ans=(ans+j*(n-i+1))%mod

    ans=(ans*4**(n-1))%mod
    print(ans)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_f:
Given are two sequences a=\{a_0,\ldots,a_{N-1}\} and b=\{b_0,\ldots,b_{N-1}\} of N non-negative integers each.
Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\{a_0',\ldots,a_{N-1}'\}, as follows:
 - a_i'= a_{i+k \mod N}\ XOR \ x
Find all pairs (k,x) such that a' will be equal to b.What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

 - When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.
For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 0 \leq a_i,b_i < 2^{30}
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{N-1}

-----Output-----
Print all pairs (k, x) such that a' and b will be equal, using one line for each pair, in ascending order of k (ascending order of x for pairs with the same k).
If there are no such pairs, the output should be empty.

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

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

If (k,x)=(1,3),
 - a_0'=(a_1\ XOR \ 3)=1
 - a_1'=(a_2\ XOR \ 3)=2
 - a_2'=(a_0\ XOR \ 3)=3
and we have a' = b.

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

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

A.append(A[0])
B.append(B[0])

AX=[]
BX=[]
for i in range(N):
    AX.append(A[i]^A[i+1])
    BX.append(B[i]^B[i+1])

AX+=AX[:-1]

# MP法

LEN=len(BX)
MP=[-1]*(LEN+1) #「接頭辞と接尾辞が最大何文字一致しているか」を記録する配列
NOW=-1 # 何文字一致しているか.

for i in range(LEN):
    while NOW>=0 and BX[i]!=BX[NOW]: # 一致していなかったら0から数え直すのではなく, MP[NOW]から数える.
        NOW=MP[NOW]
    NOW+=1
    MP[i+1]=NOW

LEN2=len(AX)

MP_SEARCH=[0]*(LEN2) # その文字までで何個一致しているかを調べる. LEN文字一致したらSが検出できたということ.
NOW=0
for i in range(LEN2):
    while NOW>=0 and AX[i]!=BX[NOW]:
        NOW=MP[NOW]
    NOW+=1
    MP_SEARCH[i]=NOW

    if NOW==LEN: # LEN文字一致したら, MP[LEN]から数える.
        NOW=MP[NOW]

for i in range(LEN2):
    if MP_SEARCH[i]==LEN:
        print(i-LEN+1,A[i-LEN+1]^B[0])


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_a:
Given is a lowercase English letter C that is not z. Print the letter that follows C in alphabetical order.

-----Constraints-----
 - C is a lowercase English letter that is not z.

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

-----Output-----
Print the letter that follows C in alphabetical order.

-----Sample Input-----
a

-----Sample Output-----
b

a is followed by b.

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


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_b:
Takahashi is taking exams on N subjects. The score on each subject will be an integer between 0 and K (inclusive).
He has already taken exams on N-1 subjects and scored A_i points on the i-th subject.
His goal is to achieve the average score of M points or above on the N subjects.
Print the minimum number of points Takahashi needs on the final subject to achieve his goal.
If the goal is unachievable, print -1 instead.

-----Constraints-----
 - 2 \leq N \leq 100
 - 1 \leq K \leq 100
 - 1 \leq M \leq K
 - 0 \leq A_i \leq K
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K M
A_1 A_2 ... A_{N-1}

-----Output-----
Print the minimum number of points required on the final subject, or -1.

-----Sample Input-----
5 10 7
8 10 3 6

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

If he scores 8 points on the final subject, his average score will be (8+10+3+6+8)/5 = 7 points, which meets the goal.

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

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

class Achieve:
    def __init__(self,subjects,points,goal):
        self.subjects = subjects
        self.points = points
        self.goal = goal

    def calculation(self):
        ans = self.subjects * self.goal - total_score
        if ans > self.points:
            return ("-1")
        if ans < 0:
            return (0)
        else:
            return (ans)

takahasi = Achieve(N,K,M)
print(takahasi.calculation())


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_c:
Takahashi participated in a contest on AtCoder.
The contest had N problems.
Takahashi made M submissions during the contest.
The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).
The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.
The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.
Find the numbers of Takahashi's correct answers and penalties.

-----Constraints-----
 - N, M, and p_i are integers.
 - 1 \leq N \leq 10^5
 - 0 \leq M \leq 10^5
 - 1 \leq p_i \leq N
 - S_i is AC or WA.

-----Input-----
Input is given from Standard Input in the following format:
N M
p_1 S_1
:
p_M S_M

-----Output-----
Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

-----Sample Input-----
2 5
1 WA
1 AC
2 WA
2 AC
2 WA

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

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.
In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.
Thus, he has two correct answers and two penalties.

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

n, m = map(int, input().split())
d = [0] * (n+1)
ac = 0
wa = 0
for i in range(m):
  p, s = input().split()
  p = int(p)
  if d[p] == -1:
    continue
  elif s == "AC":
    ac += 1
    wa += d[p]
    d[p] = -1
  else:
    d[p] += 1
print(ac, wa)


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_d:
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..
From a road square, you can move to a horizontally or vertically adjacent road square.
You cannot move out of the maze, move to a wall square, or move diagonally.
Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.
Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.
In this situation, find the maximum possible number of moves Aoki has to make.

-----Constraints-----
 - 1 \leq H,W \leq 20
 - S_{ij} is . or #.
 - S contains at least two occurrences of ..
 - Any road square can be reached from any road square in zero or more moves.

-----Input-----
Input is given from Standard Input in the following format:
H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

-----Output-----
Print the maximum possible number of moves Aoki has to make.

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

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

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

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

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

from collections import deque
def bfs(h,w,sy,sx,S):
    maze=[[10**9]*(W)for _ in range(H)]
    maze[sy-1][sx-1]=0
    que=deque([[sy-1,sx-1]])
    count=0
    while que:
        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if 0<=nexty<h and 0<=nextx<w:
                dist1=S[nexty][nextx]
                dist2=maze[nexty][nextx]
            else:
                continue
            if dist1!='#':
                if dist2>maze[y][x]+1:
                    maze[nexty][nextx]=maze[y][x]+1
                    count=max(count,maze[nexty][nextx])
                    que.append([nexty,nextx])
    return count

ans=0
for sy in range(H):
    for sx in range(W):
        if S[sy][sx]=='.':
            now=bfs(H,W,sy+1,sx+1,S)
            ans=max(ans,now)

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_e:
For a finite set of integers X, let f(X)=\max X - \min X.
Given are N integers A_1,...,A_N.
We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways.
Since the answer can be enormous, print it \bmod (10^9+7).

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq K \leq N
 - |A_i| \leq 10^9

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

-----Output-----
Print the answer \bmod (10^9+7).

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

-----Sample Output-----
11

There are six ways to choose S: \{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\} (we distinguish the two 1s). The value of f(S) for these choices are 0,2,3,2,3,1, respectively, for the total of 11.

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

from collections import defaultdict
MOD = 10**9+7
n, K = list(map(int, input().split()))
A = list(map(int, input().split()))
cnt = defaultdict(int)
for a in A:
    cnt[a] += 1

keys = sorted(cnt.keys())
key_to_idx = defaultdict(int)
for i, k in enumerate(keys):
    key_to_idx[k] = i

Acum = [0]
for k in keys:
    Acum.append(Acum[-1]+cnt[k])

U = n
fact = [0]*(U+1)
fact[0] = 1
for i in range(1, U+1):
    fact[i] = fact[i-1]*i % MOD

invfact = [0]*(U+1)
invfact[U] = pow(fact[U], MOD-2, MOD)
for i in reversed(list(range(U))):
    invfact[i] = invfact[i+1]*(i+1) % MOD

def nCr(n, r):
    if r < 0 or n < r:
        return 0
    return fact[n]*invfact[r]*invfact[n-r]

MAX = 0
for k in reversed(keys):
    x = Acum[key_to_idx[k]+1]
    y = Acum[key_to_idx[k]]
    c = nCr(x, K) - nCr(y, K)
    MAX += c*k
    MAX %= MOD

MIN = 0
for k in keys:
    x = n-Acum[key_to_idx[k]]
    y = n-Acum[key_to_idx[k]+1]
    c = nCr(x, K) - nCr(y, K)
    MIN += c*k
    MIN %= MOD

print(((MAX-MIN) % MOD))


I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_f:
Given are N points (x_i, y_i) in a two-dimensional plane.
Find the minimum radius of a circle such that all the points are inside or on it.

-----Constraints-----
 - 2 \leq N \leq 50
 - 0 \leq x_i \leq 1000
 - 0 \leq y_i \leq 1000
 - The given N points are all different.
 - The values in input are all integers.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N

-----Output-----
Print the minimum radius of a circle such that all the N points are inside or on it.
Your output will be considered correct if the absolute or relative error from our answer is at most 10^{-6}.

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

-----Sample Output-----
0.500000000000000000

Both points are contained in the circle centered at (0.5,0) with a radius of 0.5.

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

from fractions import Fraction
from math import sqrt

n = int(input())
p = []

for i in range(n):
    p.append(list(map(int, input().split())))

ans = 0

for i in range(n-1):
    for j in range(i+1,n):
        flag = True
        x1,y1 = p[i][0],p[i][1]
        x2,y2 = p[j][0],p[j][1]
        d = (x2 - x1)**2 + (y2 - y1)**2
        for k in range(n):
            if (i == k or j == k):
                continue
            x3,y3 = p[k][0],p[k][1]
            e = (x3-x1)**2 + (y3-y1)**2 + (x3-x2)**2 + (y3-y2)**2
            if (d < e):
                flag = False
                break
        if flag:
            ans = sqrt(d)/2.0

if (ans != 0):
    print(ans)
    return

ans = 100000000

for i in range(n-2):
    for j in range(i+1,n-1):
        for k in range(j+1,n):
            a,b = p[i][0],p[i][1]
            c,d = p[j][0],p[j][1]
            e,f = p[k][0],p[k][1]
            if ((a == c == e) or (b == d == f)):
                continue
            ny = (e-a) * (a*a + b*b - c*c - d*d) - (c-a) * (a*a + b*b - e*e - f*f)
            dy = 2 * (e-a) * (b-d) - 2 * (c-a) * (b-f)
            if (dy == 0):
                continue
            py = Fraction(ny,dy)
            if (c != a):
                px = 2*(b-d) * py - a*a - b*b + c*c + d*d
                px /= 2*(c-a)
            else:
                px = 2*(b-f) * py - a*a - b*b + e*e + f*f
                px /= 2*(e-a)
            r = (c-px)**2 + (d-py)**2
            flag = True
            for l in range(n):
                if (l == i or l == j or l == k):
                    continue
                x,y = p[l][0],p[l][1]
                s = (x-px)**2 + (y-py)**2
                if (r < s):
                    flag = False
                    break
            if (flag):
                q = r.numerator / r.denominator
                q = sqrt(q)
                ans = min(ans,q)

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_a:
Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.

The problem has N test cases, all of which must be passed to get an AC verdict.

Takahashi's submission has passed M cases out of the N test cases.

Determine whether Takahashi's submission gets an AC.

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

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

-----Output-----
If Takahashi's submission gets an AC, print Yes; otherwise, print No.

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

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

All three test cases have been passed, so his submission gets an AC.

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

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

if N == M: print('Yes')
else: print('No')


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_b:
Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

-----Constraints-----
 - 1 \leq a \leq 9
 - 1 \leq b \leq 9
 - a and b are integers.

-----Input-----
Input is given from Standard Input in the following format:
a b

-----Output-----
Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

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

-----Sample Output-----
3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

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

a, b = map(int, input().split())
if a > b:
  print(str(b) * a)
elif a < b:
  print(str(a) * b)
else:
  print(str(a) * a)


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_c:
Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:
 - For any integer j (1 \leq j \leq i), P_i \leq P_j.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - P_1, \ldots, P_N is a permutation of 1, \ldots, N.
 - All values in input are integers.

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

-----Output-----
Print the number of integers i that satisfy the condition.

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

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

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

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

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

ans = 0
check = 10**9 + 7

for i in range(N):
    if check > P[i]:
        ans += 1
        check = P[i]

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_d:
Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:
 - When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

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

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

-----Output-----
Print the answer.

-----Sample Input-----
25

-----Sample Output-----
17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

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

#!/usr/bin/env python3
def main():
    import numpy as np

    N = int(input())

    cnt = np.zeros((10, 10), dtype=np.int64)
    for n in [str(x) for x in range(1, N + 1)]:
        cnt[int(n[0])][int(n[-1])] += 1

    print(((cnt[:, :] * cnt.T[:, :]).sum()))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_e:
Given are N positive integers A_1,...,A_N.
Consider positive integers B_1, ..., B_N that satisfy the following condition.
Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.
Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.
Since the answer can be enormous, print the sum modulo (10^9 +7).

-----Constraints-----
 - 1 \leq N \leq 10^4
 - 1 \leq A_i \leq 10^6
 - All values in input are integers.

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

-----Output-----
Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

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

-----Sample Output-----
13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

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

# エラトステネスの篩, フェルマーの小定理
max_A = 1000000

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

m = 1000000007

sieve = [0] * (max_A + 1)
sieve[0] = -1
sieve[1] = -1
for i in range(2, max_A + 1):
    if sieve[i] != 0:
        continue
    sieve[i] = i
    for j in range(i * i, max_A + 1, i):
        if sieve[j] == 0:
            sieve[j] = i

lcm_factors = {}
for i in range(N):
    t = []
    a = A[i]
    while a != 1:
        if len(t) != 0 and t[-1][0] == sieve[a]:
            t[-1][1] += 1
        else:
            t.append([sieve[a], 1])
        a //= sieve[a]
    for k, v in t:
        if k not in lcm_factors or lcm_factors[k] < v:
            lcm_factors[k] = v

lcm = 1
for k in lcm_factors:
    for i in range(lcm_factors[k]):
        lcm *= k
        lcm %= m

result = 0
for i in range(N):
    result += lcm * pow(A[i], m - 2, m)
    result %= m
print(result)


I found an interesting problem on https://atcoder.jp/contests/abc152/tasks/abc152_f:
We have a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i.

Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?
 - The i-th (1 \leq i \leq M) restriction is represented by two integers u_i and v_i, which mean that the path connecting Vertex u_i and Vertex v_i must contain at least one edge painted black.

-----Constraints-----
 - 2 \leq N \leq 50
 - 1 \leq a_i,b_i \leq N
 - The graph given in input is a tree.
 - 1 \leq M \leq \min(20,\frac{N(N-1)}{2})
 - 1 \leq u_i < v_i \leq N
 - If i \not= j, either u_i \not=u_j or v_i\not=v_j
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
M
u_1 v_1
:
u_M v_M

-----Output-----
Print the number of ways to paint the edges that satisfy all of the M conditions.

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

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

The tree in this input is shown below:

All of the M restrictions will be satisfied if Edge 1 and 2 are respectively painted (white, black), (black, white), or (black, black), so the answer is 3.

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

# 多分TLE
from scipy.sparse.csgraph import dijkstra
from itertools import combinations

N = int(input())
edge_id = {}
D = [[-float('inf')]*N for i in range(N)]
for i in range(N-1):
  a, b = map(int, input().split())
  D[a-1][b-1] = D[b-1][a-1] = 1
  edge_id[(a-1, b-1)] = i
  edge_id[(b-1, a-1)] = i

paths = dijkstra(D, return_predecessors=True)[1]
M = int(input())
edges = [0] * M
for i in range(M):
  u, v = map(int, input().split())
  now, p = paths[u-1][v-1], v-1
  edges[i] += 1 << edge_id[(now, p)]
  while now != u-1:
    now, p = paths[u-1][now], now
    edges[i] += 1 << edge_id[(now, p)]

ans = pow(2, N-1)
coeff = -1
for m in range(1, M+1):
  for comb in combinations(edges, m):
    e = 0
    for c in comb:
      e |= c
    ans +=  coeff* pow(2, N-1-bin(e).count('1'))
  coeff *= -1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_a:
Serval is fighting with a monster.
The health of the monster is H.
In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.
Serval wins when the monster's health becomes 0 or below.
Find the number of attacks Serval needs to make before winning.

-----Constraints-----
 - 1 \leq H \leq 10^4
 - 1 \leq A \leq 10^4
 - All values in input are integers.

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

-----Output-----
Print the number of attacks Serval needs to make before winning.

-----Sample Input-----
10 4

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

 - After one attack, the monster's health will be 6.
 - After two attacks, the monster's health will be 2.
 - After three attacks, the monster's health will be -2.
Thus, Serval needs to make three attacks to win.

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

from math import ceil

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

n = ceil(h/a)
print(n)


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_b:
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i.
There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

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

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

-----Output-----
If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

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

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

The monster's health will become 0 or below after, for example, using the second and third moves.

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

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

if sum(A) - H >= 0:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_c:
Fennec is fighting with N monsters.
The health of the i-th monster is H_i.
Fennec can do the following two actions:
 - Attack: Fennec chooses one monster. That monster's health will decrease by 1.
 - Special Move: Fennec chooses one monster. That monster's health will become 0.
There is no way other than Attack and Special Move to decrease the monsters' health.
Fennec wins when all the monsters' healths become 0 or below.
Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 0 \leq K \leq 2 \times 10^5
 - 1 \leq H_i \leq 10^9
 - All values in input are integers.

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

-----Output-----
Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

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

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

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

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

N,K = map(int,input().split())
H = list(map(int,input().split()))
H.sort(reverse=True)
H = H[K:]
print(sum(H))


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_d:
Caracal is fighting with a monster.
The health of the monster is H.
Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:
 - If the monster's health is 1, it drops to 0.
 - If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.
(\lfloor r \rfloor denotes the greatest integer not exceeding r.)
Caracal wins when the healths of all existing monsters become 0 or below.
Find the minimum number of attacks Caracal needs to make before winning.

-----Constraints-----
 - 1 \leq H \leq 10^{12}
 - All values in input are integers.

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

-----Output-----
Find the minimum number of attacks Caracal needs to make before winning.

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

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

When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.
Then, Caracal can attack each of these new monsters once and win with a total of three attacks.

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

def mons(hp):
    if hp == 1:
        return 1
    else:
        return mons(hp//2)*2 + 1

print((mons(int(input()))))


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_e:
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.

-----Constraints-----
 - 1 \leq H \leq 10^4
 - 1 \leq N \leq 10^3
 - 1 \leq A_i \leq 10^4
 - 1 \leq B_i \leq 10^4
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N

-----Output-----
Print the minimum total Magic Points that have to be consumed before winning.

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

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

First, let us cast the first spell to decrease the monster's health by 8, at the cost of 3 Magic Points. The monster's health is now 1.
Then, cast the third spell to decrease the monster's health by 2, at the cost of 1 Magic Point. The monster's health is now -1.
In this way, we can win at the total cost of 4 Magic Points.

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

import numpy as np
from numba import njit, i8

@njit(i8(i8, i8[:], i8[:]), cache=True)
def solve(H, A, B):
    A_max = A.max()
    dp = np.zeros(H + A_max + 1, dtype=np.int64)
    for i in range(A_max + 1, H + A_max + 1):
        dp[i] = np.min(dp[i - A] + B)
    return dp[-1]

H, N, *AB = list(map(int, open(0).read().split()))
A = np.array(AB[::2], dtype=np.int64)
B = np.array(AB[1::2], dtype=np.int64)
print((solve(H, A, B)))


I found an interesting problem on https://atcoder.jp/contests/abc153/tasks/abc153_f:
Silver Fox is fighting with N monsters.
The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i.
Silver Fox can use bombs to attack the monsters.
Using a bomb at the coordinate x decreases the healths of all monsters between the coordinates x-D and x+D (inclusive) by A.
There is no way other than bombs to decrease the monster's health.
Silver Fox wins when all the monsters' healths become 0 or below.
Find the minimum number of bombs needed to win.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 0 \leq D \leq 10^9
 - 1 \leq A \leq 10^9
 - 0 \leq X_i \leq 10^9
 - 1 \leq H_i \leq 10^9
 - X_i are distinct.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N D A
X_1 H_1
:
X_N H_N

-----Output-----
Print the minimum number of bombs needed to win.

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

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

First, let us use a bomb at the coordinate 4 to decrease the first and second monsters' health by 2.
Then, use a bomb at the coordinate 6 to decrease the second and third monsters' health by 2.
Now, all the monsters' healths are 0.
We cannot make all the monsters' health drop to 0 or below with just one bomb.

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

import math
import sys
from collections import deque

def input():
    return sys.stdin.readline().strip()

sys.setrecursionlimit(20000000)

MOD = 10 ** 9 + 7
INF = float("inf")

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

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

    attack = []
    for i in range(N):
        attack.append(math.ceil(monster[i][1] / A))

    acc_damage = 0
    attacked = deque([])
    answer = 0

    for i in range(N):
        x = monster[i][0]
        h = attack[i]

        while attacked and x > attacked[0][0]:
            limit, damage = attacked.popleft()
            acc_damage -= damage

        need = max(0, h - acc_damage)
        answer += need

        acc_damage += need

        if need:
            attacked.append((x + 2 * D, need))

    print(answer)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_a:
We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

-----Constraints-----
 - S, T, and U are strings consisting of lowercase English letters.
 - The lengths of S and T are each between 1 and 10 (inclusive).
 - S \not= T
 - S=U or T=U.
 - 1 \leq A,B \leq 10
 - A and B are integers.

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

-----Output-----
Print the answer, with space in between.

-----Sample Input-----
red blue
3 4
red

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

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

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

import sys
s,t =input().split()
a,b = map(int, input().split())
u=input()
if u==s:
    print(a-1,b)
if u==t:
    print(a,b-1)


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_b:
Given is a string S. Replace every character in S with x and print the result.

-----Constraints-----
 - S is a string consisting of lowercase English letters.
 - The length of S is between 1 and 100 (inclusive).

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

-----Output-----
Replace every character in S with x and print the result.

-----Sample Input-----
sardine

-----Sample Output-----
xxxxxxx

Replacing every character in S with x results in xxxxxxx.

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


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_c:
Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

-----Constraints-----
 - 2 ≤ N ≤ 200000
 - 1 ≤ A_i ≤ 10^9
 - All values in input are integers.

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

-----Output-----
If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

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

-----Sample Output-----
YES

The elements are pairwise distinct.

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

n = int(input())
nums = input().split(' ')
nums = [int(x) for x in nums]
s = set()
b = False
for x in nums:
  if x in s:
    print("NO")
    b = True
    break
  s.add(x)
if not b:
  print("YES")


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_d:
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.
We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

-----Constraints-----
 - 1 ≤ K ≤ N ≤ 200000
 - 1 ≤ p_i ≤ 1000
 - All values in input are integers.

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

-----Output-----
Print the maximum possible value of the expected value of the sum of the numbers shown.
Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.

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

-----Sample Output-----
7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.

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

n,k = map(int, input().split())
p = list(map(lambda x: (int(x)+1)/2, input().split()))

t = sum(p[:k])
ans = t
for i in range(k,n):
  t += p[i] - p[i-k]
  if ans < t: ans = t
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_e:
Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

-----Constraints-----
 - 1 \leq N < 10^{100}
 - 1 \leq K \leq 3

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

-----Output-----
Print the count.

-----Sample Input-----
100
1

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

The following 19 integers satisfy the condition:
 - 1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100

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

def main():
    n = input()
    non_zero = int(input())
    length = len(n)
    dp = [[[0, 0] for _ in range(non_zero + 1)] for _ in range(length + 1)]
    dp[0][0][0] = 1
    for i in range(length):
        for j in range(non_zero + 1):
            for k in range(2):
                now_digit = int(n[i])
                for next_d in range(10):
                    new_i = i + 1
                    new_j = j
                    new_k = k
                    if next_d > 0:
                        new_j += 1
                    if new_j > non_zero:
                        continue
                    if k == 0:
                        if next_d > now_digit:
                            continue
                        elif next_d < now_digit:
                            new_k = 1
                    dp[new_i][new_j][new_k] += dp[i][j][k]
    print((sum(dp[length][non_zero])))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_f:
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.
Let us define a function f(r, c) as follows:
 - f(r,c) :=  (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operation above)
Given are integers r_1, r_2, c_1, and c_2.
Find the sum of f(i, j) over all pair of integers (i, j) such that r_1 ≤ i ≤ r_2 and c_1 ≤ j ≤ c_2, and compute this value modulo (10^9+7).

-----Constraints-----
 - 1 ≤ r_1 ≤ r_2 ≤ 10^6
 - 1 ≤ c_1 ≤ c_2 ≤ 10^6
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
r_1 c_1 r_2 c_2

-----Output-----
Print the sum of f(i, j) modulo (10^9+7).

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

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

For example, there are two paths from the point (0, 0) to the point (1, 1): (0,0) → (0,1) → (1,1) and (0,0) → (1,0) → (1,1), so f(1,1)=2.
Similarly, f(1,2)=3, f(2,1)=3, and f(2,2)=6. Thus, the sum is 14.

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


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_a:
A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.
You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

-----Constraints-----
 - A, B, and C are all integers between 1 and 9 (inclusive).

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

-----Output-----
If the given triple is poor, print Yes; otherwise, print No.

-----Sample Input-----
5 7 5

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

A and C are equal, but B is different from those two numbers, so this triple is poor.

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

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

if (A == B == C) or ( A != B and A != C and B != C):
    print('No')
else:
    print('Yes')


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_b:
You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.
According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:
 - All even numbers written on the document are divisible by 3 or 5.
If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

-----Notes-----
 - The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 100
 - 1 \leq A_i \leq 1000

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

-----Output-----
If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

-----Sample Input-----
5
6 7 9 10 31

-----Sample Output-----
APPROVED

The even numbers written on the document are 6 and 10.
All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

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

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

for i in range(0,n):
    if a[i]%2==0:
        if a[i]%3==0 or a[i]%5==0:
            b+=1
        else:
            b-=1000

if b>=0:
    print("APPROVED")
else:
    print("DENIED")


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_c:
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.
Print all strings that are written on the most number of votes, in lexicographical order.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.
 - The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

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

-----Output-----
Print all strings in question in lexicographical order.

-----Sample Input-----
7
beat
vet
beet
bed
vet
bet
beet

-----Sample Output-----
beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

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

n = int(input())
s = [input() for _ in range(n)]
count = {}

for word in s:
    if word not in count:
        count[word] = 1
    else:
        count[word] += 1

max_count = max(list(count.values()))
ans = []
for item in count.items():
    (key, value) = item
    if value == max_count:
        ans.append(key)

ans = sorted(ans)
for w in ans:
    print(w)


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_d:
We have N integers A_1, A_2, ..., A_N.
There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq K \leq \frac{N(N-1)}{2}
 - -10^9 \leq A_i \leq 10^9\ (1 \leq i \leq N)

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

-----Output-----
Print the answer.

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

-----Sample Output-----
-6

There are six ways to form a pair. The products of those pairs are 9, -12, -6, -12, -6, 8.
Sorting those numbers in ascending order, we have -12, -12, -6, -6, 8, 9. The third number in this list is -6.

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

# D - Pairs

import numpy as np

N, K = map(int, input().split())
A = np.array(sorted(list(map(int, input().split()))), np.int64)

n_zero = len(A[A == 0])
A_posi = A[A > 0]
A_nega = A[A < 0]

def n_pairs_less_than_or_equal_to_border(product_border):
    n_pairs = -np.sum(A*A <= product_border) # i==jかつ条件を満たすペアの個数を先に引き、以降重複を許して数える
    n_pairs += n_zero * N * (product_border >= 0)

    n_pairs += np.searchsorted(A, product_border//A_posi, side="right").sum()
    n_pairs += (N - np.searchsorted(A, -(-product_border//A_nega), side="left")).sum()

    # 上記2行は下記と同様の処理だが下記の実装だとTLE
    # for i in range(N):
    #     if A[i] > 0:
    #         n_pairs += np.searchsorted(A, product_border//A[i], side="right")
    #     elif A[i] < 0:
    #         n_pairs += N - np.searchsorted(A, -(-product_border//A[i]), side="left")

    n_pairs //= 2
    return n_pairs

lower = -(10**18)
upper = 10**18

while lower <= upper:
    x = (lower + upper) // 2
    if n_pairs_less_than_or_equal_to_border(x) >= K:
        ans = x
        upper = x - 1
    else:
        lower = x + 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_e:
In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}. You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.)
To make the payment, you will choose some amount of money which is at least N and give it to the clerk. Then, the clerk gives you back the change, which is the amount of money you give minus N.
What will be the minimum possible number of total banknotes used by you and the clerk, when both choose the combination of banknotes to minimize this count?
Assume that you have sufficient numbers of banknotes, and so does the clerk.

-----Constraints-----
 - N is an integer between 1 and 10^{1,000,000} (inclusive).

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

-----Output-----
Print the minimum possible number of total banknotes used by you and the clerk.

-----Sample Input-----
36

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

If you give four banknotes of value 10 each, and the clerk gives you back four banknotes of value 1 each, a total of eight banknotes are used.
The payment cannot be made with less than eight banknotes in total, so the answer is 8.

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

def resolve():
    S = "0" + input()
    N = len(S)

    dp = [[1<<60]*2 for _ in range(N+1)]
    dp[0][0] = 0
    for i in range(N):
        now = int(S[i])
        dp[i+1][0] = min(dp[i][0]+now, dp[i][1]+(10- now))
        dp[i + 1][1] = min(dp[i][0] + now + 1, dp[i][1] + (10 - now - 1))
    print((dp[N][0]))

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_f:
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout our country, AtCoder Kingdom.
Fortunately, our military team called ABC has managed to obtain a device that is a part of the system controlling the bombs.
There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted at the coordinate A_i. It is currently activated if B_i=1, and deactivated if B_i=0.
The device has M cords numbered 1 to M. If we cut Cord j, the states of all the bombs planted between the coordinates L_j and R_j (inclusive) will be switched - from activated to deactivated, and vice versa.
Determine whether it is possible to deactivate all the bombs at the same time. If the answer is yes, output a set of cords that should be cut.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 10^5
 - 1 \leq A_i \leq 10^9\ (1 \leq i \leq N)
 - A_i are pairwise distinct.
 - B_i is 0 or 1. (1 \leq i \leq N)
 - 1 \leq M \leq 2 \times 10^5
 - 1 \leq L_j \leq R_j \leq 10^9\ (1 \leq j \leq M)

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_N B_N
L_1 R_1
:
L_M R_M

-----Output-----
If it is impossible to deactivate all the bombs at the same time, print -1. If it is possible to do so, print a set of cords that should be cut, as follows:
k
c_1 c_2 \dots c_k

Here, k is the number of cords (possibly 0), and c_1, c_2, \dots, c_k represent the cords that should be cut. 1 \leq c_1 < c_2 < \dots < c_k \leq M must hold.

-----Sample Input-----
3 4
5 1
10 1
8 0
1 10
4 5
6 7
8 9

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

There are two activated bombs at the coordinates 5, 10, and one deactivated bomb at the coordinate 8.
Cutting Cord 1 switches the states of all the bombs planted between the coordinates 1 and 10, that is, all of the three bombs.
Cutting Cord 4 switches the states of all the bombs planted between the coordinates 8 and 9, that is, Bomb 3.
Thus, we can deactivate all the bombs by cutting Cord 1 and Cord 4.

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

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
from bisect import bisect_left, bisect_right

N, M = map(int, input().split())
AB = [[0, 0]] + [[int(i) for i in input().split()] for _ in range(N)] + [[1 << 40, 0]]
LR = [[int(i) for i in input().split()] for _ in range(M)]

N += 2

# 座圧
compressed = sorted([a for a, b in AB])
bomb = [0] * N
for a, b in AB :
  a = bisect_left(compressed, a)
  bomb[a] = b
diff = [bomb[i-1] ^ bomb[i] for i in range(1, N)]

# 辺を貼る
vec = [[] for _ in range(N)]
convert = {}
for i, (l, r) in enumerate(LR) :
  if compressed[-1] < l or r < compressed[0] : continue
  l = bisect_left(compressed, l) - 1
  r = bisect_right(compressed, r) - 1
  if r <= l : continue
  vec[l].append(r)
  vec[r].append(l)
  convert[(l, r)] = i

# 全域木の構築
visited = [False] * N
parent = [-1] * N
ret = []
def dfs(pre, cur) :
  for nex in vec[cur] :
    if nex == pre or visited[nex] :
      continue
    visited[nex] = True
    dfs(cur, nex)
  if pre == -1 and diff[cur] == 1 :
    return False
  if diff[cur] == 1 :
    diff[cur] ^= 1
    diff[pre] ^= 1
    ret.append(convert[(min(pre, cur), max(pre, cur))] + 1)
  return True

for i in range(N - 1) :
  if visited[i] : continue
  visited[i] = True
  if not dfs(-1, i) :
    print(-1)
    break
else :
  ret.sort()
  print(len(ret))
  print(*ret)


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_a:
Takahashi is a member of a programming competition site, ButCoder.
Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.
The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.
Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

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

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

-----Output-----
Print his Inner Rating.

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

-----Sample Output-----
3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.
Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

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

n, r =map(int,input().split())
if n >= 10:
    print(r)
else:
    print(r+1000-100*n)


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_b:
Given is an integer N. Find the number of digits that N has in base K.

-----Notes-----
For information on base-K representation, see Positional notation - Wikipedia.

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

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

-----Output-----
Print the number of digits that N has in base K.

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

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

In binary, 11 is represented as 1011.

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

def resolve():
	n,k = map(int,input().split())
	ans  = 0
	while n!=0:
		n = n//k
		ans += 1
	print(ans)
resolve()


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_c:
There are N people living on a number line.
The i-th person lives at coordinate X_i.
You are going to hold a meeting that all N people have to attend.
The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.
Find the minimum total points of stamina the N people have to spend.

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

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

-----Output-----
Print the minimum total stamina the N people have to spend.

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

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

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.
Note that you can hold the meeting only at an integer coordinate.

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

n = int(input())
x = [int(s) for s in input().split()]
hp = []
for i in range(min(x),max(x) + 1):
    sum_ = 0
    for j in x:
        sum_ = sum_ + (j - i)**2
    hp.append(sum_)
print(min(hp))


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_d:
Akari has n kinds of flowers, one of each kind.
She is going to choose one or more of these flowers to make a bouquet.
However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.
How many different bouquets are there that Akari can make?
Find the count modulo (10^9 + 7).
Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq n \leq 10^9
 - 1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

-----Input-----
Input is given from Standard Input in the following format:
n a b

-----Output-----
Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

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

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

In this case, Akari can choose 2 or 4 flowers to make the bouquet.
There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

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

n,a,b=map(int,input().split())
m=10**9+7
ALL=pow(2,n,m)-1
x=y=1

for i in range(b):
    x=x*(i+1)%m
    y=y*(n-i)%m
    if i+1==a:
        a=b
        ALL-=y*pow(x,m-2,m)

print(ALL%m)


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_e:
There is a building with n rooms, numbered 1 to n.
We can move from any room to any other room in the building.
Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).
Initially, there was one person in each room in the building.
After that, we know that there were exactly k moves happened up to now.
We are interested in the number of people in each of the n rooms now. How many combinations of numbers of people in the n rooms are possible?
Find the count modulo (10^9 + 7).

-----Constraints-----
 - All values in input are integers.
 - 3 \leq n \leq 2 \times 10^5
 - 2 \leq k \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
n k

-----Output-----
Print the number of possible combinations of numbers of people in the n rooms now, modulo (10^9 + 7).

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

-----Sample Output-----
10

Let c_1, c_2, and c_3 be the number of people in Room 1, 2, and 3 now, respectively. There are 10 possible combination of (c_1, c_2, c_3):
 - (0, 0, 3)
 - (0, 1, 2)
 - (0, 2, 1)
 - (0, 3, 0)
 - (1, 0, 2)
 - (1, 1, 1)
 - (1, 2, 0)
 - (2, 0, 1)
 - (2, 1, 0)
 - (3, 0, 0)
For example, (c_1, c_2, c_3) will be (0, 1, 2) if the person in Room 1 goes to Room 2 and then one of the persons in Room 2 goes to Room 3.

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

n, k = map(int, input().strip().split())
k=min(k,n-1)
MOD=10**9+7

# a*a**(p-2) mod p (Fermat's little theorem)
def modInv(x,m=10**9+7):
    return pow(x,m-2,m)

class combMod:
    def __init__(self,maxN,mod=10**9+7):
        self.maxN=maxN
        self.mod=mod
        self.fac=[None]*(maxN+1) # fac[0]=1, fac[1]=1, fac[2]=2 ... fac[maxN]
        self.ifac=[None]*(maxN+1)
        # self.ifac[0]=1

    def calc_fact(self): # make the table
        self.fac[0]=1
        for i in range(1,self.maxN+1):
            self.fac[i] = self.fac[i-1]*i % self.mod
        self.ifac[-1] = modInv(self.fac[-1])
        for i in range(self.maxN,0,-1):
            self.ifac[i-1] = self.ifac[i]*i % self.mod
    def modnCr(self,n, r,mod=None):
        if mod is None:
            mod=self.mod
        denom = self.fac[n]
        numer = self.ifac[r] * self.ifac[n-r] % mod
        return  denom * numer % mod

combMod=combMod(2*n+1)
combMod.calc_fact()
ans=0
for ki in range(k+1):
    ans += combMod.modnCr(n, ki)*combMod.modnCr(n-ki-1+ki, ki)%MOD
print(ans%MOD)


I found an interesting problem on https://atcoder.jp/contests/abc156/tasks/abc156_f:
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
 - The i-th query contains three integers n_i, x_i, and m_i.
Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j =  \begin{cases}    x_i & ( j = 0 ) \\    a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 )  \end{cases}\end{eqnarray}
Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).

-----Constraints-----
 - All values in input are integers.
 - 1 \leq k, q \leq 5000
 - 0 \leq d_i \leq 10^9
 - 2 \leq n_i \leq 10^9
 - 0 \leq x_i \leq 10^9
 - 2 \leq m_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q

-----Output-----
Print q lines.
The i-th line should contain the response to the i-th query.

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

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

For the first query, the sequence {a_j} will be 3,6,7,11,14.
 - (a_0~\textrm{mod}~2) > (a_1~\textrm{mod}~2)
 - (a_1~\textrm{mod}~2) < (a_2~\textrm{mod}~2)
 - (a_2~\textrm{mod}~2) = (a_3~\textrm{mod}~2)
 - (a_3~\textrm{mod}~2) > (a_4~\textrm{mod}~2)
Thus, the response to this query should be 1.

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

import numpy as np

k, q = list(map(int, input().split()))
d = np.array(list(map(int, input().split()))).astype(np.int64)
queries = [tuple(map(int, input().split())) for _ in range(q)]

for n, x, m in queries:
    d_mod = d % m
    quotient, rem = divmod(n - 1, k)
    rem_d_mod = d_mod[:rem]
    print((quotient * np.count_nonzero(d_mod) + np.count_nonzero(rem_d_mod)
          - (x % m + quotient * np.sum(d_mod) + np.sum(rem_d_mod)) // m))


I found an interesting problem on https://atcoder.jp/contests/abc157/tasks/abc157_a:
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.
At least how many sheets of paper does he need?

-----Constraints-----
 - N is an integer.
 - 1 \leq N \leq 100

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

-----Output-----
Print the answer.

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

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

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

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

N=int(input())
if N%2==0:
    print(N//2)
else:
    print(N//2+1)


I found an interesting problem on https://atcoder.jp/contests/abc157/tasks/abc157_b:
We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A_{i, j} \leq 100
 - A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))
 - 1 \leq N \leq 10
 - 1 \leq b_i \leq 100
 - b_i \neq b_j (i \neq j)

-----Input-----
Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

-----Output-----
If we will have a bingo, print Yes; otherwise, print No.

-----Sample Input-----
84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

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

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

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

A11,A12,A13 = list(map(int,input().split()))
A21,A22,A23 = list(map(int,input().split()))
A31,A32,A33 = list(map(int,input().split()))

Alist = []
Alist.append(A11)
Alist.append(A12)
Alist.append(A13)
Alist.append(A21)
Alist.append(A22)
Alist.append(A23)
Alist.append(A31)
Alist.append(A32)
Alist.append(A33)
bingolist =[0]*9

N = int(input())
#print (N)
for i in range(N):
  b = int(input())
  #print (b)
  for j in range(len(bingolist)):
    if b ==Alist[j]:
      bingolist[j] = 1

if sum(bingolist[0:3])==3 or sum(bingolist[3:6])==3 or sum(bingolist[6:9])==3 or (bingolist[0]+bingolist[3]+bingolist[6])==3 or (bingolist[1]+bingolist[4]+bingolist[7])==3 or (bingolist[2]+bingolist[5]+bingolist[8])==3 or (bingolist[0]+bingolist[4]+bingolist[8])==3 or (bingolist[2]+bingolist[4]+bingolist[6])==3:
  print ("Yes")
else :
  print ("No")
#print (bingolist[0:3])
#print (bingolist[3:6])
#print (bingolist[6:9])
#print (bingolist)


I found an interesting problem on https://atcoder.jp/contests/abc157/tasks/abc157_c:
If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print -1.
 - The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)
 - The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right)

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 3
 - 0 \leq M \leq 5
 - 1 \leq s_i \leq N
 - 0 \leq c_i \leq 9

-----Input-----
Input is given from Standard Input in the following format:
N M
s_1 c_1
\vdots
s_M c_M

-----Output-----
Print the answer.

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

-----Sample Output-----
702

702 satisfies the conditions - its 1-st and 3-rd digits are 7 and 2, respectively - while no non-negative integer less than 702 satisfies them.

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

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

ans = [-1] * n
for i in range(m):
    s, c = list(map(int, input().split()))
    s -= 1
    if ans[s] != -1 and ans[s] != c:
        print((-1))
        return
    ans[s] = c

if n > 1 and ans[0] == 0:
    print((-1))
    return

if ans[0] == -1:
    if n == 1:
        ans[0] = 0
    else:
        ans[0] = 1
for i in range(1, n):
    if ans[i] == -1:
        ans[i] = 0
print((''.join(map(str, ans))))


I found an interesting problem on https://atcoder.jp/contests/abc157/tasks/abc157_d:
An SNS has N users - User 1, User 2, \cdots, User N.
Between these N users, there are some relationships - M friendships and K blockships.
For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.
For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.
We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:
 - a \neq b.
 - There is not a friendship between User a and User b.
 - There is not a blockship between User a and User b.
 - There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.
For each user i = 1, 2, ... N, how many friend candidates does it have?

-----Constraints-----
 - All values in input are integers.
 - 2 ≤ N ≤ 10^5
 - 0 \leq M \leq 10^5
 - 0 \leq K \leq 10^5
 - 1 \leq A_i, B_i \leq N
 - A_i \neq B_i
 - 1 \leq C_i, D_i \leq N
 - C_i \neq D_i
 - (A_i, B_i) \neq (A_j, B_j) (i \neq j)
 - (A_i, B_i) \neq (B_j, A_j)
 - (C_i, D_i) \neq (C_j, D_j) (i \neq j)
 - (C_i, D_i) \neq (D_j, C_j)
 - (A_i, B_i) \neq (C_j, D_j)
 - (A_i, B_i) \neq (D_j, C_j)

-----Input-----
Input is given from Standard Input in the following format:
N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

-----Output-----
Print the answers in order, with space in between.

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

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

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.
However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

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

N, M, K = list(map(int, input().split()))
friend = [[] for _ in range(N+1)]
block = [[] for _ in range(N+1)]

for i in range(M):
  A,B = list(map(int, input().split()))
  friend[A].append(B)
  friend[B].append(A)

for i in range(K):
  C,D = list(map(int, input().split()))
  block[C].append(D)
  block[D].append(C)
#print(friend)
#print(block)

#import queue
grouping = [False]*(N+1)
#print(grouping)
grouping[0] = True
group = [0]*(N+1)
g_num = 0
g_cnt = []
for i in range(1,N+1):
  cnt = 0
  if grouping[i] == True:
    continue
  group[i] = g_num
  grouping[i] = True
  #q = queue.Queue()
  #q.put(i)
  stack = [i]
  #while not q.empty():
  while len(stack)>0:
    #print('v:',visited)
    #p = q.get()
    p = stack.pop()
    for f in friend[p]:
      #print(p,f)
      if grouping[f]==False:
        #q.put(f)
        stack.append(f)
        group[f]=g_num
        grouping[f] =True
        cnt += 1
  g_num += 1
  g_cnt.append(cnt)
  #print('g:',grouping)
ans = []
for i in range(1,N+1):
  c = g_cnt[group[i]]-len(friend[i])
  for b in block[i]:
    if group[b]==group[i]:
      c -= 1
  ans.append(c)
print((*ans))


I found an interesting problem on https://atcoder.jp/contests/abc157/tasks/abc157_f:
Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.
Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), where X and Y are real numbers, the i-th piece of meat will be ready to eat in c_i \times \sqrt{\left(X - x_i\right)^2 + \left(Y-y_i\right)^2} seconds.
Takahashi wants to eat K pieces of meat. Find the time required to have K or more pieces of meat ready if he put the heat source to minimize this time.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 60
 - 1 \leq K \leq N
 - -1000 \leq x_i , y_i \leq 1000
 - \left(x_i, y_i\right) \neq \left(x_j, y_j\right) \left(i \neq j \right)
 - 1 \leq c_i \leq 100

-----Input-----
Input is given from Standard Input in the following format:
N K
x_1 y_1 c_1
\vdots
x_N y_N c_N

-----Output-----
Print the answer.
It will be considered correct if its absolute or relative error from our answer is at most 10^{-6}.

-----Sample Input-----
4 3
-1 0 3
0 0 3
1 0 2
1 1 40

-----Sample Output-----
2.4

If we put the heat source at \left(-0.2, 0\right), the 1-st, 2-nd, and 3-rd pieces of meat will be ready to eat within 2.4 seconds. This is the optimal place to put the heat source.

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

N,K = map(int,input().split())
XYC = [tuple(map(int,input().split())) for i in range(N)]

from math import hypot,acos,atan2,cos,sin
def circles_cross_points(x1,y1,r1,x2,y2,r2):
    d = hypot(x1-x2, y1-y2)
    if r1 + r2 < d or abs(r1 - r2) >= d: return []
    x = (r1**2 + d**2 - r2**2) / (2*r1*d)
    if not -1 <= x <= 1: return []
    a = acos(x)
    t = atan2(y2-y1, x2-x1)
    return [
        (x1+cos(t+a)*r1, y1+sin(t+a)*r1),
        (x1+cos(t-a)*r1, y1+sin(t-a)*r1)
    ]

eps = 10e-10
def is_ok(t):
    cands = []
    for x,y,_ in XYC:
        cands.append((x,y))
    for i,(x1,y1,c1) in enumerate(XYC[:-1]):
        for x2,y2,c2 in XYC[i+1:]:
            ps = circles_cross_points(x1,y1,t/c1,x2,y2,t/c2)
            cands += ps
    for cx,cy in cands:
        k = 0
        for x,y,c in XYC:
            d = hypot(cx-x,cy-y)
            if c*d <= t + eps:
                k += 1
                if k >= K:
                    return True
    return False

ok = 10**10
ng = 0
for _ in range(100):
    m = (ok+ng)/2
    if is_ok(m):
        ok = m
    else:
        ng = m
    if ok-ng < 10e-7: break
print(ok)


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_a:
In AtCoder City, there are three stations numbered 1, 2, and 3.
Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.
To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.
Determine if there is a pair of stations that will be connected by a bus service.

-----Constraints-----
 - Each character of S is A or B.
 - |S| = 3

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

-----Output-----
If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

-----Sample Input-----
ABA

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

Company A operates Station 1 and 3, while Company B operates Station 2.
There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

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

s = input()
if(s=='AAA'):
  print('No')
elif(s=='BBB'):
  print('No')
else:
  print('Yes')


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_b:
Takahashi has many red balls and blue balls. Now, he will place them in a row.
Initially, there is no ball placed.
Takahashi, who is very patient, will do the following operation 10^{100} times:
 - Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.
How many blue balls will be there among the first N balls in the row of balls made this way?

-----Constraints-----
 - 1 \leq N \leq 10^{18}
 - A, B \geq 0
 - 0 < A + B \leq 10^{18}
 - All values in input are integers.

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

-----Output-----
Print the number of blue balls that will be there among the first N balls in the row of balls.

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

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

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

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

#-*-coding:utf-8-*-
import sys
input=sys.stdin.readline

def main():
    n,a,b = map(int,input().split())
    a_count=0
    d,r=divmod(n,a+b)
    a_count+=a*d
    if r > a:
        a_count+=a
    else:
        a_count+=r
    print(a_count)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_c:
Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)
Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.
If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

-----Constraints-----
 - 1 \leq A \leq B \leq 100
 - A and B are integers.

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

-----Output-----
If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

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

-----Sample Output-----
25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:
 - When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.
 - When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.
Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

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

a,b = map(int,input().split())
for i in range(1,100000):
    if i*8//100==a and i*10//100==b:
        print(i)
        break
else:
    print(-1)


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_d:
Takahashi has a string S consisting of lowercase English letters.
Starting with this string, he will produce a new one in the procedure given as follows.
The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:
 - If T_i = 1: reverse the string S.
 - If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.
 - If F_i = 1 : Add C_i to the beginning of the string S.
 - If F_i = 2 : Add C_i to the end of the string S.
Help Takahashi by finding the final string that results from the procedure.

-----Constraints-----
 - 1 \leq |S| \leq 10^5
 - S consists of lowercase English letters.
 - 1 \leq Q \leq 2 \times 10^5
 - T_i = 1 or 2.
 - F_i = 1 or 2, if provided.
 - C_i is a lowercase English letter, if provided.

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

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:
1

which means T_i = 1, and:
2 F_i C_i

which means T_i = 2.

-----Output-----
Print the resulting string.

-----Sample Input-----
a
4
2 1 p
1
2 2 c
1

-----Sample Output-----
cpa

There will be Q = 4 operations. Initially, S is a.
 - Operation 1: Add p at the beginning of S. S becomes pa.
 - Operation 2: Reverse S. S becomes ap.
 - Operation 3: Add c at the end of S. S becomes apc.
 - Operation 4: Reverse S. S becomes cpa.
Thus, the resulting string is cpa.

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

S = input()
Q = int(input())

reverse = False
left = ''
right = ''

for _ in range(Q):
    q = input().split()
    if q[0] == '1':
        reverse = not reverse
    else:
        F = q[1]
        C = q[2]
        if reverse == False:
            if F =='1':
                left = C + left
            else:
                right += C

        else:
            if F == '1':
                right += C
            else:
                left = C + left

S = left + S + right
if reverse == False:
    print(S)
    return
else:
    print((S[::-1]))
    return


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_e:
Takahashi has a string S of length N consisting of digits from 0 through 9.
He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.
Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.
Compute this count to help Takahashi.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - S consists of digits.
 - |S| = N
 - 2 \leq P \leq 10000
 - P is a prime number.

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

-----Output-----
Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

-----Sample Input-----
4 3
3543

-----Sample Output-----
6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:
 - 3: divisible by 3.
 - 35: not divisible by 3.
 - 354: divisible by 3.
 - 3543: divisible by 3.
 - 5: not divisible by 3.
 - 54: divisible by 3.
 - 543: divisible by 3.
 - 4: not divisible by 3.
 - 43: not divisible by 3.
 - 3: divisible by 3.
Six of these are divisible by 3, so print 6.

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

n,p = map(int,input().split())
s = input()
ans = 0
if p == 2 or p == 5:
    for i,c in enumerate(s,1):
        if int(c)%p == 0: ans += i
else:
    cnt = [0]*p
    cnt[0] = 1
    x = 0
    d = 1
    for c in s[::-1]:
        x += d*int(c)
        x %= p
        cnt[x%p] += 1
        d *= 10
        d %= p
    # print(cnt)
    for v in cnt: ans += v*(v-1)//2
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc158/tasks/abc158_f:
There are N robots numbered 1 to N placed on a number line. Robot i is placed at coordinate X_i. When activated, it will travel the distance of D_i in the positive direction, and then it will be removed from the number line. All the robots move at the same speed, and their sizes are ignorable.
Takahashi, who is a mischievous boy, can do the following operation any number of times (possibly zero) as long as there is a robot remaining on the number line.
 - Choose a robot and activate it. This operation cannot be done when there is a robot moving.
While Robot i is moving, if it touches another robot j that is remaining in the range [X_i, X_i + D_i) on the number line, Robot j also gets activated and starts moving. This process is repeated recursively.
How many possible sets of robots remaining on the number line are there after Takahashi does the operation some number of times? Compute this count modulo 998244353, since it can be enormous.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - -10^9 \leq X_i \leq 10^9
 - 1 \leq D_i \leq 10^9
 - X_i \neq X_j (i \neq j)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
X_1 D_1
:
X_N D_N

-----Output-----
Print the number of possible sets of robots remaining on the number line, modulo 998244353.

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

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

There are three possible sets of robots remaining on the number line: \{1, 2\}, \{1\}, and \{\}.
These can be achieved as follows:
 - If Takahashi activates nothing, the robots \{1, 2\} will remain.
 - If Takahashi activates Robot 1, it will activate Robot 2 while moving, after which there will be no robots on the number line. This state can also be reached by activating Robot 2 and then Robot 1.
 - If Takahashi activates Robot 2 and finishes doing the operation, the robot \{1\} will remain.

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

import numpy as np
import collections

Robot = collections.namedtuple('Robot', ['l', 'r'])

N = int(input())
MOD = 998244353
robots = []
for _ in range(N):
    x, d = map(int, input().split())
    robots.append(Robot(x, x + d))
robots.sort()

robots.append(Robot(10**10, 10**10 + 1))
stack = [N]

dp = np.zeros(N + 1, dtype=int)
dp[N] = 1

for i in range(N - 1, -1, -1):
    # For each i, we want the stack contains all the j such that
    # robots[j] is not affected by robot[i], therefore
    # we remove those robots that are intersected with robot[i]
    while robots[stack[-1]].l < robots[i].r:
        stack.pop()

    # dp[i] = dp[i + 1] (not activate robot i) + dp[j] (activate robot i)
    j = stack[-1]
    dp[i] = (dp[i + 1] + dp[j]) % MOD
    stack.append(i)

print(dp[0])


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_a:
We have N+M balls, each of which has an integer written on it.

It is known that:
 - The numbers written on N of the balls are even.
 - The numbers written on M of the balls are odd.
Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

-----Constraints-----
 - 0 \leq N,M \leq 100
 - 2 \leq N+M
 - All values in input are integers.

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

-----Output-----
Print the answer.

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

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

For example, let us assume that the numbers written on the three balls are 1,2,4.
 - If we choose the two balls with 1 and 2, the sum is odd;
 - If we choose the two balls with 1 and 4, the sum is odd;
 - If we choose the two balls with 2 and 4, the sum is even.
Thus, the answer is 1.

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

N, M = list(map(int, input().split()))
print(N*(N-1)//2 + M*(M-1)//2)


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_b:
A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:
 - S is a palindrome.
 - Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.
 - The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.
Determine whether S is a strong palindrome.

-----Constraints-----
 - S consists of lowercase English letters.
 - The length of S is an odd number between 3 and 99 (inclusive).

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

-----Output-----
If S is a strong palindrome, print Yes;
otherwise, print No.

-----Sample Input-----
akasaka

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

 - S is akasaka.
 - The string formed by the 1-st through the 3-rd characters is aka.
 - The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

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

def is_palindrome(s: str) -> bool:
    return s == s[::-1]

def answer(s: str) -> str:
    if not is_palindrome(s):
        return 'No'

    strings = [s[:(len(s) - 1) // 2], s[(len(s) + 3) // 2 - 1:]]
    for i in strings:
        if not is_palindrome(i):
            return 'No'

    return 'Yes'

def main():
    s = input()
    print((answer(s)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_c:
Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

-----Constraints-----
 - 1 ≤ L ≤ 1000
 - L is an integer.

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

-----Output-----
Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

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

-----Sample Output-----
1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.
On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

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


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_d:
We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.
 - Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

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

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

-----Output-----
For each k=1,2,...,N, print a line containing the answer.

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

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

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

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

n = int(input())
A = list(map(int, input().split()))
d = {}
for a in A:
    d[a] = d.get(a, 0)+1

comb = []
for i in d:
    if d[i]>1:
        comb.append(d[i]*(d[i]-1)//2)
s = sum(comb)
for a in A:
    ans = s - d[a]*(d[a]-1)//2 + (d[a]-1)*(d[a]-2)//2
    print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_e:
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.
We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.
How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

-----Constraints-----
 - 1 \leq H \leq 10
 - 1 \leq W \leq 1000
 - 1 \leq K \leq H \times W
 - S_{i,j} is 0 or 1.

-----Input-----
Input is given from Standard Input in the following format:
H W K
S_{1,1}S_{1,2}...S_{1,W}
:
S_{H,1}S_{H,2}...S_{H,W}

-----Output-----
Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

-----Sample Input-----
3 5 4
11100
10001
00111

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

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.
Note that we cannot cut the bar in the ways shown in the two figures to the right.

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

import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

def main():
    H,W,K = list(map(int, readline().split()))
    S = [list(map(int, readline().strip())) for j in range(H)]

    white = 0
    for line in S:
        white += sum(line)

    if white <= K:
        print((0))
        return

    # 横線の決め方を全探索
    ans = 10**5
    for pattern in range(2**(H-1)):
        # 初期化
        impossible = False
        x = 0
        ly = bin(pattern).count("1")
        y = [[0]*W]*(ly + 1)
        line = 0
        for i in range(H):
            y[line] = [y[line][j] + S[i][j] for j in range(W)]
            if (pattern >> i) & 1:
                line += 1

        # 各列の値を加算していく
        count = [0]*(ly + 1)
        for col in zip(*y):
            # Kより大きい値を加算する場合は不成立
            if any(a > K for a in col):
                impossible = True
                break
            for i, a in enumerate(col):
                count[i] += a
                # 和がKより大きければカット数を増やす
                if count[i] > K:
                    x += 1
                    count = list(col)
                    break
            if x + ly > ans:
                impossible = True
                break
        if impossible:
            x = 10**6

        ans = min(ans, x + ly)

    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc159/tasks/abc159_f:
Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S.

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

 - f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.
Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 3000
 - 1 \leq S \leq 3000
 - 1 \leq A_i \leq 3000

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

-----Output-----
Print the sum of f(L, R), modulo 998244353.

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

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

The value of f(L, R) for each pair is as follows, for a total of 5.
 - f(1,1) = 0
 - f(1,2) = 1 (for the sequence (1, 2))
 - f(1,3) = 2 (for (1, 2) and (3))
 - f(2,2) = 0
 - f(2,3) = 1 (for (3))
 - f(3,3) = 1 (for (3))

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

n,s = list(map(int,input().split())); arr = list(map(int,input().split()))

mod = 998244353
ans = 0
dp = [0]*(s+1)

for i in range(n):
    dp[0] += 1
    tmp = arr[i]
    for j in range(s,tmp-1,-1):
        dp[j] += dp[j-tmp]
    ans += dp[s]
    ans %= mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_a:
A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

-----Constraints-----
 - S is a string of length 6 consisting of lowercase English letters.

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

-----Output-----
If S is coffee-like, print Yes; otherwise, print No.

-----Sample Input-----
sippuu

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

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

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

s=input()

if s[2]==s[3] and s[4]==s[5]:
  print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_b:
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)
Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?
(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

-----Constraints-----
 - 0 \leq X \leq 10^9
 - X is an integer.

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

-----Output-----
Print the maximum number of happiness points that can be earned.

-----Sample Input-----
1024

-----Sample Output-----
2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

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

'''
問題：
    高橋君は金色の硬貨が好きです。
    自分が持っている 500円硬貨 1枚につき 1000、
    5円硬貨 1枚につき 5の嬉しさ を得ます。

    高橋君は X 円を持っています。
    これを高橋君の嬉しさが最大になるように両替したとき、高橋君の嬉しさはいくらになりますか？

    (なお、利用できる硬貨は 500 円玉、100 円玉、50 円玉、10 円玉、5円玉、1 円玉の 6 種類とします。)
'''

'''
    Xは整数
    0 ≦ X ≦ 1,000,000,000
'''
class A:
    def __init__(self, money, yorokobi):
        self.money = money
        self.yorokobi = yorokobi

    def calc_yorokobi(self, credit):    # credit ：残金を入力として受け取り、喜びを計算して返す
        return int(credit / self.money) * self.yorokobi

    # def print_self(self):
        # print(calc_yorokobi(self, credit))
#
# def calc_yorokobi(input_money, x, yorokobi):
#     ret = input_money // x * yorokobi
#     return ret

# 標準入力から X の値を取得する
input_x = int(input())

yorokobi_500 = A(500, 1000)
yorokobi_5 = A(5, 5)

result = 0  # 結果格納用
if input_x >= 500:
    # print("1回目：{}".format(result))
    result += yorokobi_500.calc_yorokobi(input_x)   # 高橋500円の喜び
    # print("2回目：{}".format(result))
    result += yorokobi_5.calc_yorokobi(input_x % 500)   # 高橋5円の喜び
    # print("3回目：{}".format(result))
else:
    result += yorokobi_5.calc_yorokobi(input_x)

print(result)

# ret1 = input_x // 500  # 500円で割った商
# ret2 = ret1 * 1000  # 高橋君 500円の喜び
# ret3 = input_x - (ret1 * 500)   # X円から500円の枚数分を引いたお金
# ret4 = ret3 // 5 # （X円から500円の枚数分を引いたお金）÷ 5
# ret5 = ret4 * 5 # 高橋君 5円の喜び
# print(ret2 + ret5)


I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_c:
There is a circular pond with a perimeter of K meters, and N houses around them.
The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.
When traveling between these houses, you can only go around the pond.
Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

-----Constraints-----
 - 2 \leq K \leq 10^6
 - 2 \leq N \leq 2 \times 10^5
 - 0 \leq A_1 < ... < A_N < K
 - All values in input are integers.

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

-----Output-----
Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

-----Sample Input-----
20 3
5 10 15

-----Sample Output-----
10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

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

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

c=[]
for i in range(1,n):
    c.append(a[i]-a[i-1])
c.append(k-a[-1]+a[0])

print(k-max(c))


I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_d:
We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:
 - For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.
 - There is an edge between Vertex X and Vertex Y.
For each k=1,2,...,N-1, solve the problem below:
 - Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

-----Constraints-----
 - 3 \leq N \leq 2 \times 10^3
 - 1 \leq X,Y \leq N
 - X+1 < Y
 - All values in input are integers.

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

-----Output-----
For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

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

-----Sample Output-----
5
4
1
0

The graph in this input is as follows:

There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).

There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).

There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).

There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.

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

from collections import deque

n, x, y = map(int, input().split())

g = [[] for _ in range(n)]

# make graph
for i in range(n - 1):
    g[i].append(i + 1)
    g[i + 1].append(i)

g[x - 1].append(y - 1)
g[y - 1].append(x - 1)

def bfs(g, n_node, start_node):
    dist = [-1] * n_node
    dist[start_node] = 0
    queue = deque([start_node])

    while queue:
        node = queue.popleft()
        for n in g[node]:
            if dist[n] != -1:
                continue
            dist[n] = dist[node] + 1
            queue.append(n)
    return dist

ans_array = [0] * n
for i in range(n):
    dist = bfs(g, n, i)
    for d in dist:
        ans_array[d] += 1

for i in ans_array[1:]:
    print(i // 2)