I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_e:
You are going to eat X red apples and Y green apples.

You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.

Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively.

From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible.

Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples.

-----Constraints-----
 - 1 \leq X \leq A \leq 10^5
 - 1 \leq Y \leq B \leq 10^5
 - 1 \leq C \leq 10^5
 - 1 \leq p_i \leq 10^9
 - 1 \leq q_i \leq 10^9
 - 1 \leq r_i \leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
X Y A B C
p_1 p_2 ... p_A
q_1 q_2 ... q_B
r_1 r_2 ... r_C

-----Output-----
Print the maximum possible sum of the deliciousness of the eaten apples.

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

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

The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows:
 - Eat the 2-nd red apple.
 - Eat the 1-st green apple.
 - Paint the 1-st colorless apple green and eat it.

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

from collections import deque

X,Y,A,B,C = map(int, input().split())
A=[int(a) for a in input().split()]
B=[int(b) for b in input().split()]
C=[int(c) for c in input().split()]

A=sorted(A, reverse=True)[:X]
B=sorted(B, reverse=True)[:Y]
AB=deque(sorted(A+B))

for c in sorted(C, reverse=True):
  if c >= AB[0]:
    AB.popleft()
    AB.append(c)
  else:
    break

print(sum(AB))


I found an interesting problem on https://atcoder.jp/contests/abc160/tasks/abc160_f:
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i.
For each k=1, ..., N, solve the problem below:
 - Consider writing a number on each vertex in the tree in the following manner:
 - First, write 1 on Vertex k.
 - Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
 - Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
 - Find the number of ways in which we can write the numbers on the vertices, modulo (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-----
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.

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

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

The graph in this input is as follows:

For k=1, there are two ways in which we can write the numbers on the vertices, as follows:
 - Writing 1, 2, 3 on Vertex 1, 2, 3, respectively
 - Writing 1, 3, 2 on Vertex 1, 2, 3, respectively

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

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def ZIP(n): return list(zip(*(MAP() for _ in range(n))))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
lim = N+10  # 必要そうな階乗の限界を入れる
fact = [1] * (lim+1)
fact_inv = [1] * (lim+1)
for n in range(1, lim+1):
    fact[n] = (fact[n-1] * n) % mod
fact_inv[lim] = pow(fact[lim], mod-2, mod)
for n in range(lim, 0, -1):
    fact_inv[n-1] = (n * fact_inv[n]) % mod

tree = [[] for _ in range(N+1)]  # 1-indexed
for _ in range(N-1):
	a, b = MAP()
	tree[a].append(b)
	tree[b].append(a)

root = 1
parent = [0]*(N+1)
order = []
stack = [root]
while stack:
    x = stack.pop()
    order.append(x)
    for y in tree[x]:
        if y == parent[x]:
            continue
        parent[y] = x
        stack.append(y)

size_d = [0]*(N+1)
dp_d = [1]*(N+1)

for v in order[::-1]:  # 根に遠いほうから(down方向のボトムアップ)
    dp_d[v] *= fact[size_d[v]]
    dp_d[v] %= mod
    p = parent[v]
    s = size_d[v] + 1
    size_d[p] += s
    dp_d[p] *= fact_inv[s] * dp_d[v]
    dp_d[p] %= mod

size_u = [N-1-x for x in size_d]
dp_u = [1]*(N+1)

def merge(p1, p2):
    den_inv1, v1 = p1
    den_inv2, v2 = p2
    return den_inv1*den_inv2%mod, v1*v2%mod

for v in order:
    p = parent[v]
    arr = [(fact_inv[size_d[node]+1], dp_d[node]) if node != p else (fact_inv[size_u[v]], dp_u[v]) for node in tree[v]]
    left = [(1, 1)] + list(accumulate(arr, merge))[:-1]
    right = list(accumulate(arr[::-1],...


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_a:
We have three boxes A, B, and C, each of which contains an integer.

Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.

We will now do the operations below in order. Find the content of each box afterward.
 - Swap the contents of the boxes A and B
 - Swap the contents of the boxes A and C

-----Constraints-----
 - 1 \leq X,Y,Z \leq 100
 - All values in input are integers.

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

-----Output-----
Print the integers contained in the boxes A, B, and C, in this order, with space in between.

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

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

After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.

Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.

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

x,y,z = map(int,input().split())
print(z,x,y)


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_b:
We have held a popularity poll for N items on sale. Item i received A_i votes.
From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.
If M popular items can be selected, print Yes; otherwise, print No.

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

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

-----Output-----
If M popular items can be selected, print Yes; otherwise, print No.

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

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

There were 12 votes in total. The most popular item received 5 votes, and we can select it.

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

n,m = map(int,input().split())
li = list(map(int,input().split()))
li.sort(reverse=True)

sum = 0
cnt = 0
for i in li:
    sum += i

if li[m-1]*4*m >= sum:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_c:
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

-----Constraints-----
 - 0 ≤ N ≤ 10^{18}
 - 1 ≤ K ≤ 10^{18}
 - All values in input are integers.

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

-----Output-----
Print the minimum possible value taken by N after Aoki does the operation zero or more times.

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

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

Initially, N=7.
After one operation, N becomes |7-4| = 3.
After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

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

n,k = map(int, input().split())
a = n // k
ans = min(abs(n - a*k),abs(n - (a+1)*k))
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_d:
A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
 - In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.
For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.
You are given a positive integer K. Find the K-th smallest lunlun number.

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

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

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

-----Sample Input-----
15

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

We will list the 15 smallest lunlun numbers in ascending order:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

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

from collections import deque

def main() -> None:
    k = int(input())

    d = deque(list(range(1, 10)))
    for _ in range(k):
        num = d.popleft()
        if num % 10 != 0:
            d.append(num*10 + (num%10-1))
        d.append(num*10 + num%10)
        if num % 10 != 9:
            d.append(num*10 + (num%10+1))

    print(num)
    return

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_e:
Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.
You are given an integer C and a string S. Takahashi will choose his workdays as follows:
 - After working for a day, he will refrain from working on the subsequent C days.
 - If the i-th character of S is x, he will not work on Day i, where Day 1 is tomorrow, Day 2 is the day after tomorrow, and so on.
Find all days on which Takahashi is bound to work.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 1 \leq K \leq N
 - 0 \leq C \leq N
 - The length of S is N.
 - Each character of S is o or x.
 - Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

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

-----Output-----
Print all days on which Takahashi is bound to work in ascending order, one per line.

-----Sample Input-----
11 3 2
ooxxxoxxxoo

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

Takahashi is going to work on 3 days out of the 11 days. After working for a day, he will refrain from working on the subsequent 2 days.
There are four possible choices for his workdays: Day 1,6,10, Day 1,6,11, Day 2,6,10, and Day 2,6,11.
Thus, he is bound to work on Day 6.

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

    n,k,c = map(int, input().split())
    s = input().rstrip()
    left = [0]*n
    day = 0
    temp = 0
    while day < n:
        if s[day] == 'o':
            temp += 1
            left[day] = temp
            for i in range(c):
                if day+i+1 < n:
                    left[day+i+1] = temp
            day += c
        else:
            left[day] = temp
        day += 1

    right = [0]*n
    day = n-1
    temp = 0
    while 0 <= day:
        if s[day] == 'o':
            temp += 1
            right[day] = temp
            for i in range(c):
                if day-i-1 >= 0:
                    right[day-i-1] = temp
            day -= c
        else:
            right[day] = temp
        day -= 1

    res = []
    for i in range(n):
        if s[i] == 'o':
            if i-c-1 < 0:
                pre = 0
            else:
                pre = left[i-c-1]
            if i+c+1 >= n:
                pos = 0
            else:
                pos = right[i+c+1]
            if pre + pos == k-1:
                res.append(i+1)
    for i in range(len(res)):
        if i-1>=0:
            l = res[i-1]
        else:
            l = -1000000
        if i+1<len(res):
            r = res[i+1]
        else:
            r = 10000000
        if res[i]-l>c and r-res[i] > c:
            print(res[i])

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_f:
Given is a positive integer N.
We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.
 - Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.
In how many choices of K will N become 1 in the end?

-----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 number of choices of K in which N becomes 1 in the end.

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

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

There are three choices of K in which N becomes 1 in the end: 2, 5, and 6.
In each of these choices, N will change as follows:
 - When K=2: 6 \to 3 \to 1
 - When K=5: 6 \to 1
 - When K=6: 6 \to 1

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

# 1は除外
# ・N-1の約数は全て対象
# ・Nの約数で、sqrt(N)以下であればOK　ただしN自身は対象
# これを足し合わせる

N = int(input())

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    return divisors

# N-1の約数の個数
ans = len(make_divisors(N-1)) - 1

def check(n,x):
  # xで割った余りがxの倍数でなくなるまでxで割る
  # xの倍数でなくなったときにxで割って1余ればOK
  while n % x == 0:
    n //= x
  return (n % x == 1)

# Nの約数で2以上sqrt(N)以下の数
for i in range(2,int(N ** 0.5) + 1):
  if N % i == 0:
    if check(N,i):
      ans += 1

# N自身も対象
ans += 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_a:
Given is a three-digit integer N. Does N contain the digit 7?
If so, print Yes; otherwise, print No.

-----Constraints-----
 - 100 \leq N \leq 999

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

-----Output-----
If N contains the digit 7, print Yes; otherwise, print No.

-----Sample Input-----
117

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

117 contains 7 as its last digit.

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

def resolve():
    n = input()
    print('Yes' if '7' in n else 'No')
resolve()


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_b:
Let us define the FizzBuzz sequence a_1,a_2,... as follows:
 - If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.
 - If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.
 - If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.
 - If none of the above holds, a_i=i.
Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

-----Constraints-----
 - 1 \leq N \leq 10^6

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

-----Output-----
Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

-----Sample Input-----
15

-----Sample Output-----
60

The first 15 terms of the FizzBuzz sequence are:
1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}
Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

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

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
#from operator import itemgetter
#from heapq import heappush, heappop
#import numpy as np
#from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
#from scipy.sparse import csr_matrix
#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
import sys

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

N = ni()
ans = 0
for i in range(N+1):
    if i % 3 != 0 and i % 5 != 0:
        ans += i
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_c:
Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.
Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.

-----Constraints-----
 - 1 \leq K \leq 200
 - K is an integer.

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

-----Output-----
Print the value of \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

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

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

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)=1+1+1+1+1+1+1+2=9
Thus, the answer is 9.

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

from math import gcd
def main():
    ans = 0
    k = int(input())
    for i in range(1,1+k):
        for j in range(1,1+k):
            for l in range(1,1+k):
                ans += gcd(i,gcd(j,l))
    print(ans)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_d:
We have a string S of length N consisting of R, G, and B.
Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:
 - S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.
 - j - i \neq k - j.

-----Constraints-----
 - 1 \leq N \leq 4000
 - S is a string of length N consisting of R, G, and B.

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

-----Output-----
Print the number of triplets in question.

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

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

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

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

from collections import Counter
N = int(input())
S = input()
D = Counter(S)
ans = 1
for d in D.values():
    ans *= d

if len(D.values()) < 3:
    ans = 0

for i in range(N):
    for x in range(1, (N-i+1)//2):
        if S[i] != S[i+x] and S[i+x] != S[i+2*x] and S[i+2*x] != S[i]:
            ans -= 1
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_e:
Consider sequences \{A_1,...,A_N\} of length N consisting of integers between 1 and K (inclusive).
There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them.
Since this sum can be enormous, print the value modulo (10^9+7).
Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1, ..., A_N.

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

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

-----Output-----
Print the sum of \gcd(A_1, ..., A_N) over all K^N sequences, modulo (10^9+7).

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

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

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)=1+1+1+1+1+1+1+2=9
Thus, the answer is 9.

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

mod = 10**9 + 7
n,k= [int(i) for i in input().split()]

d = [0] * (k + 1)

for i in range(1,k+1):
    d[i] = pow(k//i,n,mod)

for i in range(k,0,-1):
    for j in range(2*i,k+1,i):
        d[i] -= d[j]
        d[i] %= mod

ans = 0
for idx,i in enumerate(d):
    ans += (idx) * i
    ans %= mod

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc162/tasks/abc162_f:
Given is an integer sequence A_1, ..., A_N of length N.
We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen.
Find the maximum possible sum of the chosen elements.
Here \lfloor x \rfloor denotes the greatest integer not greater than x.

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

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

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

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

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

Choosing 2, 4, and 6 makes the sum 12, which is the maximum possible value.

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

# 写経AC
from collections import defaultdict

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

# dp[(i, x, flag)]:= i番目まででx個選んでいる時の最大値
# flag: i番目をとるフラグ
dp = defaultdict(lambda: -float("inf"))

# 初期条件
dp[(0, 0, 0)] = 0

# 貰うDP
for i, a in enumerate(A, 1):
    # i番目までで選ぶ個数
    for x in range((i // 2) - 1, (i + 1) // 2 + 1):
        dp[(i, x, 0)] = max(dp[(i - 1, x, 0)], dp[(i - 1, x, 1)])
        dp[(i, x, 1)] = dp[(i - 1, x - 1, 0)] + a

print(max(dp[(N, N // 2, 0)], dp[(N, N // 2, 1)]))


I found an interesting problem on https://atcoder.jp/contests/abc163/tasks/abc163_a:
Print the circumference of a circle of radius R.

-----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 circumference of the circle.
Your output is considered correct if and only if its absolute or relative error from our answer is at most 10^{-2}.

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

-----Sample Output-----
6.28318530717958623200

Since we accept an absolute or relative error of at most 10^{-2}, 6.28 is also an acceptable output, but 6 is not.

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

import numpy as np
r= float(input())
print(r*2*np.pi)


I found an interesting problem on https://atcoder.jp/contests/abc163/tasks/abc163_b:
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?
If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

-----Constraints-----
 - 1 \leq N \leq 10^6
 - 1 \leq M \leq 10^4
 - 1 \leq A_i \leq 10^4

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

-----Output-----
Print the maximum number of days Takahashi can hang out during the vacation, or -1.

-----Sample Input-----
41 2
5 6

-----Sample Output-----
30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

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

radi=input()
list=radi.split(" ")
N=int(list[0])
days=input()
total=0
a=days.split(" ")
for items in a:
    total+=int(items)
if total>N:
    print((-1))
else:
    print((N-total))


I found an interesting problem on https://atcoder.jp/contests/abc163/tasks/abc163_c:
A company has N members, who are assigned ID numbers 1, ..., N.
Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.
When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.
You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq A_i < i

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

-----Output-----
For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

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

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

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.
The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.
The members numbered 3, 4, and 5 do not have immediate subordinates.

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

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


N, K = map(int, input().split())
A = [i for i in range(N+1)]
mod = 10**9+7
ans = 0
head = sum(A[:K-1]) if K > 1 else 0
tail = sum(A[-K+1:]) if K > 1 else 0
for i in range(K, N+2):
    head += A[i-1]
    tail += A[-i]
    ans += tail-head+1
    ans = ans % mod

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc163/tasks/abc163_e:
There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.
You can rearrange these children just one time in any order you like.
When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.
Find the maximum total happiness points the children can earn.

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

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

-----Output-----
Print the maximum total happiness points the children can earn.

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

-----Sample Output-----
20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

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

#!/usr/bin/env python3
import sys

def solve(N: int, A: "List[int]"):
    A = sorted(enumerate(A), reverse=True, key=lambda x: x[1])

    dp = [[0 for i in range(N + 1)] for j in range(N + 1)]
    for i in range(N):
        for j in range(0, N - i):
            idx, a = A[i + j]
            #idx = indices[i + j]
            dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + a * abs(idx - i))
            dp[i][j + 1] = max(dp[i][j + 1], dp[i][j] + a * abs(N - 1 - j - idx))
    result = -1
    for i in range(N):
        tmp = dp[i][N - i]
        if tmp > result:
            result = tmp
    print(result)
    return

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc163/tasks/abc163_f:
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i.
Additionally, each vertex is painted in a color, and the color of Vertex i is c_i. Here, the color of each vertex is represented by an integer between 1 and N (inclusive). The same integer corresponds to the same color; different integers correspond to different colors.
For each k=1, 2, ..., N, solve the following problem:
 - Find the number of simple paths that visit a vertex painted in the color k one or more times.
Note: The simple paths from Vertex u to v and from v to u are not distinguished.

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

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

-----Output-----
Print the answers for k = 1, 2, ..., N in order, each in its own line.

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

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

Let P_{i,j} denote the simple path connecting Vertex i and j.
There are 5 simple paths that visit a vertex painted in the color 1 one or more times:
P_{1,1}\,,\,P_{1,2}\,,\,P_{1,3}\,,\,P_{2,3}\,,\,P_{3,3}
There are 4 simple paths that visit a vertex painted in the color 2 one or more times:
P_{1,2}\,,\,P_{1,3}\,,\,P_{2,2}\,,\,P_{2,3}
There are no simple paths that visit a vertex painted in the color 3 one or more times.

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

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
from collections import defaultdict
INF = float("inf")
MOD = 10**9+7

class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, f, t, w=1):
        self.E[f].append(t)
        self.E[t].append(f)

def make_order(g, v):
    seen = [False]*g.N
    last_order = [-1]*g.N
    parent = [-1]*g.N
    size = [1]*g.N
    counter = {"last": 0}

    def recur(v):
        seen[v] = True
        for to in g.E[v]:
            if seen[to] == True:
                continue
            parent[to] = v
            recur(to)
            size[v] += size[to]

        last_order[counter["last"]] = v
        counter["last"] += 1

    recur(v)
    return last_order, parent, size

def merge(d: dict, e: dict):
    if len(d) < len(e):
        d, e = e, d
    for k in e:
        d[k] += e[k]
    return d

N = int(input())
c = [x-1 for x in map(int, input().split())]
A = [None]*(N-1)
B = [None]*(N-1)
for i in range(N-1):
    A[i], B[i] = list(map(int, input().split()))

g = Graph(N)
for a, b in zip(A, B):
    g.add_edge(a-1, b-1)

ans = [0]*N

ret = {}
last_order, parent, size = make_order(g, 0)
for curr in last_order:
    cn = c[curr]
    rrr = defaultdict(int)
    for dest in g.E[curr]:
        if dest == parent[curr]:
            continue
        child = ret.pop(dest)

        n = size[dest]-child[cn]
        ans[cn] += n*(n+1)//2

        # マージ
        rrr = merge(rrr, child)

    rrr[cn] = size[curr]
    ret[curr] = rrr

tot = N*(N+1)//2
for color in range(N):
    if color != c[0]:
        n = N-ret[0][color]
        ans[color] += n*(n+1)//2
    print((tot-ans[color]))


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_a:
There are S sheep and W wolves.
If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.
If the wolves will attack the sheep, print unsafe; otherwise, print safe.

-----Constraints-----
 - 1 \leq S \leq 100
 - 1 \leq W \leq 100

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

-----Output-----
If the wolves will attack the sheep, print unsafe; otherwise, print safe.

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

-----Sample Output-----
unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

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

s, w = map(int, input().split())
if w>=s:
    print("unsafe")
else:
    print("safe")


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_b:
Takahashi and Aoki will have a battle using their monsters.
The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.
The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes 0 or below. The person with the monster whose health becomes 0 or below loses, and the other person wins.
If Takahashi will win, print Yes; if he will lose, print No.

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

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

-----Output-----
If Takahashi will win, print Yes; if he will lose, print No.

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

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

First, Takahashi's monster attacks Aoki's monster, whose health is now 10-9=1.
Next, Aoki's monster attacks Takahashi's monster, whose health is now 10-10=0.
Takahashi's monster is the first to have 0 or less health, so Takahashi loses.

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

A, B, C, D = map(int,input().split())
m = A // D
n = C // B
if A % D != 0:
  m += 1
if C % B != 0:
  n += 1
if m >= n:
  print("Yes")
else:
  print("No")


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_c:
You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.
How many kinds of items did you get?

-----Constraints-----
 - 1 \leq N \leq 2\times 10^5
 - S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

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

-----Output-----
Print the number of kinds of items you got.

-----Sample Input-----
3
apple
orange
apple

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

You got two kinds of items: apple and orange.

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

n=int(input())
a=set()
for i in range(n):
    b=input()
    a.add(b)
print(len(a))


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_d:
Given is a string S consisting of digits from 1 through 9.
Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:
Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

-----Constraints-----
 - 1 ≤ |S| ≤ 200000
 - S is a string consisting of digits from 1 through 9.

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

-----Output-----
Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

-----Sample Input-----
1817181712114

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

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

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

s=input()
n=len(s)
rui=[0]
juu=[1]
for i in range(n+5):
  juu.append(juu[-1]*10%2019)
for i in range(n):
  rui.append((rui[-1]+int(s[n-1-i])*juu[i])%2019)
ama=[0]*2019
for i in range(len(rui)):
  ama[rui[i]]+=1
ans=0
def ui(n):
  return max(0,n*(n-1)//2)
for i in range(2019):
  ans+=ui(ama[i])
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_e:
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes.
You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin.
The transaction takes D_i minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.

-----Constraints-----
 - 2 \leq N \leq 50
 - N-1 \leq M \leq 100
 - 0 \leq S \leq 10^9
 - 1 \leq A_i \leq 50
 - 1 \leq B_i,C_i,D_i \leq 10^9
 - 1 \leq U_i < V_i \leq N
 - There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
 - Each city t=2,...,N can be reached from City 1 with some number of railroads.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N

-----Output-----
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.

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

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

The railway network in this input is shown in the figure below.
In this figure, each city is labeled as follows:
 - The first line: the ID number i of the city (i for City i)
 - The second line: C_i / D_i
Similarly, each railroad is labeled as follows:
 - The first line: the ID number i of the railroad (i for the i-th railroad in input)
 - The second line: A_i / B_i

You can travel from City 1 to City 2 in 2 minutes, as follows:
 - Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

You can travel from City 1 to City 3 in 14 minutes, as follows:
 - Use the 1-st railroad to move from City 1 to City 2...

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

import sys

stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: list(map(int, stdin.readline().split()))
nl = lambda: list(map(int, stdin.readline().split()))

n, m, s = nm()
N = n * 3001
G = [list() for _ in range(N)]
for _ in range(m):
    u, v, a, b = nm()
    u -= 1; v -= 1
    for j in range(0, N, n):
        if v + j - a * n >= 0:
            G[u + j].append((v + j - a * n, b))
        if u + j - a * n >= 0:
            G[v + j].append((u + j - a * n, b))
for u in range(n):
    c, d = nm()
    for j in range(0, N, n):
        G[u + j].append((min(u + j + c * n, u + N - n), d))

import heapq as hq

def dijkstra(G, s, t=None):
    """
    G[v] = [(x1, c1), (x2, c2), ...]
    """
    dist = [-1]*len(G)
    dist[s] = 0
    q = [(0, s)]
    while q:
        d, v = hq.heappop(q)
        if d > dist[v]: continue
        for x, c in G[v]:
            if dist[x] < 0 or dist[x] > d + c:
                dist[x] = d + c
                hq.heappush(q, (d + c, x))
    if t is None:
        return dist
    else:
        return dist[t]

dist = dijkstra(G, min(s, 3000) * n)
for i in range(1, n):
    print((min(dist[i::n])))


I found an interesting problem on https://atcoder.jp/contests/abc164/tasks/abc164_f:
Given are an integer N and arrays S, T, U, and V, each of length N.
Construct an N×N matrix a that satisfy the following conditions:
 - a_{i,j} is an integer.
 - 0 \leq a_{i,j}  \lt 2^{64}.
 - If S_{i} = 0, the bitwise AND of the elements in the i-th row is U_{i}.
 - If S_{i} = 1, the bitwise OR of the elements in the i-th row is U_{i}.
 - If T_{i} = 0, the bitwise AND of the elements in the i-th column is V_{i}.
 - If T_{i} = 1, the bitwise OR of the elements in the i-th column is V_{i}.
However, there may be cases where no matrix satisfies the conditions.

-----Constraints-----
 - All values in input are integers.
 -  1 \leq N \leq 500
 -  0 \leq S_{i} \leq 1
 -  0 \leq T_{i} \leq 1
 -  0 \leq U_{i} \lt 2^{64}
 -  0 \leq V_{i} \lt 2^{64}

-----Input-----
Input is given from Standard Input in the following format:
N
S_{1} S_{2} ...  S_{N}
T_{1} T_{2} ...  T_{N}
U_{1} U_{2} ...  U_{N}
V_{1} V_{2} ...  V_{N}

-----Output-----
If there exists a matrix that satisfies the conditions, print one such matrix in the following format:
a_{1,1} ...  a_{1,N}
:
a_{N,1} ...  a_{N,N}

Note that any matrix satisfying the conditions is accepted.
If no matrix satisfies the conditions, print -1.

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

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

In Sample Input 1, we need to find a matrix such that:
 - the bitwise AND of the elements in the 1-st row is 1;
 - the bitwise OR of the elements in the 2-nd row is 1;
 - the bitwise OR of the elements in the 1-st column is 1;
 - the bitwise AND of the elements in the 2-nd column is 0.

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

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n = int(input())
    ans = [[0 for _ in range(n)] for _ in range(n)]
    s = list(map(int, input().split()))
    t = list(map(int, input().split()))
    u = list(map(int, input().split()))
    v = list(map(int, input().split()))
    for i in range(n):
        if not s[i]:
            for j in range(n):
                ans[i][j] = ans[i][j]|u[i]
        if not t[i]:
            for j in range(n):
                ans[j][i] = ans[j][i]|v[i]
    for i in range(n):
        for j in range(n):
            if (u[i] & v[j]):
                ans[i][j] = ans[i][j]|(u[i]&v[j])
    for x in range(n):
        if not s[x]:
            continue
        x_sum = ans[x][0]
        for y in range(n):
            x_sum = x_sum|ans[x][y]
        if x_sum == u[x]:
            continue
        up = u[x] - x_sum
        for y in range(n):
            if t[y]:
                continue
            y_mul = ans[0][y]
            for i in range(n):
                if i == x:
                    continue
                y_mul = y_mul&ans[i][y]
            up_y = (~y_mul)&up
            ans[x][y] += up_y
            up -= up_y
            if not up:
                break
    for y in range(n):
        if not t[y]:
            continue
        y_sum = ans[0][y]
        for x in range(n):
            y_sum = y_sum|ans[x][y]
        if y_sum == v[y]:
            continue
        up = v[y] - y_sum
        for x in range(n):
            if s[x]:
                continue
            x_mul = ans[x][0]
            for j in range(n):
                if y == j:
                    continue
                x_mul = x_mul&ans[x][j]
            up_x = (~x_mul)&up
            ans[x][y] += up_x
            up -= up_x
            if not up:
                break
    for i in range(n):
        check_xs = ans[i][0]
        check_ys = ans[0][i]
        check_xm = ans[i][0]
        check_ym = ans[0][i]
        for j in range(n):
            check_xs =...


I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_a:
Takahashi the Jumbo will practice golf.
His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).
If he can achieve the objective, print OK; if he cannot, print NG.

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

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

-----Output-----
If he can achieve the objective, print OK; if he cannot, print NG.

-----Sample Input-----
7
500 600

-----Sample Output-----
OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

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

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

for i in range(a,b+1):
    if i%k == 0:
        print('OK')
        return
print('NG')


I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_b:
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.
The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)
Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

-----Constraints-----
 -  101 \le X \le 10^{18}
 - All values in input are integers.

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

-----Output-----
Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

-----Sample Input-----
103

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

 - The balance after one year is 101 yen.
 - The balance after two years is 102 yen.
 - The balance after three years is 103 yen.
Thus, it takes three years for the balance to reach 103 yen or above.

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

X = int(input())
money = 100
years = 0

while money < X:
    money += money // 100
    years += 1
print(years)


I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_c:
Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).
Consider a sequence A satisfying the following conditions:
 - A is a sequence of N positive integers.
 - 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.
Let us define a score of this sequence as follows:
 - The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)
Find the maximum possible score of A.

-----Constraints-----
 - All values in input are integers.
 - 2 ≤ N ≤ 10
 - 1 \leq M \leq 10
 - 1 \leq Q \leq 50
 - 1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )
 - 0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )
 - (a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)
 - 1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

-----Input-----
Input is given from Standard Input in the following format:
N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

-----Output-----
Print the maximum possible score of A.

-----Sample Input-----
3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

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

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

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

import itertools

def abc165c_many_requirements():
    n, m, q = map(int, input().split())
    all_list = []
    for _ in range(q):
        all_list.append(list(map(int, input().split())))

    pattern = itertools.combinations_with_replacement(range(1, m+1), n)
    best = 0
    for p in pattern:
        cost = 0
        for l in all_list:
            if p[l[1]-1] - p[l[0]-1] == l[2]:
                cost += l[3]
        if cost > best:
            best = cost
    print(best)

abc165c_many_requirements()


I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_d:
Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.

-----Constraints-----
 - 1 ≤ A ≤ 10^{6}
 - 1 ≤ B ≤ 10^{12}
 - 1 ≤ N ≤ 10^{12}
 - All values in input are integers.

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

-----Output-----
Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

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

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

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

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

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

x = min(b-1, n) * 1.0

print(int(1.0 * a * x / b) - a * int(1.0 * x / b))


I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_e:
You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:
 - For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.
 - Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.
You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

-----Constraints-----
 - 1 \leq M
 - M \times 2 +1 \leq N \leq 200000

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

-----Output-----
Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.
a_1 b_1
a_2 b_2
:
a_M b_M

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

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

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.
 - The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.
 - The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.
 - The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.
 - The 4-th round is fought...

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

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def main():
    n,m = LI()

    rr = []
    if n % 2 == 1:
        t = n // 2 + 1
        for i in range(1, m+1):
            rr.append((t-i,t+i))
    else:
        t1 = (m+1) // 2
        t2 = n - m // 2
        for i in range(t1):
            rr.append((t1-i,t1+1+i))
        for i in range(1, m // 2 + 1):
            rr.append((t2-i, t2+i))

    return JAA(rr, "\n", " ")

print(main())


I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_a:
AtCoder Inc. holds a contest every Saturday.
There are two types of contests called ABC and ARC, and just one of them is held at a time.
The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.
Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

-----Constraints-----
 - S is ABC or ARC.

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

-----Output-----
Print the string representing the type of the contest held this week.

-----Sample Input-----
ABC

-----Sample Output-----
ARC

They held an ABC last week, so they will hold an ARC this week.

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

S=input()
if S == "ABC":print("ARC")
else : print("ABC")


I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_b:
N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.
There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.
Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 100
 - 1 \leq K \leq 100
 - 1 \leq d_i \leq N
 - 1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

-----Input-----
Input is given from Standard Input in the following format:
N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

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

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

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

 - Snuke 1 has Snack 1.
 - Snuke 2 has no snacks.
 - Snuke 3 has Snack 1 and 2.
Thus, there will be one victim: Snuke 2.

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

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

table = [0] * N
for _ in range(K):
  num = int(input())
  have_list = list(map(int, input().split()))
  for child in have_list:
    table[child-1] += 1

print(str(table.count(0)))


I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_c:
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.
Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.
How many good observatories are there?

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq M \leq 10^5
 - 1 \leq H_i \leq 10^9
 - 1 \leq A_i,B_i \leq N
 - A_i \neq B_i
 - Multiple roads may connect the same pair of observatories.
 - All values in input are integers.

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

-----Output-----
Print the number of good observatories.

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

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

 - From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.
 - From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.
 - From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.
 - From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.
Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

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

N, M = list(map(int, input().split()))
list_h = list(map(int, input().split()))
table = [1] * N

for i in range(M):
  A, B = list(map(int, input().split()))
  if list_h[B-1] < list_h[A-1]:
    table[B-1] = 0
  elif list_h[A-1] < list_h[B-1]:
    table[A-1] = 0
  else:
    table[A-1] = 0
    table[B-1] = 0

print(str(sum(table)))


I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_e:
You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.
There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.
According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.
 - The absolute difference of their attendee numbers is equal to the sum of their heights.
There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?
P.S.: We cannot let you know the secret.

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

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

-----Output-----
Print the number of pairs satisfying the condition.

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

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

 - A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.
 - A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.
 - A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.
No other pair satisfies the condition, so you should print 3.

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

N = int(input())
A = list(map(int, input().split()))
L = {}
R = {}
ans = 0
for i in range(N):
  t = i + 1 + A[i]
  if t in L:
    L[t] += 1
  else:
    L[t] = 1
  t = i + 1 - A[i]
  if t > 0:
    if t in R:
      R[t] += 1
    else:
      R[t] = 1
for i in R:
  if i in L:
    ans += R[i] * L[i]
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_f:
There is a game that involves three variables, denoted A, B, and C.
As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.
After each choice, none of A, B, and C should be negative.
Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - 0 \leq A,B,C \leq 10^9
 - N, A, B, C are integers.
 - s_i is AB, AC, or BC.

-----Input-----
Input is given from Standard Input in the following format:
N A B C
s_1
s_2
:
s_N

-----Output-----
If it is possible to make N choices under the condition, print Yes; otherwise, print No.
Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

-----Sample Input-----
2 1 3 0
AB
AC

-----Sample Output-----
Yes
A
C

You can successfully make two choices, as follows:
 - In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.
 - In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

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

n, a, b, c = map(int, input().split())
q = [input() for i in range(n)]
ab, ac, bc = "AB", "AC", "BC"
ans = []
for i in range(n):

  if((q[i] == ab and a == b == 0)
  or (q[i] == ac and a == c == 0)
  or (q[i] == bc and b == c == 0)):
      print("No")
      return

  elif(q[i] == ab and [a, b, c] == [1, 1, 0] and i != n - 1):
    if q[i+1] == ac:
      a, b = a+1, b-1
      ans.append("A")
    else:
      a, b = a-1, b+1
      ans.append("B")

  elif(q[i] == ac and [a, b, c] == [1, 0, 1] and i != n - 1):
    if q[i+1] == ab:
      a, c = a+1, c-1
      ans.append("A")
    else:
      a, c = a-1, c+1
      ans.append("C")

  elif(q[i] == bc and [a, b, c] == [0, 1, 1] and i != n - 1):
    if q[i+1] == ab:
      b, c = b+1, c-1
      ans.append("B")
    else:
      b, c = b-1, c+1
      ans.append("C")

  elif q[i] == ab:
    if a > b:
      a, b = a-1, b+1
      ans.append("B")
    else:
      a, b = a+1, b-1
      ans.append("A")

  elif q[i] == ac:
    if a > c:
      a, c = a-1, c+1
      ans.append("C")
    else:
      a, c = a+1, c-1
      ans.append("A")

  elif q[i] == bc:
    if b > c:
      b, c = b-1, c+1
      ans.append("C")
    else:
      b, c = b+1, c-1
      ans.append("B")

print("Yes")
for i in range(n):
  print(ans[i])


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_a:
Takahashi wants to be a member of some web service.
He tried to register himself with the ID S, which turned out to be already used by another user.
Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.
He is now trying to register with the ID T. Determine whether this string satisfies the property above.

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

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

-----Output-----
If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

-----Sample Input-----
chokudai
chokudaiz

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

chokudaiz can be obtained by appending z at the end of chokudai.

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

s = input()
t = input()

if (len(t)-len(s)==1) and (t[:-1]==s):
    print("Yes")
else:
    print("No")


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_b:
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

-----Constraints-----
 - All values in input are integers.
 - 0 \leq A, B, C
 - 1 \leq K \leq A + B + C \leq 2 \times 10^9

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

-----Output-----
Print the maximum possible sum of the numbers written on the cards chosen.

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

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

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

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

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

total = 0
if K <= A:
    print(K)
else:
    total += A
    K = K - A
    if K <= B:
        print(total)
    else:
        K = K - B
        if K <= C:
            total -= K
            print(total)
        else:
            total -= C
            print(total)


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_c:
Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.
Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.
Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

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

n,m,x = map(int,input().split())
c = [list(map(int,input().split())) for _ in range(n)]
ans = []
#n冊の本において買うか買わないかの2通りなので2**n
for i in range(2**n):
    #リストの中身は値段1と理解度m個
    a = [0]*m
    price = 0
    for j in range(n):
        #n冊あるうちj冊目を買うか買わないかを判定
        if ((i >> j) & 1):
            for k in range(m):
                a[k] += c[j][k+1]
            #j冊めを買うので、合計金額を増やす
            price += c[j][0]
    if all(j >= x for j in a):
        ans.append(price)

if len(ans) == 0:
    print("-1")
else:
    print(min(ans))


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_d:
The Kingdom of Takahashi has N towns, numbered 1 through N.
There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.
Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.
Help the king by writing a program that answers this question.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq A_i \leq N
 - 1 \leq K \leq 10^{18}

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

-----Output-----
Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

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

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

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

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

n, k = [int(x) for x in input().split()]
a_list = [int(x) - 1 for x in input().split()]

ci = 0
temp_dict = {0: 0}
temp_list = [0]
for i in range(1, k + 1):
    temp = a_list[ci]
    if temp in temp_dict:
        ci = temp_list[(k - i) % (i - temp_dict[temp]) + temp_dict[temp]]
        break
    temp_dict[temp] = i
    temp_list.append(temp)
    ci = temp
print(ci + 1)


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_e:
There are N blocks arranged in a row. Let us paint these blocks.
We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways.
Find the number of ways to paint the blocks under the following conditions:
 - For each block, use one of the M colors, Color 1 through Color M, to paint it. It is not mandatory to use all the colors.
 - There may be at most K pairs of adjacent blocks that are painted in the same color.
Since the count may be enormous, print it modulo 998244353.

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

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

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

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

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

The following ways to paint the blocks satisfy the conditions: 112, 121, 122, 211, 212, and 221. Here, digits represent the colors of the blocks.

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

N, M, K = map(int, input().split())
mod = 998244353

b = str(bin(mod-2))[2:]
blis = []
for _ in range(len(b)):
  if b[-_-1] == '1':
    blis.append(_)

def modinv(a):
  if a == 1:
    return 1
  else:
    res = 1
    n = len(b)
    li = []
    for _ in range(n):
      li.append(a%mod)
      a = a*a%mod
    for item in blis:
      res = res * li[item] %mod
    return res
"""
inv = [0,1]
for i in range(2, N):
  inv.append((-inv[mod%i]*(mod//i))%mod)
"""
if N == 1:
  print(M)
  return

m = [1]
s = 1
for _ in range(N-1):
  s = s*(M-1)%mod
  m.append(s)

ncombi = [1]
c = 1
for k in range(K):
  c = c*(N-1-k)*modinv(k+1)
  c %= mod
  ncombi.append(c)

"""
olis = ncombi
for k in range(N-1):
  nlis = [1]
  for  j in range(len(olis)-1):
    nlis.append(olis[j]+olis[j+1])
  nlis.append(1)
  olis = nlis
  #print(olis)
ncombi = olis
"""
ans = 0
for k in range(K+1):
  ans = ans + m[-k -1]*ncombi[k]
  ans %= mod

ans = ans*M%mod

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_f:
A bracket sequence is a string that is one of the following:
 - An empty string;
 - The concatenation of (, A, and ) in this order, for some bracket sequence A ;
 - The concatenation of A and B in this order, for some non-empty bracket sequences A and B /
Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

-----Constraints-----
 - 1 \leq N \leq 10^6
 - The total length of the strings S_i is at most 10^6.
 - S_i is a non-empty string consisting of ( and ).

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

-----Output-----
If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

-----Sample Input-----
2
)
(()

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

Concatenating (() and ) in this order forms a bracket sequence.

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

n = int(input())
s = []
for i in range(n):
    s.append(input())

ls1 = []
ls2 = []

for item in s:
    stk1 = []
    stk2 = []
    for ch in item:
        if ch == '(':
            stk2.append(ch)
        else:
            if len(stk2) > 0:
                stk2.pop()
            else:
                stk1.append(ch)
    l1 = len(stk1)
    l2 = len(stk2)
    if l2 >= l1:
        ls1.append((l1, l2))
    else:
        ls2.append((l1, l2))

ls1.sort()

cnt = 0

for item in ls1:
    cnt -= item[0]
    if cnt < 0:
        print('No')
        return
    else:
        cnt += item[1]

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

for item in ls2:
    cnt -= item[0]
    if cnt < 0:
        print('No')
        return
    else:
        cnt += item[1]

if cnt != 0:
    print('No')
else:
    print('Yes')


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_a:
The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.
When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:
 - hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;
 - pon when the digit in the one's place of N is 0, 1, 6 or 8;
 - bon when the digit in the one's place of N is 3.
Given N, print the pronunciation of "本" in the phrase "N 本".

-----Constraints-----
 - N is a positive integer not exceeding 999.

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

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

-----Sample Input-----
16

-----Sample Output-----
pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

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


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_b:
We have a string S consisting of lowercase English letters.
If the length of S is at most K, print S without change.
If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

-----Constraints-----
 - K is an integer between 1 and 100 (inclusive).
 - 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:
K
S

-----Output-----
Print a string as stated in Problem Statement.

-----Sample Input-----
7
nikoandsolstice

-----Sample Output-----
nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.
We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

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

K=int(input())
S=input()

if len(S)<=K:
    print(S)
else:
    print((S[0:K]+"..."))


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_c:
Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.
An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.
At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

-----Constraints-----
 - All values in input are integers.
 - 1 \leq A, B \leq 1000
 - 0 \leq H \leq 11
 - 0 \leq M \leq 59

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

-----Output-----
Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

-----Sample Input-----
3 4 9 0

-----Sample Output-----
5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

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

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

x = H / 12 * 360 + M / 60 * 30
y = M / 60 * 360

ang = abs(y - x)
ans_2 = A ** 2 + B ** 2 - 2 * A * B * math.cos(math.radians(ang))
ans = math.sqrt(ans_2)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_d:
There is a cave.
The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.
It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.
Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.
 - If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.
Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 10^5
 - 1 \leq M \leq 2 \times 10^5
 - 1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)
 - A_i \neq B_i\ (1 \leq i \leq M)
 - One can travel between any two rooms by traversing passages.

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

-----Output-----
If there is no way to place signposts satisfying the objective, print No.
Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

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

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

If we place the signposts as described in the sample output, the following happens:
 - Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.
 - Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.
 - Starting in Room 4, you will reach Room 1 after...

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

# 参考にした提出:https://atcoder.jp/contests/abc168/submissions/16604668 #
from collections import deque
n,m = map(int,input().split())
l = [[] for i in range(n+1)]
for i in range(m):
    a,b = map(int,input().split())
    l[a].append(b)
    l[b].append(a)
d = [-1] * (n+1)
d[0],d[1] = 0,0
queue = deque()
queue.append(1)
while queue:
    x = queue.popleft()
    for i in l[x]:
        if d[i] == -1:
            d[i] = x
            queue.append(i)
print('Yes')
for i in d[2:]:
    print(i)


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_e:
We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.
We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.
The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.
In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N \leq 2 \times 10^5
 - -10^{18} \leq A_i, B_i \leq 10^{18}

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

-----Output-----
Print the count modulo 1000000007.

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

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

There are five ways to choose the set of sardines, as follows:
 - The 1-st
 - The 1-st and 2-nd
 - The 2-nd
 - The 2-nd and 3-rd
 - The 3-rd

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

mod = 1000000007
n = int(input())

ab00 = 0
abx0 = 0
ab0x = 0
p = []
m = []

from math import gcd
for _ in range(n):
    i, j = map(int, input().split())
    if i == 0:
        if j == 0:
            ab00 += 1
        else:
            ab0x += 1
        continue
    elif j == 0:
        abx0 += 1
        continue
    k = gcd(i, j)
    i //= k
    j //= k
    if i > 0:
        if j > 0:
            p.append((i, j))
        else:
            m.append((-j, i))
    elif j > 0:
        m.append((j, -i))
    else:
        p.append((-i, -j))

m.sort()
p.sort()

ans = pow(2, ab0x, mod) + pow(2, abx0, mod) - 1
ans %= mod

mi = 0
pi = 0
while mi < len(m) and pi < len(p):
    if m[mi] == p[pi]:
        mi += 1
        mnum = 1
        while mi < len(m) and m[mi] == m[mi-1]:
            mi += 1
            mnum += 1
        pi += 1
        pnum = 1
        while pi < len(p) and p[pi] == p[pi-1]:
            pi += 1
            pnum += 1
        ans *= pow(2, mnum, mod) + pow(2, pnum, mod) - 1
        ans %= mod

    elif m[mi] < p[pi]:
        mi += 1
        mnum = 1
        while mi < len(m) and m[mi] < p[pi]:
            mi += 1
            mnum += 1
        ans *= pow(2, mnum, mod)
        ans %= mod

    else:
        pi += 1
        pnum = 1
        while pi < len(p) and p[pi] < m[mi]:
            pi += 1
            pnum += 1
        ans *= pow(2, pnum, mod)
        ans %= mod

ans *= pow(2, len(p) - pi, mod)
ans %= mod
ans *= pow(2, len(m) - mi, mod)
ans %= mod
ans = (ans - 1 + ab00) % mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc168/tasks/abc168_f:
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead.

-----Constraints-----
 - All values in input are integers between -10^9 and 10^9  (inclusive).
 - 1 \leq N, M \leq 1000
 - A_i < B_i\ (1 \leq i \leq N)
 - E_j < F_j\ (1 \leq j \leq M)
 - The point (0, 0) does not lie on any of the given segments.

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M

-----Output-----
If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)

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

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

