I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_a:
Takahashi is going to set a 3-character password.
How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

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

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

-----Output-----
Print the number of possible passwords.

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

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

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

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


I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_b:
Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.
The i-th dish (1 \leq i \leq N) he ate was Dish A_i.
When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.
Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.
Find the sum of the satisfaction points he gained.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 20
 - 1 \leq A_i \leq N
 - A_1, A_2, ..., A_N are all different.
 - 1 \leq B_i \leq 50
 - 1 \leq C_i \leq 50

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

-----Output-----
Print the sum of the satisfaction points Takahashi gained, as an integer.

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

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

Takahashi gained 14 satisfaction points in total, as follows:
 - First, he ate Dish 3 and gained 4 satisfaction points.
 - Next, he ate Dish 1 and gained 2 satisfaction points.
 - Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

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

for i in range(n):
  if (i == 0):
    ans =b[a[0] - 1]
    y = a[0]
  else:
    x = a[i]
    if (x - y == 1):
      ans = ans + b[x - 1] + c[y - 1]
    else:
      ans = ans + b[x - 1]
    y = x

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_c:
There is an integer sequence A of length N whose values are unknown.
Given is an integer sequence B of length N-1 which is known to satisfy the following:
 B_i \geq \max(A_i, A_{i+1})
Find the maximum possible sum of the elements of A.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 100
 - 0 \leq B_i \leq 10^5

-----Input-----
Input is given from Standard Input in the following format:
N
B_1 B_2 ... B_{N-1}

-----Output-----
Print the maximum possible sum of the elements of A.

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

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

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

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

N=int(input())
B=list(map(int,input().split()))
A=[0]*N
for i in range(N):
    A[i]=B[i-1]
    if A[i-1]>B[i-1]:
        A[i-1]=B[i-1]
A[0]=B[0]
print(sum(A))


I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_d:
There are N people standing in a queue from west to east.
Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.
A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.
You can perform the following operation any number of times between 0 and K (inclusive):
Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.
What is the maximum possible number of happy people you can have?

-----Constraints-----
 - N is an integer satisfying 1 \leq N \leq 10^5.
 - K is an integer satisfying 1 \leq K \leq 10^5.
 - |S| = N
 - Each character of S is L or R.

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

-----Output-----
Print the maximum possible number of happy people after at most K operations.

-----Sample Input-----
6 1
LRLRRL

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

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

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

import sys,math,collections,itertools
input = sys.stdin.readline

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

ori_num=0
turn_num=0
for i in range(N):
    if i>0:
        if S[i-1] =='L' and S[i] =='L':
            ori_num += 1
        if S[i-1] != S[i]:
            turn_num +=1

    if i<N-1:
        if S[i] =='R' and S[i+1] =='R':
            ori_num += 1

if turn_num >=2*K:
    ori_num += 2*K
else:
    num = turn_num//2
    num2 = turn_num%2
    ori_num += 2*num+num2

print(ori_num)


I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_e:
Given is a permutation P of \{1, 2, \ldots, N\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

-----Constraints-----
 -  2 \le N \le 10^5
 -  1 \le P_i \le N
 -  P_i \neq P_j  (i \neq j)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N

-----Output-----
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

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

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

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

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

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

num_idx = [0]*(n+1)

# 自分のidxからみて右側で，自身の値より大きな値をもつ，一番近いidx
right_idx_over_current_pos = list(range(1, n+1)) + [n, n]
# 自分のidxからみて左側で，自身の値より大きな値をもつ，一番近いidx
left_idx_over_current_pos = list(range(-1, n-1)) + [-1, -1]

# 1から見ていくとすると，上記2つとも，自分のすぐ隣のidxがそのまま該当する

for idx, num in enumerate(P):
    num_idx[num] = idx

ans = 0
for num in range(1, n+1):  # 小さいほうから決める
    now = num_idx[num]
    r1 = right_idx_over_current_pos[now]
    r2 = right_idx_over_current_pos[r1]
    l1 = left_idx_over_current_pos[now]
    l2 = left_idx_over_current_pos[l1]

    r_pattern = (r2-r1) * (now-l1)
    l_pattern = (l1-l2) * (r1-now)

    right_idx_over_current_pos[l1] = r1  # l1にある値 > nowからr1までにある値 なので nowをスキップして r1までいける
    left_idx_over_current_pos[r1] = l1  # 上の左向きver
    ans += (r_pattern + l_pattern) * num

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc140/tasks/abc140_f:
We have one slime.
You can set the health of this slime to any integer value of your choice.
A slime reproduces every second by spawning another slime that has strictly less health. You can freely choose the health of each new slime. The first reproduction of our slime will happen in one second.
Determine if it is possible to set the healths of our first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals a multiset S.
Here S is a multiset containing 2^N (possibly duplicated) integers: S_1,~S_2,~...,~S_{2^N}.

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

-----Input-----
Input is given from Standard Input in the following format:
N
S_1 S_2 ... S_{2^N}

-----Output-----
If it is possible to set the healths of the first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals S, print Yes; otherwise, print No.

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

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

We will show one way to make the multiset of the healths of the slimes that will exist in 2 seconds equal to S.
First, set the health of the first slime to 4.
By letting the first slime spawn a slime whose health is 3, the healths of the slimes that exist in 1 second can be 4,~3.
Then, by letting the first slime spawn a slime whose health is 2, and letting the second slime spawn a slime whose health is 1, the healths of the slimes that exist in 2 seconds can be 4,~3,~2,~1, which is equal to S as multisets.

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

N = int(input())
N2 = 2**N
S = list(map(int, input().split()))
S.sort(reverse=True)

slimes = [S[0]]
S[0] = float('inf')
num = 1
for i in range(N):
  slimes.sort()
  n = num
  idx = 0
  while n and idx<=N2-1:
    if S[idx] < slimes[n-1]:
      slimes.append(S[idx])
      S[idx] = float('inf')
      idx += 1
      n -= 1
    else:
      idx += 1

  if n:
    print('No')
    return

  num *= 2

print('Yes')


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_a:
The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...
Given is a string S representing the weather in the town today. Predict the weather tomorrow.

-----Constraints-----
 - S is Sunny, Cloudy, or Rainy.

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

-----Output-----
Print a string representing the expected weather tomorrow, in the same format in which input is given.

-----Sample Input-----
Sunny

-----Sample Output-----
Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

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

s = input()

print("Sunny" if s=="Rainy" else "Cloudy" if s == "Sunny" else "Rainy")


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_b:
Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.
S is said to be easily playable if and only if it satisfies both of the following conditions:
 - Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.
 - Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.
Your task is to print Yes if S is easily playable, and No otherwise.

-----Constraints-----
 - S is a string of length between 1 and 100 (inclusive).
 - Each character of S is L, R, U, or D.

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

-----Output-----
Print Yes if S is easily playable, and No otherwise.

-----Sample Input-----
RUDLUDR

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

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.
Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.
Thus, S is easily playable.

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

S = str(input())

flag = True
for i in range(len(S)):
  if i%2==0 and S[i]=="L":
    flag = False
  elif i%2!=0 and S[i]=="R":
    flag = False
if flag:
  print("Yes")
else:
  print("No")


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_c:
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.
When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.
At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.
In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

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

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

-----Output-----
Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

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

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

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).
 - Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).
 - Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).
 - Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).
 - Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).
Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

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

