# dp[i][j] := sのi文字目まで見たときに、ABCのj文字目までを部分列として取り出す方法の数。

s = input()

dp = [[0 for _ in range(4)]for _ in range(len(s))]
mod = 10 ** 9 + 7

power_3 = 1
for idx, letter in enumerate(s):
    dp[idx] = dp[idx-1].copy()

    if letter == 'A':
        dp[idx][1] += power_3
    elif letter == 'B':
        dp[idx][2] += dp[idx-1][1]
    elif letter == 'C':
        dp[idx][3] += dp[idx-1][2]
    elif letter == '?':
        dp[idx][1] *= 3
        dp[idx][2] *= 3
        dp[idx][3] *= 3
        dp[idx][1] += power_3 # 3**(この?を含まない、今までの?の個数)だけ、Aの手前の場合が考えられる。
        power_3 *= 3
        power_3 %= mod
        dp[idx][2] += dp[idx-1][1]
        dp[idx][3] += dp[idx-1][2]
        dp[idx][1] %= mod
        dp[idx][2] %= mod
        dp[idx][3] %= mod

print(dp[len(s)-1][3] % mod)
# print(dp)

Score : <var>400</var> points

Problem Statement

The ABC number of a string <var>T</var> is the number of triples of integers <var>(i, j, k)</var> that satisfy all of the following conditions:

<var>1 ≤ i < j < k ≤ |T|</var> (<var>|T|</var> is the length of <var>T</var>.)

<var>T_i =</var> A (<var>T_i</var> is the <var>i</var>-th character of <var>T</var> from the beginning.)

<var>T_j =</var> B

<var>T_k =</var> C

For example, when <var>T =</var> ABCBC, there are three triples of integers <var>(i, j, k)</var> that satisfy the conditions: <var>(1, 2, 3), (1, 2, 5), (1, 4, 5)</var>. Thus, the ABC number of <var>T</var> is <var>3</var>.

You are given a string <var>S</var>. Each character of <var>S</var> is A, B, C or ?.

Let <var>Q</var> be the number of occurrences of ? in <var>S</var>. We can make <var>3^Q</var> strings by replacing each occurrence of ? in <var>S</var> with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo <var>10^9 + 7</var>.

Constraints

<var>3 ≤ |S| ≤ 10^5</var>

Each character of <var>S</var> is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the sum of the ABC numbers of all the <var>3^Q</var> strings, modulo <var>10^9 + 7</var>.

Sample Input 1

A??C

Sample Output 1

8

In this case, <var>Q = 2</var>, and we can make <var>3^Q = 9</var> strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: <var>0</var>

AABC: <var>2</var>

AACC: <var>0</var>

ABAC: <var>1</var>

ABBC: <var>2</var>

ABCC: <var>2</var>

ACAC: <var>0</var>

ACBC: <var>1</var>

ACCC: <var>0</var>

The sum of these is <var>0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8</var>, so we print <var>8</var> modulo <var>10^9 + 7</var>, that is, <var>8</var>.

Sample Input 2

ABCBC

Sample Output 2

3

When <var>Q = 0</var>, we print the ABC number of <var>S</var> itself, modulo <var>10^9 + 7</var>. This string is the same as the one given as an example in the problem statement, and its ABC number is <var>3</var>.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the <var>3^Q</var> strings is <var>2291979612924</var>, and we should print this number modulo <var>10^9 + 7</var>, that is, <var>979596887</var>.


a, b = map(int, input().split())
if a + b == 15:
  print("+")
elif a * b == 15:
  print("*")
else:
  print("x")

Score : <var>100</var> points

Problem Statement

You are given two integers <var>a</var> and <var>b</var>.
Determine if <var>a+b=15</var> or <var>a\times b=15</var> or neither holds.

Note that <var>a+b=15</var> and <var>a\times b=15</var> do not hold at the same time.

Constraints

<var>1 \leq a,b \leq 15</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>a</var> <var>b</var>

Output

If <var>a+b=15</var>, print +;
if <var>a\times b=15</var>, print *;
if neither holds, print x.

Sample Input 1

4 11

Sample Output 1

+

<var>4+11=15</var>.

Sample Input 2

3 5

Sample Output 2

*

<var>3\times 5=15</var>.

Sample Input 3

1 1

Sample Output 3

x

<var>1+1=2</var> and <var>1\times 1=1</var>, neither of which is <var>15</var>.


a, b = map(int, input().split())
if (a+b) == 15:
    print('+')
elif (a*b) == 15:
    print('*')
else:
    print('×')


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

fact = [1,1]
finv = [1,1]
inv = [0,1]

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

def nCr(n,r,mod):
    if r > n:
        return 0
    else:
        return fact[n]*finv[r]*finv[n-r]%mod

def nPr(n,r,mod):
    if r > n:
        return 0
    else:
        return fact[n]*finv[n-r]%mod

