I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_f:
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.
Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..
In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.
Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

-----Constraints-----
 - 1 \leq H,W,K \leq 10^6
 - H \times W \leq 10^6
 - 1 \leq x_1,x_2 \leq H
 - 1 \leq y_1,y_2 \leq W
 - x_1 \neq x_2 or y_1 \neq y_2.
 - c_{i,j} is . or @.
 - c_{x_1,y_1} = .
 - c_{x_2,y_2} = .
 - All numbers in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

-----Output-----
Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

-----Sample Input-----
3 5 2
3 2 3 4
.....
.@..@
..@..

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

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:
 - From (3, 2), go west one square to (3, 1).
 - From (3, 1), go north two squares to (1, 1).
 - From (1, 1), go east two squares to (1, 3).
 - From (1, 3), go east one square to (1, 4).
 - From (1, 4), go south two squares to (3, 4).

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

from collections import deque

def resolve():
    H,W,K = map(int,input().split())
    ys, xs, yg, xg = map(int,input().split())

    board = [['@']*(W+2)]
    for i in range(H):
        board.append(['@'] + list(input())+['@'])
    board.append(['@']*(W+2))
    board[ys][xs] = '#'

    queue = deque([(xs,ys,0)])
    while queue:
        x,y,dep = queue.popleft()
        l = []
        f1 = True
        f2 = True
        f3 = True
        f4 = True
        for i in range(1,K+1):
            if f1:
                if board[y][x+i] == '.':
                    l.append((x+i,y))
                elif board[y][x+i] == '@' or board[y][x+i] != dep+1:
                    f1 = False
            if f2:
                if board[y][x-i] == '.':
                    l.append((x-i,y))
                elif board[y][x-i] == '@' or board[y][x-i] != dep+1:
                    f2 = False
            if f3:
                if board[y+i][x] == '.':
                    l.append((x,y+i))
                elif board[y+i][x] == '@' or board[y+i][x] != dep+1:
                    f3 = False
            if f4:
                if board[y-i][x] == '.':
                    l.append((x,y-i))
                elif board[y-i][x] == '@' or board[y-i][x] != dep+1:
                    f4 = False
            if not(f1 or f2 or f3 or f4):
                break
        for nx,ny in l:
            if board[ny][nx] == '.':
                board[ny][nx] = dep + 1
                if (nx,ny) == (xg,yg):
                    print(dep+1)
                    return
                else:
                    queue.append((nx,ny,dep+1))
    print(-1)
    return
resolve()


I found an interesting problem on https://atcoder.jp/contests/abc171/tasks/abc171_a:
An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

-----Constraints-----
 - \alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

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

-----Output-----
If \alpha is uppercase, print A; if it is lowercase, print a.

-----Sample Input-----
B

-----Sample Output-----
A

B is uppercase, so we should print A.

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

alp = input()
if alp==alp.upper() :
    print("A")
else :
    print("a")


I found an interesting problem on https://atcoder.jp/contests/abc171/tasks/abc171_b:
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

-----Constraints-----
 - 1 \leq K \leq N \leq 1000
 - 1 \leq p_i \leq 1000
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K
p_1 p_2 \ldots p_N

-----Output-----
Print an integer representing the minimum possible total price of fruits.

-----Sample Input-----
5 3
50 100 80 120 80

-----Sample Output-----
210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.
The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

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

n, k = map(int, input().split())
p = list(map(int, input().split()))
p.sort()
s = 0
for i in range(k):
    s += p[i]
print(s)


I found an interesting problem on https://atcoder.jp/contests/abc171/tasks/abc171_c:
1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:
 - the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;
 - the dogs numbered 27,28,29,\cdots,701,702  were respectively given the names aa, ab, ac, ..., zy, zz;
 - the dogs numbered 703,704,705,\cdots,18277,18278  were respectively given the names aaa, aab, aac, ..., zzy, zzz;
 - the dogs numbered 18279,18280,18281,\cdots,475253,475254  were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;
 - the dogs numbered 475255,475256,\cdots  were respectively given the names aaaaa, aaaab, ...;
 - and so on.
To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:
a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...
Now, Roger asks you:
"What is the name for the dog numbered N?"

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

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

-----Output-----
Print the answer to Roger's question as a string consisting of lowercase English letters.

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

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

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


I found an interesting problem on https://atcoder.jp/contests/abc171/tasks/abc171_d:
You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.
You will now successively do the following Q operations:
 - In the i-th operation, you replace every element whose value is B_{i} with C_{i}.
For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

-----Constraints-----
 - All values in input are integers.
 -  1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}
 -  B_{i} \neq C_{i}

-----Input-----
Input is given from Standard Input in the following format:
N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

-----Output-----
Print Q integers S_{i} to Standard Output in the following format:
S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

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

-----Sample Output-----
11
12
16

Initially, the sequence A is 1,2,3,4.
After each operation, it becomes the following:
 - 2, 2, 3, 4
 - 2, 2, 4, 4
 - 4, 4, 4, 4

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

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

d={}
cnt=sum(a)

for i in a:
    if i in d:
        d[i]+=1
    else:
        d[i]=1

for i in range(q):
    b,c=map(int,input().split())
    if b in d:
        if c not in d:
            d[c]=0
        e=d.pop(b)
        d[c]+=e
        cnt+=(c-b)*e
    print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc171/tasks/abc171_f:
How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?
The answer can be enormous, so print it modulo (10^9+7).

-----Constraints-----
 - K is an integer between 1 and 10^6 (inclusive).
 - S is a string of length between 1 and 10^6 (inclusive) consisting of lowercase English letters.

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

-----Output-----
Print the number of strings satisfying the condition, modulo (10^9+7).

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

-----Sample Output-----
575111451

For example, we can obtain proofend, moonwolf, and onionpuf, while we cannot obtain oofsix, oofelevennn, voxafolt, or fooooooo.

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


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_a:
Given an integer a as input, print the value a + a^2 + a^3.

-----Constraints-----
 - 1 \leq a \leq 10
 - a is an integer.

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

-----Output-----
Print the value a + a^2 + a^3 as an integer.

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

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

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.
Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

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

a = int(input())

print((a + a**2 + a**3))


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_b:
Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.
Operation: Choose one character of S and replace it with a different character.

-----Constraints-----
 - S and T have lengths between 1 and 2\times 10^5 (inclusive).
 - S and T consists of lowercase English letters.
 - S and T have equal lengths.

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

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

-----Sample Input-----
cupofcoffee
cupofhottea

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

We can achieve the objective in four operations, such as the following:
 - First, replace the sixth character c with h.
 - Second, replace the eighth character f with t.
 - Third, replace the ninth character f with t.
 - Fourth, replace the eleventh character e with a.

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

s = input()
t = input()

def counts(s, t):
    cnt = 0
    length = len(s)
    for i in range(length):
        if s[i] != t[i]:
            cnt += 1
    return cnt

print((counts(s, t)))


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_c:
We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.
It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).
Consider the following action:
 - Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.
How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

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

-----Input-----
Input is given from Standard Input in the following format:
N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

-----Output-----
Print an integer representing the maximum number of books that can be read.

-----Sample Input-----
3 4 240
60 90 120
80 150 80 150

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

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.
We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.
 - Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.
 - Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.
 - Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

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

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

a=[0]
b=[0]
for i in range(N):
    a.append(a[i]+A[i])
for i in range(M):
    b.append(b[i]+B[i])

#print(a)
#print(b)

ans=0
j=M
for i in range(N+1):
    if a[i]>K:
        break
    while b[j]>K-a[i]:
        j-=1
    #print(i,j)
    ans=max(ans,i+j)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_d:
For a positive integer X, let f(X) be the number of positive divisors of X.
Given a positive integer N, find \sum_{K=1}^N K\times f(K).

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

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

-----Output-----
Print the value \sum_{K=1}^N K\times f(K).

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

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