n, k, q = map(int, input().split())
l = [0]*n
for i in range(q):
    l[int(input()) - 1] += 1
for j in range(n):
    if l[j] > q-k:
        print("Yes")
    else:
        print("No")


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_d:
Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.
What is the minimum amount of money required to buy all the items?

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

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

-----Output-----
Print the minimum amount of money required to buy all the items.

-----Sample Input-----
3 3
2 13 8

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

We can buy all the items for 9 yen, as follows:
 - Buy the 1-st item for 2 yen without tickets.
 - Buy the 2-nd item for 3 yen with 2 tickets.
 - Buy the 3-rd item for 4 yen with 1 ticket.

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

import heapq
n, m = map(int, input().split())
a = [i*-1 for i in list(map(int, input().split()))]
heapq.heapify(a)
for i in range(m):
    x = heapq.heappop(a)
    heapq.heappush(a, ((-1*x)//2)*-1)
print(sum(a)*-1)


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_e:
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
 - l_1 + len \leq l_2
 - S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.

-----Constraints-----
 - 2 \leq N \leq 5 \times 10^3
 - |S| = N
 - S consists of lowercase English letters.

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

-----Output-----
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

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

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

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

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

from typing import List, Tuple

class RollingHash:
    """Rolling Hash"""

    __slots__ = ["_base", "_mod", "_hash", "_power"]

    def __init__(self, source: str, base: int = 1007, mod: int = 10 ** 9 + 7):
        self._base = base
        self._mod = mod
        self._hash, self._power = self._build(source)

    def _build(self, source: str) -> Tuple[List[int], List[int]]:
        """Compute "hash" and "mod of power of base" of interval [0, right)."""
        hash_, power = [0] * (len(source) + 1), [0] * (len(source) + 1)
        power[0] = 1
        for i, c in enumerate(source, 1):
            hash_[i] = (hash_[i - 1] * self._base + ord(c)) % self._mod
            power[i] = power[i - 1] * self._base % self._mod
        return hash_, power

    def get_hash(self, left: int, right: int):
        """Return hash of interval [left, right)."""
        return (
            self._hash[right] - self._hash[left] * self._power[right - left]
        ) % self._mod

def abc141_e():
    # https://atcoder.jp/contests/abc141/tasks/abc141_e
    N = int(input())
    S = input().rstrip()

    rh = RollingHash(S)
    ok, ng = 0, N // 2 + 1
    while ng - ok > 1:
        mid = (ok + ng) // 2
        flg = False
        memo = set()
        for i in range(N - 2 * mid + 1):
            memo.add(rh.get_hash(i, i + mid))
            if rh.get_hash(i + mid, i + 2 * mid) in memo:
                flg = True
                break
        if flg:
            ok = mid  # next mid will be longer
        else:
            ng = mid  # next mid will be shorter

    print(ok)  # max length of substrings appeared twice or more

def __starting_point():
    abc141_e()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc141/tasks/abc141_f:
We have N non-negative integers: A_1, A_2, ..., A_N.
Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue.
Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue.
Find the maximum possible beauty of the painting.What is \mbox{XOR}?

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

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

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 0 \leq A_i < 2^{60}\ (1 \leq i \leq N)

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

-----Output-----
Print the maximum possible beauty of the painting.

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

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

If we paint 3, 6, 5 in blue, red, blue, respectively, the beauty will be (6) + (3 \oplus 5) = 12.
There is no way to paint the integers resulting in greater beauty than 12, so the answer is 12.

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

from functools import reduce
from operator import xor
import numpy as np

def main():
    N = int(input())
    A = np.array(input().split(), np.int64)
    # とりあえず全部XORする
    A_xor_all = np.bitwise_xor.reduce(A)

    # 参考
    # https://betrue12.hateblo.jp/entry/2019/11/22/012255

    # * 全部XORして1になるビットは、どう塗り分けても片方は0, もう片方が1になる
    #   つまり、このビットはどうグループ分けしても和は1になるので、このビットは考察対象から外す
    # * 全部XORして0になるビットは、このビットが1になっている要素の個数を赤と青それぞれで奇数個にしてあげれば、
    #   XOR(赤グループ) + XOR(青グループ)を最大化できる。

    # そこで、Aの各要素を、全部XORして1になるビットを無視した(0にした)数値に変換したもの（A'）を作る
    # A'の要素を2グループに分け、各グループのXORの和が最大になるようにする。
    # ただし、各ビットにおいて、ビットが1になっているA'要素の個数は必ず偶数になっていることから、
    # どうグループ分けしたとしても、必ず「XOR(A'の赤グループ) = XOR(A'の青グループ)」となる。
    # XORを最大化するように要素を選択したときのグループをX'とすると、答えは、以下の通りとなる
    # [A全部のXOR結果] + 2 * [X'のXOR結果]

    # A'を作成
    # 1になっているビットを無視したいので、A全体のXOR結果を反転してANDをとる
    mask = ~A_xor_all
    A_dash = A & mask

    # X'を求める方法
    #   A'の要素の位置を入れ替えたり、
    #   ある要素を、その要素と別の要素とのXOR結果に置き換えたりする操作を繰り返し、
    #   A'の行標準形Rを求めると、
    #   Rの全要素のXOR結果が、X'となる

    # 行標準形: 行列の左下の方が0になるような形（連立方程式を解くときに作るようなやつ）
    #          また、i行目において、一番左にある1がn列目だとすると、n列目全体において、i行目以外では全て0になっている
    # 例
    #   1 0 ? 0 ? ? ?
    #   0 1 ? 0 ? ? ?
    #   0 0 0 1 ? ? ?
    #   0 0 0 0 0 0 0

    # 行標準形の作り方
    #  1. 最大値を見つける (=a1とする)
    #  2. a1において一番左にある1がn1列目だとすると、他の行でn1列目が1になっていたら、a1とXORする
    #  3. a1以外の最大値を見つける (=a2とする)
    #  4. a2において一番左にある1がn2列目だとすると、他の行でn2列目が1になっていたら、a2とXORする
    #     (a1も、n2列目が1になっている場合はa2とXORする)
    #  5. a1, a2以外の最大値を見つける (=a3とする)
    #  6. a3において一番左にある1がn3列目だとすると、他の行でn3列目が1になっていたら、a3とXORする
    #     (a1, a2も、n3列目が1になっている場合はa3とXORする)
    #  ....

    # 例: A = [12, 9, 7, 2] = [1100, 1001, 0111, 0010] の場合
    # XOR(A) = 0000, A' = A = [12, 9, 7, 2] =
    # [1100
    #  1001
    #  0111
    #  0010]

    # 2行目 ^= 1行目
    # [1100
    #  0101
    #  0111
    #  0010]

    # 2行目と3行目を交換
    # [1100
    #  0111
    #  0101
    #  0010]

    # 3行目 ^= 2行目, 1行目^=2行目
    # [1011
    #  0111
    #  0010
    #  0010]

    # 4行目 ^= 3行目, 2行目 ^= 3行目,...


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_a:
Given is an integer N.
Takahashi chooses an integer a from the positive integers not greater than N with equal probability.
Find the probability that a is odd.

-----Constraints-----
 - 1 \leq N \leq 100

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

-----Output-----
Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

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

-----Sample Output-----
0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

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


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_b:
N friends of Takahashi has come to a theme park.
To ride the most popular roller coaster in the park, you must be at least K centimeters tall.
The i-th friend is h_i centimeters tall.
How many of the Takahashi's friends can ride the roller coaster?

-----Constraints-----
 -  1 \le N \le 10^5
 -  1 \le K \le 500
 -  1 \le h_i \le 500
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N

-----Output-----
Print the number of people among the Takahashi's friends who can ride the roller coaster.

-----Sample Input-----
4 150
150 140 100 200

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

Two of them can ride the roller coaster: the first and fourth friends.

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

N, K = map(int, input().split())
print(sum([h >= K for h in map(int, input().split())]))


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_c:
Takahashi is a teacher responsible for a class of N students.
The students are given distinct student numbers from 1 to N.
Today, all the students entered the classroom at different times.
According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).
From these records, reconstruct the order in which the students entered the classroom.

-----Constraints-----
 -  1 \le N \le 10^5
 -  1 \le A_i \le N
 -  A_i \neq A_j  (i \neq j)
 - All values in input are integers.

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

-----Output-----
Print the student numbers of the students in the order the students entered the classroom.

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

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

First, student number 3 entered the classroom.
Then, student number 1 entered the classroom.
Finally, student number 2 entered the classroom.

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

n = int(input())
a = [int(s) for s in input().split()]
ans = [0]*n

for i in range(n):
    ans[a[i] - 1] = i + 1
print(" ".join(map(str,ans)))


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_d:
Given are positive integers A and B.
Let us choose some number of positive common divisors of A and B.
Here, any two of the chosen divisors must be coprime.
At most, how many divisors can we choose?Definition of common divisor
An integer d is said to be a common divisor of integers x and y when d divides both x and y.Definition of being coprime
Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.Definition of dividing
An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

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

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

-----Output-----
Print the maximum number of divisors that can be chosen to satisfy the condition.

-----Sample Input-----
12 18

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

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.
1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

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

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

gcd = math.gcd(A,B)
d = []
if A == 1 or B == 1 :
    print((1))
    return
ans = [1]
while gcd %2 == 0 :
    gcd //= 2
    ans.append(2)
i = 3
while i * i <= gcd :
    if gcd %i == 0 :
        ans.append(i)
        gcd //= i
    else :
        i += 2
if gcd != 1 :
    ans.append(gcd)
print((len(set(ans))))


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_e:
We have N locked treasure boxes, numbered 1 to N.
A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.
Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 12
 - 1 \leq M \leq 10^3
 - 1 \leq a_i \leq 10^5
 - 1 \leq b_i \leq N
 - 1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

-----Input-----
Input is given from Standard Input in the following format:
N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

-----Output-----
Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

-----Sample Input-----
2 3
10 1
1
15 1
2
30 2
1 2

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

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

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

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

DP = [10**9] * (2**n)
DP[0] = 0
for _ in range(m):
    cost, types = list(map(int, input().split()))
    to_open = list(map(int, input().split()))

    openable = 0
    for open in to_open:
        openable += 1 << (open-1)

    for opened in range(2 ** n):
        pattern = opened | openable
        DP[pattern] = min(DP[pattern], DP[opened] + cost)

full_open = 2**n - 1
ans = DP[full_open]

if ans == 10 ** 9:
    ans = -1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc142/tasks/abc142_f:
Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.
Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

-----Notes-----
For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:
 - V' is a (non-empty) subset of V.
 - E' is the set of all the edges in E that have both endpoints in V'.

-----Constraints-----
 - 1 \leq N \leq 1000
 - 0 \leq M \leq 2000
 - 1 \leq A_i,B_i \leq N
 - A_i \neq B_i
 - All pairs (A_i, B_i) are distinct.
 - All values in input are integers.

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

-----Output-----
If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:
K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

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

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

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

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

import sys
sys.setrecursionlimit(10 ** 6)

n, m = list(map(int, input().split()))
e = [[] for _ in range(n)]

for _ in range(m):
    a, b = list(map(int, input().split()))
    e[a-1].append(b-1)

c = [0] * n
ans = []
def search_path(p, temp):
    c[p] = 1
    for x in e[p]:
        if x in temp:
            print((-99999))
            return
        else:
            search_path(x, temp + [x])

t = 1
for i in range(n):
    if c[i] == 0:
        ans = search_path(i, [i])

print((-1))


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_a:
The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)
We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

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

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

