I found an interesting problem on https://atcoder.jp/contests/arc106/tasks/arc106_b:
Given is a simple undirected graph with N vertices and M edges. The i-th edge connects Vertex c_i and Vertex d_i.
Initially, Vertex i has the value a_i written on it. You want to change the values on Vertex 1, \ldots, Vertex N to b_1, \cdots, b_N, respectively, by doing the operation below zero or more times.
 - Choose an edge, and let Vertex x and Vertex y be the vertices connected by that edge. Choose one of the following and do it:
 - Decrease the value a_x by 1, and increase the value a_y by 1.
 - Increase the value a_x by 1, and decrease the value a_y by 1.
Determine whether it is possible to achieve the objective by properly doing the operation.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - 0 \leq M \leq 2 \times 10^5
 - -10^9 \leq a_i,b_i \leq 10^9
 - 1 \leq c_i,d_i \leq N
 - The given graph is simple, that is, has no self-loops and no multi-edges.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
a_1 \cdots a_N
b_1 \cdots b_N
c_1 d_1
\vdots
c_M d_M

-----Output-----
Print Yes if it is possible to achieve the objective by properly doing the operation, and No otherwise.

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

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

You can achieve the objective by, for example, doing the operation as follows:
 - In the first operation, choose the edge connecting Vertex 1 and 2. Then, increase a_1 by 1 and decrease a_2 by 1.
 - In the second operation, choose the edge connecting Vertex 2 and 3. Then, increase a_2 by 1 and decrease a_3 by 1.
This sequence of operations makes a_1=2, a_2=2, and a_3=2.

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

n,m=map(int,input().split())
ans=[list(map(int,input().split())) for i in range(2)]
l=[[] for i in range(n)]
for i in range(m):
    a,b=map(int,input().split())
    l[a-1].append(b-1)
    l[b-1].append(a-1)
boo=[-1]*n
flag=0
from collections import deque
for i in range(n):
    if boo[i]==-1:
        q=deque([])
        q.append(i)
        ma=0
        wa=0
        while q:
            a=q.popleft()
            if boo[a]==-1:
                boo[a]+=1
                ma+=ans[0][a]
                wa+=ans[1][a]
                for j in l[a]:
                    q.append(j)
        if ma!=wa:
            flag=1
            break
if flag==0:
    print("Yes")
else:
    print("No")


I found an interesting problem on https://atcoder.jp/contests/arc106/tasks/arc106_f:
Takahashi is about to assemble a character figure, consisting of N parts called Part 1, Part 2, ..., Part N and N-1 connecting components. Parts are distinguishable, but connecting components are not.
Part i has d_i holes, called Hole 1, Hole 2, ..., Hole d_i, into which a connecting component can be inserted. These holes in the parts are distinguishable.
Each connecting component will be inserted into two holes in different parts, connecting these two parts. It is impossible to insert multiple connecting components into a hole.
The character figure is said to be complete when it has the following properties:
 - All of the N-1 components are used to connect parts.
 - Consider a graph with N vertices corresponding to the parts and N-1 undirected edges corresponding to the pairs of vertices connected by a connecting component. Then, this graph is connected.
Two ways A and B to make the figure complete are considered the same when the following is satisfied: for every pair of holes, A uses a connecting component to connect these holes if and only if B uses one to connect them.
Find the number of ways to make the figure complete. Since the answer can be enormous, find the count modulo 998244353.

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

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

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

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

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

One way to make the figure complete is to connect Hole 1 in Part 1 and Hole 3 in Part 3 and then connect Hole 1 in Part 2 and Hole 1 in Part 3.

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

N = int(input())

D = list(map(int, input().strip().split()))

MOD = 998244353

ans = 1

for d in D:
  ans *= d
  ans %= MOD

dsum = sum(D) - N
for i in range(N-2):
  ans *= dsum - i
  ans %= MOD

print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc107/tasks/arc107_a:
Given are three positive integers A, B, and C. Compute the following value modulo 998244353:
\sum_{a=1}^{A} \sum_{b=1}^{B} \sum_{c=1}^{C} abc

-----Constraints-----
 - 1 \leq A, B, C \leq 10^9

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

-----Output-----
Print the value modulo 998244353.

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

-----Sample Output-----
18

We have: (1 \times 1 \times 1) + (1 \times 1 \times 2) + (1 \times 1 \times 3) + (1 \times 2 \times 1) + (1 \times 2 \times 2) + (1 \times 2 \times 3) = 1 + 2 + 3 + 2 + 4 + 6 = 18.

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


I found an interesting problem on https://atcoder.jp/contests/arc107/tasks/arc107_b:
Given are integers N and K.
How many quadruples of integers (a,b,c,d) satisfy both of the following conditions?
 - 1 \leq a,b,c,d \leq N
 - a+b-c-d=K

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

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

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

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

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

Four quadruples below satisfy the conditions:
 - (a,b,c,d)=(2,1,1,1)
 - (a,b,c,d)=(1,2,1,1)
 - (a,b,c,d)=(2,2,2,1)
 - (a,b,c,d)=(2,2,1,2)

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

from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n,k=nii()

ans=0
for i in range(2,2*n+1):
  j=i-k

  if not 2<=j<=2*n:
    continue

  num1=2*min(i-1,n)-i+1
  num2=2*min(j-1,n)-j+1

  ans+=num1*num2

print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc107/tasks/arc107_c:
Given are an N \times N matrix and an integer K. The entry in the i-th row and j-th column of this matrix is denoted as a_{i, j}. This matrix contains each of 1, 2, \dots, N^2 exactly once.
Sigma can repeat the following two kinds of operation arbitrarily many times in any order.
 - Pick two integers x, y (1 \leq x < y \leq N) that satisfy a_{i, x} + a_{i, y} \leq K for all i (1 \leq i \leq N) and swap the x-th and the y-th columns.
 - Pick two integers x, y (1 \leq x < y \leq N) that satisfy a_{x, i} + a_{y, i} \leq K for all i (1 \leq i \leq N) and swap the x-th and the y-th rows.
How many matrices can he obtain by these operations? Find it modulo 998244353.

-----Constraints-----
 - 1 \leq N \leq 50
 - 1 \leq K \leq 2 \times N^2
 - a_{i, j}'s are a rearrangement of 1, 2, \dots, N^2.
 - All values in input are integers.

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

-----Output-----
Print the number of matrices Sigma can obtain modulo 998244353.

-----Sample Input-----
3 13
3 2 7
4 8 9
1 6 5

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

For example, Sigma can swap two columns, by setting x = 1, y = 2. After that, the resulting matrix will be:
2 3 7
8 4 9
6 1 5

After that, he can swap two row vectors by setting x = 1, y = 3, resulting in the following matrix:
6 1 5
8 4 9
2 3 7

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

import math
N, K = list(map(int, input().split()))
A = []
mod = 998244353
for _ in range(N):
  A.append(list(map(int, input().split())))

def find(x, uf):
  if uf[x] != x:
    uf[x] = find(uf[x], uf)
  return uf[x]

def union(x, y, uf, rank):
    px, py = find(x, uf), find(y, uf)
    if px != py:
        if rank[px] > rank[py]:
            px, py = py, px
        rank[py] += rank[px]
        uf[px] = py

uf1 = {i: i for i in range(N)}
uf2 = {i: i for i in range(N)}
rank1 = {i: 1 for i in range(N)}
rank2 = {i: 1 for i in range(N)}
for i in range(N):
  for j in range(i + 1, N):
    if all(a + b <= K for a, b in zip(A[i], A[j])):
      union(i, j, uf1, rank1)
B = list(zip(*A))
for i in range(N):
  for j in range(i + 1, N):
    if all(a + b <= K for a, b in zip(B[i], B[j])):
      union(i, j, uf2, rank2)
ans = 1
for x in set(find(i, uf1) for i in range(N)):
  ans *= math.factorial(rank1[x])
  ans %= mod
for x in set(find(i, uf2) for i in range(N)):
  ans *= math.factorial(rank2[x])
  ans %= mod
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc107/tasks/arc107_e:
Consider an N \times N matrix. Let us denote by a_{i, j} the entry in the i-th row and j-th column. For a_{i, j} where i=1 or j=1 holds, its value is one of 0, 1 and 2 and given in the input. The remaining entries are defined as follows:
 - a_{i,j} = \mathrm{mex}(a_{i-1,j}, a_{i,j-1}) (2 \leq i, j \leq N) where \mathrm{mex}(x, y) is defined by the following table:\mathrm{mex}(x, y)y=0y=1y=2x=0121x=1200x=2100
How many entries of the matrix are 0, 1, and 2, respectively?

-----Constraints-----
 - 1 \leq N \leq 500{,}000
 - a_{i,j}'s given in input are one of 0, 1 and 2.

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

-----Output-----
Print the number of 0's, 1's, and 2's separated by whitespaces.

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

-----Sample Output-----
7 4 5

The matrix is as follows:
1 2 0 2
0 1 2 0
0 2 0 1
0 1 2 0

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

## coding: UTF-8

def mex(x,y):
    if(x*y>0):
        return 0
    elif(x == 1 and y == 0):
        return 2
    elif(x == 0 and y == 1):
        return 2
    else:
        return 1