The area of the region the cow can reach is 13\ \mathrm{cm^2}.

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

#写経
#https://atcoder.jp/contests/abc168/submissions/14421546
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
from bisect import bisect_left, bisect_right
INF = 10 **18

def resolve():
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for i in range(n)]
    b = [list(map(int, input().split())) for i in range(m)]

    X = {-INF, INF}
    Y = {-INF, INF}
    for i in a:
        Y.add(i[2])
    for i in b:
        X.add(i[0])

    X = list(sorted(X))
    Y = list(sorted(Y))
    n = len(X) - 1
    m = len(Y) - 1
    wallx = [[False] * m for i in range(n)]
    wally = [[False] * m for i in range(n)]

    for x1, x2, y1 in a:
        x1 = bisect_left(X, x1)
        y1 = bisect_left(Y, y1)
        x2 = bisect_right(X, x2) - 1
        for i in range(x1, x2):
            wally[i][y1] = True

    for x1, y1, y2 in b:
        x1 = bisect_left(X, x1)
        y1 = bisect_left(Y, y1)
        y2 = bisect_right(Y, y2) - 1
        for i in range(y1, y2):
            wallx[x1][i] = True

    cow = [[False] * m for i in range(n)]
    cx = bisect_right(X, 0) - 1
    cy = bisect_right(Y, 0) - 1
    cow[cx][cy] = True
    q = [(cx, cy)]
    ans = 0

    while q:
        x, y = q.pop()
        if not x or not y:
            print("INF")
            return
        ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        if x and not wallx[x][y] and not cow[x - 1][y]:
            cow[x - 1][y] = True
            q.append((x - 1, y))
        if y and not wally[x][y] and not cow[x][y - 1]:
            cow[x][y - 1] = True
            q.append((x, y - 1))
        if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]:
            cow[x + 1][y] = True
            q.append((x + 1, y))
        if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]:
            cow[x][y + 1] = True
            q.append((x, y + 1))
    print(ans)