-----Output-----
Print the total horizontal length of the uncovered parts of the window.

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

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

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

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

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

result=a-b*2

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


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_b:
It's now the season of TAKOYAKI FESTIVAL!
This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.
As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.
There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 50
 - 0 \leq d_i \leq 100

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

-----Output-----
Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

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

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

There are three possible choices:
 - Eat the first and second takoyaki. You will restore 3 health points.
 - Eat the second and third takoyaki. You will restore 2 health points.
 - Eat the first and third takoyaki. You will restore 6 health points.
The sum of these values is 11.

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

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

for i in range(0, n-1):
  for t in range(i+1, n):
    con = lis[i] * lis[t]
    ans += con

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_c:
There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.
Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.
Ultimately, how many slimes will be there?

-----Constraints-----
 - 1 \leq N \leq 10^5
 - |S| = N
 - S consists of lowercase English letters.

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

-----Output-----
Print the final number of slimes.

-----Sample Input-----
10
aabbbbaaca

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

Ultimately, these slimes will fuse into abaca.

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

# -*- coding: utf-8 -*-
"""
Created on Wed Sep  9 02:34:35 2020

@author: liang
"""

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

count = 1
for i in range(N-1):
    if S[i] != S[i+1]:
        count += 1
print(count)


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_d:
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.
He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:
 - a < b + c
 - b < c + a
 - c < a + b
How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

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

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

-----Constraints-----
Print the number of different triangles that can be formed.

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

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

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

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

from bisect import bisect_left

N = int(input())
L = sorted(list(map(int,input().split())))
cnt = 0
for i in range(N-2):
    for j in range(i+1,N-1):
        tmp = bisect_left(L,L[i]+L[j])
        cnt += tmp - j - 1

print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_e:
There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.
Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.
Process the following Q queries:
 - The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 300
 - 0 \leq M \leq \frac{N(N-1)}{2}
 - 1 \leq L \leq 10^9
 - 1 \leq A_i, B_i \leq N
 - A_i \neq B_i
 - \left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)
 - \left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)
 - 1 \leq C_i \leq 10^9
 - 1 \leq Q \leq N\left(N-1\right)
 - 1 \leq s_i, t_i \leq N
 - s_i \neq t_i
 - \left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

-----Input-----
Input is given from Standard Input in the following format:
N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

-----Output-----
Print Q lines.
The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

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

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

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.
To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

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

import numpy as np
from scipy.sparse.csgraph import floyd_warshall

N,M,L=map(int,input().split())
INF = 1 << 31
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0

for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(dist)

for i in range(N):
  for j in range(N):
    if dist[i][j]<=L:
      dist[i][j]=1
    else:
      dist[i][j]=INF

dist = floyd_warshall(dist)
dist[dist==INF]=0
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

print(*ans,sep='\n')


I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_f:
Takahashi has N cards. The i-th of these cards has an integer A_i written on it.
Takahashi will choose an integer K, and then repeat the following operation some number of times:
 - Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)