'''
import random

N = 15
matrix = []
for i in range(N):
    matrix.append([7] * N)

for i in range(N):
    matrix[0][i] = random.randint(0,2)
for j in range(1, N):
    matrix[j][0] = random.randint(0,2)

for i in range(N):
    print(matrix[i])

for i in range(1, N):
    for j in range(1, N):
        matrix[i][j] = mex(matrix[i-1][j], matrix[i][j-1])

print('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
for i in range(N):
    print(matrix[i])
gutyoku = [0,0,0]
for i in range(N):
    for j in range(N):
        gutyoku[matrix[i][j]] += 1
print(gutyoku)

print('~~~~~~~~~~~~~~~~~~~~~~~+++++++++~~~~~~~~~~~')
'''

counter = [0,0,0]

N = int(input())
#N = 15

if(N == 1):
    counter[int(input())] += 1
    print(('{} {} {}'.format(counter[0], counter[1], counter[2])))

elif(N == 2):
    A = list(map(int,input().split()))
    B = int(input())
    counter[A[0]] += 1
    counter[A[1]] += 1
    counter[B] += 1
    counter[mex(A[1], B)] += 1
    print(('{} {} {}'.format(counter[0], counter[1], counter[2])))

else:
    A = list(map(int,input().split()))
    #A = matrix[0]
    B = []
    for i in range(N-1):
        B.append(int(input()))
        #B.append(matrix[i+1][0])

    matrix = []
    #for i in range(N):
        #matrix.append([7] * N)

    #matrix[0] = A
    matrix.append(A)
    for j in range(1, N):
        #matrix[j][0] = B[j-1]
        matrix.append([B[j-1]])

    #for i in range(N):
        #print(matrix[i])

    #print(-1)

    for i in range(1, 3):
        for j in range(1, N):
            #matrix[i][j] = mex(matrix[i-1][j], matrix[i][j-1])
            matrix[i].append(mex(matrix[i-1][j], matrix[i][j-1]))

    for i in range(3, N):
        for j in range(1,3):
            #matrix[i][j] = mex(matrix[i-1][j], matrix[i][j-1])
            matrix[i].append(mex(matrix[i-1][j], matrix[i][j-1]))

    #for i in...


I found an interesting problem on https://atcoder.jp/contests/arc107/tasks/arc107_f:
Given is a simple undirected graph with N vertices and M edges.
Its vertices are numbered 1, 2, \ldots, N and its edges are numbered 1, 2, \ldots, M.
On Vertex i (1 \leq i \leq N) two integers A_i and B_i are written.
Edge i (1 \leq i \leq M) connects Vertices U_i and V_i.
Snuke picks zero or more vertices and delete them.
Deleting Vertex i costs A_i.
When a vertex is deleted, edges that are incident to the vertex are also deleted.
The score after deleting vertices is calculated as follows:
 - The score is the sum of the scores of all connected components.
 - The score of a connected component is the absolute value of the sum of B_i of the vertices in the connected component.
Snuke's profit is (score) - (the sum of costs).
Find the maximum possible profit Snuke can gain.

-----Constraints-----
 - 1 \leq N \leq 300
 - 1 \leq M \leq 300
 - 1 \leq A_i \leq 10^6
 - -10^6 \leq B_i \leq 10^6
 - 1 \leq U_i,V_i \leq N
 - The given graph does not contain self loops or multiple edges.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
U_1 V_1
U_2 V_2
\vdots
U_M V_M

-----Output-----
Print the maximum possible profit Snuke can gain.

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

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

Deleting Vertex 2 costs 1.
After that, the graph is separated into two connected components.
The score of the component consisting of Vertex 1 is |0| = 0. The score of the component consisting of Vertices 3 and 4 is |(-3) + 1| = 2.
Therefore, Snuke's profit is 0 + 2 - 1 = 1.
He cannot gain more than 1, so the answer is 1.

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

import sys
input = sys.stdin.readline

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

# node : 0<=i<=3*N-1, i:minus i+1: delete i+2: plus
# start : 3*N
# goal : 3*N+1

EDGE=[dict() for i in range(3*N+2)]
V=3*N+2
start=3*N
goal=3*N+1

for i in range(N):
    EDGE[start][3*i] = -B[i] + (1<<30)
    EDGE[3*i][3*i+1] = A[i] + (1<<30)
    EDGE[3*i+1][3*i+2] = B[i] + (1<<30)
    EDGE[3*i+2][goal] = float("inf")

for i in range(M):
    x,y=map(int,input().split())
    x-=1
    y-=1

    EDGE[3*x+1][3*y] = float("inf")
    EDGE[3*y+1][3*x] = float("inf")

ANS=0
while True:
    USED=[0]*V
    ROUTE=[-1]*V
    Q=[(start,float("inf"))]

    while Q: # DFS
        NOW,cost=Q.pop()
        if NOW==goal:
            break

        for to in EDGE[NOW]:
            if USED[to]==0 and EDGE[NOW][to]!=0:
                ROUTE[to]=NOW
                USED[to]=1
                Q.append((to,min(cost,EDGE[NOW][to])))
    else:
        break

    ANS+=cost
    i=goal
    while i!=start: # goalからたどり,Routeを使ってEDGEの更新
        j=ROUTE[i]
        EDGE[j][i]-=cost # 使ったルートをいけなく更新
        if j in EDGE[i]:
            EDGE[i][j]+=cost # 逆向きに進めるようにする.これらを重みつきにすれ普通のフロー
        else:
            EDGE[i][j]=cost

        i=j

print(-(ANS-(N<<30)))


I found an interesting problem on https://atcoder.jp/contests/arc108/tasks/arc108_a:
Given are integers S and P.
Is there a pair of positive integers (N,M) such that N + M = S and N \times M = P?

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

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

-----Output-----
If there is a pair of positive integers (N,M) such that N + M = S and N \times M = P, print Yes; otherwise, print No.

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

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

 - For example, we have N+M=3 and N \times M =2 for N=1,M=2.

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