resolve()


I found an interesting problem on https://atcoder.jp/contests/abc169/tasks/abc169_a:
Compute A \times B.

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

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

-----Output-----
Print the value A \times B as an integer.

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

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

We have 2 \times 5 = 10.

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

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

print(A*B)


I found an interesting problem on https://atcoder.jp/contests/abc169/tasks/abc169_b:
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.
However, if the result exceeds 10^{18}, print -1 instead.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 0 \leq A_i \leq 10^{18}
 - All values in input are integers.

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

-----Output-----
Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}.

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

-----Sample Output-----
1000000000000000000

We have 1000000000 \times 1000000000 = 1000000000000000000.

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

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

result = 1
A = sorted(A)

for i in A:
    result *= i
    if result > 10 ** 18:
        print((-1))
        break
else:
    print(result)


I found an interesting problem on https://atcoder.jp/contests/abc169/tasks/abc169_c:
Compute A \times B, truncate its fractional part, and print the result as an integer.

-----Constraints-----
 - 0 \leq A \leq 10^{15}
 - 0 \leq B < 10
 - A is an integer.
 - B is a number with two digits after the decimal point.

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

-----Output-----
Print the answer as an integer.

-----Sample Input-----
198 1.10

-----Sample Output-----
217

We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217.

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


I found an interesting problem on https://atcoder.jp/contests/abc169/tasks/abc169_d:
Given is a positive integer N. Consider repeatedly applying the operation below on N:
 - First, choose a positive integer z satisfying all of the conditions below:
 - z can be represented as z=p^e, where p is a prime number and e is a positive integer;
 - z divides N;
 - z is different from all integers chosen in previous operations.
 - Then, replace N with N/z.