For each K = 1,2, \ldots, N, find the maximum number of times Takahashi can do the operation.

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

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

-----Output-----
Print N integers.
The t-th (1 \le t \le N) of them should be the answer for the case K=t.

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

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

For K = 1, we can do the operation as follows:
 - Choose the first card to eat.
 - Choose the second card to eat.
 - Choose the third card to eat.
For K = 2, we can do the operation as follows:
 - Choose the first and second cards to eat.
For K = 3, we cannot do the operation at all. Note that we cannot choose the first and third cards at the same time.

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

from bisect import bisect_left

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

lst = [0] * (N + 1)
for a in A:
    lst[a - 1] += 1
lst.sort() #頻度列

s = [0] * (N + 1)
for i in range(N):
    s[i + 1] = s[i] + lst[i + 1]

# print (lst)
# print (s)

def check(x, k):
    i = bisect_left(lst, x) - 1
    total = x * (N - i) + s[i]
    return total >= x * k

ans = N
for k in range(1, N + 1):
    while True:
        if check(ans, k):
            break
        ans -= 1
    print (ans)


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_a:
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.
Given are two integers A and B.
If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.

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

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

-----Output-----
If Takahashi can calculate A \times B, print the result; if he cannot, print -1.

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

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

2 \times 5 = 10.

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

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


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_b:
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.
Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

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

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

-----Output-----
If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

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

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

10 can be represented as, for example, 2 \times 5.

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

N = int(input())
for i in range(1, 10):
    for k in range(1, 10):
        if(i*k == N):
            print('Yes')
            return
print('No')


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_c:
Takahashi is standing on a multiplication table with infinitely many rows and columns.
The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).
In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).
Given an integer N, find the minimum number of moves needed to reach a square that contains N.

-----Constraints-----
 - 2 \leq N \leq 10^{12}
 - N is an integer.

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

-----Output-----
Print the minimum number of moves needed to reach a square that contains the integer N.

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

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

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

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

N = int(input())

def low_divisors(N):
  K=1
  low_divs = []
  while K*K <= N:
    if N%K == 0:
      low_divs.append(K)
    K += 1

  return low_divs

L_divs = low_divisors(N)
D = []

for i in range(len(L_divs)):
  D.append(L_divs[i]+N//L_divs[i])

print(min(D)-2)


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_d:
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)
We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.
When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq a \leq 100
 - 1 \leq b \leq 100
 - 1 \leq x \leq a^2b

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

-----Output-----
Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

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

-----Sample Output-----
45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

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

import math
a,b,x=map(float,input().split())
volume=a**2*b
if volume<x*2:
    sub=volume-x
    sub=sub/a*2/a
    ans=math.degrees(math.atan(sub/a))
else:
    x=x/a*2/b
    ans=90.0-math.degrees((math.atan(x/b)))
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_e:
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.
In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:
 - A team should assign one member to each food, and should not assign the same member to multiple foods.
 - It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.
 - The score of a team is the longest time it takes for an individual member to finish the food.
Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.
What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

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

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

-----Output-----
Print the minimum possible score of the team.

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

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

They can achieve the score of 2, as follows:
 - Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.
 - Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.
 - Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.
They cannot achieve a score of less than 2, so the answer is 2.

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

import numpy as np
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

N, K = list(map(int, input().split()))
A = np.array(list(map(int, input().split())), dtype = np.int64)
F = np.array(list(map(int, input().split())), dtype = np.int64)
A.sort()
F.sort()
F = F[::-1]

l = 0
r = 10**12 + 100

def solve(num):
	B = num // F
	tmp = np.sum(np.maximum(0, A - B))
	if tmp <= K:
		return 1
	else:
		return 0

while r - l > 1:
	mid = (l + r) // 2
	if solve(mid):
		r = mid
	else:
		l = mid

if solve(l):
	print(l)
else:
	print(r)


I found an interesting problem on https://atcoder.jp/contests/abc144/tasks/abc144_f:
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N.
Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each room except Room N, there is at least one passage going from that room.
Takahashi will escape from the cave. Each time he reaches a room (assume that he has reached Room 1 at the beginning), he will choose a passage uniformly at random from the ones going from that room and take that passage.
Aoki, a friend of Takahashi's, can block one of the passages (or do nothing) before Takahashi leaves Room 1. However, it is not allowed to block a passage so that Takahashi is potentially unable to reach Room N.
Let E be the expected number of passages Takahashi takes before he reaches Room N. Find the value of E when Aoki makes a choice that minimizes E.

-----Constraints-----
 - 2 \leq N \leq 600
 - N-1 \leq M \leq \frac{N(N-1)}{2}
 - s_i < t_i
 - If i != j, (s_i, t_i) \neq (s_j, t_j). (Added 21:23 JST)
 - For every v = 1, 2, ..., N-1, there exists i such that v = s_i.

-----Input-----
Input is given from Standard Input in the following format:
N M
s_1 t_1
:
s_M t_M

-----Output-----
Print the value of E when Aoki makes a choice that minimizes E.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

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

-----Sample Output-----
1.5000000000

If Aoki blocks the passage from Room 1 to Room 2, Takahashi will go along the path 1 → 3 → 4 with probability \frac{1}{2} and 1 → 4 with probability \frac{1}{2}. E = 1.5 here, and this is the minimum possible value of E.

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

N, M = map(int, input().split())
edge_out = [[] for i in range(N)] #edge_out[i]はiから出ている道
edge_in = [[] for i in range(N + 1)] # edge_in[i]はiに行く道
for i in range(M):
    s, t = map(int, input().split())
    edge_out[s].append(t)
    edge_in[t].append(s)

edge_sum = [len(edge_out[i]) for i in range(N)] # edge_sum[i] = iから出ている道の本数

dp = [0.0]*(N + 1) # dp[i]はiからNへの距離の期待値
dp[N - 1] = 1.0
# 道を塞がない場合
for i in range(N - 2, 0, - 1):
    dp[i] = 1 + sum(dp[j] for j in edge_out[i])/edge_sum[i]

p_to_i = [0]*(N + 1) # p_to_i[i]は1から各iへ到達する確率
p_to_i[1] = 1
for i in range(2, N + 1):
    p_to_i[i] = sum(p_to_i[j]/edge_sum[j] for j in edge_in[i])

t = 0

for i in range(1, N - 1):
    if edge_sum[i] == 1:
        continue
        # iから出ている道の先にある部屋のうち、その部屋からNまでの距離の期待値が最も大きいものへ通ずる道を塞ぐ
    t = max(t, p_to_i[i]*(dp[i] - 1- ((dp[i] - 1)*edge_sum[i] - max(dp[j] for j in edge_out[i]))/(edge_sum[i] - 1)))

print(dp[1] - t)


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_a:
Given is an integer r.
How many times is the area of a circle of radius r larger than the area of a circle of radius 1?
It can be proved that the answer is always an integer under the constraints given.

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

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

-----Output-----
Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

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

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

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.
Note that output must be an integer - for example, 4.0 will not be accepted.

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


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_b:
Given are a positive integer N and a string S of length N consisting of lowercase English letters.
Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

-----Constraints-----
 - 1 \leq N \leq 100
 - S consists of lowercase English letters.
 - |S| = N

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