##divisor func.
def div(n):
    res=[]
    i=int(1)
    while i*i<=n:
        if n%i==0:
            res.append(i)
            if n!=i**2:
                res.append(n//i)
        i+=1
    res.sort()
    return res

s,p=map(int,input().split())
A=div(p)
for i in range(len(A)):
    if A[i]+p//A[i]==s:
        print('Yes')
        return
print('No')


I found an interesting problem on https://atcoder.jp/contests/arc108/tasks/arc108_b:
Given is a string S of length N consisting of lowercase English letters.
Snuke can do this operation any number of times: remove fox occurring as a substring from s and concatenate the remaining parts of s.
What is the minimum possible length of s after some number of operations by Snuke?

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^{5}
 - s is a string of length N consisting of lowercase English letters.

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

-----Print-----
Print the minimum possible length of s after some number of operations by Snuke.

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

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

 - By removing the fox at the end of icefox, we can turn s into ice.

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

def main():
  n = int(input())
  s = str(input())
  num = len(s)
  n = 0
  while True:
    if n+3 > num:
      break
    if s[n:n+3] == "fox":
      s = s[:n] + s[n+3:]
      n = max(0, n-3)
    else:
      n += 1
  print(len(s))

def __starting_point():
  main()
__starting_point()


I found an interesting problem on https://atcoder.jp/contests/arc108/tasks/arc108_d:
Given are an integer N and four characters c_{\mathrm{AA}}, c_{\mathrm{AB}}, c_{\mathrm{BA}}, and c_{\mathrm{BB}}.
Here, it is guaranteed that each of those four characters is A or B.
Snuke has a string s, which is initially AB.
Let |s| denote the length of s.
Snuke can do the four kinds of operations below zero or more times in any order:
 - Choose i such that 1 \leq i < |s|, s_{i} = A, s_{i+1} = A and insert c_{\mathrm{AA}} between the i-th and (i+1)-th characters of s.
 - Choose i such that 1 \leq i < |s|, s_{i} = A, s_{i+1} = B and insert c_{\mathrm{AB}} between the i-th and (i+1)-th characters of s.
 - Choose i such that 1 \leq i < |s|, s_{i} = B, s_{i+1} = A and insert c_{\mathrm{BA}} between the i-th and (i+1)-th characters of s.
 - Choose i such that 1 \leq i < |s|, s_{i} = B, s_{i+1} = B and insert c_{\mathrm{BB}} between the i-th and (i+1)-th characters of s.
Find the number, modulo (10^9+7), of strings that can be s when Snuke has done the operations so that the length of s becomes N.

-----Constraints-----
 - 2 \leq N \leq 1000
 - Each of c_{\mathrm{AA}}, c_{\mathrm{AB}}, c_{\mathrm{BA}}, and c_{\mathrm{BB}} is A or B.

-----Input-----
Input is given from Standard Input in the following format:
N
c_{\mathrm{AA}}
c_{\mathrm{AB}}
c_{\mathrm{BA}}
c_{\mathrm{BB}}

-----Output-----
Print the number, modulo (10^9+7), of strings that can be s when Snuke has done the operations so that the length of s becomes N.

-----Sample Input-----
4
A
B
B
A

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

 - There are two strings that can be s when Snuke is done: ABAB and ABBB.

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

n = int(input())
c_aa = input()
c_ab = input()
c_ba = input()
c_bb = input()
mod = 10**9 + 7
if(n==2):
    print(1)
    return

num = 0
for ci,i in zip([c_aa,c_ab,c_ba,c_bb], [0,1,2,3]):
    if(ci == 'B'):
        num += 2**i

if(num in [1,6,7,9]):
    dp = [0] * (n+1)
    dp[2] = 1
    for i in range(3,n+1):
        dp[i] = (dp[i-1] + dp[i-2])%mod
    print(dp[-1])
    return

elif(num in [2,3,5,13]):
    ans = pow(2, n-3, mod)
    print(ans)
    return

print(1)


I found an interesting problem on https://atcoder.jp/contests/arc108/tasks/arc108_f:
Given is a tree with N vertices numbered 1 to N, and N-1 edges numbered 1 to N-1.
Edge i connects Vertex a_i and b_i bidirectionally and has a length of 1.
Snuke will paint each vertex white or black.
The niceness of a way of painting the graph is \max(X, Y), where X is the maximum among the distances between white vertices, and Y is the maximum among the distances between black vertices.
Here, if there is no vertex of one color, we consider the maximum among the distances between vertices of that color to be 0.
There are 2^N ways of painting the graph. Compute the sum of the nicenesses of all those ways, modulo (10^{9}+7).

-----Constraints-----
 - 2 \leq N \leq 2 \times 10^{5}
 - 1 \leq a_i, b_i \leq N
 - The given graph is a tree.

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

-----Output-----
Print the sum of the nicenesses of the ways of painting the graph, modulo (10^{9}+7).

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

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

 - If we paint Vertex 1 and 2 the same color, the niceness will be 1; if we paint them different colors, the niceness will be 0.
 - The sum of those nicenesses is 2.

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

n = int(input())
graph = [[] for i in range(n + 1)]
for _ in range(n - 1):
  i, j = map(int, input().split())
  graph[i].append(j)
  graph[j].append(i)
mod = 10 ** 9 + 7
start = 1
stack = [1]
s_dist = [0]+[0]+[10**9]*(n-1)
while stack:
  x = stack.pop()
  for y in graph[x]:
    if s_dist[y] > s_dist[x] + 1:
      s_dist[y] = s_dist[x]+1
      stack.append(y)
maxdist = max(s_dist)
black = s_dist.index(maxdist)
b_dist = [10**9]*(n+1)
b_dist[0] = 0
b_dist[black] = 0
stack = [black]
while stack:
  x = stack.pop()
  for y in graph[x]:
    if b_dist[y] > b_dist[x] + 1:
      b_dist[y] = b_dist[x]+1
      stack.append(y)
maxdist = max(b_dist)
white = b_dist.index(maxdist)
w_dist = [10**9]*(n+1)
w_dist[0] = 0
w_dist[white] = 0
stack = [white]
while stack:
  x = stack.pop()
  for y in graph[x]:
    if w_dist[y] > w_dist[x] + 1:
      w_dist[y] = w_dist[x]+1
      stack.append(y)
mindls = [0]*n
maxdls = [0]*n
for i in range(1,n+1):
  if i in (white,black):
    continue
  mindls[min(w_dist[i],b_dist[i])] += 1
  maxdls[max(w_dist[i],b_dist[i])] += 1
ans = pow(2,n-1,mod)*maxdist%mod
number = 0
for i in range(1,maxdist+1):
  if i == maxdist and maxdls[i] == 0:
    continue
  maxdls[i] += maxdls[i-1]
  if i < maxdist and mindls[i+1]:
    continue
  ans += (pow(2,maxdls[i],mod)-number)*i*2
  ans %= mod
  number = pow(2,maxdls[i],mod)
print(ans)


I found an interesting problem on https://atcoder.jp/contests/arc109/tasks/arc109_a:
There are two 100-story buildings, called A and B. (In this problem, the ground floor is called the first floor.)
For each i = 1,\dots, 100, the i-th floor of A and that of B are connected by a corridor.
Also, for each i = 1,\dots, 99, there is a corridor that connects the (i+1)-th floor of A and the i-th floor of B.
You can traverse each of those corridors in both directions, and it takes you x minutes to get to the other end.
Additionally, both of the buildings have staircases. For each i = 1,\dots, 99, a staircase connects the i-th and (i+1)-th floors of a building, and you need y minutes to get to an adjacent floor by taking the stairs.
Find the minimum time needed to reach the b-th floor of B from the a-th floor of A.

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

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

-----Output-----
Print the minimum time needed to reach the b-th floor of B from the a-th floor of A.

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

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

There is a corridor that directly connects the 2-nd floor of A and the 1-st floor of B, so you can travel between them in 1 minute.
This is the fastest way to get there, since taking the stairs just once costs you 5 minutes.

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

#標準入力
s = list(map(int, input().split()))

a = int(s[0])
b = int(s[1])
x = int(s[2])
y = int(s[3])

move_withoutstep_1 = 9999999999
move_withoutstep_2 = 9999999999

#階段移動を使わない場合の移動時間
# a > bの時
if a > b:
    move_withoutstep_1 = ((a-b)-1)*x + (a-b)*x
#a < bの時
elif a <= b:
    move_withoutstep_2 = ((b-a)+1)*x + (b-a)*x

#階段移動を使う場合の移動時間
move_upstairs = 9999999999
move_downstairs = 9999999999

if a < b:
    move_upstairs = (b-a)*y + x
elif a > b:
    #最後の下りはななめ移動（廊下を使った移動）の方が早いので、それを考慮して階段移動の回数を1回分減らす。
    #x+yよりもxの方が小さいのは条件より自明。
    move_downstairs = (a-b-1)*y + x

#print(move_withoutstep_1,move_withoutstep_2,move_upstairs,move_downstairs,move_downstairs_2)
print((min(move_withoutstep_1,move_withoutstep_2,move_upstairs,move_downstairs)))


I found an interesting problem on https://atcoder.jp/contests/arc109/tasks/arc109_b:
Snuke is visiting a shop in Tokyo called 109 to buy some logs.
He wants n logs: one of length 1, one of length 2, ..., and one of length n.
The shop has n+1 logs in stock: one of length 1, one of length 2, \dots, and one of length n+1. Each of these logs is sold for 1 yen (the currency of Japan).
He can cut these logs as many times as he wants after buying them. That is, he can get k logs of length L_1, \dots, L_k from a log of length L, where L = L_1 + \dots + L_k. He can also throw away unwanted logs.
Snuke wants to spend as little money as possible to get the logs he wants.
Find the minimum amount of money needed to get n logs of length 1 to n.

-----Constraints-----
 - 1 \leq n \leq 10^{18}

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

-----Output-----
Print the minimum amount of money needed to get n logs of length 1 to n.

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

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

One way to get the logs he wants with 3 yen is:
 - Buy logs of length 2, 4, and 5.
 - Cut the log of length 5 into two logs of length 1 each and a log of length 3.
 - Throw away one of the logs of length 1.

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

n = int(input())
LOW = 0
HIGH = n
r = 0
now = (LOW+HIGH)//2
if n < 3:
    print(1)
    return
while 1:
    now = (LOW+HIGH)//2
    cur = (now*(now+1))//2
    nex = ((now+1)*(now+2))//2
    if cur <= n+1 and n+1 < nex:
        r = now
        break
    elif cur < n+1:
        LOW = now
    else:
        HIGH = now
print(n-r+1)


I found an interesting problem on https://atcoder.jp/contests/arc109/tasks/arc109_c:
To decide which is the strongest among Rock, Paper, and Scissors, we will hold an RPS tournament.
There are 2^k players in this tournament, numbered 0 through 2^k-1. Each player has his/her favorite hand, which he/she will use in every match.
A string s of length n consisting of R, P, and S represents the players' favorite hands.
Specifically, the favorite hand of Player i is represented by the ((i\text{ mod } n) + 1)-th character of s; R, P, and S stand for Rock, Paper, and Scissors, respectively.
For l and r such that r-l is a power of 2, the winner of the tournament held among Players l through r-1 will be determined as follows:
 - If r-l=1 (that is, there is just one player), the winner is Player l.
 - If r-l\geq 2, let m=(l+r)/2, and we hold two tournaments, one among Players l through m-1 and the other among Players m through r-1. Let a and b be the respective winners of these tournaments. a and b then play a match of rock paper scissors, and the winner of this match - or a if the match is drawn - is the winner of the tournament held among Players l through r-1.
Find the favorite hand of the winner of the tournament held among Players 0 through 2^k-1.

-----Notes-----
 - a\text{ mod } b denotes the remainder when a is divided by b.
 - The outcome of a match of rock paper scissors is determined as follows:
 - If both players choose the same hand, the match is drawn;
 - R beats S;
 - P beats R;
 - S beats P.

-----Constraints-----
 - 1 \leq n,k \leq 100
 - s is a string of length n consisting of R, P, and S.

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

-----Output-----
Print the favorite hand of the winner of the tournament held among Players 0 through 2^k-1, as R, P, or S.

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

-----Sample Output-----
P

 - The favorite hand of the winner of the tournament held among Players 0 through 1 is P.
 - The favorite hand of the winner of the tournament held among Players 2 through 3 is R.
 - The favorite hand of the winner of the tournament held...

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

#template
def inputlist(): return [int(j) for j in input().split()]
#template
n,k = inputlist()
s = input()
s = s+s
n*=2

def returnWinner(a,b):
    if a == b:
        return a
    else:
        if a+b == "RS" or a+b == "SR":
            return "R"
        if a+b == "RP" or a+b == "PR":
            return "P"
        if a+b == "PS" or a+b == "SP":
            return "S"

if k == 1:
    ans = returnWinner(s[0],s[1])
    print(ans)
    return
from copy import deepcopy
for i in range(k-1):
    s = s+s
    t = ["R"]*min(len(s)//2,2**(k-1-i))
    for j in range(0,min(len(s),2**(k-i)),2):
        t[j//2] = returnWinner(s[j],s[j+1])
    s = deepcopy(t)
    if len(s) == 1:
        print(s[0])
        return

print(s[0])


I found an interesting problem on https://atcoder.jp/contests/arc109/tasks/arc109_e:
Kuro and Shiro are playing with a board composed of n squares lining up in a row.
The squares are numbered 1 to n from left to right, and Square s has a mark on it.
First, for each square, Kuro paints it black or white with equal probability, independently from other squares. Then, he puts on Square s a stone of the same color as the square.
Kuro and Shiro will play a game using this board and infinitely many black stones and white stones. In this game, Kuro and Shiro alternately put a stone as follows, with Kuro going first:
 - Choose an empty square adjacent to a square with a stone on it. Let us say Square i is chosen.
 - Put on Square i a stone of the same color as the square.
 - If there are squares other than Square i that contain a stone of the same color as the stone just placed, among such squares, let Square j be the one nearest to Square i. Change the color of every stone between Square i and Square j to the color of Square i.
The game ends when the board has no empty square.
Kuro plays optimally to maximize the number of black stones at the end of the game, while Shiro plays optimally to maximize the number of white stones at the end of the game.
For each of the cases s=1,\dots,n, find the expected value, modulo 998244353, of the number of black stones at the end of the game.

-----Notes-----
When the expected value in question is represented as an irreducible fraction p/q, there uniquely exists an integer r such that rq=p ~(\text{mod } 998244353) and 0 \leq r \lt 998244353, which we ask you to find.

-----Constraints-----
 - 1 \leq n \leq 2\times 10^5

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

-----Output-----
Print n values.
The i-th value should be the expected value, modulo 998244353, of the number of black stones at the end of the game for the case s=i.

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

-----Sample Output-----
499122178
499122178
499122178

Let us use b to represent a black square and w to represent a white square.
There are eight possible boards: www, wwb, wbw,...

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

N=int(input())
mod=998244353
inv4=249561088
A=[inv4,0,3]
for i in range(N):
    A.append(9*A[-1]-24*A[-2]+16*A[-3])
    A[-1]%=mod
A[0]-=inv4
B=[0 for i in range(N)]
for i in range(N):
    x=i
    y=N-i-1
    if x<=y:
        B[x]=A[i]
        B[y]=A[i]

P=N*pow(2,N-2+mod-1,mod)
for i in range(N):
    B[i]+=P
    B[i]%=mod
Q=pow(2,N-1,mod)
Qinv=pow(Q,mod-2,mod)
for i in range(N):
    B[i]*=Qinv
    B[i]%=mod
for i in range(N):
    print((B[i]))


I found an interesting problem on https://atcoder.jp/contests/arc110/tasks/arc110_a:
We have an integer N.
Print an integer x between N and 10^{13} (inclusive) such that, for every integer y between 2 and N (inclusive), the remainder when x is divided by y is 1.
Under the constraints of this problem, there is always at least one such integer x.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 30

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

-----Output-----
Print an integer x between N and 10^{13} (inclusive) such that, for every integer y between 2 and N (inclusive), the remainder when x is divided by y is 1.
If there are multiple such integers, any of them will be accepted.

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

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

The remainder when 7 is divided by 2 is 1, and the remainder when 7 is divided by 3 is 1, too.
7 is an integer between 3 and 10^{13}, so this is a desirable output.

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

from math import gcd

def lcm(a, b):
    return a // gcd(a, b) * b

n = input()
n = int(n)
ll = 2
for i in range(3, n + 1):
    ll = lcm(ll, i)
print((ll + 1))


I found an interesting problem on https://atcoder.jp/contests/arc110/tasks/arc110_b:
Let S be the concatenation of 10^{10} copies of the string 110. (For reference, the concatenation of 3 copies of 110 is 110110110.)
We have a string T of length N.
Find the number of times T occurs in S as a contiguous substring.

-----Constraints-----
 - 1 \leq N \leq 2 \times 10^5
 - T is a string of length N consisting of 0 and 1.

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

-----Output-----
Print the number of times T occurs in S as a contiguous substring.

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

-----Sample Output-----
9999999999

S is so long, so let us instead count the number of times 1011 occurs in the concatenation of 3 copies of 110, that is, 110110110. We can see it occurs twice:
 - 1 1011 0110
 - 1101 1011 0

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

import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

n=n_in()
s=s_in()

N=3*(10**10)
t = '110'*2*n

res = 0

if s == "0":
    print((10**10))
    return

if s == "1":
    print((2*10**10))
    return

if s == "10":
    print((10**10))
    return

if s == "11":
    print((10**10))
    return

if s == "00":
    print((0))
    return

if s == "01":
    print((10**10-1))
    return

if s == t[:n]:
    res += (N-n)//3+1
if s == t[1:n+1]:
    res += (N-n-1)//3+1
if s == t[2:n+2]:
    res += (N-n-2)//3+1

print(res)


I found an interesting problem on https://atcoder.jp/contests/arc110/tasks/arc110_c:
We have a permutation P = P_1, P_2, \ldots, P_N of 1, 2, \ldots, N.
You have to do the following N - 1 operations on P, each exactly once, in some order:
 - Swap P_1 and P_2.
 - Swap P_2 and P_3.
\vdots
 - Swap P_{N-1} and P_N.
Your task is to sort P in ascending order by configuring the order of operations.
If it is impossible, print -1 instead.

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

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

-----Output-----
If it is impossible to sort P in ascending order by configuring the order of operations, print -1.
Otherwise, print N-1 lines to represent a sequence of operations that sorts P in ascending order.
The i-th line (1 \leq i \leq N - 1) should contain j, where the i-th operation swaps P_j and P_{j + 1}.
If there are multiple such sequences of operations, any of them will be accepted.

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

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

The following sequence of operations sort P in ascending order:
 - First, swap P_4 and P_5, turning P into 2, 4, 1, 3, 5.
 - Then, swap P_2 and P_3, turning P into 2, 1, 4, 3, 5.
 - Then, swap P_3 and P_4, turning P into 2, 1, 3, 4, 5.
 - Finally, swap P_1 and P_2, turning P into 1, 2, 3, 4, 5.

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

def main():
  import sys
  input=sys.stdin.readline
  n=int(input())
  p=list(map(int,input().split()))
  c=[-1]*n
  for i in range(n):
    p[i]-=1
    c[p[i]]=i
  r=[False]*(n-1)
  ans=[]
  for i in range(n):
    j=c[i]
    while j!=i:
      if r[j-1]:
        print(-1)
        return
      ans.append(j)
      r[j-1]=True
      p[j-1],p[j]=p[j],p[j-1]
      c[p[j]]=j
      c[p[j-1]]=j-1
      j-=1
  for i in r:
    if not i:
      print(-1)
      return
  for i in ans:
    print(i)
main()


I found an interesting problem on https://atcoder.jp/contests/arc110/tasks/arc110_e:
We have a string S of length N consisting of A, B, and C.
You can do the following operation on S zero or more times:
 - Choose i (1 \leq i \leq |S| - 1) such that S_i \neq S_{i + 1}. Replace S_i with the character (among A, B, and C) that is different from both S_i and S_{i + 1}, and remove S_{i + 1} from S.
Find the number of distinct strings that S can be after zero or more operations, and print the count modulo (10^9+7).

-----Constraints-----
 - 1 \leq N \leq 10^6
 - S is a string of length N consisting of A, B, and C.

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

-----Output-----
Print the number of distinct strings that S can be after zero or more operations, modulo (10^9+7).

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

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

For example, the following sequence of operations turns S into ACB:
 - First, choose i=2. We replace S_2 with C and remove S_3, turning S into ACAC.
 - Then, choose i=3. We replace S_3 with B and remove S_4, turning S into ACB.

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

n = int(input())
s = input()
s = list(map('_ABC'.index, s))

MOD = 10 ** 9 + 7

dp = [0, 0, 0, 0]
dp[s[0]] = 1

xor = s[0]
p = 1
potential = 0
while p < n and s[p] == s[0]:
    xor ^= s[p]
    p += 1
    potential += 1

for i, c in enumerate(s[p:], start=p):

    d, e = c % 3 + 1, (c + 1) % 3 + 1

    dp[c] = sum(dp) % MOD
    dp[d], dp[e] = dp[e], dp[d]

    if potential > 0:
        if s[i - 1] == d:
            dp[c] += (potential + 1) // 2
            dp[e] += potential // 2
        else:
            dp[c] += (potential + 1) // 2
            dp[d] += potential // 2
        potential = 0
    elif xor == 0:
        dp[c] += 1
    xor ^= c

print((sum(dp) % MOD))


I found an interesting problem on https://codeforces.com/problemset/problem/1000/A:
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.

The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.

There are $n$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office.

Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.

What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?

The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 100$) — the number of T-shirts.

The $i$-th of the next $n$ lines contains $a_i$ — the size of the $i$-th T-shirt of the list for the previous year.

The $i$-th of the next $n$ lines contains $b_i$ — the size of the $i$-th T-shirt of the list for the current year.

It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $b$ from the list $a$.

-----Output-----

Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.

-----Examples-----
Input
3
XS
XS
M
XL
S
XS

Output
2

Input
2
XXXL
XXL
XXL
XXXS

Output
1

Input
2
M
XS
XS
M

Output
0

-----Note-----

In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of...

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

n  = int(input())
a = []
b = []
for i in range(n):
  a.append(input())
for i in range(n):
  k = input()
  if k in a:
    a.remove(k)
  else:
    b.append(k)
c = [0,0,0,0]
for i in range(len(a)):
  c[len(a[i])-1] += 1
print(sum(c))


I found an interesting problem on https://codeforces.com/problemset/problem/1000/B:
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.

The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.

The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.

Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.

Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.

-----Input-----

First line contains two space separated integers $n$ and $M$ ($1 \le n \le 10^5$, $2 \le M \le 10^9$) — the length of program $a$ and the moment when power turns off.

Second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($0 < a_1 < a_2 < \dots < a_n < M$) —...

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

3

def solve(N, M, A):
    A = [0] + A + [M]

    D = [A[i + 1] - A[i] for i in range(N + 1)]
    LD = len(D)

    evensum = 0
    oddsum = 0
    for i in range(LD):
        if i % 2 == 0:
            evensum += D[i]
        else:
            oddsum += D[i]

    best = evensum
    accum = 0
    for i in range(LD):
        d = D[i]

        if i % 2 == 0:
            evensum -= d
            if d > 1:
                best = max(best, accum + d - 1 + oddsum)
            accum += d
        else:
            oddsum -= d
            if d > 1:
                best = max(best, accum + d - 1 + oddsum)

    return best

def main():
    N, M = [int(e) for e in input().split(' ')]
    A = [int(e) for e in input().split(' ')]
    assert len(A) == N
    print(solve(N, M, A))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1000/C:
You are given $n$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.

Your task is the following: for every $k \in [1..n]$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $k$. A segment with endpoints $l_i$ and $r_i$ covers point $x$ if and only if $l_i \le x \le r_i$.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of segments.

The next $n$ lines contain segments. The $i$-th line contains a pair of integers $l_i, r_i$ ($0 \le l_i \le r_i \le 10^{18}$) — the endpoints of the $i$-th segment.

-----Output-----

Print $n$ space separated integers $cnt_1, cnt_2, \dots, cnt_n$, where $cnt_i$ is equal to the number of points such that the number of segments that cover these points equals to $i$.

-----Examples-----
Input
3
0 3
1 3
3 8

Output
6 2 1

Input
3
1 3
2 4
5 7

Output
5 2 0

-----Note-----

The picture describing the first example:

[Image]

Points with coordinates $[0, 4, 5, 6, 7, 8]$ are covered by one segment, points $[1, 2]$ are covered by two segments and point $[3]$ is covered by three segments.

The picture describing the second example:

[Image]

Points $[1, 4, 5, 6, 7]$ are covered by one segment, points $[2, 3]$ are covered by two segments and there are no points covered by three segments.

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

n = int(input())
pos = {}
for _ in range(n):
    L, R = list(map(int, input().split()))
    if L in pos: pos[L] += 1
    else: pos[L] = 1
    if R+1 in pos: pos[R+1] -= 1
    else: pos[R+1] = -1
a = sorted(list(pos.items()), key=lambda x: x[0])
res = [0]*n
s = 0
for i in range(len(a)):
    if 1 <= s <= n:
        res[s - 1] += a[i][0] - a[i - 1][0]
    s += a[i][1]
print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/1000/D:
The sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ — are not.

A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ — are not.

For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.

-----Input-----

The first line contains the number $n~(1 \le n \le 10^3)$ — the length of the initial sequence. The following line contains $n$ integers $a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$ — the sequence itself.

-----Output-----

In the single line output one integer — the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.

-----Examples-----
Input
3
2 1 1

Output
2

Input
4
1 1 1 1

Output
7

-----Note-----

In the first test case, two good subsequences — $[a_1, a_2, a_3]$ and $[a_2, a_3]$.

In the second test case, seven good subsequences — $[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$ and $[a_3, a_4]$.

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

from copy import deepcopy
import itertools
from bisect import bisect_left
from bisect import bisect_right
import math
from collections import deque

def read():
    return int(input())

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

def readlist():
    return list(map(int, input().split()))

MAX = 10000
MOD = 998244353
fac = [0] * MAX
finv = [0] * MAX
inv = [0] * MAX

def COMinit():
    fac[0] = 1
    fac[1] = 1
    finv[0] = 1
    finv[1] = 1
    inv[1] = 1;
    for i in range(2, MAX):
        fac[i] = fac[i - 1] * i % MOD
        inv[i] = MOD - inv[MOD%i] * (MOD // i) % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD
    return None

def COM(n, k):
    if n < k:
        return 0
    if n < 0 or k < 0:
        return 0
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD

N = read()
A = readlist()

for i in range(N):
    A[i] = max(0, A[i])
    if A[i] > N - i - 1:
        A[i] = 0

COMinit()

dp = [0] * N

for n in range(1, N):
    dp[n] = dp[n-1]
    for i in range(n):
        if i == 0:
            dp[n] = (dp[n] + COM(n - i - 1, A[i] - 1)) % MOD
        else:
            dp[n] = (dp[n] + COM(n - i - 1, A[i] - 1) * (dp[i - 1] + 1)) % MOD

print(dp[N - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/1003/A:
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.

For example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.

Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of coins.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$) — values of coins.

-----Output-----

Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.

-----Examples-----
Input
6
1 2 4 3 3 2

Output
2

Input
1
100

Output
1

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

a = int(input())
b = [int(i) for i in input().split()]
c = [0] * 101
for elem in b:
    c[elem] += 1
print(max(c))


I found an interesting problem on https://codeforces.com/problemset/problem/1003/B:
You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \le i < n$) such that $s_i \ne s_{i + 1}$. It is guaranteed that the answer always exists.

For example, for the string "01010" there are four indices $i$ such that $1 \le i < n$ and $s_i \ne s_{i + 1}$ ($i = 1, 2, 3, 4$). For the string "111001" there are two such indices $i$ ($i = 3, 5$).

Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1.

-----Input-----

The first line of the input contains three integers $a$, $b$ and $x$ ($1 \le a, b \le 100, 1 \le x < a + b)$.

-----Output-----

Print only one string $s$, where $s$ is any binary string satisfying conditions described above. It is guaranteed that the answer always exists.

-----Examples-----
Input
2 2 1

Output
1100

Input
3 3 3

Output
101100

Input
5 3 6

Output
01010100

-----Note-----

All possible answers for the first example:   1100;  0011.

All possible answers for the second example:   110100;  101100;  110010;  100110;  011001;  001101;  010011;  001011.

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

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

if a > b:
    print(0, end='')
    prev = 0
    a -= 1
else:
    print(1, end='')
    prev = 1
    b -= 1

for i in range(x - 1):
    if prev == 0:
        print(1, end='')
        prev = 1
        b -= 1
    else:
        print(0, end='')
        prev = 0
        a -= 1

if prev == 0:
    for i in range(a):
        print(0, end='')

    for i in range(b):
        print(1, end='')

else:
    for i in range(b):
        print(1, end='')

    for i in range(a):
        print(0, end='')


I found an interesting problem on https://codeforces.com/problemset/problem/1003/C:
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.

Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:

Suppose we want to analyze the segment of $n$ consecutive days. We have measured the temperatures during these $n$ days; the temperature during $i$-th day equals $a_i$.

We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $x$ to day $y$, we calculate it as $\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $k$ consecutive days. For example, if analyzing the measures $[3, 4, 1, 2]$ and $k = 3$, we are interested in segments $[3, 4, 1]$, $[4, 1, 2]$ and $[3, 4, 1, 2]$ (we want to find the maximum value of average temperature over these segments).

You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 5000$) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 5000$) — the temperature measures during given $n$ days.

-----Output-----

Print one real number — the heat intensity value, i. e., the maximum of average temperatures...

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

#import math
#import itertools
#from collections import defaultdict, Counter, deque

def max_average(nums, k):
    def get_delta(avg, nums, k):
        n = len(nums)
        accu = [0.0] * (n + 1)
        minval_pos = None
        delta = 0.0
        for i in range(n):
            accu[i+1] = nums[i] + accu[i] - avg
            if i >= (k-1):
                if minval_pos == None or accu[i-k+1] < accu[minval_pos]:
                    minval_pos = i-k+1
                if accu[i+1] - accu[minval_pos] >= 0:
                    delta = max(delta, (accu[i+1] - accu[minval_pos]) / (i+1 - minval_pos))
        return delta

    left, delta = min(nums), float("inf")
    while delta > 1e-6:
        delta = get_delta(left, nums, k)
        left += delta
    return left

def f(arr, k):
    return max_average(arr, k)

n, k = [int(i) for i in input().split()]
arr = [int(i) for i in input().split()]
print(f(arr, k))


I found an interesting problem on https://codeforces.com/problemset/problem/1003/D:
Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some non-negative integer number $d$).

Polycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the query is the minimum number of coins that is necessary to obtain the value $b_j$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $b_j$, the answer to the $j$-th query is -1.

The queries are independent (the answer on the query doesn't affect Polycarp's coins).

-----Input-----

The first line of the input contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) — the number of coins and the number of queries.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ — values of coins ($1 \le a_i \le 2 \cdot 10^9$). It is guaranteed that all $a_i$ are integer powers of $2$ (i.e. $a_i = 2^d$ for some non-negative integer number $d$).