Find the maximum number of times the operation can be applied.

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

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

-----Output-----
Print the maximum number of times the operation can be applied.

-----Sample Input-----
24

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

We can apply the operation three times by, for example, making the following choices:
 - Choose z=2 (=2^1). (Now we have N=12.)
 - Choose z=3 (=3^1). (Now we have N=4.)
 - Choose z=4 (=2^2). (Now we have N=1.)

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

N = int(input())
div = 2
dic = {}
while div**2 <= N:
  if N % div == 0:
    count = 0
    while N % div == 0:
      N = N // div
      count += 1
    dic[div] = count
  div += 1
if N != 1:
  dic[N] = 1
ans = 0
for v in dic.values():
  tmp = 1
  while v >= tmp:
    v -= tmp
    tmp += 1
    ans += 1
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc169/tasks/abc169_e:
There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

-----Notes-----
The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.
 - If N is odd, the median is x_{(N+1)/2};
 - if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

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

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

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

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

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

 - If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};
 - if X_1 = 1 and X_2 = 3, the median is 2;
 - if X_1 = 2 and X_2 = 2, the median is 2;
 - if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.
Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

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

#!/usr/bin/env python3
import sys
from itertools import chain
import numpy as np

# from itertools import combinations as comb
# form bisect import bisect_left, bisect_right, insort_left, insort_right
# from collections import Counter