-----Output-----
If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

-----Sample Input-----
6
abcabc

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

Let T =  abc, and S = T + T.

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

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

ans = 'No'
# Nが偶数のときを考えればよい
if N % 2 == 0:
  if S[:N // 2] == S[N // 2:]: ans = 'Yes'

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_c:
There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.
There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

-----Constraints-----
 - 2 \leq N \leq 8
 - -1000 \leq x_i \leq 1000
 - -1000 \leq y_i \leq 1000
 - \left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)
 - (Added 21:12 JST) All values in input are integers.

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

-----Output-----
Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

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

-----Sample Output-----
2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.
The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.
By calculating the lengths of the other paths in this way, we see that the average length of all routes is:
\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

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

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

def slove():
    N = int(input())
    town_position = np.array([list(map(float,input().split())) for i in range(N)])
    distance = 0
    for i in range(N-1):
        x1, y1 = town_position[i]
        for j in range(i+1,N):
            x2, y2 = town_position[j]
            distance += np.sqrt((x2-x1)**2 + (y2-y1)**2)

    ans = distance * 2 / N
    print(ans)

def __starting_point():
    slove()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_d:
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.

-----Constraints-----
 - 1 \leq X \leq 10^6
 - 1 \leq Y \leq 10^6
 - All values in input are integers.

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

-----Output-----
Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

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

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

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

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

X, Y = map(int, input().split())
MOD = 10 ** 9 + 7

def modpow(x, n):
    ret = 1
    while n > 0:
        if n & 1:
            ret = ret * x % MOD
        x = x * x % MOD
        n >>= 1
    return ret

def modinv(x):
    return modpow(x, MOD - 2)

def modf(x):
    ret = 1
    for i in range(2, x + 1):
        ret *= i
        ret %= MOD
    return ret

ans = 0
if (X + Y) % 3 == 0:
    m = (2 * X - Y) // 3
    n = (2 * Y - X) // 3
    if m >= 0 and n >= 0:
        ans = modf(m + n) * modinv(modf(n) * modf(m))
        ans %= MOD
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_e:
Takahashi is at an all-you-can-eat restaurant.
The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.
The restaurant has the following rules:
 - You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.
 - You cannot order the same kind of dish more than once.
 - Until you finish eating the dish already served, you cannot order a new dish.
 - After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.
Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.
What is the maximum possible happiness achieved by making optimal choices?

-----Constraints-----
 - 2 \leq N \leq 3000
 - 1 \leq T \leq 3000
 - 1 \leq A_i \leq 3000
 - 1 \leq B_i \leq 3000
 - All values in input are integers.

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

-----Output-----
Print the maximum possible happiness Takahashi can achieve.

-----Sample Input-----
2 60
10 10
100 100

-----Sample Output-----
110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.
Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

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

from numpy import*
N,T,*L=int_(open(0).read().split())
d=int_([0]*6010)
for w,v in sorted(zip(*[iter(L)]*2)):d[w:T+w]=maximum(d[w:T+w],d[:T]+v)
print(max(d))


I found an interesting problem on https://atcoder.jp/contests/abc145/tasks/abc145_f:
We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns.

The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column.

Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive).

Different values can be chosen for different columns.

Then, you will create the modified artwork by repeating the following operation:

 - Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)
Find the minimum number of times you need to perform this operation.

-----Constraints-----
 - 1 \leq N \leq 300
 - 0 \leq K \leq N
 - 0 \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_2 ... H_N

-----Output-----
Print the minimum number of operations required.

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

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

For example, by changing the value of H_3 to 2, you can create the modified artwork by the following three operations:
 - Paint black the 1-st through 4-th squares from the left in the 1-st row from the bottom.
 - Paint black the 1-st through 3-rd squares from the left in the 2-nd row from the bottom.
 - Paint black the 2-nd square from the left in the 3-rd row from the bottom.

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

def solve():
    from sys import stdin
    f_i = stdin

    N, K = map(int, f_i.readline().split())
    H = tuple(map(int, f_i.readline().split()))

    if N == K:
        return 0

    dp1 = list(H)
    for i in range(1, N - K):
        dp2 = dp1[:i]
        for x, H_x in enumerate(H[i:], start=i):
            v = min(dp_j + max(0, H_x - H_j) for dp_j, H_j in zip(dp1[i-1:x], H[i-1:x]))
            dp2.append(v)
        dp1 = dp2
    return min(dp1[N-K-1:])

print(solve())


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_a:
Given is a string S representing the day of the week today.
S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.
After how many days is the next Sunday (tomorrow or later)?

-----Constraints-----
 - S is SUN, MON, TUE, WED, THU, FRI, or SAT.

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

-----Output-----
Print the number of days before the next Sunday.

-----Sample Input-----
SAT

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

It is Saturday today, and tomorrow will be Sunday.

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

Week = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
S = input()
print(7 - Week.index(S))


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_b:
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).

-----Constraints-----
 - 0 \leq N \leq 26
 - 1 \leq |S| \leq 10^4
 - S consists of uppercase English letters.

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

-----Output-----
Print the string resulting from shifting each character of S by N in alphabetical order.

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

-----Sample Output-----
CDEZAB

Note that A follows Z.

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

N=int(input())
S=input()
ans=[]

for i in range(len(S)):
	temp=ord(S[i])
	if temp+N>90:
		ans.append(chr(temp+N-26))

	else:
		ans.append(chr(temp+N))

print(("".join(ans)))


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_c:
Takahashi has come to an integer shop to buy an integer.
The shop sells the integers from 1 through 10^9. The integer N is sold for A \times N + B \times d(N) yen (the currency of Japan), where d(N) is the number of digits in the decimal notation of N.
Find the largest integer that Takahashi can buy when he has X yen. If no integer can be bought, print 0.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A \leq 10^9
 - 1 \leq B \leq 10^9
 - 1 \leq X \leq 10^{18}

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

-----Output-----
Print the greatest integer that Takahashi can buy. If no integer can be bought, print 0.

-----Sample Input-----
10 7 100

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

The integer 9 is sold for 10 \times 9 + 7 \times 1 = 97 yen, and this is the greatest integer that can be bought.
Some of the other integers are sold for the following prices:
 - 10: 10 \times 10 + 7 \times 2 = 114 yen
 - 100: 10 \times 100 + 7 \times 3 = 1021 yen
 - 12345: 10 \times 12345 + 7 \times 5 = 123485 yen

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

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

lo = 1
hi = 10**9
idx = 0
while lo<=hi:
    idx = (lo+hi)//2
    m = a*idx + b*len(str(idx))
    if m==x:
        hi = idx
        break
    elif m>x:
        hi = idx - 1
    else:
        lo = idx + 1
print(hi)


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_d:
Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.
Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.
Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

-----Constraints-----
 -  2 \le N \le 10^5
 -  1 \le a_i \lt b_i \le N
 - All values in input are integers.
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

-----Output-----
Print N lines.
The first line should contain K, the number of colors used.
The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.
If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

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

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

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

from collections import deque

n=int(input())
r=[[] for _ in range(n)]
kumi=[]
for _ in range(n-1):
  s=list(map(int,input().split()))
  kumi.append(str(s[0]-1)+'+'+str(s[1]-1))
  r[s[0]-1].append(s[1]-1)
  r[s[1]-1].append(s[0]-1)