ans = 0
for i in range(n+1):
    if i*a > k:
        break
    d = k-i*a
    if d%b or d//b > n:
        continue
    ans += nCr(n,i,mod)*nCr(n,d//b,mod)%mod
    ans %= mod
print(ans)

def nCr(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 998244353 #出力の制限
size = 10**6 # size >= n
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, size + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

N, A, B, K = map(int,input().split())
ans = 0
for k in range(N + 1):
    if A * k > K:
        break
    if (K - A * k) % B != 0:
        continue
    l = (K - A * k) // B
    ans += nCr(N,k,mod) * nCr(N,l,mod)
    ans %= mod
print(ans)

Score : <var>700</var> points

Problem Statement

Takahashi has a tower which is divided into <var>N</var> layers.
Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower.
He defines the beauty of the tower as follows:

The beauty of the tower is the sum of the scores of the <var>N</var> layers, where the score of a layer is <var>A</var> if the layer is painted red, <var>A+B</var> if the layer is painted green, <var>B</var> if the layer is painted blue, and <var>0</var> if the layer is uncolored.

Here, <var>A</var> and <var>B</var> are positive integer constants given beforehand. Also note that a layer may not be painted in two or more colors.

Takahashi is planning to paint the tower so that the beauty of the tower becomes exactly <var>K</var>.
How many such ways are there to paint the tower? Find the count modulo <var>998244353</var>.
Two ways to paint the tower are considered different when there exists a layer that is painted in different colors, or a layer that is painted in some color in one of the ways and not in the other.

Constraints

<var>1 ≤ N ≤ 3×10^5</var>

<var>1 ≤ A,B ≤ 3×10^5</var>

<var>0 ≤ K ≤ 18×10^{10}</var>

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var> <var>K</var>

Output

Print the number of the ways to paint tiles, modulo <var>998244353</var>.

Sample Input 1

4 1 2 5

Sample Output 1

40

In this case, a red layer worth <var>1</var> points, a green layer worth <var>3</var> points and the blue layer worth <var>2</var> points. The beauty of the tower is <var>5</var> when we have one of the following sets of painted layers:

<var>1</var> green, <var>1</var> blue

<var>1</var> red, <var>2</var> blues

<var>2</var> reds, <var>1</var> green

<var>3</var> reds, <var>1</var> blue

The total number of the ways to produce them is <var>40</var>.

Sample Input 2

2 5 6 0

Sample Output 2

1

The beauty of the tower is <var>0</var> only when all the layers are uncolored. Thus, the answer is <var>1</var>.

Sample Input 3

90081 33447 90629 6391049189

Sample Output 3

577742975


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

pair = []
for x in range(n+1):
    y, r = divmod(k-a*x, b)
    if y < 0:
        continue
    if r == 0:
        pair.append((x, y))

memo = [0]*n

def com(n, r):
    X = Y = 1
    if n < r:
        return 0
    if n-r < r:
        r = n-r
    if memo[r] != 0:
        return memo[r]
    for i in range(1, r+1):
        Y = Y*i % MOD
        X = X*(n-i+1) % MOD
        memo[i] = X*pow(Y, MOD-2, MOD)
    return memo[r]

com(n, n//2)

ans = 0
for x, y in pair:
    ans += com(n, x)*com(n, y) % MOD
print(ans % MOD)


from collections import deque

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

buf = deque()  # 計算用配列
tmp = 0        # 計算用配列の全要素のxor値
ans = 0

for i in A_list:
    while tmp & i:
        #print(tmp, i, bin(tmp & i))
        remove_0_pos = buf.popleft()
        tmp ^= remove_0_pos #引き算
    buf.append(i)
    tmp ^= i # XORする
    ans += len(buf)
print(ans)

def ind(S):
  L4=list()
  for i in range(len(S)):
    if S[len(S)-i-1]=="1":
      L4.append(i)
  return set(L4)
N=int(input())
L=list(map(int,input().split()))
L=[ind(bin(i)[2:]) for i in L]
ans=0
n=0
i=0
T=set()
while True:
  if i==N and n==N:
    break
  elif i==N:
    ans+=i-n
    n+=1
    continue
  if T&L[i]==set():
    T=T|L[i]
    ans+=1
    i+=1
  else:
    T=T-L[n]
    n+=1
    ans+=i-n
  if i==N and n!=N:
    n+=1
print(ans)

Score : <var>500</var> points

Problem Statement

There is an integer sequence <var>A</var> of length <var>N</var>.

Find the number of the pairs of integers <var>l</var> and <var>r</var> (<var>1 \leq l \leq r \leq N</var>) that satisfy the following condition:

<var>A_l\ xor\ A_{l+1}\ xor\ ...\ xor\ A_r = A_l\ +\ A_{l+1}\ +\ ...\ +\ A_r</var>

Here, <var>xor</var> denotes the bitwise exclusive OR.

Definition of XOR

The XOR of integers <var>c_1, c_2, ..., c_m</var> is defined as follows:

Let the XOR be <var>X</var>. In the binary representation of <var>X</var>, the digit in the <var>2^k</var>'s place (<var>0 \leq k</var>; <var>k</var> is an integer) is <var>1</var> if there are an odd number of integers among <var>c_1, c_2, ...c_m</var> whose binary representation has <var>1</var> in the <var>2^k</var>'s place, and <var>0</var> if that number is even.

For example, let us compute the XOR of <var>3</var> and <var>5</var>. The binary representation of <var>3</var> is <var>011</var>, and the binary representation of <var>5</var> is <var>101</var>, thus the XOR has the binary representation <var>110</var>, that is, the XOR is <var>6</var>.


n = int(input())
pyl = list(map(int,input().split()))
cnt = 0
for i in pyl:
    for j in pyl:
        if i^j == i+j:
            cnt = cnt + 1
print(cnt)


import sys

input = sys.stdin.readline
N = int(input())

pre = int(input())
if pre != 0:
    print(-1)
    sys.exit()
ans = 0
for _ in range(N-1):
    x = int(input())
    if pre + 1 < x:
        print(-1)
        sys.exit()
    elif pre + 1 == x:
        ans += 1
    else:
        ans += x
    pre = x

print(ans)

def main():
    n = int(input())
    a = []
    for _ in range(n):
        a.append(int(input()))
    x = a[-1]
    ans = a[-1]
    for i in range(1,n):
        if x==0:
            x = a[-1-i]
        e = x-1
        if e>a[-1-i]:
            print(-1)
            return
        elif e<a[-1-i]:
            x = a[-1-i]
            ans += a[-1-i]
        else:
            x -= 1
    if x==0:
        print(ans)
    else:
        print(-1)

if __name__ == "__main__":
    main()

Score : <var>700</var> points

Problem Statement

There is a sequence <var>X</var> of length <var>N</var>, where every element is initially <var>0</var>. Let <var>X_i</var> denote the <var>i</var>-th element of <var>X</var>.

You are given a sequence <var>A</var> of length <var>N</var>. The <var>i</var>-th element of <var>A</var> is <var>A_i</var>. Determine if we can make <var>X</var> equal to <var>A</var> by repeating the operation below. If we can, find the minimum number of operations required.

Choose an integer <var>i</var> such that <var>1\leq i\leq N-1</var>. Replace the value of <var>X_{i+1}</var> with the value of <var>X_i</var> plus <var>1</var>.

Constraints

<var>1 \leq N \leq 2 \times 10^5</var>

<var>0 \leq A_i \leq 10^9(1\leq i\leq N)</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var>
<var>:</var>
<var>A_N</var>

Output

If we can make <var>X</var> equal to <var>A</var> by repeating the operation, print the minimum number of operations required. If we cannot, print <var>-1</var>.

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make <var>X</var> equal to <var>A</var> as follows:

Choose <var>i=2</var>. <var>X</var> becomes <var>(0,0,1,0)</var>.

Choose <var>i=1</var>. <var>X</var> becomes <var>(0,1,1,0)</var>.

Choose <var>i=3</var>. <var>X</var> becomes <var>(0,1,1,2)</var>.

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8


import sys
input = sys.stdin.buffer.readline

N = int(input())
A = [int(input()) for _ in range(N)]

if A[0] != 0 or any(l + 1 < r for l, r in zip(A, A[1:])):
    print(-1)
    exit()

ans = 0
for l, r in zip(A, A[1:]):
    if l <= r:
        ans += 1
    elif r > 0:
        ans += 2

print(ans)


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

N = int(readline())
data = read().split()
m = map(int,data[:-1])
XY = zip(m,m)
C = [0] + [1 * (x == ord('W')) for x in data[-1]]

graph = [set() for _ in range(N+1)]
for x,y in XY:
    graph[x].add(y)
    graph[y].add(x)

deg = [len(x) for x in graph]
b_leaf = [i for i in range(N+1) if deg[i] == 1 and not C[i]]

while b_leaf:
    x = b_leaf.pop()
    for y in graph[x]:
        graph[y].remove(x)
        deg[y] -= 1
        if deg[y] == 1 and not C[y]:
            b_leaf.append(y)
    deg[x] = 0
    graph[x].clear()

V = set(i for i,E in enumerate(graph) if E)
if len(V) <= 2:
    print(sum(C))
    exit()
root = None
for v in V:
    if deg[v] > 1:
        root = v
        break

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

"""
・Euler tourの状態から、パスをひとつ除く
・葉と葉を結ぶとしてよい。通ると2コスト安くなる点がある
"""

for i in range(N+1):
    C[i] ^= (1&deg[i])

cost_full = sum(deg) + sum(C)

# C[i] == 1 となる i を最もたくさん含むパスを探す

opt = 0
dp = [0] * (N+1)
for v in order[::-1]:
    if deg[v] == 1:
        continue
    arr = sorted((dp[w] for w in graph[v] if w != parent[v]),reverse = True) + [0]
    x = arr[0] + arr[1] + C[v]
    if opt < x:
        opt = x
    dp[v] = arr[0] + C[v]

answer = cost_full - 2 * opt
print(answer)

"""

https://atcoder.jp/contests/arc097/tasks/arc097_d

始点と終点関係ある？
→逆にしても問題はない

黒い葉は完全に無視できる(落とせる)
よって、葉はすべて白
葉以外は白黒どっちもあり得る

すべての葉をめぐる最短経路？
ある葉からスタートするのは自明っぽい？
ある白からスタートするのはそう

→自分を塗ってからdfsする
→全方位木dp?

行きのみで帰らない場所が1つ存在するはず
→始点と終点のパスとそこから生える木って感じのイメージ

足踏み(停止)の回数を極力少なくしたい
→始点でも終点でもない場合、 e本の辺がつながってたらe回訪問は確定
　e^colorが黒でない場合は+1
→つまり、各頂点で消費する回数は始点・終点でない限り常に一定？

終点はまず葉→始点も葉でおｋ
始点は足踏みなので1秒つかう　終点も1秒使う
パス上の点は、e-1回訪問(ここが根本的に違う！)

つまり、あるパスがあって　その長さがL(両端除く)の時、最大でL減る
ただし、パス上にあっても回数が減らない点もある

B=0 W=1とするか
(color^E) == 1 の点は、E-1回訪問になると足踏みがいらないから2減る
つまり、そのような点が最大数あるパスを求めればいい

"""

import sys
sys.setrecursionlimit(200000)
from collections import deque

MM = 0

def dfs(v,p):
    global MM

    if v != p and linknum[v] == 1:
        return 0

    cl = []
    for nex in lis[v]:
        if nex != p and exist[nex]:
            tmp = dfs(nex,v)
            cl.append(tmp)
    cl.sort()
    cl.reverse()

    if len(cl) == 1:
        MM = max(MM , cl[0])
    else:
        if (linknum[v]+c[v])%2 == 1:
            MM = max(MM , cl[0] + cl[1] + 2)
        else:
            MM = max(MM , cl[0] + cl[1])

    if (linknum[v]+c[v]) % 2 == 1:
        return cl[0]+ 2
    else:
        return cl[0]

N = int(input())

lis =  [ [] for i in range(N) ]
linknum = [0] * N
for i in range(N-1):
    u,v = map(int,input().split())
    u -= 1
    v -= 1

    lis[u].append(v)
    lis[v].append(u)
    linknum[u] += 1
    linknum[v] += 1

ctmp = input()
c = []

for i in ctmp:
    if i == "B":
        c.append(0)
    else:
        c.append(1)

exist = [True] * N

q = deque([])
for i in range(N):
    if linknum[i] <= 1 and c[i] == 0:
        q.append(i)

while len(q) > 0:
    now = q.popleft()
    exist[now] = False
    linknum[now] = 0

    for nex in lis[now]:
        linknum[nex] -= 1

        if linknum[nex] == 1 and c[nex] == 0:
            q.append(nex)

#print (exist)
start = None
for i in range(N):
    if exist[i]:
        start = i
        break
else:
    print (0)
    sys.exit()

if linknum[start] == 0:
    print (1)
    sys.exit()

ans = 0
#print (linknum)
for i in range(N):
    if exist[i]:

        if (linknum[i] + c[i]) % 2 == 0:
            ans += linknum[i]
        else:
            ans += linknum[i] + 1

MM = 0
pick = dfs(start,start)
print (ans - MM)

Score : <var>800</var> points

Problem Statement

There is a tree with <var>N</var> vertices numbered <var>1</var> through <var>N</var>.
The <var>i</var>-th edge connects Vertex <var>x_i</var> and <var>y_i</var>.
Each vertex is painted white or black.
The initial color of Vertex <var>i</var> is represented by a letter <var>c_i</var>.
<var>c_i</var> <var>=</var> W represents the vertex is white; <var>c_i</var> <var>=</var> B represents the vertex is black.

A cat will walk along this tree.
More specifically, she performs one of the following in one second repeatedly:

Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.

Invert the color of the vertex where she is currently.

The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex.
At least how many seconds does it takes for the cat to achieve her objective?

Constraints

<var>1</var> <var>≤</var> <var>N</var> <var>≤</var> <var>10^5</var>

<var>1</var> <var>≤</var> <var>x_i,y_i</var> <var>≤</var> <var>N</var> (<var>1</var> <var>≤</var> <var>i</var> <var>≤</var> <var>N-1</var>)

The given graph is a tree.

<var>c_i</var> <var>=</var> W or <var>c_i</var> <var>=</var> B.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>y_1</var>
<var>x_2</var> <var>y_2</var>
<var>:</var>
<var>x_{N-1}</var> <var>y_{N-1}</var>
<var>c_1c_2..c_N</var>

Output

Print the minimum number of seconds required to achieve the objective.

Sample Input 1

5
1 2
2 3
2 4
4 5
WBBWW

Sample Output 1

5

The objective can be achieved in five seconds, for example, as follows:

Start at Vertex <var>1</var>. Change the color of Vertex <var>1</var> to black.

Move to Vertex <var>2</var>, then change the color of Vertex <var>2</var> to white.

Change the color of Vertex <var>2</var> to black.

Move to Vertex <var>4</var>, then change the color of Vertex <var>4</var> to black.

Move to Vertex <var>5</var>, then change the color of Vertex <var>5</var> to black.

Sample Input 2

6
3 1
4 5
2 6
6 1
3 4
WWBWBB

Sample Output 2

7

Sample Input 3

1
B

Sample Output 3

0

Sample Input 4

20
2 19
5 13
6 4
15 6
12 19
13 19
3 11
8 3
3 20
16 13
7 14
3 17
7 8
10 20
11 9
8 18
8 2
10 1
6 13
WBWBWBBWWWBBWWBBBBBW

Sample Output 4

21


input = __import__('sys').stdin.readline
MIS = lambda: map(int,input().split())

n = int(input())
adj = [set() for i in range(n+1)]
white = [False]
for i in range(n-1):
    a, b = MIS()
    adj[a].add(b); adj[b].add(a)
s = input().rstrip()
for i in range(n): white.append(s[i] == 'W')

# Corner cases
if sum(white) <= 1: print(sum(white)); exit()

# Remove black leaves
stack = [i for i in range(1,n+1) if len(adj[i]) == 1 and not white[i]]
while stack:
    p = stack.pop()
    pa = min(adj[p])
    adj[pa].remove(p); adj[p].clear()
    if len(adj[pa]) == 1 and not white[pa]: stack.append(pa)

# Simulate Euler tour
root = 1
while not adj[root]: root+= 1
tadj = [[] for i in range(n+1)]
vis = [False]*(n+1); vis[root] = True
stack = [root]
while stack:
    p = stack.pop()
    for q in adj[p]:
        if vis[q]: continue
        vis[q] = True; tadj[p].append(q)
        stack.append(q)
for i in range(1, n+1):
    if adj[i] and len(tadj[i])%2 == 0: white[i] = not white[i]
white[root] = not white[root]

# Diameter
def bfs(v):
    stack = [v]
    dist = [-1]*(n+1); dist[v] = white[v]
    while stack:
        p = stack.pop()
        for q in adj[p]:
            if dist[q] != -1: continue
            dist[q] = dist[p] + white[q]
            stack.append(q)
    return dist

numedge = sum(map(len, adj))
d1 = bfs(root)
u = d1.index(max(d1))
d2 = bfs(u)
diam = max(d2)
print(numedge - diam)


H,W = map(int,input().split())

canvas = []

for i in range(H):
  canvas.append(list(input()))

#print(canvas)
for i in range(H):
  for j in range(W):
    cnt = 0
    if canvas[i][j] == "#":
      for h in range(-1,2):
        for w in range(-1,2):
          if canvas[min(max(i+h,0),H-1)][min(max(j+w,0),W-1)]=="#" and (abs(h)+abs(w))%2==1:
            cnt+=1
      if cnt==0:
        print("No")
        exit()
print("Yes")

H, W = map(int, input().split())
L = ['.' + input() + '.' for _ in range(H)]
L = ['.' * (W + 2)] + L + ['.' * (W + 2)]
for i in range(1, H + 1):
  for j in range(1, W + 1):
    if L[i][j] == "#":
      l = [L[i-1][j], L[i+1][j], L[i][j-1], L[i][j+1]]
      if '#' not in l:
        print('No')
        break
  else:
    continue
  break
else:
  print('Yes')

Score: <var>300</var> points

Problem Statement

We have a canvas divided into a grid with <var>H</var> rows and <var>W</var> columns. The square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left is represented as <var>(i, j)</var>.

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square <var>(i, j)</var> black when <var>s_{i, j}=</var> #, and to make Square <var>(i, j)</var> white when <var>s_{i, j}=</var> ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

<var>H</var> is an integer between <var>1</var> and <var>50</var> (inclusive).

<var>W</var> is an integer between <var>1</var> and <var>50</var> (inclusive).

For every <var>(i, j)</var> <var>(1 \leq i \leq H, 1 \leq j \leq W)</var>, <var>s_{i, j}</var> is # or ..

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}</var>
<var>s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}</var>
  <var>:</var>   <var>:</var>
<var>s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}</var>

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