def solve(N: int, A: "List[int]", B: "List[int]"):
    A = sorted(A)
    B = sorted(B)
    if N % 2 == 1:
        l = A[N // 2]
        r = B[N // 2]
        return r - l + 1
    else:
        l2 = A[N // 2 - 1] + A[N // 2]
        r2 = B[N // 2 - 1] + B[N // 2]
        return r2 - l2 + 1

def main():
    tokens = chain(*(line.split() for line in sys.stdin))
    # N, A, B = map(int, line.split())
    N = int(next(tokens))  # type: int
    AB = np.array(list(map(int, tokens)), dtype=np.int32)
    A = AB[0::2]
    B = AB[1::2]
    answer = solve(N, A, B)
    print(answer)

def __starting_point():
    main()

__starting_point()


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

For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:

 - f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.
Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.

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

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

-----Output-----
Print the sum of f(T) modulo 998244353.

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

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

For each T, the value of f(T) is shown below. The sum of these values is 6.
 - f(\{1\}) = 0
 - f(\{2\}) = 0
 - f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)
 - f(\{1, 2\}) = 1 (\{1, 2\})
 - f(\{2, 3\}) = 1 (\{3\})
 - f(\{1, 3\}) = 1 (\{3\})
 - f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})

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

def main():
    mod = 998244353
    n, s = list(map(int, input().split()))
    a = list(map(int, input().split()))
    a = [i for i in a if i <= s]
    dp = [0 for i in range(s+1)]
    half = pow(2, mod-2, mod)
    for i in a:
        dp2 = [j for j in dp]
        dp2[i] = (dp2[i]+pow(2, n-1, mod)) % mod
        for j in range(s-i+1):
            dp2[j+i] = (dp2[j+i]+dp[j]*half) % mod
        dp = dp2
    print((dp[s]))

main()


I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_a:
We have five variables x_1, x_2, x_3, x_4, and x_5.
The variable x_i was initially assigned a value of i.
Snuke chose one of these variables and assigned it 0.
You are given the values of the five variables after this assignment.
Find out which variable Snuke assigned 0.

-----Constraints-----
 - The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

-----Input-----
Input is given from Standard Input in the following format:
x_1 x_2 x_3 x_4 x_5

-----Output-----
If the variable Snuke assigned 0 was x_i, print the integer i.

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

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

In this case, Snuke assigned 0 to x_1, so we should print 1.

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

li = input().split()
print ((li.index("0")) + 1)


I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_b:
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

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

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

-----Output-----
If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

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

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

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

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

X, Y = list(map(int,input().split()))

if Y % 2 == 0 and 2*X <= Y <= 4*X:
    print('Yes')
else:
    print('No')


I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_c:
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.
Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

-----Constraints-----
 - 1 \leq X \leq 100
 - 0 \leq N \leq 100
 - 1 \leq p_i \leq 100
 - p_1, \ldots, p_N are all distinct.
 - All values in input are integers.

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

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

-----Sample Input-----
6 5
4 7 10 6 5

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

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

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

X, N = map(int, input().split())
if N != 0:
  p = list(map(int, input().split()))
  for i in range(N):
    if X - i not in p:
      print(X - i)
      break
    elif X + i not in p:
      print(X + i)
      break
  else:
    print(X - i - 1)
else:
  print(X)


I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_d:
Given is a number sequence A of length N.
Find the number of integers i \left(1 \leq i \leq N\right) with the following property:
 - For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.

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

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

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

-----Sample Input-----
5
24 11 8 3 16

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

The integers with the property are 2, 3, and 4.

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

'''
Created on 2020/08/23

@author: harurun
'''
def main():
  from collections import Counter
  import sys
  pin=sys.stdin.readline
  pout=sys.stdout.write
  perr=sys.stderr.write

  ans=0
  N=int(pin())
  A=list(map(int,pin().split()))
  c=Counter(A)
  t=max(A)
  dp=[True]*t
  for i in A:
    if dp[i-1]:
      n=2*i
      while n<=t:
        dp[n-1]=False
        n+=i
  for k in A:
    if c[k]==1 and dp[k-1]:
      ans+=1
  print(ans)
  return
main()


I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_e:
There are N infants registered in AtCoder, numbered 1 to N, and 2\times 10^5 kindergartens, numbered 1 to 2\times 10^5.
Infant i has a rating of A_i and initially belongs to Kindergarten B_i.
From now on, Q transfers will happen.
After the j-th transfer, Infant C_j will belong to Kindergarten D_j.
Here, we define the evenness as follows. For each kindergarten with one or more infants registered in AtCoder, let us find the highest rating of an infant in the kindergarten. The evenness is then defined as the lowest among those ratings.
For each of the Q transfers, find the evenness just after the transfer.

-----Constraints-----
 - 1 \leq N,Q \leq 2 \times 10^5
 - 1 \leq A_i \leq 10^9
 - 1 \leq C_j \leq N
 - 1 \leq B_i,D_j \leq 2 \times 10^5
 - All values in input are integers.
 - In the j-th transfer, Infant C_j changes the kindergarten it belongs to.

-----Input-----
Input is given from Standard Input in the following format:
N Q
A_1 B_1
A_2 B_2
:
A_N B_N
C_1 D_1
C_2 D_2
:
C_Q D_Q

-----Output-----
Print Q lines.
The j-th line should contain the evenness just after the j-th transfer.

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

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

Initially, Infant 1, 4 belongs to Kindergarten 1, Infant 2, 5 belongs to Kindergarten 2, and Infant 3, 6 belongs to Kindergarten 3.
After the 1-st transfer that makes Infant 4 belong to Kindergarten 3, Infant 1 belongs to Kindergarten 1, Infant 2, 5 belong to Kindergarten 2, and Infant 3, 4, 6 belong to Kindergarten 3. The highest ratings of an infant in Kindergarten 1, 2, 3 are 8, 6, 9, respectively. The lowest among them is 6, so the 1-st line in the output should contain 6.
After the 2-nd transfer that makes Infant 2 belong to Kindergarten 1, Infant 1, 2 belong to Kindergarten 1, Infant 5 belongs to Kindergarten 2, and Infant 3, 4, 6 belong to Kindergarten 3. The highest ratings of an infant in Kindergarten 1, 2, 3 are 8, 2, 9, respectively. The lowest among them is 2, so the 2-nd line in the output should contain 2.
After the 3-rd...

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

import heapq

class HeapDict:
    def __init__(self):
        # heapqとdictを用意
        self.h = []
        self.d = dict()

    def insert(self, x):
        heapq.heappush(self.h, x)
        if x not in self.d:
            self.d[x] = 1
        else:
            self.d[x] += 1

    def erase(self, x):
        if x not in self.d or self.d[x] == 0:
            print((x, "is not in HeapDict"))
            return
        else:
            self.d[x] -= 1

        while len(self.h) != 0:
            if self.d[self.h[0]] == 0:
                heapq.heappop(self.h)
            else:
                break

    def is_exist(self, x):
        if x in self.d and self.d[x] != 0:
            return True
        else:
            False

    def get_min(self):
        return self.h[0]

    def size(self):
        return len(self.h)

def main():
    N, Q = list(map(int, input().split()))
    A = []  # レート
    B = []  # 所属幼稚園
    con = 2 * 10 ** 5
    INF = 10 ** 18
    youchi = [HeapDict() for _ in range(con)]  # 各幼稚園に対するHeapDict
    max_values = HeapDict()  # 各幼稚園の最大値のHeapDict
    for i in range(N):
        a, b = list(map(int, input().split()))
        b -= 1
        A.append(a)
        B.append(b)
        youchi[b].insert(-a)

    for i in range(con):  # 各幼稚園の最大値をまとめる
        if youchi[i].size() != 0:
            max_values.insert(-youchi[i].get_min())
        else:
            max_values.insert(INF)

    for i in range(Q):
        c, d = list(map(int, input().split()))
        c -= 1
        d -= 1
        rate = A[c]
        youchi_now = B[c]
        youchi_next = d

        # 最強園児のレートの集合から、転園する園児の元の幼稚園の元の最強園児のレートを、削除する
        max_values.erase(-youchi[youchi_now].get_min())

        # 転園する園児の元の幼稚園のレートの集合から、転園する園児のレートを、削除する
        youchi[youchi_now].erase(-rate)

        # 最強園児のレートの集合に、転園する園児の元の幼稚園の新しい最強園児のレートを、挿入する(園児が一人もいない場合何もしない)
        if youchi[youchi_now].size() != 0:
            max_values.insert(-youchi[youchi_now].get_min())

        # 最強園児のレートの集合から、転園する園児の新しい幼稚園の元の最強園児のレートを、削除する(園児が一人もいない場合何もしない)
        if...