ans=0
for i in range(n):
  ans=max(len(r[i]),ans)

print(ans)

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

iro=[-1 for _ in range(n)]
iro[0]=1
ch=1
d=[]
di={}
for i in r[0]:
  iro[i]=ch
  di[str(min(0,i))+'+'+str(max(0,i))]=ch
  ch+=1
  d.append(i)

d=deque(d)

while d:
  v=d.popleft()
  ch=1
  for i in r[v]:
    if iro[i]==-1:
      if ch==iro[v]:
        ch+=1
        iro[i]=ch
        di[str(min(v,i))+'+'+str(max(v,i))]=ch
        ch+=1
      else:
        iro[i]=ch
        di[str(min(v,i))+'+'+str(max(v,i))]=ch
        ch+=1

      d.append(i)

for g in kumi:
  print((di[g]))


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_e:
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.
Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

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

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

-----Output-----
Print the number of subsequences that satisfy the condition.

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

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

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

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

from collections import defaultdict

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

S = [0]
for i in range(N):
    S.append((S[-1]+A[i]-1)%K)

D = defaultdict(int)

count = 0

for i in range(N+1):
    count += D[S[i]]
    D[S[i]] += 1
    if i-K+1 >= 0:
        D[S[i-K+1]] -= 1

print(count)


I found an interesting problem on https://atcoder.jp/contests/abc146/tasks/abc146_f:
Takahashi is playing a board game called Sugoroku.
On the board, there are N + 1 squares numbered 0 to N. Takahashi starts at Square 0, and he has to stop exactly at Square N to win the game.
The game uses a roulette with the M numbers from 1 to M. In each turn, Takahashi spins the roulette. If the number x comes up when he is at Square s, he moves to Square s+x. If this makes him go beyond Square N, he loses the game.
Additionally, some of the squares are Game Over Squares. He also loses the game if he stops at one of those squares. You are given a string S of length N + 1, representing which squares are Game Over Squares. For each i (0 \leq i \leq N), Square i is a Game Over Square if S[i] = 1 and not if S[i] = 0.
Find the sequence of numbers coming up in the roulette in which Takahashi can win the game in the fewest number of turns possible. If there are multiple such sequences, find the lexicographically smallest such sequence. If Takahashi cannot win the game, print -1.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - |S| = N + 1
 - S consists of 0 and 1.
 - S[0] = 0
 - S[N] = 0

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

-----Output-----
If Takahashi can win the game, print the lexicographically smallest sequence among the shortest sequences of numbers coming up in the roulette in which Takahashi can win the game, with spaces in between.
If Takahashi cannot win the game, print -1.

-----Sample Input-----
9 3
0001000100

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

If the numbers 1, 3, 2, 3 come up in this order, Takahashi can reach Square 9 via Square 1, 4, and 6. He cannot reach Square 9 in three or fewer turns, and this is the lexicographically smallest sequence in which he reaches Square 9 in four turns.

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

import sys
N, M = map(int,input().split())
S = input()
S = S[::-1]
i = 0
ans = []
while i < N:
    flag = 0
    for j in range(M,0,-1):
        if i + j <= N and S[i + j] == '0':
            i += j
            flag = 1
            ans.append(j)
            break
    if flag:
        continue
    print(-1)
    return
ans.reverse()
print(*ans)


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_a:
Given are three integers A_1, A_2, and A_3.
If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

-----Constraints-----
 - 1 \leq A_i \leq 13 \ \ (i=1,2,3)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
A_1 A_2 A_3

-----Output-----
If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

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

-----Sample Output-----
win

5+7+9=21, so print win.

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


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_b:
Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.
Given is a string S. Find the minimum number of hugs needed to make S palindromic.

-----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-----
Print the minimum number of hugs needed to make S palindromic.

-----Sample Input-----
redcoder

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

For example, we can change the fourth character to o and get a palindrome redooder.

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

S = input()
dis = len(S)-1
ans = 0
for i in range(len(S)//2):
    if S[i] != S[dis]:
        ans += 1
    dis -= 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_c:
There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.
Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.
How many honest persons can be among those N people at most?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 15
 - 0 \leq A_i \leq N - 1
 - 1 \leq x_{ij} \leq N
 - x_{ij} \neq i
 - x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)
 - y_{ij} = 0, 1

-----Input-----
Input is given from Standard Input in the following format:
N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

-----Output-----
Print the maximum possible number of honest persons among the N people.

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

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

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

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

from sys import stdin, stdout # only need for big input

max_honest = 0
testomonies = []
state = []

def dfs(person):
    nonlocal max_honest
    if person >= len(state):
        correctState = True
        for p in range(len(state)):
            if state[p] == 1:
                for t in testomonies[p]:
                    x, y = t
                    if state[x] != y:
                        correctState = False
                        break
        if correctState:
            sum = 0
            for s in state:
                sum += s
            max_honest = max(max_honest, sum)
        return

    state[person] = 0
    dfs(person + 1)

    state[person] = 1
    dfs(person + 1)

def solve():
    nonlocal state
    n = int(stdin.readline())
    for _ in range(n):
        a = int(stdin.readline())
        t = []
        for _ in range(a):
            x, y = [int(inp) for inp in stdin.readline().split()]
            t.append((x - 1,y))
        testomonies.append(t)
    # print(testomonies)
    state = [-1] * n
    dfs(0)
    print(max_honest)

def main():
    solve()

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_d:
We have N integers. The i-th integer is A_i.
Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).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-----
 - 2 \leq N \leq 3 \times 10^5
 - 0 \leq A_i < 2^{60}
 - All values in input are integers.

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

-----Output-----
Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

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

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

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

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

import sys

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

def resolve():
    n = int(input())
    A = list(map(int, input().split()))

    res = 0
    for i in range(60):
        cnt_one = 0
        for a in A:
            if (a >> i) & 1:
                cnt_one += 1
        res += (n - cnt_one) * cnt_one * pow(2, i)
        res %= mod
    print(res)

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_e:
We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
The square (i, j) has two numbers A_{ij} and B_{ij} written on it.
First, for each square, Takahashi paints one of the written numbers red and the other blue.
Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.
Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).
Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.
Find the minimum unbalancedness possible.

-----Constraints-----
 - 2 \leq H \leq 80
 - 2 \leq W \leq 80
 - 0 \leq A_{ij} \leq 80
 - 0 \leq B_{ij} \leq 80
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

-----Output-----
Print the minimum unbalancedness possible.

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

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

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

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

def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

    h,w = map(int, input().split())
    a = [list(map(int, input().split())) for _ in range(h)]
    b = [list(map(int, input().split())) for _ in range(h)]
    c = [[0]*w for _ in range(h)]
    for i in range(h):
        for j in range(w):
            c[i][j] = abs(a[i][j] -b[i][j])

    mid = 12800
    dp = [[0]*w for _ in range(h)]
    dp[0][0] = (1<<(mid+c[0][0])) | (1<<(mid-c[0][0]))
    for x in range(h):
        for y in range(w):
            for dx, dy in [[0, 1], [1, 0]]:
                nx = x + dx
                ny = y + dy
                if 0<=nx<h and 0<=ny<w:
                    dp[nx][ny] = dp[nx][ny] | (dp[x][y]<<c[nx][ny])
                    dp[nx][ny] = dp[nx][ny] | (dp[x][y]>>c[nx][ny])

    for i in range(mid+1):
        if (dp[-1][-1]>>i) & 1:
            res = mid - i

    print(res)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc147/tasks/abc147_f:
We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq  i < N ) holds.
Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.
Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible values of S - T are there?

-----Constraints-----
 - -10^8 \leq X, D \leq 10^8
 - 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 X D

-----Output-----
Print the number of possible values of S - T.

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

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

A is (4, 6, 8).
There are eight ways for (Takahashi, Aoki) to take the elements: ((), (4, 6, 8)), ((4), (6, 8)), ((6), (4, 8)), ((8), (4, 6))), ((4, 6), (8))), ((4, 8), (6))), ((6, 8), (4))), and ((4, 6, 8), ()).
The values of S - T in these ways are -18, -10, -6, -2, 2, 6, 10, and 18, respectively, so there are eight possible values of S - T.

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

import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

# 総和は一定なので高橋君が何点(?)とるかの問題に置き換えられる
# d=0かつx=0のときは1、x!=0ならn+1で確定
# d,xと-d,-xは同値なので、dを正にすることで増加数列で考える
# d,xを同じ数で割っても答えは変わらないので、互いに素にする
def gcd(a, b):
    if b == 0: return a
    return gcd(b, a % b)

def main():
    n, x, d = MI()
    if d == 0:
        if x == 0:
            print(1)
        else:
            print(n + 1)
        return
    if d < 0: d, x = -d, -x
    g = gcd(d, abs(x))
    d, x = d // g, x // g
    #print(x, d)
    # aをk個選ぶと和sはs=k*x+c*dで、cは最小で0からk-1の和
    # 最大でn-kからn-1の和
    # kを固定するとs//dは1ずつの単調増加なので、最小と最大で個数が分かる
    # sはs mod d = x*k mod dが同じなので、それで分類する
    kk = list(range(n + 1))
    kk.sort(key=lambda k: (k * x % d, k))
    #print(kk)
    ans = 0
    pmd = -1
    pl, pr = 1, 0
    for k in kk:
        l = (k * x + (k - 1) * k // 2 * d) // d
        r = (k * x + (2 * n - k - 1) * k // 2 * d) // d
        md = x * k % d
        if md == pmd and l <= pr and pl<=r:
            pl,pr=min(pl,l),max(pr,r)
        else:
            ans += pr - pl + 1
            pl, pr = l, r
        pmd = md
        #print(k, l, r, pl, pr, ans)
    ans += pr - pl + 1
    print(ans)

main()


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_a:
Takahashi is solving quizzes. He has easily solved all but the last one.
The last quiz has three choices: 1, 2, and 3.
With his supernatural power, Takahashi has found out that the choices A and B are both wrong.
Print the correct choice for this problem.

-----Constraints-----
 - Each of the numbers A and B is 1, 2, or 3.
 - A and B are different.

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

-----Output-----
Print the correct choice.

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

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

When we know 3 and 1 are both wrong, the correct choice is 2.

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

a = int(input())
b = int(input())
print(6-a-b)


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_b:
Given are strings s and t of length N each, both consisting of lowercase English letters.
Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

-----Constraints-----
 - 1 \leq N \leq 100
 - |S| = |T| = N
 - S and T are strings consisting of lowercase English letters.

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

-----Output-----
Print the string formed.

-----Sample Input-----
2
ip cc

-----Sample Output-----
icpc

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

n = int(input())
s,t = map(str, input().split())
ans = list()
for i in range(n):
	ans.append(s[i])
	ans.append(t[i])
print(*ans,sep="")


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_c:
Takahashi is organizing a party.
At the party, each guest will receive one or more snack pieces.
Takahashi predicts that the number of guests at this party will be A or B.
Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.
We assume that a piece cannot be divided and distributed to multiple guests.

-----Constraints-----
 - 1 \leq A, B \leq 10^5
 - A \neq B
 - All values in input are integers.

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

-----Output-----
Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

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

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

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

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

import math
#h,w=map(int,input().split())
#S=[list(map(int,input().split())) for _ in range(h)]
a,b=list(map(int,input().split()))
print(((a*b)//math.gcd(a,b)))


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_d:
We have N bricks arranged in a row from left to right.
The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.
Among them, you can break at most N-1 bricks of your choice.
Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.
Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 200000
 - 1 \leq a_i \leq N

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

-----Output-----
Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

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

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

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

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

N = int(input())

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

count = 0
for i in a:
    if i == count + 1:
        count += 1
if count != 0:
    print(N - count)
else:
    print('-1')


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_e:
For an integer n not less than 0, let us define f(n) as follows:
 - f(n) = 1 (if n < 2)
 - f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).

-----Constraints-----
 - 0 \leq N \leq 10^{18}

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

-----Output-----
Print the number of trailing zeros in the decimal notation of f(N).

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

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

f(12) = 12 × 10 × 8 × 6 × 4 × 2 = 46080, which has one trailing zero.

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

n = int(input())
i = 10
ans = 0

while  i <= n:
    ans += (n // i)
    i *= 5

print((ans if n & 1 == 0 else 0))


I found an interesting problem on https://atcoder.jp/contests/abc148/tasks/abc148_f:
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:
 - 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
 - 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
 - 3. Go back to step 1.
Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible.
Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy.
It can be proved that the game is bound to end.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq u,v \leq N
 - u \neq v
 - 1 \leq A_i,B_i \leq N
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N u v
A_1 B_1
:
A_{N-1} B_{N-1}

-----Output-----
Print the number of moves Aoki will perform before the end of the game.

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

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

If both players play optimally, the game will progress as follows:
 - Takahashi moves to Vertex 3.
 - Aoki moves to Vertex 2.
 - Takahashi moves to Vertex 5.
 - Aoki moves to Vertex 3.
 - Takahashi moves to Vertex 3.
Here, Aoki performs two moves.
Note that, in each move, it is prohibited to stay at the current vertex.

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

import sys
sys.setrecursionlimit(10**9)
f=lambda:map(int,sys.stdin.readline().split())
n,st,sa=f()
g=[set() for _ in range(n)]
for _ in range(n-1):
  a,b=f()
  g[a-1].add(b-1)
  g[b-1].add(a-1)
def dfs(l,v,p=-1,d=0):
  l[v]=d
  for c in g[v]:
    if c!=p: dfs(l,c,v,d+1)
lt=[0]*n
dfs(lt,st-1)
la=[0]*n
dfs(la,sa-1)
print(max(la[i] for i in range(n) if lt[i]<la[i])-1)


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_a:
Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

-----Constraints-----
 - S and T are strings consisting of lowercase English letters.
 - The lengths of S and T are between 1 and 100 (inclusive).

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

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

-----Sample Input-----
oder atc

-----Sample Output-----
atcoder

When S =  oder and T =  atc, concatenating T and S in this order results in atcoder.

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


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_b:
Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:
 - If Takahashi has one or more cookies, eat one of his cookies.
 - Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.
 - If they both have no cookies, do nothing.
In the end, how many cookies will Takahashi and Aoki have, respectively?

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

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

-----Output-----
Print the numbers of Takahashi's and Aoki's cookies after K actions.

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

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

Takahashi will do the following:
 - He has two cookies, so he eats one of them.
 - Now he has one cookie left, and he eats it.
 - Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.
Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

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

a, b, k = (int(n) for n in input().split())
if k < a: print(a-k, b)
elif a <= k <= a + b: print("0", b - (k - a))
else:print("0","0")


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_c:
Find the minimum prime number greater than or equal to X.

-----Notes-----
A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.
For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

-----Constraints-----
 -  2 \le X \le 10^5
 - All values in input are integers.

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

-----Output-----
Print the minimum prime number greater than or equal to X.

-----Sample Input-----
20

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

The minimum prime number greater than or equal to 20 is 23.

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

x = int(input())

def isprime(s):
  if s>2 and s%2==0:
    return False
  else:
    flg = True
    for i in range(3, s//2+1, 2):
      if s%i == 0:
        flg = False
        break
    return flg

for i in range(x, 10**6):
  if isprime(i) == True:
    print(i)
    break


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_d:
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
 - The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
 - Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):
 - R points for winning with Rock;
 - S points for winning with Scissors;
 - P points for winning with Paper.
 - However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)
Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.
The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.
What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

-----Notes-----
In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.
 - If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;
 - if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;
 - if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;
 - if both players play the same hand, it is a draw.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq K \leq N-1
 - 1 \leq R,S,P \leq 10^4
 - N,K,R,S, and P are all integers.
 - |T| = N
 - T consists of r, p, and s.

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

-----Output-----
Print the maximum total score earned in the game.

-----Sample Input-----
5 2
8 7 6
rsrpr

-----Sample Output-----
27

The machine...

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

# import itertools
# import math
# import sys
# sys.setrecursionlimit(500*500)
# import numpy as np

# N = int(input())
# S = input()
# n, *a = map(int, open(0))
N, K = map(int, input().split())
# A = list(map(int, input().split()))
# B = list(map(int, input().split()))
# tree = [[] for _ in range(N + 1)]
# B_C = [list(map(int,input().split())) for _ in range(M)]
# S = input()

# B_C = sorted(B_C, reverse=True, key=lambda x:x[1])
# all_cases = list(itertools.permutations(P))
# a = list(itertools.combinations_with_replacement(range(1, M + 1), N))
# itertools.product((0,1), repeat=n)

# A = np.array(A)
# cum_A = np.cumsum(A)
# cum_A = np.insert(cum_A, 0, 0)

# def dfs(tree, s):
#     for l in tree[s]:
#         if depth[l[0]] == -1:
#             depth[l[0]] = depth[s] + l[1]
#             dfs(tree, l[0])
# dfs(tree, 1)

# def factorization(n):
#     arr = []
#     temp = n
#     for i in range(2, int(-(-n**0.5//1))+1):
#         if temp%i==0:
#             cnt=0
#             while temp%i==0:
#                 cnt+=1
#                 temp //= i
#             arr.append([i, cnt])
#     if temp!=1:
#         arr.append([temp, 1])
#     if arr==[]:
#         arr.append([n, 1])
#     return arr

R, S, P = map(int, input().split())
T = input()
win = {"r": ["p", P], "s": ["r", R], "p": ["s", S]}

hands = []
tot = 0
for i, c in enumerate(T):
    if i >= K and win[c][0] == hands[i - K]:
        hands.append("anything")
        continue
    hands.append(win[c][0])
    tot += win[c][1]

print(tot)


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_e:
Takahashi has come to a party as a special guest.
There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.
Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0).
A handshake will be performed as follows:
 - Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).
 - Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.
However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:
 - Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).