The next $q$ lines contain one integer each. The $j$-th line contains one integer $b_j$ — the value of the $j$-th query ($1 \le b_j \le 10^9$).

-----Output-----

Print $q$ integers $ans_j$. The $j$-th integer must be equal to the answer on the $j$-th query. If Polycarp can't obtain the value $b_j$ the answer to the $j$-th query is -1.

-----Example-----
Input
5 4
2 4 8 2 4
8
5
14
10

Output
1
-1
3
2

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

from collections import Counter

n, q = map(int, input().split())
a = map(int, input().split())
b = [int(input()) for _ in range(q)]

counts = 32 * [0]

for value, count in Counter(a).items():
    counts[value.bit_length() - 1] = count

for bj in b:
    ans = 0

    for i in reversed(range(32)):
        count = min(bj >> i, counts[i])
        ans += count
        bj -= count << i

    if bj != 0:
        print(-1)
    else:
        print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1003/E:
You are given three integers $n$, $d$ and $k$.

Your task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible.

An undirected tree is a connected undirected graph with $n - 1$ edges.

Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.

Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $u$ it is the number of edges $(u, v)$ that belong to the tree, where $v$ is any other vertex of a tree).

-----Input-----

The first line of the input contains three integers $n$, $d$ and $k$ ($1 \le n, d, k \le 4 \cdot 10^5$).