We have f(1)=1, f(2)=2, f(3)=2, and f(4)=3, so the answer is 1\times 1 + 2\times 2 + 3\times 2 + 4\times 3 =23.

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

N = int(input())
ans = 0
for i in range(1, N+1):
    j = N // i
    ans += i * j * (j+1) // 2

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_e:
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:
 - A_i \neq B_i, for every i such that 1\leq i\leq N.
 - A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.
Since the count can be enormous, print it modulo (10^9+7).

-----Constraints-----
 - 1\leq N \leq M \leq 5\times10^5
 - All values in input are integers.

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

-----Output-----
Print the count modulo (10^9+7).

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

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

A_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.

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

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

mod = 10 ** 9 + 7
#L = 5 * 10**5
fac = [1, 1]
finv = [1, 1]
inv = [0, 1]

def comb(n, r):
  return fac[n] * ( finv[r] * finv[n-r] % mod ) % mod

def perm(n, r):
  return  fac[n] * finv[n-r] % mod

for i in range(2, M + 1):
  fac.append( ( fac[-1] * i ) % mod )
  inv.append( mod - ( inv[mod % i] * (mod // i) % mod ) )
  finv.append( finv[-1] * inv[-1]  % mod )

ans = 0

for K in range(N+1):
  ans += comb(N, K) * (-1)**(K%2) % mod * perm(M, K) % mod * pow(perm(M-K, N-K), 2, mod)
  ans %= mod

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_f:
There are N piles of stones. The i-th pile has A_i stones.
Aoki and Takahashi are about to use them to play the following game:
 - Starting with Aoki, the two players alternately do the following operation:
 - Operation: Choose one pile of stones, and remove one or more stones from it.
 - When a player is unable to do the operation, he loses, and the other player wins.
When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.
In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.
If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

-----Constraints-----
 - 2 \leq N \leq 300
 - 1 \leq A_i \leq 10^{12}

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

-----Output-----
Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead.

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

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

Without moving stones, if Aoki first removes 2 stones from the 1-st pile, Takahashi cannot win in any way.
If Takahashi moves 1 stone from the 1-st pile to the 2-nd before the game begins so that both piles have 4 stones, Takahashi can always win by properly choosing his actions.

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

def main():
    n = int(input())
    a = list(map(int, input().split()))
    x, y = a[0], a[1]
    nim = 0
    for i in range(2, n):
        nim ^= a[i]
    ans = 0

    while((x ^ y) != nim):
        for i in range(50, -1, -1):
            j = (nim >> i) & 1
            xy = ((x >> i) ^ (y >> i)) & 1
            if j != xy:
                m = min(x % (2**i)+1, 2**i-(y % (2**i)))
                if x % (2**i)+1 == 2**i-(y % (2**i)):
                    print((-1))
                    return
                x -= m
                y += m
                ans += m
                if x <= 0:
                    print((-1))
                    return
                break
        else:
            if (x ^ y) != nim:
                print((-1))
                return
    print(ans)

main()


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_a:
We will buy a product for N yen (the currency of Japan) at a shop.
If we use only 1000-yen bills to pay the price, how much change will we receive?
Assume we use the minimum number of bills required.

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

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

-----Output-----
Print the amount of change as an integer.

-----Sample Input-----
1900

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

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

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

n = int(input())
r = n % 1000
if r == 0:
    print("0")
else:
    otu = 1000 - r
    print(otu)


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_b:
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.
The problem has N test cases.
For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.
See the Output section for the output format.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - S_i is AC, WA, TLE, or RE.

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

-----Output-----
Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:
AC x C_0
WA x C_1
TLE x C_2
RE x C_3

-----Sample Input-----
6
AC
TLE
AC
AC
WA
TLE

-----Sample Output-----
AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

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

N = int(input())
S = ['' for i in range(N)]
for i in range(N):
  S[i] = str(input())

item = [0, 0, 0, 0]
rslt = ['AC', 'WA', 'TLE', 'RE']
for i in range(N):
  if S[i] == rslt[0]:
    item[0] += 1
  elif S[i] == rslt[1]:
    item[1] += 1
  elif S[i] == rslt[2]:
    item[2] += 1
  else:
    item[3] += 1

for i in range(4):
  print(rslt[i], 'x', item[i])


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_c:
We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.
Consider doing the following operation:
 - Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.
You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

-----Constraints-----
 - 1 \leq H, W \leq 6
 - 1 \leq K \leq HW
 - c_{i,j} is . or #.

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

-----Output-----
Print an integer representing the number of choices of rows and columns satisfying the condition.

-----Sample Input-----
2 3 2
..#
###

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

Five choices below satisfy the condition.
 - The 1-st row and 1-st column
 - The 1-st row and 2-nd column
 - The 1-st row and 3-rd column
 - The 1-st and 2-nd column
 - The 3-rd column

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

h, w, k = map(int, input().split())
board = [[-1 for j in range(w)] for i in range(h)]
for i in range(h):
    color = input()
    for j in range(w):
        if color[j] == "#":
            board[i][j] = 1 #黒=1
        else:
            board[i][j] = 0 #白=0
ans = 0

for row_choose in range(1<<h):
    for col_choose in range(1<<w):
        count = 0
        for i in range(h):
            for j in range(w):
                if not (row_choose & (1<<i)) and not (col_choose & (1<<j)) and board[i][j]:
                    count += 1
        if count == k:
            ans += 1

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_d:
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.
The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.
When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.
What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

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

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

-----Output-----
Print the maximum total comfort the N players can get.

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

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

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

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

N = int(input())
A = sorted(list(map(int,input().split())),reverse=True)
ans = A[0]
for i in range(1,N//2):
    ans += 2* A[i]
if N%2 == 1:
    ans += A[N//2]
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_e:
Given are N integers A_1,\ldots,A_N.
We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.
Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

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

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

-----Output-----
Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

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

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

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

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

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

mod=10**9+7

if A[-1]<0 and k%2==1:
    now=1
    for i in range(k):
        now= now*A[-i-1]%mod
        # now%=mod
    print(now) ;return

l=0 ; r=n-1
ans=1
if k%2==1:
    ans=A[-1]
    r-=1

for i in range(k//2):
    mi=A[l]*A[l+1]
    pl=A[r]*A[r-1]
    if mi>pl:
        ans= ans*mi%mod
        l+=2
    else:
        ans= ans*pl%mod
        r-=2
print((ans%mod))


I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_f:
We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.
For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:
 - Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.
Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 1 \leq u_i, v_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
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

-----Output-----
Print \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

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

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

We have six possible pairs (L, R) as follows:
 - For L = 1, R = 1, S = \{1\} and we have 1 connected component.
 - For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.
 - For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.
 - For L = 2, R = 2, S = \{2\} and we have 1 connected component.
 - For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.
 - For L = 3, R = 3, S = \{3\} and we have 1 connected component.
The sum of these is 7.

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

import sys

input = sys.stdin.readline

n = int(input())
num_edge = 0
num_vertex = 0
for i in range(1, n):
    u_v = list(map(int, input().split()))
    u = u_v[0]
    v = u_v[1]
    if v < u:
        tmp = v
        v = u
        u = tmp
    num_edge += u * (n - v + 1)
    num_vertex += i * (n - i + 1)
num_vertex += n

print((num_vertex - num_edge))


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_a:
You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.
The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

-----Constraints-----
 - -40 \leq X \leq 40
 - X is an integer.

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

-----Output-----
Print Yes if you will turn on the air conditioner; print No otherwise.

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

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

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

x = int(input())

if x >= 30:
  print('Yes')
else:
  print('No')


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_b:
We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).
Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?
We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

-----Constraints-----
 - 1 \leq N \leq 2\times 10^5
 - 0 \leq D \leq 2\times 10^5
 - |X_i|,|Y_i| \leq 2\times 10^5
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N D
X_1 Y_1
\vdots
X_N Y_N

-----Output-----
Print an integer representing the number of points such that the distance from the origin is at most D.

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

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

The distance between the origin and each of the given points is as follows:
 - \sqrt{0^2+5^2}=5
 - \sqrt{(-2)^2+4^2}=4.472\ldots
 - \sqrt{3^2+4^2}=5
 - \sqrt{4^2+(-4)^2}=5.656\ldots
Thus, we have three points such that the distance from the origin is at most 5.

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

N,D = (int(x) for x in input().split())
xy = [map(int, input().split()) for _ in range(N)]
num = 0
for x,y in xy:
    if( x**2 + y**2 <= D**2):
        num += 1
print(num)


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_c:
Takahashi loves the number 7 and multiples of K.
Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)
If the sequence contains no multiples of K, print -1 instead.

-----Constraints-----
 - 1 \leq K \leq 10^6
 - K is an integer.

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

-----Output-----
Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

-----Sample Input-----
101

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

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

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

k = int(input())
count = 0
n = 0
for i in range(k):
    n = (10*n + 7)%k
    if n % k == 0:
        print(i+1)
        count+=1
        break
if count == 0:
    print(-1)


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_d:
An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.
You can do the following two kinds of operations any number of times in any order:
 - Choose two stones (not necessarily adjacent) and swap them.
 - Choose one stone and change its color (from red to white and vice versa).
According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

-----Constraints-----
 - 2 \leq N \leq 200000
 - c_i is R or W.

-----Input-----
Input is given from Standard Input in the following format:
N
c_{1}c_{2}...c_{N}

-----Output-----
Print an integer representing the minimum number of operations needed.

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

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

For example, the two operations below will achieve the objective.
 - Swap the 1-st and 3-rd stones from the left, resulting in RWWR.
 - Change the color of the 4-th stone from the left, resulting in RWWW.

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

N = int(input())
c = str(input())

count_red = 0
flag_red = []

for i in c:
	if i == 'W':
		flag_red.append(0)
	else:
		flag_red.append(1)
		count_red += 1

if count_red == 0:
	ans = 0
else:
	ans = count_red - sum(flag_red[0:count_red])

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_e:
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 0 \leq K \leq 10^9
 - 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 K
A_1 A_2 \cdots A_N

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

-----Sample Input-----
2 3
7 9

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

 - First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.
 - Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.
 - Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.
In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.

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

# coding: utf-8
import numpy as np

def solve(*args: str) -> str:
    n, k = list(map(int, args[0].split()))
    A = np.array(tuple(map(int, args[1].split())))

    l, r = 0, np.max(A)
    while l+1 < r:
        m = (l+r)//2
        if k < np.sum(np.ceil(A/m)-1):
            l = m
        else:
            r = m

    return str(r)

def __starting_point():
    print((solve(*(open(0).read().splitlines()))))

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc174/tasks/abc174_f:
We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.
You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

-----Constraints-----
 - 1\leq N,Q \leq 5 \times 10^5
 - 1\leq c_i \leq N
 - 1\leq l_i \leq r_i \leq N
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

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

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

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

 - The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.
 - The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.
 - The 3-rd ball from the left has the color 1 - just one color.

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

import sys
import numpy as np
from numba import njit

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

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

C=np.array(input().split(), int)

# Query取得-rightでソート
# dtypeQuery = [("index", int), ("start", int), ("end", int)]
queries=np.empty((Q,2),int)
# #rights=[[] for _ in range(N+1)]

for q in range(Q):
	l,r=list(map(int,input().split()))
	#queries[q] = (q,l,r)
	queries[q][0] = l
	queries[q][1] = r
	#queries=np.sort(queries,order="end")

#queries=np.array(sys.stdin.buffer.read().split(),int).reshape(Q,2)

orderByR=np.argsort(queries[:,1])

# 各色の現在の一番右のindex
mostRightColorIndex = np.zeros(N+1, int)
# bit indexed tree
bitArray=np.zeros(N+1,int)

@njit
def main(N,Q,C,queries,orderByR,mostRightColorIndex,bitArray):

	def add(itemCount, items, i, value):
		while i <= itemCount:
			items[i] += value
			i += (i & (-i))

	def sumFromStart(items, end):
		summary = 0
		i = end
		while i > 0:
			summary += items[i]
			i -= (i & (-i))
		return summary

	def sum(items, start,end):
		summary = sumFromStart(items, end) - sumFromStart(items, start-1)
		return summary

	# 答え配列
	#ans=np.zeros(Q, int)
	ans=[0]*Q
	# 左からBITと現在色の更新をしながら、クエリのrightに到達したときにBITにクエリ発行する
	qindex = 0

	for n in range(N):
		# 外側のループでは、全部の色をループ

		if Q <= qindex:
			break

		if 0 < mostRightColorIndex[C[n]]:
			# ループ中の場所の色のindexが既にある場合(=過去に、同じ色が登録されていた場合)
			# 今回で、同じ色の一番右側の要素はループ中の要素になる
			# 前登録したこの色の一番右のindexを一度BITから抜く(↓で再度登録される)
			add(N,bitArray,mostRightColorIndex[C[n]], -1 )

		# この要素の色の一番右のindexを、BITに登録
		mostRightColorIndex[C[n]] = n+1
		add(N,bitArray,n+1, 1)

		# while qindex < Q and n+1 == queries[qindex][2]:
		while qindex < Q and n+1 == queries[orderByR[qindex]][1]:
			# 今のBITが次のクエリ発行するための状態(n==query.right)だったら、クエリ発行
			tmpIndex = orderByR[qindex]
			start = queries[tmpIndex][0]
			end = queries[tmpIndex][1]
			ans[tmpIndex]=sum(bitArray,start,end)
			# print(tmpIndex,start,end,ans[tmpIndex])
			qindex += 1

	return ans

for a in main(N,Q,C,queries,orderByR,mostRightColorIndex,bitArray):
	print(a)


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_a:
We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.
Find the maximum number of consecutive rainy days in this period.

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

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

-----Output-----
Print the maximum number of consecutive rainy days in the period.

-----Sample Input-----
RRS

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

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

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

s = input()
if s == 'RRR':
  print(3)
elif s == 'RRS' or s == 'SRR':
  print(2)
elif s == 'SSS':
  print(0)
else:
  print(1)


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_b:
We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.
In how many ways can we choose three of the sticks with different lengths that can form a triangle?
That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:
 - L_i, L_j, and L_k are all different.
 - There exists a triangle whose sides have lengths L_i, L_j, and L_k.

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

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

-----Output-----
Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

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

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

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

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

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

x = 0
for i in range(n-2):
  for j in range(i+1,n-1):
    for k in range(j+1,n):
      if b[i] != b[j] and b[j] != b[k] and b[k] != b[i]:
        if b[i] < b[j] + b[k] and b[j] < b[i] + b[k] and b[k] < b[i] + b[j]:
          x += 1

print(x)


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_c:
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.

-----Constraints-----
 - -10^{15} \leq X \leq 10^{15}
 - 1 \leq K \leq 10^{15}
 - 1 \leq D \leq 10^{15}
 - All values in input are integers.

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

-----Output-----
Print the minimum possible absolute value of the coordinate of the destination.

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

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

Takahashi is now at coordinate 6. It is optimal to make the following moves:
 - Move from coordinate 6 to (6 - 4 =) 2.
 - Move from coordinate 2 to (2 - 4 =) -2.
Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

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

x,k,d = map(int,input().split())

if x >= 0 :
    a = abs(x//d)
    if a <= k :
        if (k - a) % 2 == 0 :
            print(abs(x-a*d))
        else :
            print(abs(x-(a+1)*d))
    else :
        print(abs(x-k*d))
else :
    if x%d == 0 :
        a = abs(x//d)
    else :
        a = abs(x//d+1)

    if a <= k :
        if (k - a) % 2 == 0 :
            print(abs(x+a*d))
        else :
            print(abs(x+(a+1)*d))
    else :
            print(abs(x+k*d))


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_d:
Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.
Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):
 - In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.
Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

-----Constraints-----
 - 2 \leq N \leq 5000
 - 1 \leq K \leq 10^9
 - 1 \leq P_i \leq N
 - P_i \neq i
 - P_1, P_2, \cdots, P_N are all different.
 - -10^9 \leq C_i \leq 10^9
 - All values in input are integers.

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

-----Output-----
Print the maximum possible score at the end of the game.

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

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

When we start at some square of our choice and make at most two moves, we have the following options:
 - If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.
 - If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.
 - If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.
 - If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.
 - If we start at Square 5, making one move sends the piece to Square 3, after which the...

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

from collections import deque
it = lambda: list(map(int, input().strip().split()))

def maximise(L, R, cycle):
    cur = 0
    ans = max(cycle)
    queue = deque([0])
    dp = [0] * (2 * L + 1)
    for i, num in enumerate(cycle + cycle):
        j = i + 1
        cur += num
        while queue and j - queue[0] > R:
            queue.popleft()
        if queue:
            ans = max(ans, cur - dp[queue[0]])
        while queue and dp[queue[-1]] >= cur:
            queue.pop()
        queue.append(j)
        dp[j] = cur
    return ans

def get(K, cycle):
    L = len(cycle)
    T = sum(cycle)

    if K > L:
        B = (K - 1) // L
        R = K - B * L
    else:
        B = 0
        R = K
    return max(maximise(L, K, cycle), maximise(L, R, cycle) + max(0, B * T))

def solve():
    # square labelled from 1 to N
    N, K = it()
    P = it()
    C = it()

    for i in range(N):
        P[i] -= 1

    cycles = []
    seen = [False] * N
    for i in range(N):
        if not seen[i]:
            cycle = []
            first = curr = i
            while True:
                seen[curr] = True
                cycle.append(C[curr])
                curr = P[curr]
                if curr == first:
                    break
            cycles.append(cycle)

    # print(cycles)
    ans = float('-inf')
    for cycle in cycles:
        ans = max(ans, get(K, cycle))
    return ans

def __starting_point():
    ans = solve()
    print(ans)
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_e:
There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.
Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).
He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.
Find the maximum possible sum of the values of items he picks up.

-----Constraints-----
 - 1 \leq R, C \leq 3000
 - 1 \leq K \leq \min(2 \times 10^5, R \times C)
 - 1 \leq r_i \leq R
 - 1 \leq c_i \leq C
 - (r_i, c_i) \neq (r_j, c_j) (i \neq j)
 - 1 \leq v_i \leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

-----Output-----
Print the maximum possible sum of the values of items Takahashi picks up.

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

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

He has two ways to get to the goal:
 - Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.
 - Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.
Thus, the maximum possible sum of the values of items he picks up is 8.

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

import math
from numba import jit
import numpy as np

@jit
def solve():

    r,c,k = map(int,input().split())

    value = np.zeros((r,c), dtype=np.int64)
    for i in range(k):
        r_t,c_t,v_t = map(int,input().split())
        value[r_t-1][c_t-1] = v_t

    dp = np.zeros((r,c,4), dtype=np.int64)
    dp[0][0][0] = 0

    for i in range(r):
        for j in range(c):
            for m in range(4):
                if i + 1 < r:
                    dp[i+1][j][0] = max(dp[i+1][j][0],dp[i][j][m])
                if j + 1 < c:
                    dp[i][j+1][m] = max(dp[i][j+1][m],dp[i][j][m])
                if value[i][j] != 0 and m < 3:
                    if i + 1 < r:
                        dp[i+1][j][0] = max(dp[i+1][j][0],dp[i][j][m]+value[i][j])
                    if j + 1 < c:
                        dp[i][j+1][m+1] = max(dp[i][j+1][m+1],dp[i][j][m]+value[i][j])

    for m in range(2,-1,-1):
        dp[r-1][c-1][m+1] = max(dp[r-1][c-1][m+1],dp[r-1][c-1][m]+value[r-1][c-1])
    return max(dp[r-1][c-1])

print(solve())


I found an interesting problem on https://atcoder.jp/contests/abc175/tasks/abc175_f:
We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N.
Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice.
The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times.
Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome.
If there is no choice of strings in which he can make a palindrome, print -1.

-----Constraints-----
 - 1 \leq N \leq 50
 - 1 \leq |S_i| \leq 20
 - S_i consists of lowercase English letters.
 - 1 \leq C_i \leq 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
S_1 C_1
S_2 C_2
:
S_N C_N

-----Output-----
Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice.

-----Sample Input-----
3
ba 3
abc 4
cbaa 5

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

We have ba, abc, and cbaa.
For example, we can use ba once and abc once for a cost of 7, then concatenate them in the order abc, ba to make a palindrome.
Also, we can use abc once and cbaa once for a cost of 9, then concatenate them in the order cbaa, abc to make a palindrome.
We cannot make a palindrome for a cost less than 7, so we should print 7.

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

'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

def main():
    n = int(ipt())
    wrds = []
    hq = []
    usd = set()
    for i in range(n):
        s,c = input().split()
        c = int(c)
        wrds.append((s,c))
        hpq.heappush(hq,(c,s,1))

    while hq:
        hc,hs,hp = hpq.heappop(hq)
        usd.add((hs,hp))
        ls = len(hs)
        if hs == hs[::-1]:
            print(hc)
            return
        for si,ci in wrds:
            lsi = len(si)
            if lsi > ls:
                if hp == 1:
                    wt = si[::-1]
#                    print(wt)
                    if hs == wt[:ls:] and not (wt[ls::],-1) in usd:
                        hpq.heappush(hq,(hc+ci,wt[ls::],-1))
                else:
                    if hs == si[:ls:] and not (si[ls::],1) in usd:
                        hpq.heappush(hq,(hc+ci,si[ls::],1))
            else:
                if hp == 1:
                    wt = si[::-1]
                    if wt == hs[:lsi:] and not (hs[lsi::],1) in usd:
                        hpq.heappush(hq,(hc+ci,hs[lsi::],1))
                else:
                    if si == hs[:lsi:] and not (hs[lsi::],-1) in usd:
                        hpq.heappush(hq,(hc+ci,hs[lsi::],-1))
#        print(hq)

    print((-1))

    return None

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc176/tasks/abc176_a:
Takahashi loves takoyaki - a ball-shaped snack.
With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.
How long does it take to make N takoyaki?

-----Constraints-----
 - 1 \leq N,X,T \leq 1000
 - All values in input are integers.

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

-----Output-----
Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

-----Sample Input-----
20 12 6

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

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.
Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

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

N, X, T = map(int, input().split())

check = N % X
kaisu = N // X

if check == 0:
    print(kaisu * T)
else:
    print((kaisu + 1) * T)


I found an interesting problem on https://atcoder.jp/contests/abc176/tasks/abc176_b:
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.
Determine whether N is a multiple of 9.

-----Constraints-----
 - 0 \leq N < 10^{200000}
 - N is an integer.

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

-----Output-----
If N is a multiple of 9, print Yes; otherwise, print No.

-----Sample Input-----
123456789

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

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

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

N = input()
List = [N[i] for i in range(len(N))]
ans = 0
for i in range(len(List)):
    ans += int(List[i])
    ans %= 9
if ans % 9 == 0:
    print("Yes")
else:
    print("No")


I found an interesting problem on https://atcoder.jp/contests/abc176/tasks/abc176_c:
N persons are standing in a row. The height of the i-th person from the front is A_i.
We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:
Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.
Find the minimum total height of the stools needed to meet this goal.

-----Constraints-----
 - 1 \leq N \leq 2\times 10^5
 - 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 \ldots A_N

-----Output-----
Print the minimum total height of the stools needed to meet the goal.

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

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

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.
We cannot meet the goal with a smaller total height of the stools.

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

N = int(input())
A = list(map(int,input().split()))
count = 0
mh = A[0]
for i in range(1,len(A)):
    if mh > A[i]:
        count += mh-A[i]
    else:
        mh = A[i]
print(count)


I found an interesting problem on https://atcoder.jp/contests/abc176/tasks/abc176_d:
A maze is composed of a grid of H \times W squares - H vertical, W horizontal.
The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..
There is a magician in (C_h,C_w). He can do the following two kinds of moves:
 - Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.
 - Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.
In either case, he cannot go out of the maze.
At least how many times does he need to use the magic to reach (D_h, D_w)?

-----Constraints-----
 - 1 \leq H,W \leq 10^3
 - 1 \leq C_h,D_h \leq H
 - 1 \leq C_w,D_w \leq W
 - S_{ij} is # or ..
 - S_{C_h C_w} and S_{D_h D_w} are ..
 - (C_h,C_w) \neq (D_h,D_w)

-----Input-----
Input is given from Standard Input in the following format:
H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

-----Output-----
Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

-----Sample Input-----
4 4
1 1
4 4
..#.
..#.
.#..
.#..

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

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.
Note that he cannot walk diagonally.

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

from collections import deque

def main():
    h, w = list(map(int, input().split()))
    c = list([int(x)+1 for x in input().split()])
    d = list([int(x)+1 for x in input().split()])
    s = ['#'*(w+4)]*2 + ['#'*2 + input() + '#'*2 for _ in range(h)] + ['#'*(w+4)]*2

    ans = [[-1]*(w+4) for _ in range(h+4)]
    for i in range(h+4):
        for j in range(w+4):
            if s[i][j] == '#':
                ans[i][j] = -2
    ans[c[0]][c[1]] = 0

    move1 = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    move2 = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if abs(i)+abs(j) > 1]

    yet = deque([(c[0], c[1])])
    done = deque()

    while yet:
        y, x = yet.popleft()
        done.append((y, x))
        for dy, dx in move1:
            ydy, xdx = y+dy, x+dx
            if ans[ydy][xdx] == -1:
                yet.append((ydy, xdx))
                ans[ydy][xdx] = ans[y][x]

        if len(yet) == 0:
            while done:
                y, x = done.popleft()
                for dy, dx in move2:
                    ydy, xdx = y+dy, x+dx
                    if ans[ydy][xdx] == -1:
                        ans[ydy][xdx] = ans[y][x] + 1
                        yet.append((ydy, xdx))

    print((ans[d[0]][d[1]]))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://atcoder.jp/contests/abc176/tasks/abc176_e:
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).
Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.
Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq H, W \leq 3 \times 10^5
 - 1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)
 - 1 \leq h_i \leq H
 - 1 \leq w_i \leq W
 - \left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

-----Input-----
Input is given from Standard Input in the following format:
H W M
h_1 w_1
\vdots
h_M w_M

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

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

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

We can destroy all the targets by placing the bomb at \left(1, 2\right).

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

#https://atcoder.jp/contests/abc176/submissions/16118386
import collections
import sys
import math
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())
def NIJIGEN(H): return [list(input()) for i in range(H)]
H,W,M=map(int,input().split())
A=list()
B=list()
for i in range(M):
  a,b=map(int,input().split())
  A.append(a)
  B.append(b)
c = collections.Counter(A)
s=c.most_common()
k=s[0][0]
t=s[0][1]
L=list()
for i in range(M):
  if A[i]!=k:
    L.append(B[i])
c = collections.Counter(L)
s=c.most_common()
if len(s)!=0:
  ans=s[0][1]+t
else:
  ans=t
c = collections.Counter(B)
s=c.most_common()
k=s[0][0]
t=s[0][1]
L=list()
for i in range(M):
  if B[i]!=k:
    L.append(A[i])
c = collections.Counter(L)
s=c.most_common()
if len(s)!=0:
  q=s[0][1]+t
else:
  q=t
ans=max(ans,q)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_a:
Takahashi is meeting up with Aoki.
They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.
Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.
Will he arrive in time?

-----Constraints-----
 - 1 \leq D \leq 10000
 - 1 \leq T \leq 10000
 - 1 \leq S \leq 10000
 - All values in input are integers.

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

-----Output-----
If Takahashi will reach the place in time, print Yes; otherwise, print No.

-----Sample Input-----
1000 15 80

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

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

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

D, T, S = map(int, input().split())
print(('Yes' if T * S >= D else 'No'))


I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_b:
Given are two strings S and T.
Let us change some of the characters in S so that T will be a substring of S.
At least how many characters do we need to change?
Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

-----Constraints-----
 - The lengths of S and T are each at least 1 and at most 1000.
 - The length of T is at most that of S.
 - S and T consist of lowercase English letters.

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

-----Output-----
Print the minimum number of characters in S that need to be changed.

-----Sample Input-----
cabacc
abc

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

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.
Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

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

import sys
from collections import deque, defaultdict, Counter
from itertools import accumulate, product, permutations, combinations
from operator import itemgetter
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush
from math import ceil, floor, sqrt, gcd, inf
from copy import deepcopy
import numpy as np
import scipy as sp

INF = inf
MOD = 1000000007

s = input()
t = input()

tmp = 0
res = 0

res = INF
ls = len(s)
lt = len(t)
for i in range(ls - lt + 1):
    tmp = 0
    for j in range(lt):
        if t[j] != s[i + j]:
            tmp += 1
    res = min(res, tmp)

print(res)


I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_c:
Given are N integers A_1,\ldots,A_N.
Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

-----Constraints-----
 - 2 \leq N \leq 2\times 10^5
 - 0 \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 \ldots A_N

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

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

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

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

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

import numpy as np
n=int(input())
a= sorted(map(int,input().split()))
b=np.cumsum(a)
c=0
mod=10**9+7
for i in range(n-1):
    c+=int(a[i])*(int(b[-1])-int(b[i]))
    c%=mod
print(c)


I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_d:
There are N persons called Person 1 through Person N.
You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.
If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.
Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.
At least how many groups does he need to make?

-----Constraints-----
 - 2 \leq N \leq 2\times 10^5
 - 0 \leq M \leq 2\times 10^5
 - 1\leq A_i,B_i\leq N
 - A_i \neq B_i

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

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

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

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

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

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

def A():
    d, t, s = list(map(int, input().split()))
    print(("Yes" if t*s>=d else "No"))

def B():
    s = input()
    t = input()
    sa = len(s) - len(t)
    ret = 10000000000
    for i in range(sa+1):
        cnt = 0
        for j in range(len(t)):
            if s[j+i] != t[j]: cnt += 1
        ret = min(ret, cnt)
    print(ret)

def C():
    int(input())
    A = list(map(int, input().split()))
    S = sum(A)
    T = 0
    for e in A:
        T += e*e
    print(((S * S - T)//2))

class UF:
    def __init__(self, N):
        self.N = N
        self.sz = [1] * N
        self.par = [i for i in range(N)]
        self.d = [1] * N

    def find(self, x):
        if self.par[x] == x: return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y: return False
        if self.d[y] > self.d[x]:
            self.par[x] = y
            self.sz[y] += self.sz[x]
        else:
            self.par[y] = x
            self.sz[x] += self.sz[y]
            if self.d[x] == self.d[y]: self.d[x] += 1

def D():
    n, m = list(map(int, input().split()))
    uf = UF(n+1)
    for i in range(m):
        a, b = list(map(int, input().split()))
        uf.unite(a, b)
    print((max(uf.sz)))

D()


I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_e:
We have N integers. The i-th number is A_i.
\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.
\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.
Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.
Here, GCD(\ldots) denotes greatest common divisor.

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

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

-----Output-----
If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

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

-----Sample Output-----
pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

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

from math import gcd
from functools import reduce

N, *A = list(map(int, open(0).read().split()))

def f():
    t = [0] * (10 ** 6 + 1)
    for a in A:
        t[a] += 1

    c = 0
    for j in range(2, 10 ** 6 + 1, 2):
        c += t[j]
    if c > 1:
        return False

    for i in range(3, 10 ** 6 + 1, 2):
        c = 0
        for j in range(i, 10 ** 6 + 1, i):
            c += t[j]
        if c > 1:
            return False

    return True

if f():
    print('pairwise coprime')
elif reduce(gcd, A) == 1:
    print('setwise coprime')
else:
    print('not coprime')


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_a:
Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

-----Constraints-----
 - 0 \leq x \leq 1
 - x is an integer

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

-----Output-----
Print 1 if x is equal to 0, or 0 if x is equal to 1.

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

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

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


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_b:
Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

-----Constraints-----
 - -10^9 \leq a \leq b \leq 10^9
 - -10^9 \leq c \leq d \leq 10^9
 - All values in input are integers.

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

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

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

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

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

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

a, b, c, d = map(int,input().split())
ans_list = [a*c, a*d, b*c, b*d]
ans_list.sort()
ans = ans_list.pop()
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_c:
How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?
 - 0 \leq A_i \leq 9
 - There exists some i such that A_i=0 holds.
 - There exists some i such that A_i=9 holds.
The answer can be very large, so output it modulo 10^9 + 7.

-----Constraints-----
 - 1 \leq N \leq 10^6
 - N is an integer.

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

-----Output-----
Print the answer modulo 10^9 + 7.

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

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

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

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


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_d:
Given is an integer S.
Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S.
The answer can be very large, so output it modulo 10^9 + 7.

-----Constraints-----
 - 1 \leq S \leq 2000
 - All values in input are integers.

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

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

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

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

3 sequences satisfy the condition: \{3,4\}, \{4,3\} and \{7\}.

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

from sys import stdin

def main():
    input = stdin.readline

    s = int(input())
    dp = [0] * (s + 1)
    dp[0] = 1
    for i in range(s):
        if dp[i] == 0:
            continue
        for x in range(3, s + 1):
            if i + x <= s:
                dp[i + x] += dp[i]
                dp[i + x] %= 1000000007
            else:
                break
    print(dp[s])
main()


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_e:
There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?
Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

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

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

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

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

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

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

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

n=int(input())
p=[]
q=[]
for _ in range(n):
  x,y=map(int,input().split())
  p.append(x+y)
  q.append(x-y)
print(max(max(p)-min(p),max(q)-min(q)))


I found an interesting problem on https://atcoder.jp/contests/abc178/tasks/abc178_f:
Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

-----Constraints-----
 - 1\leq N \leq 2 \times 10^5
 - 1\leq A_i,B_i \leq N
 - A and B are each sorted in the ascending order.
 - All values in input are integers.

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

-----Output-----
If there exist no reorderings that satisfy the condition, print No.
If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print any of them.

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

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

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

#解説参照
n=int(input())
*a,=map(int, input().split())
*b,=map(int, input().split())
shift=0
from bisect import bisect_right,bisect_left
from collections import Counter
sb=Counter(b)
sa=Counter(a)
for bi in sb:
    if bi in sa:
        if sa[bi]+sb[bi]>n:
            print("No")
            return
for bi in sb:
    lb=bisect_left(b,bi)
    ra=bisect_right(a,bi)
    if a[ra-1]==b[lb]:
        shift=max(shift,ra-lb)
ans=[b[(i-shift)%n] for i in range(n)]##
print("Yes")
print(*ans)


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_a:
In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.
In Taknese, the plural form of a noun is spelled based on the following rules:
 - If a noun's singular form does not end with s, append s to the end of the singular form.
 - If a noun's singular form ends with s, append es to the end of the singular form.
You are given the singular form S of a Taknese noun. Output its plural form.

-----Constraints-----
 - S is a string of length 1 between 1000, inclusive.
 - S contains only lowercase English letters.

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

-----Output-----
Print the plural form of the given Taknese word.

-----Sample Input-----
apple

-----Sample Output-----
apples

apple ends with e, so its plural form is apples.

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

s=input()
print(s+'es' if s[-1]=='s' else s+'s')


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_b:
Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.
Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

-----Constraints-----
 - 3 \leq N \leq 100
 - 1\leq D_{i,j} \leq 6
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

-----Output-----
Print Yes if doublets occurred at least three times in a row. Print No otherwise.

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

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

From the second roll to the fourth roll, three doublets occurred in a row.

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

N=  int(input())
YN_list = []

a=0
for i in range(N):
  Di1,Di2 = input().split()
  if Di1 == Di2:
    a = a + 1
    if a >= 3:
      YN_list.append("Yes")
    else:
      YN_list.append("No")
  else:
    a = 0
    if a >= 3:
      YN_list.append("Yes")
    else:
      YN_list.append("No")

if 'Yes' in YN_list:
  print("Yes")
else:
  print("No")


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_c:
Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

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

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

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

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

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

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

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

n=int(input())
cnt=0
for a in range(1,n+1):
    cnt += (n-1)//a
print(cnt)


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_d:
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
 - When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^5
 - 1 \leq K \leq \min(N, 10)
 - 1 \leq L_i \leq R_i \leq N
 - [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K

-----Output-----
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

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

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

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.
There are 4 possible ways to get to Cell 5:
 - 1 \to 2 \to 3 \to 4 \to 5,
 - 1 \to 2 \to 5,
 - 1 \to 4 \to 5 and
 - 1 \to 5.

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

N,K = list(map(int,input().split()))
mod = 998244353
dp = [0] * (N+1)
dpSum = [0] * (N+1)
R = []
L = []

for i in range(K):
  l,r = list(map(int,input().split()))
  L.append(l)
  R.append(r)

dp[1] = 1
dpSum[1] = 1
for i in range(2,N+1,1):
  for j in range(K):
    li = i - R[j]
    ri = i - L[j]
    if ri < 1:
      continue
    li = max(li, 1)
    dp[i] += dpSum[ri] % mod - dpSum[li-1] % mod
  dpSum[i] = dpSum[i-1] % mod + dp[i] % mod
ans = dp[N] % mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_e:
Let us denote by f(x, m) the remainder of the Euclidean division of x by m.
Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

-----Constraints-----
 - 1 \leq N \leq 10^{10}
 - 0 \leq X < M \leq 10^5
 - All values in input are integers.

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

-----Output-----
Print \displaystyle{\sum_{i=1}^N A_i}.

-----Sample Input-----
6 2 1001

-----Sample Output-----
1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

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, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
#mod = 10 ** 9 + 7
mod = 998244353
#from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, X, M = MAP()

check = [0]*(10**5+1)
sum_acc = [0]

i = X
cnt = 0
while check[i] < 2 and cnt < N:
	check[i] += 1
	cnt += 1
	sum_acc.append(sum_acc[-1]+i)
	i = i**2%M

if cnt == N:
	print(sum_acc[-1])
	return

cnt_1 = check.count(1)
cnt_2 = check.count(2)
loop_sum = (sum_acc[-1] - sum_acc[cnt_1])//2

ans = sum_acc[cnt_1]
ans += loop_sum*((N-cnt_1)//cnt_2)
ans += sum_acc[cnt_1+((N-cnt_1)%cnt_2)] - sum_acc[cnt_1]

print(ans)


I found an interesting problem on https://atcoder.jp/contests/abc179/tasks/abc179_f:
There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.
Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it.
Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.
Q queries are given. We ask you to process them in order.
There are two kinds of queries. Their input format and description are as follows:
 - 1 x: Place a white stone on (1, x). After that, for each black stone between (1, x) and the first white stone you hit if you go down from (1, x), replace it with a white stone.
 - 2 x: Place a white stone on (x, 1). After that, for each black stone between (x, 1) and the first white stone you hit if you go right from (x, 1), replace it with a white stone.
How many black stones are there on the grid after processing all Q queries?

-----Constraints-----
 - 3 \leq N \leq 2\times 10^5
 - 0 \leq Q \leq \min(2N-4,2\times 10^5)
 - 2 \leq x \leq N-1
 - Queries are pairwise distinct.

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

-----Output-----
Print how many black stones there are on the grid after processing all Q queries.

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

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

After each query, the grid changes in the following way:

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

def main():
    N, Q = [int(v) for v in input().split()]

    Query = [[int(v)-1 for v in input().split()] for _ in range(Q)]

    rows = [N-1] * (N - 1)
    cols = [N-1] * (N - 1)

    black = (N - 2) * (N - 2)
    min_row = N - 1
    min_col = N - 1

    for ty, x in Query:
        if ty == 0:
            if x < min_col:
                rows[x:min_col] = [min_row] * (min_col - x)
                min_col = x
            black -= rows[x] - 1
        else:
            if x < min_row:
                cols[x:min_row] = [min_col] * (min_row - x)
                min_row = x
            black -= cols[x] - 1

    print(black)

main()


I found an interesting problem on https://atcoder.jp/contests/agc001/tasks/agc001_a:
Snuke is having a barbeque party.
At the party, he will make N servings of Skewer Meal.
Example of a serving of Skewer Meal
He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.
To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.
What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

-----Constraints-----
 - 1≦N≦100
 - 1≦L_i≦100
 - For each i, L_i is an integer.

-----Input-----
The input is given from Standard Input in the following format:
N
L_1 L_2 ... L_{2N}

-----Output-----
Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

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

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

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

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

n = int(input()); a = list(map(int, input().split()))
a.sort(); b = 0
for i in range(n): b += a[2*i]
print(b)


I found an interesting problem on https://atcoder.jp/contests/arc060/tasks/arc060_b:
For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:
 - f(b,n) = n, when n < b
 - f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b
Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.
Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:
 - f(10,\,87654)=8+7+6+5+4=30
 - f(100,\,87654)=8+76+54=138
You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

-----Constraints-----
 - 1 \leq n \leq 10^{11}
 - 1 \leq s \leq 10^{11}
 - n,\,s are integers.

-----Input-----
The input is given from Standard Input in the following format:
n
s

-----Output-----
If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

-----Sample Input-----
87654
30

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

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

import math
n=int(input())
s=int(input())

def f(b,n):
    if n<b:
        return n
    else:
        return f(b,n//b)+(n%b)

def abc(N,S):
    if N==S:
        return N+1
    else:
        for b in range(2,int(math.sqrt(N))+2):
            if f(b,N)==S:
                return b
        tmp=-1
        for p in range(1,int(math.sqrt(N))+2):
            if (N-S)%p!=0:
                continue
            b=(N-S)//p+1
            if b<=1:
                continue
            if f(b,N)==S:
                tmp=b
        return tmp
ans=abc(n,s)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc061/tasks/arc061_d:
Alice, Bob and Charlie are playing Card Game for Three, as below:
 - At first, each of the three players has a deck consisting of some number of cards. Alice's deck has N cards, Bob's deck has M cards, and Charlie's deck has K cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.
 - The players take turns. Alice goes first.
 - If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)
 - If the current player's deck is empty, the game ends and the current player wins the game.
There are 3^{N+M+K} possible patters of the three player's initial decks. Among these patterns, how many will lead to Alice's victory?
Since the answer can be large, print the count modulo 1\,000\,000\,007 (=10^9+7).

-----Constraints-----
 - 1 \leq N \leq 3×10^5
 - 1 \leq M \leq 3×10^5
 - 1 \leq K \leq 3×10^5

-----Partial Scores-----
 - 500 points will be awarded for passing the test set satisfying the following: 1 \leq N \leq 1000, 1 \leq M \leq 1000, 1 \leq K \leq 1000.

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

-----Output-----
Print the answer modulo 1\,000\,000\,007 (=10^9+7).

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

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

 - If Alice's card is a, then Alice will win regardless of Bob's and Charlie's card. There are 3×3=9 such patterns.
 - If Alice's card is b, Alice will only win when Bob's card is a, or when Bob's card is c and Charlie's card is a. There are 3+1=4 such patterns.
 - If Alice's card is c, Alice will only win when Charlie's card is a, or when Charlie's card is b and Bob's card is a. There are 3+1=4 such patterns.
Thus, there are total of 9+4+4=17 patterns that will lead to Alice's victory.

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

import sys
input = sys.stdin.readline

import numpy as np

MOD = 10**9 + 7

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

def cumprod(arr):
    L = len(arr); Lsq = int(L**.5+1)
    arr = np.resize(arr,Lsq**2).reshape(Lsq,Lsq)
    for n in range(1,Lsq):
        arr[:,n] *= arr[:,n-1]; arr[:,n] %= MOD
    for n in range(1,Lsq):
        arr[n] *= arr[n-1,-1]; arr[n] %= MOD
    return arr.ravel()[:L]

U = 10**6
x = np.full(U,2,dtype=np.int64); x[0] = 1
pow2 = cumprod(x)
x = np.full(U,3,dtype=np.int64); x[0] = 1
pow3 = cumprod(x)
x = np.full(U,pow(2,MOD-2,MOD),dtype=np.int64); x[0] = 1
pow2_inv = cumprod(x)
x = np.full(U,pow(3,MOD-2,MOD),dtype=np.int64); x[0] = 1
pow3_inv = cumprod(x)
x = np.arange(U,dtype=np.int64); x[0] = 1
fact = cumprod(x)
x = np.arange(U,0,-1,dtype=np.int64); x[0] = pow(int(fact[-1]),MOD-2,MOD)
fact_inv = cumprod(x)[::-1]

L = N+M
A = np.zeros(N+M,dtype=np.int64)
A[1:L] = (-1) * pow2[0:L-1] * pow3_inv[0:L-1] % MOD
A[1:L] *= fact[K+1:K+L] * fact_inv[K] % MOD * fact_inv[1:L] % MOD; A %= MOD
A[1:L] *= pow3_inv[K+1]; A %= MOD
A[0] = 3 * (1 - pow3_inv[K+1]) % MOD * pow2_inv[1] % MOD
np.cumsum(A,out=A); A %= MOD
A *= pow3[:L]; A %= MOD
A *= pow2_inv[:L]; A %= MOD

comb = fact[N-1:N+M] * fact_inv[:M+1] % MOD * fact_inv[N-1] % MOD
answer = (comb * pow3[K+M:K-1:-1] % MOD * A[N-1:N+M] % MOD).sum() % MOD
print(answer)


I found an interesting problem on https://atcoder.jp/contests/arc062/tasks/arc062_c:
AtCoDeer the deer has N square tiles. The tiles are numbered 1 through N, and the number given to each tile is written on one side of the tile. Also, each corner of each tile is painted in one of the 1000 colors, which are represented by the integers 0 between 999. The top-left, top-right, bottom-right and bottom-left corner of the tile with the number i are painted in color C_{i,0}, C_{i,1}, C_{i,2} and C_{i,3}, respectively, when seen in the direction of the number written on the tile (See Figure 1).
Figure 1: The correspondence between the colors of a tile and the input
AtCoDeer is constructing a cube using six of these tiles, under the following conditions:
 - For each tile, the side with the number must face outward.
 - For each vertex of the cube, the three corners of the tiles that forms it must all be painted in the same color.
Help him by finding the number of the different cubes that can be constructed under the conditions.
Since each tile has a number written on it, two cubes are considered different if the set of the used tiles are different, or the tiles are used in different directions, even if the formation of the colors are the same. (Each tile can be used in one of the four directions, obtained by 90° rotations.) Two cubes are considered the same only if rotating one in the three dimensional space can obtain an exact copy of the other, including the directions of the tiles.
Figure 2: The four directions of a tile

-----Constraints-----
 - 6≦N≦400
 - 0≦C_{i,j}≦999 (1≦i≦N , 0≦j≦3)

-----Input-----
The input is given from Standard Input in the following format:
N
C_{1,0} C_{1,1} C_{1,2} C_{1,3}
C_{2,0} C_{2,1} C_{2,2} C_{2,3}
:
C_{N,0} C_{N,1} C_{N,2} C_{N,3}

-----Output-----
Print the number of the different cubes that can be constructed under the conditions.

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

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

The cube below can be constructed.

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

from collections import defaultdict
N, = list(map(int, input().split()))

def normal(xs):
    return tuple(min((xs[j:] + xs[:j] for j in range(1, 5))))

dd = defaultdict(int)
cc = dict()
norm = dict()
ss = []
for _ in range(N):
    xs = list(map(int, input().split()))
    cnd = [tuple(xs[j:] + xs[:j]) for j in range(1, 5)]
    x = min(cnd)
    for item in cnd:
        norm[item] = x
    dd[x] += 1
    cc[x] = (4 if x[0] == x[1] else 2)if x[0] == x[2] and x[1] == x[3] else 1
    ss.append(x)

def icr(x):
    dd[x] += 1

def dcr(x):
    dd[x] -= 1

def f(ff, gg):
    a,b,c,d=ff
    e,h,g,f=gg
    tl = [(a,e,f,b), (b,f,g,c), (c,g,h,d), (d,h,e,a)]
    for cp in tl:
        if cp not in norm:
            return 0
    r = 1
    for cp in tl:
        cp = norm[cp]
        r *= dd[cp]*cc[cp]
        dcr(cp)
    for cp in tl:
        cp = norm[cp]
        icr(cp)
    return r

r = 0
for i in range(N):
    ff = ss[i]
    dcr(ff)
    for j in range(i+1, N):
        sl = ss[j]
        dcr(sl)
        x, y, z, w = sl
        sls = [(x,y,z,w), (y,z,w,x), (z,w,x,y), (w,x,y,z)]
        for s in sls:
            r += f(ff, s)
        icr(sl)
    icr(ff)
print((r//3))


I found an interesting problem on https://atcoder.jp/contests/arc064/tasks/arc064_b:
There is a string s of length 3 or greater.
No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:
 - Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.
The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

-----Constraints-----
 - 3 ≤ |s| ≤ 10^5
 - s consists of lowercase English letters.
 - No two neighboring characters in s are equal.

-----Input-----
The input is given from Standard Input in the following format:
s

-----Output-----
If Takahashi will win, print First. If Aoki will win, print Second.

-----Sample Input-----
aba

-----Sample Output-----
Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

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

s = input()
n = len(s)

if s[0] == s[-1]:
    move = 1
else:
    move = 0

move = (n - move) % 2

if move == 1:
    print('First')
else:
    print('Second')


I found an interesting problem on https://atcoder.jp/contests/arc064/tasks/arc064_d:
Takahashi and Aoki are going to together construct a sequence of integers.
First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions:
 - The length of a is N.
 - Each element in a is an integer between 1 and K, inclusive.
 - a is a palindrome, that is, reversing the order of elements in a will result in the same sequence as the original.
Then, Aoki will perform the following operation an arbitrary number of times:
 - Move the first element in a to the end of a.
How many sequences a can be obtained after this procedure, modulo 10^9+7?

-----Constraints-----
 - 1≤N≤10^9
 - 1≤K≤10^9

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

-----Output-----
Print the number of the sequences a that can be obtained after the procedure, modulo 10^9+7.

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

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

The following six sequences can be obtained:
 - (1, 1, 1, 1)
 - (1, 1, 2, 2)
 - (1, 2, 2, 1)
 - (2, 2, 1, 1)
 - (2, 1, 1, 2)
 - (2, 2, 2, 2)

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

import sys
input = sys.stdin.readline

import numpy as np

MOD = 10**9 + 7

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

U=int(10**4.5+10)
div = np.arange(1,U,dtype=np.int64)
div = div[N%div==0]
div = sorted(np.union1d(div,N//div))

A = {d:pow(K,int((d+1)//2),MOD) for d in div}
B = {}
for d in div:
    B[d] = A[d] - sum(B[dd] for dd in div if dd < d and d%dd == 0)

answer = sum(B[d] * (d//2 if d%2 == 0 else d) for d in div)
answer %= MOD
print(answer)


I found an interesting problem on https://atcoder.jp/contests/arc065/tasks/arc065_a:
You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:
 - Append one of the following at the end of T: dream, dreamer, erase and eraser.

-----Constraints-----
 - 1≦|S|≦10^5
 - S consists of lowercase English letters.

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

-----Output-----
If it is possible to obtain S = T, print YES. Otherwise, print NO.

-----Sample Input-----
erasedream

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

Append erase and dream at the end of T in this order, to obtain S = T.

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

s = input()
s = s[::-1]
lis = ['remaerd', 'resare', 'esare', 'maerd']
i = 0
j = 0
#s = s[::-1]
while i < len(s):
    tmp = ''
    while j < len(s):
        tmp += s[j]
        #print(tmp)
        if len(tmp) == 8:
            print('NO')
            return
        elif tmp in lis:
            i = j + 1
            j = i
            break
        else:
            j += 1
print('YES')


I found an interesting problem on https://atcoder.jp/contests/arc065/tasks/arc065_d:
There is a string S of length N consisting of characters 0 and 1. You will perform the following operation for each i = 1, 2, ..., m:
 - Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?

-----Constraints-----
 - 2≦N≦3000
 - 1≦M≦3000
 - S consists of characters 0 and 1.
 - The length of S equals N.
 - 1≦l_i < r_i≦N
 - l_i ≦ l_{i+1}

-----Input-----
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M

-----Output-----
Print the number of the possible values for S after the M operations, modulo 1000000007.

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

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

After the first operation, S can be one of the following three: 01001, 00101 and 00011.
After the second operation, S can be one of the following six: 01100, 01010, 01001, 00011, 00101 and 00110.

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

import sys
input = sys.stdin.readline

import numpy as np

MOD = 10**9 + 7

N,M = map(int,input().split())
S = np.array(list(input().rstrip()),dtype='U1')
LR = [[int(x) for x in input().split()] for _ in range(M)]

cnt_0 = (S=='0').cumsum()
cnt_1 = (S=='1').cumsum()
canuse_0 = cnt_0
canuse_1 = cnt_1
for L,R in LR:
    canuse_0[L-1] = max(canuse_0[L-1],cnt_0[R-1])
    canuse_1[L-1] = max(canuse_1[L-1],cnt_1[R-1])
np.maximum.accumulate(canuse_0,out=canuse_0)
np.maximum.accumulate(canuse_1,out=canuse_1)

# 1を使った個数で
dp = np.zeros(N+1,dtype=np.int64)
dp[0] = 1
for i in range(N):
    prev = dp
    dp = np.zeros(N+1,dtype=np.int64)
    # i番目を置いた後で、1の個数の範囲
    left = max(0,(i+1)-canuse_0[i])
    right = canuse_1[i]
    # 0を使う
    dp[left:right+1] += prev[left:right+1]
    # 1を使う
    left = max(1,left)
    dp[left:right+1] += prev[left-1:right]
    dp %= MOD

answer = dp.sum()
print(answer)


I found an interesting problem on https://atcoder.jp/contests/arc068/tasks/arc068_a:
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.
Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:
 - Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.
For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.
Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

-----Constraints-----
 - 1 ≦ x ≦ 10^{15}
 - x is an integer.

-----Input-----
The input is given from Standard Input in the following format:
x

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

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

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

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