h, w = map(int, input().split())
table = [list(input()) for _ in range(h)]

mx = [0, 1, 0, -1]
my = [1, 0, -1, 0]
for i in range(h):
    for  j in range(w):
        if table[i][j] == "#":
            for k in range(4):
                tx, ty = j + mx[k], i + my[k]
                if 0 <= tx < w and 0 <= ty < h and table[ty][tx] == "#":
                    break
                else:
                    print("No")
                    exit(0)
print("Yes")


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

"""
・両端のマンション → どういうルートをたどっても順序が決まる → 彼らの意見は常に一致するとしてよい
"""

N,S,*XP = map(int,read().split())
X = XP[::2]
P = XP[1::2]

leftN = sum(x<S for x in X)
leftX = X[leftN-1::-1] # 内側から順にもつ
leftP = P[leftN-1::-1] # 内側から順にもつ
rightN = N-leftN
rightX = X[leftN:]
rightP = P[leftN:]

visit = [] # 後ろ側から訪問順
while leftN and rightN:
    p1 = leftP[-1]; x1 = leftX[-1]
    p2 = rightP[-1]; x2 = rightX[-1]
    if p1 < p2:
        visit.append(x1)
        leftP.pop(); leftX.pop(); leftN -= 1
        rightP[-1] = p1 + p2
    else:
        visit.append(x2)
        rightP.pop(); rightX.pop(); rightN -= 1
        leftP[-1] = p1 + p2

if leftN:
    visit += leftX[::-1]
else:
    visit += rightX[::-1]
visit.append(S)

answer = sum(x-y if x>y else y-x for x,y in zip(visit,visit[1:]))
print(answer)

import numpy as np

def solve(l, r):
    l.reverse()

    stops = []

    if l and r:
        while l and r:
            lx, lp = l.pop()
            rx, rp = r.pop()
            if lp >= rp:
                l.append((lx, lp + rp))
                stops.append(rx)
            else:
                r.append((rx, lp + rp))
                stops.append(lx)

    if l:
        stops.append(l[-1][0])
    else:
        stops.append(r[-1][0])
    stops.append(s)

    return abs(np.diff(np.array(stops, dtype=np.int64))).sum()

n, s = map(int, input().split())
l, r = [], []
for _ in range(n):
    x, p = map(int, input().split())
    if x < s:
        l.append((x, p))
    else:
        r.append((x, p))

print(solve(l, r))

Score : <var>1200</var> points

Problem Statement

There are <var>N</var> apartments along a number line, numbered <var>1</var> through <var>N</var>.
Apartment <var>i</var> is located at coordinate <var>X_i</var>.
Also, the office of AtCoder Inc. is located at coordinate <var>S</var>.
Every employee of AtCoder lives in one of the <var>N</var> apartments.
There are <var>P_i</var> employees who are living in Apartment <var>i</var>.

All employees of AtCoder are now leaving the office all together.
Since they are tired from work, they would like to get home by the company's bus.
AtCoder owns only one bus, but it can accommodate all the employees.
This bus will leave coordinate <var>S</var> with all the employees and move according to the following rule:

Everyone on the bus casts a vote on which direction the bus should proceed, positive or negative. (The bus is autonomous and has no driver.) Each person has one vote, and abstaining from voting is not allowed. Then, the bus moves a distance of <var>1</var> in the direction with the greater number of votes. If a tie occurs, the bus moves in the negative direction. If there is an apartment at the coordinate of the bus after the move, all the employees who live there get off.

Repeat the operation above as long as there is one or more employees on the bus.

For a specific example, see Sample Input 1.

The bus takes one seconds to travel a distance of <var>1</var>.
The time required to vote and get off the bus is ignorable.

Every employee will vote so that he himself/she herself can get off the bus at the earliest possible time.
Strictly speaking, when a vote is taking place, each employee see which direction results in the earlier arrival at his/her apartment, assuming that all the employees follow the same strategy in the future.
Based on this information, each employee makes the optimal choice, but if either direction results in the arrival at the same time, he/she casts a vote to the negative direction.

Find the time the bus will take from departure to arrival at the last employees' apartment.
It can be proved that, given the positions of the apartments, the numbers of employees living in each apartment and the initial position of the bus, the future movement of the bus is uniquely determined, and the process will end in a finite time.

Constraints

<var>1 \leq N \leq 10^5</var>

<var>1 \leq S \leq 10^9</var>

<var>1 \leq X_1 < X_2 < ... < X_N \leq 10^9</var>

<var>X_i \neq S</var> ( <var>1 \leq i \leq N</var> )

<var>1 \leq P_i \leq 10^9</var> ( <var>1 \leq i \leq N</var> )

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>S</var>
<var>X_1</var> <var>P_1</var>
<var>X_2</var> <var>P_2</var>
<var>:</var>
<var>X_N</var> <var>P_N</var>

Output

Print the number of seconds the bus will take from departure to arrival at the last employees' apartment.

Sample Input 1

3 2
1 3
3 4
4 2

Sample Output 1

4

Assume that the bus moves in the negative direction first.
Then, the coordinate of the bus changes from <var>2</var> to <var>1</var>, and the employees living in Apartment <var>1</var> get off.
The movement of the bus after that is obvious: it just continues moving in the positive direction.
Thus, if the bus moves in the negative direction first, the coordinate of the bus changes as <var>2 → 1 → 2 → 3 → 4</var> from departure.
The time it takes to get home for the employees living in Apartment <var>1</var>, <var>2</var>, <var>3</var> are <var>1</var>, <var>3</var>, <var>4</var> seconds, respectively.

Next, assume that the bus moves in the positive direction first.
Then, the coordinate of the bus changes from <var>2</var> to <var>3</var>, and the employees living in Apartment <var>2</var> get off.
Afterwards, the bus starts heading to Apartment <var>1</var>, because there are more employees living in Apartment <var>1</var> than in Apartment <var>3</var>.
Then, after arriving at Apartment <var>1</var>, the bus heads to Apartment <var>3</var>.
Thus, if the bus moves in the positive direction first, the coordinate of the bus changes as <var>2 → 3 → 2 → 1 → 2 → 3 → 4</var> from departure.
The time it takes to get home for the employees living in Apartment <var>1</var>, <var>2</var>, <var>3</var> are <var>3</var>, <var>1</var>, <var>6</var> seconds, respectively.

Therefore, in the beginning, the employees living in Apartment <var>1</var> or <var>3</var> will try to move the bus in the negative direction.
On the other hand, the employees living in Apartment <var>2</var> will try to move the bus in the positive direction in the beginning.
There are a total of <var>3 + 2 = 5</var> employees living in Apartment <var>1</var> and <var>3</var> combined, which is more than those living in Apartment <var>2</var>, which is <var>4</var>.
Thus, the bus will move in the negative direction first, and the coordinate of the bus will change as <var>2 → 1 → 2 → 3 → 4</var> from departure.

Sample Input 2

6 4
1 10
2 1000
3 100000
5 1000000
6 10000
7 100

Sample Output 2

21

Since the numbers of employees living in different apartments are literally off by a digit, the bus consistently head to the apartment where the most number of employees on the bus lives.

Sample Input 3

15 409904902
94198000 15017
117995501 7656764
275583856 313263626
284496300 356635175
324233841 607
360631781 148
472103717 5224
497641071 34695
522945827 816241
554305668 32
623788284 22832
667409501 124410641
876731548 12078
904557302 291749534
918215789 5

Sample Output 3

2397671583


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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    n,s = LI()
    a = [LI() for _ in range(n)]
    x = [_[0] for _ in a]
    p = [_[1] for _ in a]
    if x[0] > s:
        return x[-1] - s
    if x[-1] < s:
        return s - x[0]
    r = 0
    i = 0
    j = n - 1
    d = p[:]
    e = collections.defaultdict(list)
    sk = set()
    while i < j:
        if x[i] > s:
            break
        if x[j] < s:
            break
        if d[i] >= d[j]:
            d[i] += d[j]
            j -= 1
            if j >= 0 and d[j] < d[j+1]:
                d[j] = d[j+1]
                sk.add(i)
        else:
            d[j] += d[i]
            i += 1
            if i < n and d[i] < d[i-1]:
                d[i] = d[i-1]
                sk.add(i)
    t = s
    if i == j:
        r += abs(x[i]-s)
        t = x[i]
        i -= 1
        j += 1
    else:
        if x[i] > s:
            r += abs(x[j]-s)
            t = x[j]
            i -= 1
            j += 1
        else:
            r += abs(x[i]-s)
            t = x[i]
            i -= 1
            j += 1

    while i >= 0 or j < n:
        if i < 0:
            r += abs(x[-1]-t)
            break
        if j >= n:
            r += abs(x[0]-t)
            break
        if i in sk:
            d[i-1] = d[i]
            i-=1
            continue
        if j in sk:
            d[j+1] = d[j]
            J+=1
            continue

        if d[i] >= d[j]:
            r += abs(x[i]-t)
            t = x[i]
            i -= 1
        else:
            r += abs(x[j]-t)
            t = x[j]
            j += 1

    return r

print(main())


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

res = a*x + b*y
for i in range(1, max(x, y)+1):
    ab = i*2
    cand = ab*c + a*max(0, x-i) + b*max(0, y-i)

    res = min(res, cand)

print(res)

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

ans = a*x + b*y
for i in range(1, max(x,y)+1):
    C = 2*i*c + a*max(0,x-i) + b*max(0,y-i)
    ans = min(ans, C)
print(ans)

Score : <var>300</var> points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are <var>A</var> yen, <var>B</var> yen and <var>C</var> yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare <var>X</var> A-pizzas and <var>Y</var> B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

<var>1 ≤ A, B, C ≤ 5000</var>

<var>1 ≤ X, Y ≤ 10^5</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>C</var> <var>X</var> <var>Y</var>

Output

Print the minimum amount of money required to prepare <var>X</var> A-pizzas and <var>Y</var> B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy <var>200000</var> AB-pizzas and rearrange them into <var>100000</var> A-pizzas and <var>100000</var> B-pizzas. We will have <var>10000</var> more A-pizzas than necessary, but that is fine.


A,B,C,X,Y = map(int, input().split())
ans = X*A + Y*B
for i in range(max(X,Y)+1):
    C = 2*C*i + max(0,X-i)*A + max(0,Y-i)*B
    ans = min(ans, C)
print(ans)