-----Output-----

If there is no tree satisfying the conditions above, print only one word "NO" (without quotes).

Otherwise in the first line print "YES" (without quotes), and then print $n - 1$ lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from $1$ to $n$. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1

-----Examples-----
Input
6 3 3

Output
YES
3 1
4 1
1 2
5 2
2 6

Input
6 2 3

Output
NO

Input
10 4 3

Output
YES
2 9
2 10
10 3
3 1
6 10
8 2
4 3
5 6
6 7

Input
8 5 3

Output
YES
2 5
7 2
3 7
3 1
1 6
8 7
4 3

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

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

if d+1 > n:
    print('NO')
    return

ans = []
dist = [0]*n
deg = [0]*n
for i in range(d+1):
    if i == 0 or i == d:
        deg[i] = 1
    else:
        deg[i] = 2
    if i != d:
        ans.append((i+1, i+2))
    dist[i] = max(i, d-i)

for i in range(n):
    if deg[i] > k:
        print('NO')
        return

from collections import deque
q = deque(list(range(d+1)))
cur = d+1
while q and cur < n:
    v = q.pop()
    if dist[v] < d and deg[v] < k:
        deg[v] += 1
        dist[cur] = dist[v]+1
        deg[cur] = 1
        ans.append((v+1, cur+1))
        q.append(v)
        q.append(cur)
        cur += 1
    else:
        continue