What is the maximum possible happiness after M handshakes?

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 1 \leq M \leq N^2
 - 1 \leq A_i \leq 10^5
 - 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 maximum possible happiness after M handshakes.

-----Sample Input-----
5 3
10 14 19 34 33

-----Sample Output-----
202

Let us say that Takahashi performs the following handshakes:
 - In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4.
 - In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5.
 - In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4.
Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202.
We cannot achieve the happiness of 203 or greater, so the answer is 202.

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

from bisect import bisect_left
from itertools import accumulate
def resolve():
    def getCount(x):
        count = 0
        for Ai in A:
            idx = bisect_left(A, x - Ai)
            count += N - idx
        return count >= M

    N, M = list(map(int, input().split()))
    A = sorted(map(int, input().split()))
    A_r = A[::-1]
    B = [0] + list(accumulate(A_r))

    MIN = 0
    MAX = 2 * 10 ** 5 + 1
    while MAX - MIN > 1:
        MID = (MIN + MAX) // 2
        if getCount(MID):
            MIN = MID
        else:
            MAX = MID

    ans = 0
    count = 0

    for Ai in A_r:
        idx = bisect_left(A, MIN - Ai)
        ans += Ai * (N - idx) + B[N - idx]
        count += N - idx
    print((ans - (count - M) * MIN))

def __starting_point():
    resolve()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc149/tasks/abc149_f:
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)
Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.
Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.

-----Notes-----
When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers, and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).
Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq A_i,B_i \leq N
 - The given graph is a tree.

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_{N-1} B_{N-1}

-----Output-----
Print the expected holeyness of S, \bmod 10^9+7.

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

-----Sample Output-----
125000001

If the vertices 1, 2, 3 are painted black, white, black, respectively, the holeyness of S is 1.
Otherwise, the holeyness is 0, so the expected holeyness is 1/8.
Since 8 \times 125000001 \equiv 1 \pmod{10^9+7}, we should print 125000001.

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

#f
import sys
sys.setrecursionlimit(2 * 10 ** 5 + 10)

n = int(input())
E = [[] for _ in range(n)]
mod = 10**9 + 7

for i in range(n-1):
    a,b = [int(x) for x in input().split()]
    E[a-1].append((b-1, i))
    E[b-1].append((a-1, i))

X = [0] * n

def dfs(u,e):
    num = 1
    for v,c in E[u]:
        if c != e:
            num += dfs(v,c)
    X[e] = num
    return num

dfs(0, -1)

I = [1]
inv = pow(2, mod-2, mod)
for i in range(n):
    I.append(I[-1] * inv % mod)

ans = 0
for i in range(n):
    x = X[i]
    ans += (1-I[x])*(1-I[n-x]) % mod

ans -= n * I[1]
ans += 1 - I[n]
ans %= mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_a:
Takahashi has K 500-yen coins. (Yen is the currency of Japan.)
If these coins add up to X yen or more, print Yes; otherwise, print No.

-----Constraints-----
 - 1 \leq K \leq 100
 - 1 \leq X \leq 10^5

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

-----Output-----
If the coins add up to X yen or more, print Yes; otherwise, print No.

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

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

Two 500-yen coins add up to 1000 yen, which is not less than X = 900 yen.

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

k, x = map(int, input().split())
if k * 500 >= x:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc150/tasks/abc150_b:
We have a string S of length N consisting of uppercase English letters.
How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

-----Constraints-----
 - 3 \leq N \leq 50
 - S consists of uppercase English letters.

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

-----Output-----
Print number of occurrences of ABC in S as contiguous subsequences.

-----Sample Input-----
10
ZABCDBABCQ

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

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

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

n = int(input())
lst = list(input())
count = 0
for i in range(0, len(lst)):
    if lst[i - 2] == 'A' and lst[i - 1] == 'B' and lst[i] == 'C':
        count += 1

print(count)