n = int(input())
aa = sorted(list(map(int, input().split())))
list1 = []
ma = aa[-1]
for i in range(n):
  d = abs(aa[i]-(ma+1)//2)
  list1.append([d,i])
md = min(list1, key=lambda x:x[0])

print(ma, aa[md[1]])

Score : <var>400</var> points

Problem Statement

Let <var>{\rm comb}(n,r)</var> be the number of ways to choose <var>r</var> objects from among <var>n</var> objects, disregarding order.
From <var>n</var> non-negative integers <var>a_1, a_2, ..., a_n</var>, select two numbers <var>a_i > a_j</var> so that <var>{\rm comb}(a_i,a_j)</var> is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

<var>2 \leq n \leq 10^5</var>

<var>0 \leq a_i \leq 10^9</var>

<var>a_1,a_2,...,a_n</var> are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>n</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_n</var>

Output

Print <var>a_i</var> and <var>a_j</var> that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

<var>\rm{comb}(a_i,a_j)</var> for each possible selection is as follows:

<var>\rm{comb}(4,2)=6</var>

<var>\rm{comb}(6,2)=15</var>

<var>\rm{comb}(6,4)=15</var>

<var>\rm{comb}(9,2)=36</var>

<var>\rm{comb}(9,4)=126</var>

<var>\rm{comb}(9,6)=84</var>

<var>\rm{comb}(11,2)=55</var>

<var>\rm{comb}(11,4)=330</var>

<var>\rm{comb}(11,6)=462</var>

<var>\rm{comb}(11,9)=55</var>

Thus, we should print <var>11</var> and <var>6</var>.

Sample Input 2

2
100 0

Sample Output 2

100 0


n = int(input())
a = [int(x) for x in input().split()]
a.sort()
m = max(a) // 2
res = 0
for i in range(n-1):
  if abs(m - a[i]) < abs(res - a[i]):
    res = a[i]
print(max(a),res)


N = int(input())

print(0)
l = str(input())
if l == 'Vacant':
  exit()
print(N-1)
r = str(input())
if r == 'Vacant':
  exit()

left, right = 0, N-1
for i in range(20):
  n = (right+left) // 2
  print(n)
  a = str(input())
  if a == 'Vacant':
    exit()
  if (n-left) % 2 == 0:
    if l == a:
      left = n
    else:
      right = n
  else:
    if l == a:
      right = n
    else:
      left = n
      l = a

def apc001_c():
    import sys
    n = int(input())

    def ask(x:int):
        print(x)
        sys.stdout.flush()
        res = str(input())
        return res

    lower = 0
    seat_low = ask(lower)
    if seat_low == 'Vacant': return

    upper = n-1
    seat_up = ask(upper)
    if seat_up == 'Vacant': return

    while upper - lower > 1:
        x = (upper + lower) // 2
        s = ask(x)
        if s == 'Vacant': return
        if x % 2 == 0:
            if s == seat_low: lower = x
            else: upper = x
        else:
            if s == seat_up: lower = x
            else: upper = x

if __name__ == '__main__':
    apc001_c()

Score : <var>500</var> points

Problem Statement

This is an interactive task.

Let <var>N</var> be an odd number at least <var>3</var>.

There are <var>N</var> seats arranged in a circle.
The seats are numbered <var>0</var> through <var>N-1</var>.
For each <var>i</var> (<var>0 ≤ i ≤ N - 2</var>), Seat <var>i</var> and Seat <var>i + 1</var> are adjacent.
Also, Seat <var>N - 1</var> and Seat <var>0</var> are adjacent.

Each seat is either vacant, or oppupied by a man or a woman.
However, no two adjacent seats are occupied by two people of the same sex.
It can be shown that there is at least one empty seat where <var>N</var> is an odd number at least <var>3</var>.

You are given <var>N</var>, but the states of the seats are not given.
Your objective is to correctly guess the ID number of any one of the empty seats.
To do so, you can repeatedly send the following query:

Choose an integer <var>i</var> (<var>0 ≤ i ≤ N - 1</var>). If Seat <var>i</var> is empty, the problem is solved. Otherwise, you are notified of the sex of the person in Seat <var>i</var>.

Guess the ID number of an empty seat by sending at most <var>20</var> queries.

Constraints

<var>N</var> is an odd number.

<var>3 ≤ N ≤ 99</var> <var>999</var>

Input and Output

First, <var>N</var> is given from Standard Input in the following format:

<var>N</var>

Then, you should send queries.
A query should be printed to Standart Output in the following format.
Print a newline at the end.

<var>i</var>

The response to the query is given from Standard Input in the following format:

<var>s</var>

Here, <var>s</var> is Vacant, Male or Female.
Each of these means that Seat <var>i</var> is empty, occupied by a man and occupied by a woman, respectively.

Notice

Flush Standard Output each time you print something. Failure to do so may result in TLE.

Immediately terminate the program when <var>s</var> is Vacant. Otherwise, the verdict is indeterminate.

The verdict is indeterminate if more than <var>20</var> queries or ill-formatted queries are sent.

Sample Input / Output 1

In this sample, <var>N = 3</var>, and Seat <var>0</var>, <var>1</var>, <var>2</var> are occupied by a man, occupied by a woman and vacant, respectively.

Input	Output

3

	0

Male

	1

Female

	2

Vacant


N = int(input())

print(0)
l = str(input())
if l == 'Vacant':
  exit()

left, right = 0, N-1
for i in range(20):
  n = (right-left) // 2
  print(n)
  a = str(input())
  if a == 'Vacant':
    exit()
  if (n-left) % 2 == 0:
    if l == a:
      left = n
    else:
      right = n
  else:
    if l == a:
      right = n
    else:
      left = n
      l = a


K = int(input())
A = list(map(int,input().split()))
I = [[-1,-1] for _ in range(K+1)]
I[K] = [2,2]
fg = True
for i in range(K-1,-1,-1):
    #consider range I[i]
    left = A[i]*((I[i+1][0]+A[i]-1)//A[i])
    I[i][0] = max(A[i],left)
    I[i][1] = A[i]*(I[i+1][1]//A[i] + 1) -1
    #print(i,*I[i])
    if(I[i][0] > I[i][1]):
        fg = False
        #break
if(not fg):
    print(-1)
else:
    print(*I[0])

K = int(input())
A = list(map(int,input().split()))
I = [[-1,-1] for _ in range(K+1)]
I[K] = [2,2]
fg = True
for i in range(K-1,-1,-1):
    #consider range I[i]
    left = A[i]*((I[i+1][0]+A[i]-1)//A[i])
    I[i][0] = max(A[i],left)
    I[i][1] = A[i]*(I[i+1][1]//A[i] + 1) -1
    #print(i,*I[i])
    if(I[i][0] > I[i][1]):
        fg = False
        break
if(not fg):
    print(-1)
else:
    print(*I[0])

Score : <var>500</var> points

Problem Statement

An adult game master and <var>N</var> children are playing a game on an ice rink.
The game consists of <var>K</var> rounds.
In the <var>i</var>-th round, the game master announces:

Form groups consisting of <var>A_i</var> children each!

Then the children who are still in the game form as many groups of <var>A_i</var> children as possible.
One child may belong to at most one group.
Those who are left without a group leave the game. The others proceed to the next round.
Note that it's possible that nobody leaves the game in some round.

In the end, after the <var>K</var>-th round, there are exactly two children left, and they are declared the winners.

You have heard the values of <var>A_1</var>, <var>A_2</var>, ..., <var>A_K</var>. You don't know <var>N</var>, but you want to estimate it.

Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of <var>N</var> exist.

Constraints

<var>1 \leq K \leq 10^5</var>

<var>2 \leq A_i \leq 10^9</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_K</var>

Output

Print two integers representing the smallest and the largest possible value of <var>N</var>, respectively,
or a single integer <var>-1</var> if the described situation is impossible.

Sample Input 1

4
3 4 3 2

Sample Output 1

6 8

For example, if the game starts with <var>6</var> children, then it proceeds as follows:

In the first round, <var>6</var> children form <var>2</var> groups of <var>3</var> children, and nobody leaves the game.

In the second round, <var>6</var> children form <var>1</var> group of <var>4</var> children, and <var>2</var> children leave the game.

In the third round, <var>4</var> children form <var>1</var> group of <var>3</var> children, and <var>1</var> child leaves the game.

In the fourth round, <var>3</var> children form <var>1</var> group of <var>2</var> children, and <var>1</var> child leaves the game.

The last <var>2</var> children are declared the winners.

Sample Input 2

5
3 4 100 3 2

Sample Output 2

-1

This situation is impossible.
In particular, if the game starts with less than <var>100</var> children, everyone leaves after the third round.

Sample Input 3

10
2 2 2 2 2 2 2 2 2 2

Sample Output 3

2 3


import math
K = int(input())
A = list(map(int, input().split()))
def check(init, A):
    cnt = init
    for a in A:
        group = cnt // a
        cnt = group * a
    return cnt

l,r = 2, 2**100
while r-l > 1:
    mid = (l+r)//2
    if check(mid, A) >= 2:
        r = mid
    else:
        l = mid
mincnt = r

l,r = 2, 2**100
while r-l > 1:
    mid = (l+r)//2
    if check(mid, A) <= 2:
        l = mid
    else:
        r = mid
maxcnt = l

if check(mincnt, A) == check(maxcnt, A) == 2:
    print(mincnt, maxcnt)
else:
    print(-1)


Score : <var>100</var> points

Problem Statement

How many hours do we have until New Year at <var>M</var> o'clock (24-hour notation) on <var>30</var>th, December?

Constraints

<var>1≤M≤23</var>

<var>M</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>M</var>

Output

If we have <var>x</var> hours until New Year at <var>M</var> o'clock on <var>30</var>th, December, print <var>x</var>.

Sample Input 1

21

Sample Output 1

27

We have <var>27</var> hours until New Year at <var>21</var> o'clock on <var>30</var>th, December.

Sample Input 2

12

Sample Output 2

36


import re
A, B = map(int, input().split())
S = input()

ans = 'No'
p = '\d{' + str(A) + '}-\d{' + str(B) + '}'
if re.match(p, S):
    ans = 'Yes'
print(ans)

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

if ("-" in s) and s.count("-") == 1:
    s = s.split("-")
    if len(s[0]) == (a) and len(s[1]) == b:
        print("Yes")
    else:
        print("No")

else:
    print("No")

Score : <var>200</var> points

Problem Statement

The postal code in Atcoder Kingdom is <var>A+B+1</var> characters long, its <var>(A+1)</var>-th character is a hyphen -, and the other characters are digits from 0 through 9.

You are given a string <var>S</var>. Determine whether it follows the postal code format in Atcoder Kingdom.

Constraints

<var>1≤A,B≤5</var>

<var>|S|=A+B+1</var>

<var>S</var> consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var>
<var>S</var>

Output

Print Yes if <var>S</var> follows the postal code format in AtCoder Kingdom; print No otherwise.

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

The <var>(A+1)</var>-th character of <var>S</var> is -, and the other characters are digits from 0 through 9, so it follows the format.

Sample Input 2

1 1
---

Sample Output 2

No

<var>S</var> contains unnecessary -s other than the <var>(A+1)</var>-th character, so it does not follow the format.

Sample Input 3

1 2
7444

Sample Output 3

No


import re
a,b= map(int, input().split())
s = input()

m = re.search(r'\d{1,5}-\d{1,5}',s)
if m is None:
    print("No")
else:
    print("Yes")


#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)

s = list(str(input()))

max_ = len(s)
for i in range(len(s)-1):
    if s[i] != s[i+1]:
        left = i+1
        right = len(s)-left
        # print(left, right)
        tmp = max(left, right)

        max_ = min(max_, tmp)
print(max_)

def main():
    S = input()
    l = len(S)
    ans = l
    #データ加工
    for i, s in enumerate(S[1:]):
        if s != S[i]:
            ans = min(ans, max(i+1, l-1-i))
    print(ans)

main()

Score : <var>500</var> points

Problem Statement

You are given a string <var>S</var> consisting of 0 and 1.
Find the maximum integer <var>K</var> not greater than <var>|S|</var> such that we can turn all the characters of <var>S</var> into 0 by repeating the following operation some number of times.

Choose a contiguous segment <var>[l,r]</var> in <var>S</var> whose length is at least <var>K</var> (that is, <var>r-l+1\geq K</var> must be satisfied). For each integer <var>i</var> such that <var>l\leq i\leq r</var>, do the following: if <var>S_i</var> is 0, replace it with 1; if <var>S_i</var> is 1, replace it with 0.

Constraints

<var>1\leq |S|\leq 10^5</var>

<var>S_i(1\leq i\leq N)</var> is either 0 or 1.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the maximum integer <var>K</var> such that we can turn all the characters of <var>S</var> into 0 by repeating the operation some number of times.

Sample Input 1

010

Sample Output 1

2

We can turn all the characters of <var>S</var> into 0 by the following operations:

Perform the operation on the segment <var>S[1,3]</var> with length <var>3</var>. <var>S</var> is now 101.

Perform the operation on the segment <var>S[1,2]</var> with length <var>2</var>. <var>S</var> is now 011.

Perform the operation on the segment <var>S[2,3]</var> with length <var>2</var>. <var>S</var> is now 000.

Sample Input 2

100000000

Sample Output 2

8

Sample Input 3

00001111

Sample Output 3

4


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

S = input()

lis = []

tmp = S[0]
cnt = 0

for s in S:
	if s == tmp:
		cnt += 1
	else:
		lis.append(cnt)
		tmp = s
		cnt = 1
lis.append(cnt)

lis_acc = list(accumulate(lis))

ans = 0
for i in range(len(lis)-1):
	tmp = min(max(lis_acc[i], lis_acc[-1]-lis_acc[i]), lis[i]+lis[i+1])
	ans = max(ans, tmp)

if len(lis) == 1:
	print(lis[0])
else:
	print(ans)


#!python3

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

def judge(l, m):
    s = sum(l)
    t = s - m if m > 0 else s + m
    if t < 0 or t % 2 == 1:
        return False

    t //= 2
    n = len(l)
    w = [[False] * (t + 1) for _ in range(n + 1)]
    w[0][0] = True
    for i in range(1, n + 1):
        for j in range(t + 1):
            if w[i - 1][j]:
                w[i][j] = True
                if j + l[i - 1] <= t:
                    w[i][j + l[i - 1]] = True

    return w[-1][-1]

def main():
    n = len(S)
    d = 0
    for s in S:
        if s == "F":
            d += 1
        else:
            break

    dx, dy = [], []
    side = True
    i = d
    while i < n:
        # change
        while i < n and S[i] == "T":
            side = not side
            i += 1

        # forward
        c = 0
        while i < n and S[i] == "F":
            c += 1
            i += 1
        if side:
            dx.append(c)
        else:
            dy.append(c)

    b1 = judge(dx, X - d)
    b2 = judge(dy, Y)
    ans = "Yes" if b1 and b2 else "No"
    print(ans)

if __name__ == "__main__":
    main()

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

D = map(len, S.split("T"))
X, Y = {next(D)}, {0}
for i, d in enumerate(D, 1):
    if i % 2 == 0:
        X = {x + d for x in X} | {x - d for x in X}
    else:
        Y = {y + d for y in Y} | {y - d for y in Y}

if x in X and y in Y:
    print("Yes")
else:
    print("No")

Score : <var>500</var> points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive <var>x</var>-axis direction.

This robot will be given an instruction sequence <var>s</var>.
<var>s</var> consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance <var>1</var>.

T : Turn <var>90</var> degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates <var>(x, y)</var> after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

<var>s</var> consists of F and T.

<var>1 \leq |s| \leq 8</var> <var>000</var>

<var>x</var> and <var>y</var> are integers.

<var>|x|, |y| \leq |s|</var>

Input

Input is given from Standard Input in the following format:

<var>s</var>
<var>x</var> <var>y</var>

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


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

class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N #parent[i] は(i+1)番目の要素が含まれる要素数の(-1)倍
    #要素が負-->その数を親とするグループに属する要素の数×(-1)
    #要素が正-->親のindex

    #Aがどのグループに属しているかを調べる
    def root(self, A):
        if self.parent[A-1] < 0: #負の数-->その数は親
            return A
        self.parent[A-1] = self.root(self.parent[A-1]) #負では無い時、親の場所が入っているから、親が属しているグループを、自分自身に入れる(一度確認したところは直接親を見れるようにする)
        return self.parent[A-1] #親の位置を返す

    #Aが含まれているグループに属している数を返す
    def size(self, A):
        return -1 * self.parent[self.root(A)-1]

    #AとBをくっ付ける
    def connect(self, A, B):
        A = self.root(A) #Aを含むグループの親を返す
        B = self.root(B) #Bを含むグループの親を返す
        if A == B: #親が同じならなにもしない
            return False

        #大きい方(A)に小さい方(B)をつなぎたい
        if self.size(A) < self.size(B): #大小関係が逆の時は入れ替える
            A, B = B, A

        self.parent[A-1] += self.parent[B-1] #大きい方に小さい方を加える　（負の数＋負の数 = 新しいグループに含まれる数×(-1)）
        self.parent[B-1] = A #加えられた親の値を、加えた先の親の位置に書き変える
        return True

    def same(self, A, B):
        if self.root(A) == self.root(B):
            return True
        else:
            return False

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

uni = UnionFind(N)
for _ in range(M):
    a, b = map(int, input().split())
    uni.connect(a, b)

group1 = uni.size(1)
group2 = uni.size(2)

other = 0 #どっちとも繋がっていない頂点の数
for i in range(3, N + 1):
    # print ('親', uni.root(i))
    if (uni.same(1, i)):
        continue
    if (uni.same(2, i)):
        continue
    other += 1

#片方に固めたほうが良い？
if group1 < group2:
    group2 += other
else:
    group1 += other

# print (group1, group2)
ans = group1 * (group1 - 1) // 2 + group2 * (group2 - 1) // 2 - M
print (ans)
# print (uni.parent)

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)  # -1ならそのノードが根,で絶対値が木の要素数
        self.rank = [0] * (n + 1)

    def find(self, x):  # xの根となる要素番号を返す
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def isSame(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        elif self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def size(self, x):
        return -self.root[self.find(x)]

if __name__ == "__main__":
    N, M = map(int, input().split())
    uf = UF_tree(N)
    edge = [0] * (N + 1)
    for _ in range(M):
        a, b = map(int, input().split())
        uf.unite(a, b)
        edge[a] += 1
        edge[b] += 1

    x_root = uf.size(1)
    y_root = uf.size(2)
    if x_root < y_root:
        t = 2
    else:
        t = 1

    ans = 0
    other = N - uf.size(1) - uf.size(2)  # 1とも2ともつながってないやつ
    for x in range(1, N + 1):
        if uf.isSame(x, 1):
            if t == 2:
                other_v = 0
            else:
                other_v = other
            self_v = uf.size(1) - edge[x] - 1
            ans += other_v + self_v
        elif uf.isSame(x, 2):
            if t == 1:
                other_v = 0
            else:
                other_v = other
            self_v = uf.size(2) - edge[x] - 1
            ans += other_v + self_v
        else:
            root_v = uf.size(t)
            other_v = other - edge[x] - 1
            ans += other_v + root_v

    print(ans//2)

Score : <var>100</var> points

Problem Statement

You are given an undirected graph <var>G</var>. <var>G</var> has <var>N</var> vertices and <var>M</var> edges. The vertices are numbered from <var>1</var> through <var>N</var>, and the <var>i</var>-th edge <var>(1 ≤ i ≤ M)</var> connects Vertex <var>a_i</var> and <var>b_i</var>. <var>G</var> does not have self-loops and multiple edges.

You can repeatedly perform the operation of adding an edge between two vertices. However, <var>G</var> must not have self-loops or multiple edges as the result. Also, if Vertex <var>1</var> and <var>2</var> are connected directly or indirectly by edges, your body will be exposed to a voltage of <var>1000000007</var> volts. This must also be avoided.

Under these conditions, at most how many edges can you add? Note that Vertex <var>1</var> and <var>2</var> are never connected directly or indirectly in the beginning.

Constraints

<var>2 ≤ N ≤ 10^5</var>

<var>0 ≤ M ≤ 10^5</var>

<var>1 ≤ a_i < b_i ≤ N</var>

All pairs <var>(a_i, b_i)</var> are distinct.

Vertex <var>1</var> and <var>2</var> in <var>G</var> are not connected directly or indirectly by edges.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_M</var> <var>b_M</var>

Output

Print the maximum number of edges that can be added.

Sample Input 1

4 1
1 3

Sample Output 1

2

As shown above, two edges can be added. It is not possible to add three or more edges.

Sample Input 2

2 0

Sample Output 2

0

No edge can be added.

Sample Input 3

9 6
1 4
1 8
2 5
3 6
4 8
5 7

Sample Output 3

12


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

class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N #parent[i] は(i+1)番目の要素が含まれる要素数の(-1)倍
    #要素が負-->その数を親とするグループに属する要素の数×(-1)
    #要素が正-->親のindex

    #Aがどのグループに属しているかを調べる
    def root(self, A):
        if self.parent[A-1] < 0: #負の数-->その数は親
            return A
        self.parent[A-1] = self.root(self.parent[A-1]) #負では無い時、親の場所が入っているから、親が属しているグループを、自分自身に入れる(一度確認したところは直接親を見れるようにする)
        return self.parent[A-1] #親の位置を返す

    #Aが含まれているグループに属している数を返す
    def size(self, A):
        return -1 * self.parent[self.root(A)-1]

    #AとBをくっ付ける
    def connect(self, A, B):
        A = self.root(A) #Aを含むグループの親を返す
        B = self.root(B) #Bを含むグループの親を返す
        if A == B: #親が同じならなにもしない
            return False

        #大きい方(A)に小さい方(B)をつなぎたい
        if self.size(A) < self.size(B): #大小関係が逆の時は入れ替える
            A, B = B, A

        self.parent[A-1] += self.parent[B-1] #大きい方に小さい方を加える　（負の数＋負の数 = 新しいグループに含まれる数×(-1)）
        self.parent[B-1] = A #加えられた親の値を、加えた先の親の位置に書き変える
        return True

    def same(self, A, B):
        if self.root(A) == self.root(B):
            return True
        else:
            return False

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

uni = UnionFind(N)
for _ in range(M):
    a, b = map(int, input().split())
    uni.connect(a, b)

group1 = uni.size(1)
group2 = uni.size(2)

other = 0 #どっちとも繋がっていない頂点の数
for i in range(3, N + 1):
    # print ('親', uni.root(i))
    if uni.root(i) > 2:
        other += 1

#片方に固めたほうが良い？
if group1 < group2:
    group2 += other
else:
    group1 += other

if group1 + group2 != N:
    print ('error')
# print (group1, group2)
ans = group1 * (group1 - 1) // 2 + group2 * (group2 - 1) // 2 - M
print (ans)
# print (uni.parent)


import math
import numpy as np
import decimal
import collections
import itertools
import sys
import random
#Union-Find
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.par = [-1 for i in range(self.n)]
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    def unite(self, x, y):
        p = self.find(x)
        q = self.find(y)
        if p == q:
            return None
        if p > q:
            p, q = q, p
        self.par[p] += self.par[q]
        self.par[q] = p
    def same(self, x, y):
        return self.find(x) == self.find(y)
    def size(self, x):
        return -self.par[self.find(x)]

#素数関連
def prime_numbers(x):
    if x < 2:
        return []
    prime_numbers = [i for i in range(x)]
    prime_numbers[1] = 0
    for prime_number in prime_numbers:
        if prime_number > math.sqrt(x):
            break
        if prime_number == 0:
            continue
        for composite_number in range(2 * prime_number, x, prime_number):
            prime_numbers[composite_number] = 0
    return [prime_number for prime_number in prime_numbers if prime_number != 0]
def is_prime(x):
    if x < 2:
        return False
    if x == 2 or x == 3 or x == 5:
        return True
    if x % 2 == 0 or x % 3 == 0 or x % 5 == 0:
        return False
    prime_number = 7
    difference = 4
    while prime_number <= math.sqrt(x):
        if x % prime_number == 0:
            return False
        prime_number += difference
        difference = 6 - difference
    return True
#Prime-Factorize
def prime_factorize(n):
    res = []
    while n % 2 == 0:
        res.append(2)
        n //= 2
    f = 3
    while f ** 2 <= n:
        if n % f == 0:
            res.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        res.append(n)
    return res
#nCr
mod = 10 ** 9 + 7
class nCr():
    def __init__(self, n):
        self.n = n
        self.fa = [1] * (self.n + 1)
        self.fi = [1] * (self.n + 1)
        for i in range(1, self.n + 1):
            self.fa[i] = self.fa[i - 1] * i % mod
            self.fi[i] = pow(self.fa[i], mod - 2, mod)
    def comb(self, n, r):
        if n < r:return 0
        if n < 0 or r < 0:return 0
        return self.fa[n] * self.fi[r] % mod * self.fi[n - r] % mod
#拡張Euclidの互除法
def extgcd(a, b, d = 0):
    g = a
    if b == 0:
        x, y = 1, 0
    else:
        x, y, g = extgcd(b, a % b)
        x, y = y, x - a // b * y
    return x, y, g
#BIT
class BinaryIndexedTree():
    def __init__(self, n):
        self.n = n
        self.BIT = [0] * (self.n + 1)
    def add(self, i, x):
        while i <= self.n:
            self.BIT[i] += x
            i += i & -i
    def query(self, i):
        res = 0
        while i > 0:
            res += self.BIT[i]
            i -= i & -i
        return res
#Associative Array
class AssociativeArray():
    def __init__(self, q):
        self.dic = dict()
        self.q = q
    def solve(self):
        for i in range(self.q):
            Query = list(map(int, input().split()))
            if Query[0] == 0:
                x, y, z = Query
                self.dic[y] = z
            else:
                x, y = Query
                if y in self.dic:
                    print(self.dic[y])
                else:
                    print(0)
#Floor Sum
def floor_sum(n, m, a, b):
    res = 0
    if a >= m:
        res += (n - 1) * n * (a // m) // 2
        a %= m
    if b >= m:
        res += n * (b // m)
        b %= m
    y_max = (a * n + b) // m
    x_max = y_max * m - b
    if y_max == 0:
        return res
    res += y_max * (n + (-x_max // a))
    res += floor_sum(y_max, a, m, (a - x_max % a) % a)
    return res
#Z-Algorithm
def z_algorithm(s):
    str_len = len(s)
    res = [0] * str_len
    res[str_len - 1] = str_len
    i, j = 1, 0
    while i < str_len:
        while i + j < str_len and s[i + j] == s[j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i + k < str_len and j > res[k] + k:
            res[i + k] = res[k]
            k += 1
        i += k
        j -= k
    return res
class Manacher():
    def __init__(self, s):
        self.s = s
    def coustruct(self):
        i, j = 0, 0
        s_len = len(self.s)
        res = [0] * s_len
        while i < s_len:
            while i - j >= 0 and i + j < s_len and self.s[i - j] == self.s[i + j]:
                j += 1
            res[i] = j
            k = 1
            while i - k >= 0 and k + res[i - k] < j:
                k += 1
            i += k
            j -= k
#mod-sqrt
def mod_sqrt(a, p):
    if a == 0:
        return 0
    if p == 2:
        return 1
    k = (p - 1) // 2
    if pow(a, k, p) != 1:
        return -1
    while True:
        n = random.randint(2, p - 1)
        r = (n ** 2 - a) % p
        if r == 0:
            return n
        if pow(r, k, p) == p - 1:
            break
    k += 1
    w, x, y, z = n, 1, 1, 0
    while k:
        if k % 2:
            y, z = w * y + r * x * z, x * y + w * z
        w, x = w * w + r * x * x, 2 * w * x
        w %= p
        x %= p
        y %= p
        z %= p
        k >>= 1
    return y
n = int(input())
t = list(map(int, input().split()))
v = list(map(int, input().split()))
s_t = sum(t)
ans = [0]
for i in range(n):
    ans[-1] = min(ans[-1], v[i])
    for j in range(t[i] * 2):
        ans.append(v[i])
ans.pop()
ans.append(0)
for i in range(1, s_t * 2 + 1):
    ans[i] = min(ans[i - 1] + 1 / 2, ans[i])
for i in range(1, s_t * 2 + 1)[::-1]:
    ans[i - 1] = min(ans[i] + 1 / 2, ans[i - 1])
print(sum(ans) / 2)

from collections import deque

def main():
    with open(0) as f:
        N, *Temp = map(int, f.read().split())
        T, V = Temp[:N], Temp[N:]
        del Temp
    #v-tグラフを仮定して、各区間の境界条件を求める
    v_left = deque([0]) #初期時刻から走査した結果
    v_right = deque([0]) #終了時刻から走査した結果
    #区間i(1<=i<=N)の境界条件は [min(vin[i-1], vout[i-1]), max(vin[i], vout[i])
    #走査処理
    now = 0
    for t,v in zip(T, V):
        now = min(now+t, v)
        v_left.append(now)
    now = 0
    for t, v in zip(reversed(T), reversed(V)):
        now = min(now+t, v)
        v_right.appendleft(now)

    BC = [min(x,y) for x,y in zip(v_left, v_right)] #境界条件
    #区間ごとに2倍の面積計算
    S = [squareMeasure(vin, vout, vsup, t) for vin, vout, vsup, t in zip(BC[:N], BC[1:], V, T)]
    ans = sum(S)/2
    print(ans)

def squareMeasure(vin, vout, vsup, t):
    vmax = (t+vout+vin)/2 #y=x+vinとy=-x+t+vout の交点のy
    if vmax > vsup:
        a, b = vsup-vin, t+vout-vsup #y=vsupと2直線の交点
        S = (vin+vsup)*a + 2*(b-a)*vsup + (vsup+vout)*(t-b)
    else:
        S = (vin+vmax)*(vmax-vin) + (vmax+vout)*(t+vin-vmax)
    return S #2倍の面積である

if __name__ == '__main__':
    main()

Score : <var>400</var> points

Problem Statement

In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.

In the plan developed by the president Takahashi, the trains will run as follows:

A train will run for <var>(t_1 + t_2 + t_3 + ... + t_N)</var> seconds.

In the first <var>t_1</var> seconds, a train must run at a speed of at most <var>v_1</var> m/s (meters per second). Similarly, in the subsequent <var>t_2</var> seconds, a train must run at a speed of at most <var>v_2</var> m/s, and so on.

According to the specifications of the trains, the acceleration of a train must be always within <var>±1m/s^2</var>. Additionally, a train must stop at the beginning and the end of the run.

Find the maximum possible distance that a train can cover in the run.

Constraints

<var>1 \leq N \leq 100</var>

<var>1 \leq t_i \leq 200</var>

<var>1 \leq v_i \leq 100</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>t_1</var> <var>t_2</var> <var>t_3</var> … <var>t_N</var>
<var>v_1</var> <var>v_2</var> <var>v_3</var> … <var>v_N</var>

Output

Print the maximum possible that a train can cover in the run.

Output is considered correct if its absolute difference from the judge's output is at most <var>10^{-3}</var>.

Sample Input 1

1
100
30

Sample Output 1

2100.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>30</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>450</var> meters.

In the subsequent <var>40</var> seconds, it maintains the velocity of <var>30m/s</var>, covering <var>1200</var> meters.

In the last <var>30</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>450</var> meters.

The total distance covered is <var>450</var> + <var>1200</var> + <var>450</var> = <var>2100</var> meters.

Sample Input 2

2
60 50
34 38

Sample Output 2

2632.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>34</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>578</var> meters.

In the subsequent <var>26</var> seconds, it maintains the velocity of <var>34m/s</var>, covering <var>884</var> meters.

In the subsequent <var>4</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>144</var> meters.

In the subsequent <var>8</var> seconds, it maintains the velocity of <var>38m/s</var>, covering <var>304</var> meters.

In the last <var>38</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>722</var> meters.

The total distance covered is <var>578</var> + <var>884</var> + <var>144</var> + <var>304</var> + <var>722</var> = <var>2632</var> meters.

Sample Input 3

3
12 14 2
6 2 7

Sample Output 3

76.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>6</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>18</var> meters.

In the subsequent <var>2</var> seconds, it maintains the velocity of <var>6m/s</var>, covering <var>12</var> meters.

In the subsequent <var>4</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>16</var> meters.

In the subsequent <var>14</var> seconds, it maintains the velocity of <var>2m/s</var>, covering <var>28</var> meters.

In the last <var>2</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>2</var> meters.

The total distance covered is <var>18</var> + <var>12</var> + <var>16</var> + <var>28</var> + <var>2</var> = <var>76</var> meters.

Sample Input 4

1
9
10

Sample Output 4

20.250000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>4.5</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>10.125</var> meters.

In the last <var>4.5</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>10.125</var> meters.

The total distance covered is <var>10.125</var> + <var>10.125</var> = <var>20.25</var> meters.

Sample Input 5

10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70

Sample Output 5

20291.000000000000


import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N = I()
t = LI()
v = LI()

max_v = [0]*(N+1)  # 0秒後,t1秒後,t1+t2秒後,…の時点で出せる最大速度
for i in range(N-1):
    max_v[i+1] = min(v[i+1],max_v[i]+t[i])
for i in range(N-2,-1,-1):
    max_v[i+1] = min(max_v[i+1],v[i],max_v[i+2]+t[i+1])

ans = 0
for i in range(N):
    if t[i] >= (v[i]-max_v[i]) + (v[i]-max_v[i+1]):
        ans += t[i]*v[i]-(v[i]-max_v[i])**2/2-(v[i]-max_v[i+1])**2/2
    else:
        x = (t[i]+max_v[i]+max_v[i+1])/2
        ans += t[i]*x-(x-max_v[i])**2/2-(x-max_v[i+1])**2/2

print(ans)


N = int(input())
K = int(input())
X = list(map(int, input().split()))
Y = [i for i in range(1, N+1)]
ans = 0

for x in X:
    distance_a = x
    distance_b = abs(K-x)
    if distance_a < distance_b:
        ans += distance_a
    else:
        ans += distance_b

print(ans*2)

def int_list(sepalate=" "): return list(map(int, input().split(sepalate)))

def solve1(n, k, x):
    ans = 0

    for i in range(n):
        ans += min(abs(k-x[i]), x[i]) * 2

    return ans

n = int(input())
k = int(input())
x = int_list()
print(solve1(n, k, x))

Score : <var>200</var> points

Problem Statement

There are <var>N</var> balls in the <var>xy</var>-plane. The coordinates of the <var>i</var>-th of them is <var>(x_i, i)</var>.
Thus, we have one ball on each of the <var>N</var> lines <var>y = 1</var>, <var>y = 2</var>, <var>...</var>, <var>y = N</var>.

In order to collect these balls, Snuke prepared <var>2N</var> robots, <var>N</var> of type A and <var>N</var> of type B.
Then, he placed the <var>i</var>-th type-A robot at coordinates <var>(0, i)</var>, and the <var>i</var>-th type-B robot at coordinates <var>(K, i)</var>.
Thus, now we have one type-A robot and one type-B robot on each of the <var>N</var> lines <var>y = 1</var>, <var>y = 2</var>, <var>...</var>, <var>y = N</var>.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates <var>(0, a)</var>, it will move to the position of the ball on the line <var>y = a</var>, collect the ball, move back to its original position <var>(0, a)</var> and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates <var>(K, b)</var>, it will move to the position of the ball on the line <var>y = b</var>, collect the ball, move back to its original position <var>(K, b)</var> and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Snuke will activate some of the <var>2N</var> robots to collect all of the balls. Find the minimum possible total distance covered by robots.

Constraints

<var>1 \leq N \leq 100</var>

<var>1 \leq K \leq 100</var>

<var>0 < x_i < K</var>

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

<var>N</var>
<var>K</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Outputs

Print the minimum possible total distance covered by robots.

Sample Input 1

1
10
2

Sample Output 1

4

There are just one ball, one type-A robot and one type-B robot.

If the type-A robot is used to collect the ball, the distance from the robot to the ball is <var>2</var>, and the distance from the ball to the original position of the robot is also <var>2</var>, for a total distance of <var>4</var>.

Similarly, if the type-B robot is used, the total distance covered will be <var>16</var>.

Thus, the total distance covered will be minimized when the type-A robot is used. The output should be <var>4</var>.

Sample Input 2

2
9
3 6

Sample Output 2

12

The total distance covered will be minimized when the first ball is collected by the type-A robot, and the second ball by the type-B robot.

Sample Input 3

5
20
11 12 9 17 12

Sample Output 3

74


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

for p in x:
  a = 2*p
  b = 2*abs(K-p)
  if a > b:
    sum_min += b
  elif a < b:
    sum_min += a

print(sum_min)


n=int(input())
hito=0
for i in range(n):
    l,r=map(int, input().split())
    hito+=r-l+1
print(hito)

from typing import List

def answer(n: int, lrs: List[List[int]]) -> int:
    number_of_people_sitting = 0
    for lr in lrs:
        l, r = lr
        number_of_people_sitting += r - l + 1

    return number_of_people_sitting

def main():
    n = int(input())
    lrs = [map(int, input().split()) for _ in range(n)]
    print(answer(n, lrs))

if __name__ == '__main__':
    main()

Score : <var>200</var> points

Problem Statement

Joisino is working as a receptionist at a theater.

The theater has <var>100000</var> seats, numbered from <var>1</var> to <var>100000</var>.

According to her memo, <var>N</var> groups of audiences have come so far, and the <var>i</var>-th group occupies the consecutive seats from Seat <var>l_i</var> to Seat <var>r_i</var> (inclusive).

How many people are sitting at the theater now?

Constraints

<var>1≤N≤1000</var>

<var>1≤l_i≤r_i≤100000</var>

No seat is occupied by more than one person.

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>l_1</var> <var>r_1</var>
<var>:</var>
<var>l_N</var> <var>r_N</var>

Output

Print the number of people sitting at the theater.

Sample Input 1

1
24 30

Sample Output 1

7

There are <var>7</var> people, sitting at Seat <var>24,25,26,27,28,29</var> and <var>30</var>.

Sample Input 2

2
6 8
3 3

Sample Output 2

4


n = int(input())
flg = [0]*100000
for _ in range(n):
    l,r = map(int,input().split())
    flg[l:r+1] = []
print(100000-len(flg))


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

def main():
    q,h,s,d = map(int,input().split())
    n = int(input())
    q=4*q
    h=2*h
    sp1=min(q,h,s)
    dp2=min(2*q,2*h,2*s,d)
    c=n//2
    if n%2==0:
        print(c*dp2)
    else:
        print(c*dp2+sp1)

if __name__=="__main__":
    main()

Score : <var>300</var> points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a <var>0.25</var>-liter bottle costs <var>Q</var> yen, a <var>0.5</var>-liter bottle costs <var>H</var> yen, a <var>1</var>-liter bottle costs <var>S</var> yen, and a <var>2</var>-liter bottle costs <var>D</var> yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly <var>N</var> liters of ice tea. How many yen do you have to spend?

Constraints

<var>1 \leq Q, H, S, D \leq 10^8</var>

<var>1 \leq N \leq 10^9</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>Q</var> <var>H</var> <var>S</var> <var>D</var>
<var>N</var>

Output

Print the smallest number of yen you have to spend to buy exactly <var>N</var> liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one <var>2</var>-liter bottle and two <var>0.5</var>-liter bottles. You'll get <var>3</var> liters for <var>90 + 30 + 30 = 150</var> yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a <var>2</var>-liter bottle costs just <var>10</var> yen, you need only <var>1</var> liter.
Thus, you have to buy a <var>1</var>-liter bottle for <var>100</var> yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four <var>0.25</var>-liter bottles for <var>10 + 10 + 10 + 10 = 40</var> yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942


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

def main():
    q,h,s,d = map(int,input().split())
    n = int(input())
    q=4*q
    h=2*h
    sp1=min(q,h,s)
    dp2=min(2*q,2*h,2*s,d)

    if n==1:
        print(sp1)
    elif n%2==0:
        print(n*dp2)
    else:
        c=n//2
        print(c*dp2+sp1)

if __name__=="__main__":
    main()


Score : <var>400</var> points

Problem Statement

We have a board with a <var>2 \times N</var> grid.
Snuke covered the board with <var>N</var> dominoes without overlaps.
Here, a domino can cover a <var>1 \times 2</var> or <var>2 \times 1</var> square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo <var>1000000007</var>.

The arrangement of the dominoes is given to you as two strings <var>S_1</var> and <var>S_2</var> in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The <var>j</var>-th character in <var>S_i</var> represents the domino that occupies the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left.

Constraints

<var>1 \leq N \leq 52</var>

<var>|S_1| = |S_2| = N</var>

<var>S_1</var> and <var>S_2</var> consist of lowercase and uppercase English letters.

<var>S_1</var> and <var>S_2</var> represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>S_2</var>

Output

Print the number of such ways to paint the dominoes, modulo <var>1000000007</var>.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902


mod = 10**9+7
n = int(input())
s1 = input() + '@'
s2 = input() + '@'

p = []
i = 0
while i<n:
  if s1[i]==s1[i+1]:
    p.append(2)
    i+=1
  else:
    p.append(1)
  i+=1

if p[0] == 1:
  ans = 3
  i = 1
else:
  ans = 6
  i = 2

while i<len(p):
  if p[i-1]==2 and p[i] == 1:
    pass
  elif p[i-1]==2 and p[i] == 2:
    ans = (3*ans)%mod
  else:
    ans = (2*ans)%mod
  i+=1
print(ans)


H, W = map(int, input().split())
N = int(input())
A = list(map(int, input().split()))
ans = [[0]*W for _ in range(H)]
h = 0
w = 0
for i, a in enumerate(A):
    for _ in range(a):
        if w == W:
            h += 1
            w = 0

        if h % 2 != 0:
            ind = W-w-1
        else:
            ind = w
        ans[h][ind] = i+1
        w += 1
for _ in range(H):
    print(*ans[_])

H,W = map(int,input().split())
N = int(input())
a = list(map(int,input().split()))
b = []
for i in range(N):
    for j in range(a[i]):
        b.append(i+1)
s = 0
for i in range(H):
    if i % 2== 0:
        print(*b[s:s+W])
    else:
        print(*b[s+W-1:s-1:-1])
    s += W

Score : <var>400</var> points

Problem Statement

We have a grid with <var>H</var> rows and <var>W</var> columns of squares.
Snuke is painting these squares in colors <var>1</var>, <var>2</var>, <var>...</var>, <var>N</var>.
Here, the following conditions should be satisfied:

For each <var>i</var> (<var>1 ≤ i ≤ N</var>), there are exactly <var>a_i</var> squares painted in Color <var>i</var>. Here, <var>a_1 + a_2 + ... + a_N = H W</var>.

For each <var>i</var> (<var>1 ≤ i ≤ N</var>), the squares painted in Color <var>i</var> are 4-connected. That is, every square painted in Color <var>i</var> can be reached from every square painted in Color <var>i</var> by repeatedly traveling to a horizontally or vertically adjacent square painted in Color <var>i</var>.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

<var>1 ≤ H, W ≤ 100</var>

<var>1 ≤ N ≤ H W</var>

<var>a_i ≥ 1</var>

<var>a_1 + a_2 + ... + a_N = H W</var>

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>N</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_N</var>

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

<var>c_{1 1}</var> <var>...</var> <var>c_{1 W}</var>
<var>:</var>
<var>c_{H 1}</var> <var>...</var> <var>c_{H W}</var>

Here, <var>c_{i j}</var> is the color of the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color <var>1</var> are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

1 4 4 4 3
2 5 4 5 3
2 5 5 5 3

Sample Input 3

1 1
1
1

Sample Output 3

1


import math
from math import gcd,pi,sqrt
INF = float("inf")

import sys
sys.setrecursionlimit(10**6)
import itertools
from collections import Counter,deque
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]

def main():
    h,w = i_map()
    n = i_input()

    a = i_list()
    ans = ""
    for m,i in enumerate(a):
        ans = ans + (str(m+1))*i
    ans = list(ans)
    for i in range(1,h+1):
        if i%2 == 0:
            print(" ".join(ans[w*(i-1):w*(i-1)+w]))
        else:
            print(" ".join(ans[w*(i-1):w*(i-1)+w][::-1]))

if __name__=="__main__":
    main()


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

ans = 0
while True:
    add = 0
    B = [0] * N
    cut = [0] * N
    for i, a in enumerate(A):
        d, m = divmod(a, N)
        B[i] = m
        cut[i] = d
        add += d

    for i, c in enumerate(cut):
        B[i] += add - c

    if not add:
        break

    ans += add
    A = B

print(ans)

n = int(input())
A = list(map(int, input().split()))
m = min(A)
cnt = 0
while max(A) >= n:
  temp = 0
  for i in range(n):
    t = (A[i]+1)//(n+1)
    temp += t
    A[i] -= t*(n+1)
  for i in range(n):
    A[i] += temp
  cnt += temp
print(cnt)

Score : <var>600</var> points

Problem Statement

We have a sequence of length <var>N</var> consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes <var>N-1</var> or smaller. (The operation is the same as the one in Problem D.)

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by <var>N</var>, and increase each of the other elements by <var>1</var>.

It can be proved that the largest element in the sequence becomes <var>N-1</var> or smaller after a finite number of operations.

You are given the sequence <var>a_i</var>. Find the number of times we will perform the above operation.

Constraints

<var>2 ≤ N ≤ 50</var>

<var>0 ≤ a_i ≤ 10^{16} + 1000</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> ... <var>a_N</var>

Output

Print the number of times the operation will be performed.

Sample Input 1

4
3 3 3 3

Sample Output 1

0

Sample Input 2

3
1 0 3

Sample Output 2

1

Sample Input 3

2
2 2

Sample Output 3

2

Sample Input 4

7
27 0 0 0 0 0 0

Sample Output 4

3

Sample Input 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425

Sample Output 5

1234567894848


import numpy as np
I,S=input,sum
n,c=int(I()),0
a=np.array(list(map(int, I().split())))
while max(a)>=n:c+=S(a//n);a=a-a//n*n-(S(a//n)-a//n)
print(c)


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

"""
・pseudo-tree graph
・in_deg = 1が保証されているので、向きの揃ったcycleがある
・1箇所の2択を決めれば全部決まる
"""

N = int(readline())
parent = [0] + list(map(int,read().split()))

child = [[] for _ in range(N+1)]
for i,x in enumerate(parent):
    child[x].append(i)

out_deg = [len(x) for x in child]

out_deg

G = [-1] * (N+1)

# とりあえず唯一のサイクル以外を処理：out_deg=0の頂点を捨てていく

stack = [i for i,x in enumerate(out_deg) if not x]
while stack:
    x = stack.pop()
    se = set(G[c] for c in child[x])
    g = 0
    while g in se:
        g += 1
    G[x] = g
    p = parent[x]
    out_deg[p] -= 1
    if not out_deg[p]:
        stack.append(p)

"""
・grundy数の候補は2種。
・片方決め打って計算。2周grundy数を計算してstableになっていればよい。
"""

for i,x in enumerate(out_deg[1:],1):
    if x==1:
        root = i
        break

cycle_len = sum(out_deg[1:])

is_stable = False
x = root
for _ in range(cycle_len*2+10):
    se = set(G[c] for c in child[x])
    g = 0
    while g in se:
        g += 1
    if g == G[x]:
        is_stable = True
        break
    G[x] = g
    x = parent[x]

answer = 'POSSIBLE' if is_stable else 'IMPOSSIBLE'
print(answer)

import sys
sys.setrecursionlimit(10**6)
n = int(input())
p = list(map(int, input().split()))
c = [[] for _ in range(n)]
is_leaf = [True for _ in range(n)]
for i in range(n):
	p[i] -= 1
	c[p[i]].append(i)
	is_leaf[p[i]] = False

if sum(is_leaf) == 0:
	if n%2 == 0:
		print("POSSIBLE")
	else:
		print("IMPOSSIBLE")
	sys.exit()

for i in range(n):
	if is_leaf[i]:
		cur = i
		break

visited_set = {cur}
visited_list = [cur]
while p[cur] not in visited_set:
	visited_list.append(p[cur])
	visited_set.add(p[cur])
	cur = p[cur]

root = p[cur]

grundy = [-1 for _ in range(n)]
g_set = [set() for _ in range(n)]

def dfs(x):
	res = 0
	for v in c[x]:
		dfs(v)
		g_set[x].add(grundy[v])
	while res in g_set[x]:
		res += 1
	grundy[x] = res
	return res

loop = [False for _ in range(n)]
loop[root] = True
ind = len(visited_list)-1
while visited_list[ind] != root:
	loop[visited_list[ind]] = True
	ind -= 1
#print(loop)

for i in range(n):
	if loop[i]:
		for x in c[i]:
			if not loop[x]:
				dfs(x)
				g_set[i].add(grundy[x])

cand = []
num = 0
while num in g_set[root]:
	num += 1
cand.append(num)
num += 1
while num in g_set[root]:
	num += 1
cand.append(num)

for x in cand:
	cur = root
	grundy[root] = x
	while True:
		num = 0
		while num in g_set[p[cur]] or num == grundy[cur]:
			num += 1
		grundy[p[cur]] = num
		if p[cur] == root:
			break
		cur = p[cur]
	if grundy[root] == x:
		#print(grundy)
		print("POSSIBLE")
		sys.exit()

print("IMPOSSIBLE")

Score : <var>800</var> points

Problem Statement

There is a directed graph with <var>N</var> vertices and <var>N</var> edges. The vertices are numbered <var>1, 2, ..., N</var>.

The graph has the following <var>N</var> edges: <var>(p_1, 1), (p_2, 2), ..., (p_N, N)</var>, and the graph is weakly connected. Here, an edge from Vertex <var>u</var> to Vertex <var>v</var> is denoted by <var>(u, v)</var>, and a weakly connected graph is a graph which would be connected if each edge was bidirectional.

We would like to assign a value to each of the vertices in this graph so that the following conditions are satisfied. Here, <var>a_i</var> is the value assigned to Vertex <var>i</var>.

Each <var>a_i</var> is a non-negative integer.

For each edge <var>(i, j)</var>, <var>a_i \neq a_j</var> holds.

For each <var>i</var> and each integer <var>x(0 ≤ x < a_i)</var>, there exists a vertex <var>j</var> such that the edge <var>(i, j)</var> exists and <var>x = a_j</var> holds.

Determine whether there exists such an assignment.

Constraints

<var>2 ≤ N ≤ 200</var> <var>000</var>

<var>1 ≤ p_i ≤ N</var>

<var>p_i \neq i</var>

The graph is weakly connected.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>p_1</var> <var>p_2</var> ... <var>p_N</var>

Output

If the assignment is possible, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

4
2 3 4 1

Sample Output 1

POSSIBLE

The assignment is possible: {<var>a_i</var>} = {<var>0, 1, 0, 1</var>} or {<var>a_i</var>} <var>=</var> {<var>1, 0, 1, 0</var>}.

Sample Input 2

3
2 3 1

Sample Output 2

IMPOSSIBLE

Sample Input 3

4
2 3 1 1

Sample Output 3

POSSIBLE

The assignment is possible: {<var>a_i</var>} <var>=</var> {<var>2, 0, 1, 0</var>}.

Sample Input 4

6
4 5 6 5 6 4

Sample Output 4

IMPOSSIBLE


# F
N = int(input())
p_list = list(map(int, input().split()))

# usagi to kame
# start from 1
usagi = 1
kame  = 1

def back(i):
    return p_list[i - 1]

usagi = back(back(usagi))
kame = back(kame)

while usagi != kame:
    usagi = back(back(usagi))
    kame = back(kame)

# begin loop
# length of loop
L = 1
usagi = back(back(usagi))
kame = back(kame)

while usagi != kame:
    usagi = back(back(usagi))
    kame = back(kame)
    L += 1

if L % 2 == 0:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")


# chokudaiブログの典型力の話を意識しつつ考えたら思いついた!

# 「ある集合の部分集合の中で、〜〜〜の値が最小になるものを求めよ」のパターン
# 愚直にやると2^Nを調べねばならず無理。
# したがって「一部を調べればよい」に帰着するのが多いだろう。
# 何らかの形でソートしておいて、空集合から1つずつ付け加えるとか。全体集合から1つずつ取り去るとか。

# 今回は全体集合から1つずつ取り去るのを考えるとできる。
# 全体集合である競技m0が最多の人数p0人を集めたとする。
# すると、全ての部分集合のうち「m0を含む集合」を考えると、競技m0は必ずp0人以上集まるので解もp0以上。
# ここで「m0を含む集合」について一気に計算できていることに注意! 一撃で多数の集合について計算が終わる。
# 次に全体集合からm0を取り去ったものを考える。
# ここである競技m1が最多の人数p1人を集めたとする。すると……以下同様。
# なお複数種目の競技が同率1位になった場合は全て一度に取り除いて良い。
# これで空集合までやって、最大が最小のものを出力すればOK!

n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] # 1-index → 0-index

ans = n
held_sports = set(range(m))

while held_sports:
    # 各競技に参加する人数を求める
    parti = [0] * m
    for pref in preference:
        for s in pref:
            if s in held_sports:
                parti[s] += 1
                break

    temp = max(parti)
    ans = min(ans, temp)
    # 集合から最大人数を取った要素を除外
    for idx, par in enumerate(parti):
        if par == temp:
            held_sports.remove(idx)

print(ans)

# chokudaiブログの典型力の話を意識しつつ考えたら思いついた!

# 「ある集合の部分集合の中で、〜〜〜の値が最小になるものを求めよ」のパターン
# 愚直にやると2^Nを調べねばならず無理。
# したがって「一部を調べればよい」に帰着するのが多いだろう。
# 何らかの形でソートしておいて、空集合から1つずつ付け加えるとか。全体集合から1つずつ取り去るとか。

# 今回は全体集合から1つずつ取り去るのを考えるとできる。
# 全体集合である競技m0が最多の人数p0人を集めたとする。
# すると、全ての部分集合のうち「m0を含む集合」を考えると、競技m0は必ずp0人以上集まるので解もp0以上。
# ここで「m0を含む集合」について一気に計算できていることに注意! 一撃で多数の集合について計算が終わる。
# 次に全体集合からm0を取り去ったものを考える。
# ここである競技m1が最多の人数p1人を集めたとする。すると……以下同様。
# なお複数種目の競技が同率1位になった場合は全て一度に取り除いて良い。
# これで空集合までやって、最大が最小のものを出力すればOK!

n, m = list(map(int, input().split()))
preference = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] # 1-index → 0-index

ans = n
held_sports = set(range(m))

while held_sports:
    # 各競技に参加する人数を求める
    parti = [0] * m
    for pref in preference:
        for s in pref:
            if s in held_sports:
                parti[s] += 1
                break

    temp = max(parti)
    ans = min(ans, temp)
    # 集合から最大人数を取った要素を除外
    indices = [i for i,val in enumerate(parti) if val == temp]
    held_sports = held_sports - set(indices)

print(ans)

Score : <var>700</var> points

Problem Statement

Takahashi is hosting an sports meet.
There are <var>N</var> people who will participate. These people are conveniently numbered <var>1</var> through <var>N</var>.
Also, there are <var>M</var> options of sports for this event. These sports are numbered <var>1</var> through <var>M</var>.
Among these options, Takahashi will select one or more sports (possibly all) to be played in the event.

Takahashi knows that Person <var>i</var>'s <var>j</var>-th favorite sport is Sport <var>A_{ij}</var>.
Each person will only participate in his/her most favorite sport among the ones that are actually played in the event, and will not participate in the other sports.

Takahashi is worried that one of the sports will attract too many people.
Therefore, he would like to carefully select sports to be played so that the number of the participants in the sport with the largest number of participants is minimized.
Find the minimum possible number of the participants in the sport with the largest number of participants.

Constraints

<var>1 \leq N \leq 300</var>

<var>1 \leq M \leq 300</var>

<var>A_{i1}</var> , <var>A_{i2}</var> , <var>...</var> , <var>A_{iM}</var> is a permutation of the integers from <var>1</var> to <var>M</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_{11}</var> <var>A_{12}</var> <var>...</var> <var>A_{1M}</var>
<var>A_{21}</var> <var>A_{22}</var> <var>...</var> <var>A_{2M}</var>
<var>:</var>
<var>A_{N1}</var> <var>A_{N2}</var> <var>...</var> <var>A_{NM}</var>

Output

Print the minimum possible number of the participants in the sport with the largest number of participants.

Sample Input 1

4 5
5 1 3 4 2
2 5 3 1 4
2 3 1 4 5
2 5 4 3 1

Sample Output 1

2

Assume that Sports <var>1</var>, <var>3</var> and <var>4</var> are selected to be played. In this case, Person <var>1</var> will participate in Sport <var>1</var>, Person <var>2</var> in Sport <var>3</var>, Person <var>3</var> in Sport <var>3</var> and Person <var>4</var> in Sport <var>4</var>.
Here, the sport with the largest number of participants is Sport <var>3</var>, with two participants.
There is no way to reduce the number of participants in the sport with the largest number of participants to <var>1</var>. Therefore, the answer is <var>2</var>.

Sample Input 2

3 3
2 1 3
2 1 3
2 1 3

Sample Output 2

3

Since all the people have the same taste in sports, there will be a sport with three participants, no matter what sports are selected.
Therefore, the answer is <var>3</var>.


N,M=map(int, input().split())
A=[]
for i in range(N):
  d=list(map(int, input().split()))
  A.append(d)
S=[1]*M
num=[0]*N
ans=M
for i in range(M-1):
  cnt=[0]*M
  for j in range(N):
    d=A[j][num[j]]
    while S[d-1]==0:
      num[j]+=1
      d=A[j][num[j]]
    cnt[d-1]+=1
  e=max(cnt)
  ans=min(e,ans)
  f=cnt.index(e)
  S[f]=0
print(ans)