if cur != n:
    print('NO')
else:
    print('YES')
    for i in range(len(ans)):
        print(*ans[i])


I found an interesting problem on https://codeforces.com/problemset/problem/1003/F:
You are given a text consisting of $n$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $w_i$ is the $i$-th word of text. All words consist only of lowercase Latin letters.

Let's denote a segment of words $w[i..j]$ as a sequence of words $w_i, w_{i + 1}, \dots, w_j$. Two segments of words $w[i_1 .. j_1]$ and $w[i_2 .. j_2]$ are considered equal if $j_1 - i_1 = j_2 - i_2$, $j_1 \ge i_1$, $j_2 \ge i_2$, and for every $t \in [0, j_1 - i_1]$ $w_{i_1 + t} = w_{i_2 + t}$. For example, for the text "to be or not to be" the segments $w[1..2]$ and $w[5..6]$ are equal, they correspond to the words "to be".

An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words $w[2..4]$ and $w[6..8]$ with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words $w[2..5]$ and $w[6..9]$ with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".

What is the minimum length of the text after at most one abbreviation?

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 300$) — the number of words in the text.

The next line contains $n$ space-separated words of the text $w_1, w_2, \dots, w_n$. Each word consists only of lowercase Latin letters.

It is guaranteed that the length of text does not exceed $10^5$.

-----Output-----

Print one integer — the minimum length of the text after at most one abbreviation.

-----Examples-----
Input
6
to be or not to be

Output
12

Input
10
a ab a a b ab a a b...

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

# import time
N = 303
eq = []
dp = []
for i in range(N):
    eq.append([False] * N)
for i in range(N):
    dp.append([0] * N)
n = int(input())
s = input()
# t = time.time()
allsum = len(s)
s = s.split()
for i in range(n):
    eq[i][i] = True
    for j in range(i):
        eq[i][j] = eq[j][i] = s[i] == s[j]
for i in range(n - 1, -1, -1):
    for j in range(n - 1, -1, -1):
        if eq[i][j]:
            if i < n - 1 and j < n - 1:
                dp[i][j] = dp[i + 1][j + 1] + 1
            else:
                dp[i][j] = 1
ans = allsum
for i in range(n):
    su = 0
    for j in range(n - i):
        su += len(s[i + j])
        cnt = 1
        pos = i + j + 1
        while pos < n:
            if dp[i][pos] > j:
                cnt += 1
                pos += j
            pos += 1
        cur = allsum - su * cnt + (j + 1) * cnt - j * cnt
        if cnt > 1 and ans > cur:
            # print(allsum, su, cnt, j)
            ans = cur
print(ans)
# print(time.time() - t)


I found an interesting problem on https://codeforces.com/problemset/problem/1004/A:
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.

The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city.

Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel.

Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.

-----Input-----

The first line contains two integers $n$ and $d$ ($1\leq n\leq 100$, $1\leq d\leq 10^9$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others.

The second line contains $n$ different integers in strictly increasing order $x_1, x_2, \ldots, x_n$ ($-10^9\leq x_i\leq 10^9$) — coordinates of Sonya's hotels.

-----Output-----

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $d$.

-----Examples-----
Input
4 3
-3 2 9 16

Output
6

Input
5 2
4 8 11 18 19

Output
5

-----Note-----

In the first example, there are $6$ possible cities where Sonya can build a hotel. These cities have coordinates $-6$, $5$, $6$, $12$, $13$, and $19$.

In the second example, there are $5$ possible cities where Sonya can build a hotel. These cities have coordinates $2$, $6$, $13$, $16$, and $21$.

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

#!/usr/bin/env python3

n, d = [int(i) for i in input().split()]

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

ans = 2
for i in range(1, len(x)):
    if x[i] - x[i - 1] == 2 * d:
        ans += 1
    if x[i] - x[i - 1] > 2 * d:
        ans += 2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1004/B:
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.

There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily.

She knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.

Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.

-----Input-----

The first line contains two integers $n$ and $m$ ($1\leq n, m\leq 10^3$) — the number of flowers and visitors respectively.

Each of the next $m$ lines contains two integers $l_i$ and $r_i$ ($1\leq l_i\leq r_i\leq n$), meaning that $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive.

-----Output-----

Print the string of $n$ characters. The $i$-th symbol should be «0» if you want to put a rose in the $i$-th position, otherwise «1» if you want to put a lily.

If there are multiple answers, print any.

-----Examples-----
Input
5 3
1 3
2 4
2 5

Output
01100
Input
6 3
5 6
1 4
4 6

Output
110010

-----Note-----

In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;

  in the segment $[1\ldots3]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$;  in the segment $[2\ldots4]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$;  in the segment $[2\ldots5]$, there are two roses and two lilies, so the beauty is equal to $2\cdot 2=4$.

The total beauty is equal to $2+2+4=8$.

In the second example, Sonya can put roses in the third, fourth, and sixth...

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

n, m = map(int, input().split(' '))
l = []
r = []
for i in range(m):
    l_i, r_i = map(int, input().split(' '))
    l.append(l_i)
    r.append(r_i)
s = ''
for i in range(n):
    if i % 2==0:
        s += '0'
    else:
        s += '1'
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/1004/C:
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.

Sonya has drawn $n$ numbers in a row, $a_i$ is located in the $i$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.

Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.

For example, if the numbers $[1, 5, 4, 1, 3]$ are written, and Sonya gives the number $1$ to the first robot and the number $4$ to the second one, the first robot will stop in the $1$-st position while the second one in the $3$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $4$ to the first robot and the number $5$ to the second one, they will meet since the first robot will stop in the $3$-rd position while the second one is in the $2$-nd position.

Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.

Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($p$, $q$), where she will give $p$ to the first robot and $q$ to the second one. Pairs ($p_i$, $q_i$) and ($p_j$, $q_j$) are different if $p_i\neq p_j$ or $q_i\neq q_j$.

Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of...

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

n = int(input())
positions = input().split()
s1 = set()
l1 = [1] * (n - 1)
s2 = set()
l2 = []
count = 0
for i in range(n - 1):
    if positions[i] in s1:l1[i] = 0
    s1.add(positions[i])
for i in range(n - 1):
    s2.add(positions[-1 - i])
    l2.append(len(s2))
for i in range(n - 1):
    count+=l1[i] * l2[-1 - i]
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/1004/D:
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.

Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.

The Manhattan distance between two cells ($x_1$, $y_1$) and ($x_2$, $y_2$) is defined as $|x_1 - x_2| + |y_1 - y_2|$. For example, the Manhattan distance between the cells $(5, 2)$ and $(7, 1)$ equals to $|5-7|+|2-1|=3$. [Image] Example of a rhombic matrix.

Note that rhombic matrices are uniquely defined by $n$, $m$, and the coordinates of the cell containing the zero.

She drew a $n\times m$ rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of $n\cdot m$ numbers). Note that Sonya will not give you $n$ and $m$, so only the sequence of numbers in this matrix will be at your disposal.

Write a program that finds such an $n\times m$ rhombic matrix whose elements are the same as the elements in the sequence in some order.

-----Input-----

The first line contains a single integer $t$ ($1\leq t\leq 10^6$) — the number of cells in the matrix.

The second line contains $t$ integers $a_1, a_2, \ldots, a_t$ ($0\leq a_i< t$) — the values in the cells in arbitrary order.

-----Output-----

In the first line, print two positive integers $n$ and $m$ ($n \times m = t$) — the size of the matrix.

In the second line, print two integers $x$ and $y$ ($1\leq x\leq n$, $1\leq y\leq m$) — the row number and the column number where the cell with $0$ is located.

If there are multiple possible answers, print any of them. If there is no solution, print the single integer $-1$.

-----Examples-----
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4

Output
4 5
2 2

Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1

Output
3 6
2 3

Input
6
2 1 0 2 1...

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

import math
t = int(input())
L = [int(x) for x in input().split()]
L.sort()
ma = max(L)
S = 2*sum(L)
Div = []

for i in range(1,int(math.sqrt(t))+1):
    if t%i == 0:
        Div.append(i)
        Div.append(t//i)

if len(Div) >= 2:
    if Div[-1] == Div[-2]:
        Div.pop()

Div.sort()

D = {}

for i in L:
    if i in D:
        D[i] += 1
    else:
        D[i] = 1

Candidates = []

for i in range(len(Div)):
    n = Div[i]
    m = Div[-i-1]
    for j in range(ma,ma-m,-1):
        if D.get(j,-1) > ma-j+1:
            break
    else:
        j -= 1
    good = ma-j
    y = 1+(m-good)//2
    x = m+n-ma-y
    T = x+y
    if y >= 1:
        if y <= (m+1)//2:
            if x <= (n+1)//2:
                if m*(x*(x-1)+(n-x)*(n-x+1))+n*((T-x)*(T-x-1)+(m-T+x)*(m-T+x+1)) == S:
                    temp = []
                    for j in range(m*n):
                        temp.append(abs(1+(j%n)-x)+abs(1+(j//n)-y))
                    temp.sort()
                    if temp == L:
                        print(n,m)
                        print(x,y)
                        break
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1005/A:
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ steps, she will pronounce the numbers $1, 2, 3, 1, 2, 3, 4$.

You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.

The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

-----Input-----

The first line contains $n$ ($1 \le n \le 1000$) — the total number of numbers pronounced by Tanya.

The second line contains integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $x$ steps, she will pronounce the numbers $1, 2, \dots, x$ in that order.

The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

-----Output-----

In the first line, output $t$ — the number of stairways that Tanya climbed. In the second line, output $t$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

-----Examples-----
Input
7
1 2 3 1 2 3 4

Output
2
3 4
Input
4
1 1 1 1

Output
4
1 1 1 1
Input
5
1 2 3 4 5

Output
1
5
Input
5
1 2 1 2 1

Output
3
2 2 1

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

n = int(input())
steps = list(map(int, input().split()))
number = 0
single = []
curr = 0
for i in steps:
    if i==1:
        single.append(curr)
        curr = 1
        number += 1
    else:
        curr += 1
single.append(curr)
print(number)
print(*single[1:])


I found an interesting problem on https://codeforces.com/problemset/problem/1005/B:
You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.

For example:  by applying a move to the string "where", the result is the string "here",  by applying a move to the string "a", the result is an empty string "".

You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.

Write a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.

-----Input-----

The first line of the input contains $s$. In the second line of the input contains $t$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $2\cdot10^5$, inclusive.

-----Output-----

Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.

-----Examples-----
Input
test
west

Output
2

Input
codeforces
yes

Output
9

Input
test
yes

Output
7

Input
b
ab

Output
1

-----Note-----

In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".

In the second example, the move should be applied to the string "codeforces" $8$ times. As a result, the string becomes "codeforces" $\to$ "es". The move should be applied to the string "yes" once. The result is the same string "yes" $\to$ "es".

In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.

In the fourth example, the first character of the...

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

a = input().strip()
b = input().strip()

common = 0
while True:
    if common >= min(len(a), len(b)):
        break

    if a[-(common + 1)] != b[-(common + 1)]:
        break

    common += 1

print(len(a) - common + len(b) - common)


I found an interesting problem on https://codeforces.com/problemset/problem/1005/C:
A sequence $a_1, a_2, \dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$).

For example, the following sequences are good:  $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$. Note that their sum is a power of two. Similarly, such an element can be found for $a_2$ and $a_3$),  $[1, 1, 1, 1023]$,  $[7, 39, 89, 25, 89]$,  $[]$.

Note that, by definition, an empty sequence (with a length of $0$) is good.

For example, the following sequences are not good:  $[16]$ (for $a_1=16$, it is impossible to find another element $a_j$ such that their sum is a power of two),  $[4, 16]$ (for $a_1=4$, it is impossible to find another element $a_j$ such that their sum is a power of two),  $[1, 3, 2, 8, 8, 8]$ (for $a_3=2$, it is impossible to find another element $a_j$ such that their sum is a power of two).

You are given a sequence $a_1, a_2, \dots, a_n$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.

-----Input-----

The first line contains the integer $n$ ($1 \le n \le 120000$) — the length of the given sequence.

The second line contains the sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).

-----Output-----

Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $n$ elements, make it empty, and thus get a good sequence.

-----Examples-----
Input
6
4 7 1 5 4 9

Output
1

Input
5
1 2 3 4 5

Output
2

Input
1
16

Output
1

Input
4
1 1 1 1023

Output
0

-----Note-----

In the first example, it is enough to delete one element $a_4=5$. The remaining elements form the sequence $[4, 7, 1, 4, 9]$, which is good.

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

import bisect
n = int(input())
nums = list(map(int,input().split()))
pows = [pow(2,x) for x in range(31)]
dict = {}
for num in nums:
  if num not in dict:
    dict[num] = 1
  else:
    dict[num] += 1

count = 0
for k,v in dict.items():
  count += v
  for i in range(bisect.bisect_right(pows,k),31):
    if (pows[i] - k) in dict:
      if pows[i] == 2*k and v == 1:
        continue
      count -= v
      break
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/1005/D:
Polycarp likes numbers that are divisible by 3.

He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$.

For example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$.

Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.

What is the maximum number of numbers divisible by $3$ that Polycarp can obtain?

-----Input-----

The first line of the input contains a positive integer $s$. The number of digits of the number $s$ is between $1$ and $2\cdot10^5$, inclusive. The first (leftmost) digit is not equal to 0.

-----Output-----

Print the maximum number of numbers divisible by $3$ that Polycarp can get by making vertical cuts in the given number $s$.

-----Examples-----
Input
3121

Output
2

Input
6

Output
1

Input
1000000000000000000000000000000000

Output
33

Input
201920181

Output
4

-----Note-----

In the first example, an example set of optimal cuts on the number is 3|1|21.

In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $3$.

In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $33$ digits 0. Each of the $33$ digits 0 forms a number that is divisible by $3$.

In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers...

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

s = [int(i) for i in input()]

count = 0
current = []
for h, i in enumerate(s):
    for j in range(len(current)):
        current[j] = current[j] * 10 + i
    current.append(i)
    if h + 1 < len(s) and s[h + 1] != 0:
        for m in current:
            if m % 3 == 0:
                count += 1
                current = []
                break
    else:
        for m in current:
            if m % 3 == 0:
                count += 1
                current = []
                break
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/1005/E1:
You are given a permutation $p_1, p_2, \dots, p_n$. A permutation of length $n$ is a sequence such that each integer between $1$ and $n$ occurs exactly once in the sequence.

Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$.

The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.

For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.

Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of the median of $p_l, p_{l+1}, \dots, p_r$ is exactly the given number $m$.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \le n \le 2\cdot10^5$, $1 \le m \le n$) — the length of the given sequence and the required value of the median.

The second line contains a permutation $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$). Each integer between $1$ and $n$ occurs in $p$ exactly once.

-----Output-----

Print the required number.

-----Examples-----
Input
5 4
2 4 5 3 1

Output
4

Input
5 5
1 2 3 4 5

Output
1

Input
15 8
1 15 2 14 3 13 4 8 12 5 11 6 10 7 9

Output
48

-----Note-----

In the first example, the suitable pairs of indices are: $(1, 3)$, $(2, 2)$, $(2, 3)$ and $(2, 4)$.

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

MAXN = 200001
n, m = list(map(int, input().split(' ')))
s = list(map(int, input().split(' ')))

f = [0 for i in range(n+1)]
count = [0 for i in range(-MAXN, MAXN+1)]

f[0] = 0

last = 0
res = 0

#print(n, m, s)

for i in range(1, n+1):
    if s[i-1] == m:
        for j in range(last, i):
            count[f[j]] += 1
        last = i

    if s[i-1] > m:
        f[i] = f[i-1] - 1
    else:
        f[i] = f[i-1] + 1

    #print(i, last, count[f[i]] + count[f[i]-1])
    res += count[f[i]] + count[f[i]-1]

#print(f)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1005/E2:
You are given an integer sequence $a_1, a_2, \dots, a_n$.

Find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.

The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.

For example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.

Write a program to find the number of pairs of indices $(l, r)$ ($1 \le l \le r \le n$) such that the value of median of $a_l, a_{l+1}, \dots, a_r$ is exactly the given number $m$.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \le n,m \le 2\cdot10^5$) — the length of the given sequence and the required value of the median.

The second line contains an integer sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2\cdot10^5$).

-----Output-----

Print the required number.

-----Examples-----
Input
5 4
1 4 5 60 4

Output
8

Input
3 1
1 1 1

Output
6

Input
15 2
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

Output
97

-----Note-----

In the first example, the suitable pairs of indices are: $(1, 3)$, $(1, 4)$, $(1, 5)$, $(2, 2)$, $(2, 3)$, $(2, 5)$, $(4, 5)$ and $(5, 5)$.

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

L1=list(map(int, input().split()))
numList=list(map(int, input().split()))
length=L1[0]
m=L1[1]
def greaterCount(numList,m):
    countDic={0:1}
    sum=0
    total=0
    rem=0
    for number in numList:
        if number>=m:
            sum+=1
            rem+=countDic[sum-1]
            total+=rem
        else:
            sum-=1
            if sum in countDic:
                rem-=countDic[sum]
            total+=rem

        if sum in countDic:
            countDic[sum] += 1
        else:
            countDic[sum] = 1

    #print("m=", m, "number=", number, "sum=", sum, "total=", total, "rem=", rem, "countDic=", countDic)
    return total
print(greaterCount(numList,m)-greaterCount(numList,m+1))


I found an interesting problem on https://codeforces.com/problemset/problem/1005/F:
There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $1$ to $n$.

It is known that, from the capital (the city with the number $1$), you can reach any other city by moving along the roads.

The President of Berland plans to improve the country's road network. The budget is enough to repair exactly $n-1$ roads. The President plans to choose a set of $n-1$ roads such that:

  it is possible to travel from the capital to any other city along the $n-1$ chosen roads,  if $d_i$ is the number of roads needed to travel from the capital to city $i$, moving only along the $n-1$ chosen roads, then $d_1 + d_2 + \dots + d_n$ is minimized (i.e. as minimal as possible).

In other words, the set of $n-1$ roads should preserve the connectivity of the country, and the sum of distances from city $1$ to all cities should be minimized (where you can only use the $n-1$ chosen roads).

The president instructed the ministry to prepare $k$ possible options to choose $n-1$ roads so that both conditions above are met.

Write a program that will find $k$ possible ways to choose roads for repair. If there are fewer than $k$ ways, then the program should output all possible valid ways to choose roads.

-----Input-----

The first line of the input contains integers $n$, $m$ and $k$ ($2 \le n \le 2\cdot10^5, n-1 \le m \le 2\cdot10^5, 1 \le k \le 2\cdot10^5$), where $n$ is the number of cities in the country, $m$ is the number of roads and $k$ is the number of options to choose a set of roads for repair. It is guaranteed that $m \cdot k \le 10^6$.

The following $m$ lines describe the roads, one road per line. Each line contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \ne b_i$) — the numbers of the cities that the $i$-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from...

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

import sys
input=lambda:sys.stdin.readline().rstrip()
sys.setrecursionlimit(200001)
n,m,k=list(map(int,input().split()))
edge=[[]for _ in range(n)]
di={}
for i in range(m):
  a,b=list(map(int,input().split()))
  a-=1
  b-=1
  if a>b:a,b=b,a
  di[(a,b)]=i
  edge[a].append(b)
  edge[b].append(a)
d=[10**10]*n
d[0]=0
root=[set()for _ in range(n)]
queue=[0]
for node in queue:
  for mode in edge[node]:
    if d[mode]!=10**10:
      if d[mode]+1==d[node]:
        root[node].add(mode)
      elif d[mode]==d[node]+1:
        root[mode].add(node)
      continue
    d[mode]=d[node]+1
    queue.append(mode)
for i in range(n):root[i]=list(root[i])
t=1
for i in range(1,n):t*=len(root[i])
print(min(t,k))
for i in range(min(t,k)):
  ans=["0"]*m
  for j in range(1,n):
    i,jj=divmod(i,len(root[j]))
    ans[di[(min(j,root[j][jj]),max(j,root[j][jj]))]]="1"
  print("".join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1006/A:
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).

Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:  Replace each occurrence of $1$ in the array $a$ with $2$;  Replace each occurrence of $2$ in the array $a$ with $1$;  Replace each occurrence of $3$ in the array $a$ with $4$;  Replace each occurrence of $4$ in the array $a$ with $3$;  Replace each occurrence of $5$ in the array $a$ with $6$;  Replace each occurrence of $6$ in the array $a$ with $5$;  $\dots$  Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$;  Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.

Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \in\{1, 2, \ldots, 5 \cdot 10^8\}$ as described above.

For example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:

$[1, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $1$ with $2$) $\rightarrow$ $[2, 2, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $2$ with $1$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $3$ with $4$) $\rightarrow$ $[1, 1, 4, 5, 10]$ $\rightarrow$ (replace all occurrences of $4$ with $3$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $5$ with $6$) $\rightarrow$ $[1, 1, 3, 6, 10]$ $\rightarrow$ (replace all occurrences of $6$ with $5$) $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ $\dots$ $\rightarrow$ $[1, 1, 3, 5, 10]$ $\rightarrow$ (replace all occurrences of $10$ with $9$) $\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.

Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.

-----Input-----

The...

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

n = int(input())
a = [int(x) for x in input().split()]

print(*[x - ((x ^ 1) & 1) for x in a])


I found an interesting problem on https://codeforces.com/problemset/problem/1006/B:
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.

Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.

The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.

You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.

For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of problems and the number of days, respectively.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2000$) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).

-----Output-----

In the first line of the output print the maximum possible total profit.

In the second line print exactly $k$ positive integers $t_1, t_2, \dots, t_k$...

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

n, m = map(int, input().split())
a = list(map(int, input().split()))
q = []
for i in range(n):
    q.append(a[i])
q.sort()
q = q[(-m):]
s = 0
for i in range(m):
    s += q[i]
print(s)
s = 1
w = []
f = 1
for i in range(n):
    if(a[0] in q):
        w.append(s)
        f+=s
        s = 0
        q.remove(a[0])
    a.remove(a[0])
    s+=1
w[-1] += n-f+1
for i in range(m):
    print(w[i], end = " ")


I found an interesting problem on https://codeforces.com/problemset/problem/1006/C:
You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers.

Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array.

Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.

More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then:

$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$ $$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$ $$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$

The sum of an empty array is $0$.

Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in the array $d$.

The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^9$) — the elements of the array $d$.

-----Output-----

Print a single integer — the maximum possible value of $sum_1$, considering that the condition $sum_1 = sum_3$ must be met.

Obviously, at least one valid way to split the array exists (use $a=c=0$ and $b=n$).

-----Examples-----
Input
5
1 3 1 1 4

Output
5

Input
5
1 3 2 1 4

Output
4

Input
3
4 1 2

Output
0

-----Note-----

In the first example there is only one possible splitting which maximizes $sum_1$: $[1, 3, 1], [~], [1, 4]$.

In the second example the only way to have $sum_1=4$ is: $[1, 3], [2, 1], [4]$.

In the third example there is only one way to split the array: $[~], [4, 1, 2], [~]$.

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

n = int(input())
a = list(map(int, input().split()))
i, j, si, sj, r = -1, len(a), 0, 0, 0
while i <  j:
    if si == sj: r = si
    if si < sj:
        i += 1
        si += a[i]
    else:
        j -= 1
        sj += a[j]
print( r )


I found an interesting problem on https://codeforces.com/problemset/problem/1006/D:
You are given two strings $a$ and $b$ consisting of lowercase English letters, both of length $n$. The characters of both strings have indices from $1$ to $n$, inclusive.

You are allowed to do the following changes:   Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $b_i$;  Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $a_{n - i + 1}$;  Choose any index $i$ ($1 \le i \le n$) and swap characters $b_i$ and $b_{n - i + 1}$.

Note that if $n$ is odd, you are formally allowed to swap $a_{\lceil\frac{n}{2}\rceil}$ with $a_{\lceil\frac{n}{2}\rceil}$ (and the same with the string $b$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.

You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.

In one preprocess move you can replace a character in $a$ with another character. In other words, in a single preprocess move you can choose any index $i$ ($1 \le i \le n$), any character $c$ and set $a_i := c$.

Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $a$ and $b$ equal by applying some number of changes described in the list above.

Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $b$ or make any preprocess moves after the first change is made.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 10^5$) — the length of strings $a$ and $b$.

The second line contains the string $a$ consisting of exactly $n$ lowercase English letters.

The third line contains the string $b$ consisting of exactly $n$ lowercase English letters.

-----Output-----

Print a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $a$ equal to string $b$...

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

from collections import Counter
n = int(input())
a = input()[:n]
b = input()[:n]
prelim =0
for i in range(n//2):
    c = Counter([a[i],a[n-1-i],b[i],b[n-1-i]])
    k = len(c)
    if k == 4:
        """
        a x +2op
        b y
        """
        prelim +=2
    elif k == 3:
        """
        a c  +1op
        a b

        a a  +2op
        b c

        a c  +1op
        b b
        """
        prelim += 2 if a[i]==a[n-1-i] else 1
    elif k==2:
        """
        3 3
        3 5

        3 5
        3 3

        2 5
        2 5
        """
        if 3 in list(c.values()):
            prelim += 1
if n%2:
    if a[n//2]!=b[n//2]:
        prelim +=1

print(prelim)