n = int(input())
x = input()

f = [-1] * (n+10)
f[0] = 0

for i in range(1, n+10):
    # python bitcount で見つけたこれを参考に https://ameblo.jp/316228/entry-10518720149.html
    f[i] = f[i % bin(i).count('1')] + 1

init_bitcount = x.count('1')
# Xを init_bitcount+1とinit_bitcount-1で割った余り

x_mod_01 = 0
for digit in x:
    x_mod_01 *= 2
    if digit == '1':
        x_mod_01 += 1
    x_mod_01 %= (init_bitcount+1)

if init_bitcount != 1:
    x_mod_10 = 0
    for digit in x:
        x_mod_10 *= 2
        if digit == '1':
            x_mod_10 += 1
        x_mod_10 %= (init_bitcount-1)

# print(x_mod_01, x_mod_10, init_bitcount)

power_mod_01 = [-1] * (n+10)
power_mod_01[0] = 1
for i in range(1, n+10):
    power_mod_01[i] = power_mod_01[i-1] * 2 % (init_bitcount + 1)

if init_bitcount != 1:
    power_mod_10 = [-1] * (n+10)
    power_mod_10[0] = 1
    for i in range(1, n+10):
        power_mod_10[i] = power_mod_10[i-1] * 2 % (init_bitcount - 1)

for i in range(n):
    if x[i] == '0':
        # 0→1
        first_residue = (x_mod_01 + power_mod_01[n - i - 1]) % (init_bitcount+1)
        print(f[first_residue] + 1)
    else:
        if init_bitcount == 1:
            # 立っているビットの数は0桁、つまりX_i = 0なのでf(X_i) = 0
            print(0)
            continue
        # 1→0
        first_residue = (x_mod_10 - power_mod_10[n - i - 1]) % (init_bitcount-1)
        print(f[first_residue] + 1)

# https://twitter.com/kyopro_friends/status/1281949470100353024
# https://atcoder.jp/contests/aising2020/editorial 公式
# 1回の操作で桁数以下に落ちることに注意すると、操作の繰り返しで急速に値が小さくなり、少ない回数で0に到着する。
# したがってfの表を作るのは今回不要。愚直にやってもできるので。初回の高速化だけが必要。

n = int(input())
x = input()

f = [-1] * (n+10)
f[0] = 0

for i in range(1, n+10):
    # python bitcount で見つけたこれを参考に https://ameblo.jp/316228/entry-10518720149.html
    f[i] = f[i % bin(i).count('1')] + 1

init_bitcount = x.count('1')
# Xを init_bitcount+1とinit_bitcount-1で割った余り

x_mod_01 = 0
x_mod_10 = 0
for digit in x:
    x_mod_01 *= 2
    x_mod_10 *= 2
    if digit == '1':
        x_mod_01 += 1
        x_mod_10 += 1
    x_mod_01 %= (init_bitcount+1)
    if init_bitcount != 1:
        x_mod_10 %= (init_bitcount-1)

# print(x_mod_01, x_mod_10, init_bitcount)

power_mod_01 = [-1] * (n+10)
power_mod_01[0] = 1
for i in range(1, n+10):
    power_mod_01[i] = power_mod_01[i-1] * 2 % (init_bitcount + 1)

if init_bitcount != 1:
    power_mod_10 = [-1] * (n+10)
    power_mod_10[0] = 1
    for i in range(1, n+10):
        power_mod_10[i] = power_mod_10[i-1] * 2 % (init_bitcount - 1)

for i in range(n):
    if x[i] == '0':
        # 0→1
        first_residue = (x_mod_01 + power_mod_01[n - i - 1]) % (init_bitcount+1)
        print(f[first_residue] + 1)
    else:
        if init_bitcount == 1:
            print(0)
            continue
        # 1→0
        first_residue = (x_mod_10 - power_mod_10[n - i - 1]) % (init_bitcount-1)
        print(f[first_residue] + 1)

Score : <var>400</var> points

Problem Statement

Let <var>\mathrm{popcount}(n)</var> be the number of 1s in the binary representation of <var>n</var>.
For example, <var>\mathrm{popcount}(3) = 2</var>, <var>\mathrm{popcount}(7) = 3</var>, and <var>\mathrm{popcount}(0) = 0</var>.

Let <var>f(n)</var> be the number of times the following operation will be done when we repeat it until <var>n</var> becomes <var>0</var>: "replace <var>n</var> with the remainder when <var>n</var> is divided by <var>\mathrm{popcount}(n)</var>." (It can be proved that, under the constraints of this problem, <var>n</var> always becomes <var>0</var> after a finite number of operations.)

For example, when <var>n=7</var>, it becomes <var>0</var> after two operations, as follows:

<var>\mathrm{popcount}(7)=3</var>, so we divide <var>7</var> by <var>3</var> and replace it with the remainder, <var>1</var>.

<var>\mathrm{popcount}(1)=1</var>, so we divide <var>1</var> by <var>1</var> and replace it with the remainder, <var>0</var>.

You are given an integer <var>X</var> with <var>N</var> digits in binary.
For each integer <var>i</var> such that <var>1 \leq i \leq N</var>, let <var>X_i</var> be what <var>X</var> becomes when the <var>i</var>-th bit from the top is inverted.
Find <var>f(X_1), f(X_2), \ldots, f(X_N)</var>.

Constraints

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

<var>X</var> is an integer with <var>N</var> digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X</var>

Output

Print <var>N</var> lines. The <var>i</var>-th line should contain the value <var>f(X_i)</var>.

Sample Input 1

3
011

Sample Output 1

2
1
1

<var>X_1 = 7</var>, which will change as follows: <var>7 \rightarrow 1 \rightarrow 0</var>. Thus, <var>f(7) = 2</var>.

<var>X_2 = 1</var>, which will change as follows: <var>1 \rightarrow 0</var>. Thus, <var>f(1) = 1</var>.

<var>X_3 = 2</var>, which will change as follows: <var>2 \rightarrow 0</var>. Thus, <var>f(2) = 1</var>.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


n = int(input())
x = input()

f = [-1] * (n+10)
f[0] = 0

for i in range(1, n+10):
    # python bitcount で見つけたこれを参考に https://ameblo.jp/316228/entry-10518720149.html
    f[i] = f[i % bin(i).count('1')] + 1

init_bitcount = x.count('1')
# Xを init_bitcount+1とinit_bitcount-1で割った余り

x_mod_01 = 0
x_mod_10 = 0
for digit in x:
    x_mod_01 *= 2
    x_mod_10 *= 2
    if digit == '1':
        x_mod_01 += 1
        x_mod_10 += 1
    x_mod_01 %= (init_bitcount+1)
    if init_bitcount != 1:
        x_mod_10 %= (init_bitcount-1)

# print(x_mod_01, x_mod_10, init_bitcount)

power_mod_01 = [-1] * (n+10)
power_mod_01[0] = 1
for i in range(1, n+10):
    power_mod_01[i] = power_mod_01[i-1] * 2 % (init_bitcount + 1)

if init_bitcount != 1:
    power_mod_10 = [-1] * (n+10)
    power_mod_10[0] = 1
    for i in range(1, n+10):
        power_mod_10[i] = power_mod_10[i-1] * 2 % (init_bitcount - 1)

for i in range(n):
    if x[i] == '0':
        # 0→1
        first_residue = (x_mod_01 + power_mod_01[n - i - 1]) % (init_bitcount+1)
        print(f[first_residue] + 1)
    else:
        if init_bitcount == 1:
            print(1)
            continue
        # 1→0
        first_residue = (x_mod_10 - power_mod_10[n - i - 1]) % (init_bitcount-1)
        print(f[first_residue] + 1)


D = int(input())
C = [int(T) for T in input().split()]
S = [[] for TD in range(0,D)]
for TD in range(0,D):
    S[TD] = [int(T) for T in input().split()]
for TD in range(0,D):
    print(S[TD].index(max(S[TD]))+1)

from random import randint
for TD in range(0,365):
    print(randint(1,26))

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for <var>D</var> days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type <var>i</var> on day <var>d</var> will increase the satisfaction by <var>s_{d,i}</var>.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type <var>i</var> has an integer <var>c_i</var>, and at the end of each day <var>d=1,2,...,D</var>, the satisfaction decreases as follows. Let <var>\mathrm{last}(d,i)</var> be the last day before day <var>d</var> (including <var>d</var>) on which a contest of type <var>i</var> was held. If contests of type <var>i</var> have never been held yet, we define <var>\mathrm{last}(d,i)=0</var>. At the end of day <var>d</var>, the satisfaction decreases by <var>\sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i))</var>.

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day <var>D</var> is <var>S</var>, you will get a score of <var>\max(10^6 + S, 0)</var>.
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

<var>D = 365</var>

Each <var>c_i</var> is an integer satisfying <var>0\leq c_i \leq 100</var>.

Each <var>s_{d,i}</var> is an integer satisfying <var>0\leq s_{d,i} \leq 20000</var>.

Input

Input is given from Standard Input in the following format:

<var>D</var>
<var>c_1</var> <var>c_2</var> <var>\cdots</var> <var>c_{26}</var>
<var>s_{1,1}</var> <var>s_{1,2}</var> <var>\cdots</var> <var>s_{1,26}</var>
<var>\vdots</var>
<var>s_{D,1}</var> <var>s_{D,2}</var> <var>\cdots</var> <var>s_{D,26}</var>

Output

Let <var>t_d</var> (<var>1\leq t_d \leq 26</var>) be the type of the contest that will be held at day <var>d</var>.
Print <var>D</var> integers <var>t_d</var> to Standard Output in the following format:

<var>t_1</var>
<var>t_2</var>
<var>\vdots</var>
<var>t_D</var>

Any output that does not follow the above format may result in <s>0 points</s>WA for that test case.

Input Generation

Each integer <var>c_i</var> and <var>s_{d,i}</var> is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint <var>D=365</var> and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.


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

D = int(input())
c = np.array(input().split(), dtype=np.int32)
s = np.array([input().split() for _ in range(D)], dtype=np.int32)
last = np.zeros(26, dtype=np.int32)

ans = []
point = 0
for i in range(D):
    down = (i+1-last)*c
    loss = down * 3 + s[i,:]
    idx = np.argmax(loss)
    ans.append(idx+1)
    point += s[i, idx] - down.sum()
    last[idx] = i+1
    print(down)

for i in range(D):
    print(ans[i])


def main(n,a):
    s=a[0]+a[1]
    z=0
    for ai in a[2:]:
        z^=ai
    # i+j=s,i<=a[0],i^j=z となるi,jを探す
    # i+j=i^j+2*(i & j)
    # s = z + 2*(i & j)
    # i & j = (s-z)/2 = d
    # z = 2*(i & j) - s = i ^ j
    # d = (s-z) / 2
    # z = x^y , x&y=0
    # d^x,d^yは条件を満たす。d^x+d^y=d^x^d^y + 2*((d^x)&(d^y))= z + 2*d = s
    # (d^x)^(d^y)=x^y=z
    # (d^x)&(d^y)=d (z & d = 0 のときのみ)
    if s-z<0 or (s-z)%2==1:return -1
    d=(s-z)//2
    if d&z!=0:return -1
    if not d<=a[0]:return -1
    part=[]
    i=0
    while z//pow(2,i):
        if (z//pow(2,i))%2==1:part.append(pow(2,i))
        i+=1
    ans=float('inf')
    k=len(part)
    x=0
    while part:
        tmp=part.pop()
        if d^(x+tmp)<=a[0]:
            x+=tmp
    return a[0]-(d^x) if d^x else -1

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

def main():
    n = int(input())
    a = list(map(int, input().split()))
    xor = 0
    for i in range(2, n):
        xor ^= a[i]
    s = a[0] + a[1]
    dp = [[[-1 for k in range(2)] for j in range(2)] for i in range(45)]
    p = a[0]
    dp[0][0][0] = 0
    for i in range(44):
        crrx = xor&1
        crrs = s&1
        crrp = p&1
        for j in range(2):
            for k in range(2):
                if dp[i][j][k] == -1:
                    continue
                for nxtp in range(2):
                    for nxtq in range(2):
                        nxti = i+1
                        nxtj = 0
                        nxtk = k
                        if (nxtp ^ nxtq) != crrx:
                            continue
                        nxts = nxtp+nxtq+j
                        if nxts%2 != crrs:
                            continue
                        if nxts >= 2:
                            nxtj = 1
                        if crrp < nxtp:
                            nxtk = 1
                        elif crrp == nxtp:
                            nxtk = k
                        else:
                            nxtk = 0
                        dp[nxti][nxtj][nxtk] = max(dp[nxti][nxtj][nxtk], dp[i][j][k]+(1<<i)*nxtp)
        xor //= 2
        s //= 2
        p //= 2
    if dp[-1][0][0] > 0:
        print(a[0] - dp[-1][0][0])
    else:
        print(-1)

if __name__ == "__main__":
    main()

Score : <var>600</var> points

Problem Statement

There are <var>N</var> piles of stones. The <var>i</var>-th pile has <var>A_i</var> stones.

Aoki and Takahashi are about to use them to play the following game:

Starting with Aoki, the two players alternately do the following operation:

Operation: Choose one pile of stones, and remove one or more stones from it.

When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most <var>(A_1 - 1)</var> stones from the <var>1</var>-st pile to the <var>2</var>-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

Constraints

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

<var>1 \leq A_i \leq 10^{12}</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>\ldots</var> <var>A_N</var>

Output

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

Sample Input 1

2
5 3

Sample Output 1

1

Without moving stones, if Aoki first removes <var>2</var> stones from the <var>1</var>-st pile, Takahashi cannot win in any way.

If Takahashi moves <var>1</var> stone from the <var>1</var>-st pile to the <var>2</var>-nd before the game begins so that both piles have <var>4</var> stones, Takahashi can always win by properly choosing his actions.

Sample Input 2

2
3 5

Sample Output 2

-1

It is not allowed to move stones from the <var>2</var>-nd pile to the <var>1</var>-st.

Sample Input 3

3
1 1 2

Sample Output 3

-1

It is not allowed to move all stones from the <var>1</var>-st pile.

Sample Input 4

8
10 9 8 7 6 5 4 3

Sample Output 4

3

Sample Input 5

3
4294967297 8589934593 12884901890

Sample Output 5

1

Watch out for overflows.


def Q(x):
    print("?",x,flush=True)
    return int(input())

x=Q("A")
if x==128:
    L=128
else:
    y=Q("A"*x)
    z=Q("A"*(x+1))

    if z==y:
        L=x+1
    else:
        L=x

S=[chr(i) for i in range(48,58)]+[chr(i) for i in range(65,91)]+[chr(i) for i in range(97,123)]
K=[-1]*62

for i in range(62):
    K[i]=L-Q(S[i]*L)

import heapq
A=[(K[i],S[i]*K[i]) for i in range(62)]
heapq.heapify(A)

while len(A)>1:
    x,y=heapq.heappop(A)
    if x==0:
        continue
    z,w=heapq.heappop(A)

    ind=0
    for i in range(len(w)):
        while Q(y[:ind]+w[i]+y[ind:])>=L-x-i:
            ind+=1
        y=y[:ind]+w[i]+y[ind:]
        ind+=1
    heapq.heappush(A,(x+z,y))

print("!",A[0][1],flush=True)

import string
from heapq import heapify, heappop, heappush

def judge():
    import Levenshtein
    import subprocess

    ans = 'OQqZbgyIYiB59fqHVsXu0PZVEWy1sApStRxCJFMeNkr5O0U4jEX9ksBTpKw7Z3ylYd3Hnd'
    query_count = 0
    with subprocess.Popen(['python', __file__, 'EXE'],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as p:
        while True:
            query = p.stdout.readline().decode().strip()
            print(query)
            if query[0] == '?':
                d = Levenshtein.distance(query[2:], ans)
                print(d)
                p.stdin.write(f'{d}\n'.encode())
                p.stdin.flush()
                query_count += 1
            elif query[0] == '!':
                print(query[2:] == ans)
                print(query_count)
                break
            else:
                pass

# import sys
#
# if len(sys.argv) == 1:
#     print('Interactive Test Mode')
#     judge()
#     exit()

STR = string.ascii_letters + string.digits
counter = {}
for c in STR:
    print(f'? {c * 128}')
    a = int(input())
    if a == 128:
        continue
    counter[c] = 128 - a

l = sum(counter.values())
q = [(cnt, [c] * cnt) for c, cnt in counter.items()]
heapify(q)

while len(q) > 1:
    l1, t1 = heappop(q)
    l2, t2 = heappop(q)
    i = 0
    j = 0
    while i < len(t1) and j < l2:
        t1.insert(i, t2[j])
        s = ''.join(t1)
        print(f'? {s}')
        a = int(input())
        if len(t1) > l - a:
            t1.pop(i)
        else:
            j += 1
        i += 1
    if j < len(t2):
        t1.extend(t2[j:])

    heappush(q, (l1 + l2, t1))

_, t = q[0]
s = ''.join(t)
print(f'! {s}')

Score : <var>1100</var> points

Problem Statement

This is an interactive task.

You have to guess a secret password <var>S</var>.
A password is a nonempty string whose length is at most <var>L</var>.
The characters of a password can be lowercase and uppercase english letters (a, b, ... , z, A, B, ... , Z) and digits (0, 1, ... , 9).

In order to guess the secret password <var>S</var> you can ask queries.
A query is made of a valid password <var>T</var>, the answer to such query is the edit distance between <var>S</var> and <var>T</var> (the operations considered for the edit distance are: removal, insertion, substitution).
You can ask at most <var>Q</var> queries.

Note: For a definition of edit distance (with operations: removal, insertion, substitution), see this wikipedia page.

Constraints

<var>L = 128</var>

<var>Q = 850</var>

The secret password <var>S</var> is chosen before the beginning of the interaction.

Interaction

To ask a query, print on Standard Output (with a newline at the end)

? <var>T</var>

The string <var>T</var> must be a valid password.

The answer <var>ans</var> to each query shall be read from Standard Input in the form:

<var>ans</var>

As soon as you have determined the hidden password <var>S</var>, you should print on Standard Output (with a newline at the end)

! <var>S</var>

and terminate your program.

Judgement

After each output, you must flush Standard Output. Otherwise you may get TLE.

After you print (your guess of) the hidden password, the program must be terminated immediately. Otherwise, the behavior of the judge is undefined.

If the password you have determined is wrong, you will get WA.

If you ask a malformed query (for example because the string is not a valid password, or you forget to put ?) or if your program crashes or if you ask more than <var>Q</var> queries, the behavior of the judge is undefined (it does not necessarily give WA).

Samples

In the only sample testcase of this problem the hidden password is Atcod3rIsGreat.

The following one is an example of interaction if <var>S=</var>Atcod3rIsGreat.

Input
Output

<var>\texttt{? AtcoderIsBad}</var>

<var>5</var>

<var>\texttt{? AtcoderIsGreat}</var>

<var>1</var>

<var>\texttt{! Atcod3rIsGreat}</var>


import sys
import string

def test():
    import Levenshtein
    import subprocess

    ans = 'Atcod3rIsGreat'
    with subprocess.Popen(['python', __file__, 'EXE'],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as p:
        while True:
            query = p.stdout.readline().decode().strip()
            print(query)
            if query[0] == '!':
                print(query[2:] == ans)
                break
            elif query[0] == '?':
                d = Levenshtein.distance(query[2:], ans)
                print(d)
                p.stdin.write(f'{d}\n'.encode())
                p.stdin.flush()
            else:
                pass

# if len(sys.argv) == 1:
#     test()
#     exit()

STR = string.ascii_letters + string.digits
counter = {}
for c in STR:
    print(f'? {c * 128}')
    a = int(input())
    if a == 128:
        continue
    counter[c] = 128 - a

l = sum(counter.values())
c, cnt = counter.popitem()
t = [c] * cnt
for c, cnt in counter.items():
    i = 0
    while i < len(t) and cnt:
        t.insert(i, c)
        s = ''.join(t)
        print(f'? {s}')
        a = int(input())
        if len(t) > l - a:
            t.pop(i)
        else:
            cnt -= 1
        i += 1
    if cnt:
        t.extend([c] * cnt)

s = ''.join(t)
print(f'! {s}')


K=int(input())
S=input()
N=len(S)

if N<=K:
    print(S)
else:
    ans=[]
    for i in range(K):
        ans.append(S[i])
    print(''.join(ans)+'...')

K = int(input())
S = input()
words = int(len(S))

if K < words:
    print(S[0:K] + "...")

else:
    print(S)

Score: <var>200</var> points

Problem Statement

We have a string <var>S</var> consisting of lowercase English letters.

If the length of <var>S</var> is at most <var>K</var>, print <var>S</var> without change.

If the length of <var>S</var> exceeds <var>K</var>, extract the first <var>K</var> characters in <var>S</var>, append ... to the end of them, and print the result.

Constraints

<var>K</var> is an integer between <var>1</var> and <var>100</var> (inclusive).

<var>S</var> is a string consisting of lowercase English letters.

The length of <var>S</var> is between <var>1</var> and <var>100</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>K</var>
<var>S</var>

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of <var>15</var>, which exceeds <var>K=7</var>.

We should extract the first <var>7</var> characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


k = int(input())
s = str(input())
if len(s) >= k:
    print(s[0:7] + "...")
else:
    print(s)


S = input()
T = input()

if S == T[:-1]:
  print('Yes')
else:
  print('No')

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

Score : <var>100</var> points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID <var>S</var>, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of <var>S</var> as his ID.

He is now trying to register with the ID <var>T</var>. Determine whether this string satisfies the property above.

Constraints

<var>S</var> and <var>T</var> are strings consisting of lowercase English letters.

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

<var>|T| = |S| + 1</var>

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>T</var>

Output

If <var>T</var> satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

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

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


S = input()
T = input()
if S in T:
    ans = 'Yes'
else:
    ans = 'No'
print(ans)


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

a = input()
if a =='ABC':
    print('ARC')
else:
    print('ABC')

Score : <var>100</var> points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string <var>S</var> representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

<var>S</var> is ABC or ARC.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

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

Sample Input 1

ABC

Sample Output 1

ARC

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


s = input()

if s == "ABC" :
  print("ARC")

else :
  print("ARC")


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

for i in range(1,1000):
  if a<=k*i and k*i<=b:
    print('OK')
    q=1
    break

if q==0:
  print('NG')

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

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

Score: <var>100</var> points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of <var>K</var>, while he can only make a carry distance of between <var>A</var> and <var>B</var> (inclusive).

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

Constraints

All values in input are integers.

<var>1 \leq A \leq B \leq 1000</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of <var>7</var>, for example, <var>567</var> lies between <var>500</var> and <var>600</var>.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of <var>4</var> lies between <var>5</var> and <var>7</var>.

Sample Input 3

1
11 11

Sample Output 3

OK


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

if a%k==0 or b%k==0:
  print("OK")
elif (a-b)==0 and k==1:
  print("OK")
elif (a-b)>=k:
  print("OK")
else:
  print("NG")


import heapq
from heapq import heappush,heappop

class Heap1D:
    def __init__(self, shift=20):
        self.shift = shift
        self.data = []
        self.mask = (1<<shift)-1

    def push(self, x):
        a, b = x
        heapq.heappush(self.data, (a<<self.shift) | b)

    def pop(self):
        a = heapq.heappop(self.data)
        b = a & self.mask
        a >>= self.shift
        return a,b

    def __len__(self):
        return len(self.data)

def dijkstra(start = 0):
    d = [INF for i in range(len(G))]
    d[start] = 0
    que = Heap1D()
    que.push((0, start))

    while len(que):
        p = que.pop()
        v = p[1]
        if d[v] < p[0]:
            continue
        for u in G[v].keys():
            if d[u] > d[v] + G[v][u]:
                d[u] = d[v] + G[v][u]
                que.push((d[u], u))
    return d

N,M,S=map(int,input().split())
edges = [tuple(map(int,input().split())) for _ in range(M)]
cd = [tuple(map(int,input().split())) for _ in range(N)]
INF= 10**15
mod=55

mmax = sum([edges[i][2] for i in range(M)])
if S>mmax:
  S = mmax

G=[{} for _ in range((mmax+1)*mod+N+1)]
for i in range(M):
  u,v,a,b=edges[i]
  for p in range(a,mmax+1):
    G[u+p*mod][v+(p-a)*mod] = b
    G[v+p*mod][u+(p-a)*mod] = b

for i in range(N):
  c,d=cd[i]
  for p in range(mmax+1-c):
    G[i+1+p*mod][i+1+(p+c)*mod] = d

start = 1+S*mod
d = dijkstra(start)

ans=[INF]*(N+1)
for i in range(2,len(G)+1):
  v = i%mod
  if v>N or v<2:continue
  ans[v] = min(ans[v],d[i])

print(*ans[2:])

import sys
import heapq
def input(): return sys.stdin.readline().rstrip()

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

graph = [[] for _ in range(n+1)]

maxcoin = 0

for i in range(m):
    u, v, a, b = map(int, input().split())
    graph[u].append((v, a, b))
    graph[v].append((u, a, b))
    maxcoin += a

ryougae = [0, 0]*(n+1)

for i in range(1, n+1):
    c, d = map(int, input().split())
    ryougae[i] = [c, d]

mindist = [[10**20]*(maxcoin+1) for _ in range(n+1)]
hq = []
heapq.heappush(hq, (0, 1, min(maxcoin, s)))
while hq:
    minute, city, coin = heapq.heappop(hq)
    if mindist[city][coin] != 10**20:
        continue
    mindist[city][coin] = minute
    for i, pay, length in graph[city]:
        if coin >= pay:
            if mindist[i][coin-pay] != 10**20:
                continue
            heapq.heappush(hq, (minute+length, i, coin-pay))
    if coin < maxcoin:
        kankin = min(maxcoin, ryougae[city][0]+coin)
        if mindist[city][kankin] != 10**20:
            continue
        heapq.heappush(hq, (minute+ryougae[city][1], city, kankin))

for i in range(2, n+1):
    print(min(mindist[i]))

Score : <var>500</var> points

Problem Statement

There are <var>N</var> cities numbered <var>1</var> to <var>N</var>, connected by <var>M</var> railroads.

You are now at City <var>1</var>, with <var>10^{100}</var> gold coins and <var>S</var> silver coins in your pocket.

The <var>i</var>-th railroad connects City <var>U_i</var> and City <var>V_i</var> bidirectionally, and a one-way trip costs <var>A_i</var> silver coins and takes <var>B_i</var> minutes.
You cannot use gold coins to pay the fare.

There is an exchange counter in each city. At the exchange counter in City <var>i</var>, you can get <var>C_i</var> silver coins for <var>1</var> gold coin.
The transaction takes <var>D_i</var> minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.

For each <var>t=2, ..., N</var>, find the minimum time needed to travel from City <var>1</var> to City <var>t</var>. You can ignore the time spent waiting for trains.

Constraints

<var>2 \leq N \leq 50</var>

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

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

<var>1 \leq A_i \leq 50</var>

<var>1 \leq B_i,C_i,D_i \leq 10^9</var>

<var>1 \leq U_i < V_i \leq N</var>

There is no pair <var>i, j(i \neq j)</var> such that <var>(U_i,V_i)=(U_j,V_j)</var>.

Each city <var>t=2,...,N</var> can be reached from City <var>1</var> with some number of railroads.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>S</var>
<var>U_1</var> <var>V_1</var> <var>A_1</var> <var>B_1</var>
<var>:</var>
<var>U_M</var> <var>V_M</var> <var>A_M</var> <var>B_M</var>
<var>C_1</var> <var>D_1</var>
<var>:</var>
<var>C_N</var> <var>D_N</var>

Output

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

Sample Input 1

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

Sample Output 1

2
14

The railway network in this input is shown in the figure below.

In this figure, each city is labeled as follows:

The first line: the ID number <var>i</var> of the city (<var>i</var> for City <var>i</var>)

The second line: <var>C_i</var> / <var>D_i</var>

Similarly, each railroad is labeled as follows:

The first line: the ID number <var>i</var> of the railroad (<var>i</var> for the <var>i</var>-th railroad in input)

The second line: <var>A_i</var> / <var>B_i</var>

You can travel from City <var>1</var> to City <var>2</var> in <var>2</var> minutes, as follows:

Use the <var>1</var>-st railroad to move from City <var>1</var> to City <var>2</var> in <var>2</var> minutes.

You can travel from City <var>1</var> to City <var>3</var> in <var>14</var> minutes, as follows:

Use the <var>1</var>-st railroad to move from City <var>1</var> to City <var>2</var> in <var>2</var> minutes.

At the exchange counter in City <var>2</var>, exchange <var>3</var> gold coins for <var>3</var> silver coins in <var>6</var> minutes.

Use the <var>1</var>-st railroad to move from City <var>2</var> to City <var>1</var> in <var>2</var> minutes.

Use the <var>2</var>-nd railroad to move from City <var>1</var> to City <var>3</var> in <var>4</var> minutes.

Sample Input 2

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

Sample Output 2

5
5
7

The railway network in this input is shown in the figure below:

You can travel from City <var>1</var> to City <var>4</var> in <var>7</var> minutes, as follows:

At the exchange counter in City <var>1</var>, exchange <var>2</var> gold coins for <var>6</var> silver coins in <var>2</var> minutes.

Use the <var>2</var>-nd railroad to move from City <var>1</var> to City <var>3</var> in <var>4</var> minutes.

Use the <var>4</var>-th railroad to move from City <var>3</var> to City <var>4</var> in <var>1</var> minutes.

Sample Input 3

6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1

Sample Output 3

1
9003
14606
16510
16576

The railway network in this input is shown in the figure below:

You can travel from City <var>1</var> to City <var>6</var> in <var>16576</var> minutes, as follows:

Use the <var>1</var>-st railroad to move from City <var>1</var> to City <var>2</var> in <var>1</var> minute.

At the exchange counter in City <var>2</var>, exchange <var>3</var> gold coins for <var>3</var> silver coins in <var>9000</var> minutes.

Use the <var>1</var>-st railroad to move from City <var>2</var> to City <var>1</var> in <var>1</var> minute.

Use the <var>2</var>-nd railroad to move from City <var>1</var> to City <var>3</var> in <var>1</var> minute.

At the exchange counter in City <var>3</var>, exchange <var>8</var> gold coins for <var>8</var> silver coins in <var>5600</var> minutes.

Use the <var>2</var>-nd railroad to move from City <var>3</var> to City <var>1</var> in <var>1</var> minute.

Use the <var>1</var>-st railroad to move from City <var>1</var> to City <var>2</var> in <var>1</var> minute.

Use the <var>3</var>-rd railroad to move from City <var>2</var> to City <var>4</var> in <var>1</var> minute.

At the exchange counter in City <var>4</var>, exchange <var>19</var> gold coins for <var>19</var> silver coins in <var>1900</var> minutes.

Use the <var>3</var>-rd railroad to move from City <var>4</var> to City <var>2</var> in <var>1</var> minute.

Use the <var>1</var>-st railroad to move from City <var>2</var> to City <var>1</var> in <var>1</var> minute.

Use the <var>2</var>-nd railroad to move from City <var>1</var> to City <var>3</var> in <var>1</var> minute.

Use the <var>4</var>-th railroad to move from City <var>3</var> to City <var>5</var> in <var>1</var> minute.

At the exchange counter in City <var>5</var>, exchange <var>63</var> gold coins for <var>63</var> silver coins in <var>63</var> minutes.

Use the <var>4</var>-th railroad to move from City <var>5</var> to City <var>3</var> in <var>1</var> minute.

Use the <var>2</var>-nd railroad to move from City <var>3</var> to City <var>1</var> in <var>1</var> minute.

Use the <var>5</var>-th railroad to move from City <var>1</var> to City <var>6</var> in <var>1</var> minute.

Sample Input 4

4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7

Sample Output 4

1
3
5

The railway network in this input is shown in the figure below:

Sample Input 5

2 1 0
1 2 1 1
1 1000000000
1 1

Sample Output 5

1000000001

The railway network in this input is shown in the figure below:

You can travel from City <var>1</var> to City <var>2</var> in <var>1000000001</var> minutes, as follows:

At the exchange counter in City <var>1</var>, exchange <var>1</var> gold coin for <var>1</var> silver coin in <var>1000000000</var> minutes.

Use the <var>1</var>-st railroad to move from City <var>1</var> to City <var>2</var> in <var>1</var> minute.


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

N, M, S = map(int, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
    u, v, a, b = map(int, input().split())
    u -= 1
    v -= 1
    edge[u].append((v, a, b))
    edge[v].append((u, a, b))
CD = tuple(tuple(map(int, input().split())) for _ in range(N))

inf = 10**18
U = N*50
S = min(S, U)
dist = [[inf] * (U + 1) for _ in range(N)]
dist[0][S] = 0

que = [(0, 0, S)]  # 時間、現在地、銀貨の数
while que:
    time, now, silver = heapq.heappop(que)
    if dist[now][silver] < time:
        continue
    # 両替する
    c, d = CD[now]
    for i in range(1, U + 1):
        if silver + i > U:
            break
        t = (i + c - 1) // c * d
        if dist[now][silver + i] > time + t:
            dist[now][silver + i] = time + t
            heapq.heappush(que, (time + t, now, silver + i))
        else:
            break
    # 移動する
    for nxt, s, t in edge[now]:
        if silver < s:
            continue
        if dist[nxt][silver - s] > time + t:
            dist[nxt][silver - s] = time + t
            heapq.heappush(que, (time + t, nxt, silver - s))

for i in range(1, N):
    print(min(dist[i]))


import numpy as np

N = int(input())

S = list(map(int,input().split()))
T = list(map(int,input().split()))
U = np.array(list(map(int,input().split())),dtype = np.uint64)
V = np.array(list(map(int,input().split())),dtype = np.uint64)

ans = np.zeros((N,N),dtype = np.uint64)

for n in range(64):
  u = (U>>n)&1
  v = (V>>n)&1
  su = [int(S[i]*2+u[i]) for i in range(N)]
  tv = [int(T[i]*2+v[i]) for i in range(N)]
  suzerozero = []
  suoneone = []
  tvzerozero = []
  tvoneone = []
  for i in range(N):
    if su[i] == 0:
      suzerozero.append(i)
    if su[i] == 3:
      suoneone.append(i)
  for i in range(N):
    if tv[i] == 0:
      tvzerozero.append(i)
    if tv[i] == 3:
      tvoneone.append(i)

  b = np.zeros((N,N),dtype = np.uint64)
  ###行のAND=1とOR=0を埋める###
  for i in range(N):
    if su[i] == 1:
      b[i] = np.ones(N,int)
  ###列のAND=1とOR=0を埋める###
  for i in range(N):
    if tv[i] == 1:
      b[:,i] = np.ones(N,int)
  ###行と列の値が一致するところを埋める###
  b |= np.dot(np.array([u]).T,np.ones((1,N),dtype = np.uint64)) & np.dot(np.array([v]).T,np.ones((1,N),dtype = np.uint64)).T
  ###行のOR=1を満たしていく###
  if 1 not in tv and 3 not in tv:
    m = len(tvzerozero)
    now = 0
    for i in suoneone:
      b[i][tvzerozero[now%m]] += 1
      now += 1
  ###列のOR=1を満たしていく###
  if 1 not in su and 3 not in su:
    m = len(suzerozero)
    now = 0
    for i in tvoneone:
      b[suzerozero[now%m]][i] += 1
      now += 1
  ans += b<<n

def end():
  print(-1)
  exit()
for i in range(N):
  if S[i] == 0:
    now = ans[i][0]
    for j in range(1,N):
      now &= ans[i][j]
  if S[i] == 1:
    now = ans[i][0]
    for j in range(1,N):
      now |= ans[i][j]
  if now != U[i]:
    end()
for i in range(N):
  if T[i] == 0:
    now = ans[0][i]
    for j in range(1,N):
      now &= ans[j][i]
  if T[i] == 1:
    now = ans[0][i]
    for j in range(1,N):
      now |= ans[j][i]
  if now != V[i]:
    end()

for item in ans:
  print(*list(item))

def numba_compile(numba_config):
    import os, sys
    if sys.argv[-1] == "ONLINE_JUDGE":
        from numba import njit
        from numba.pycc import CC
        cc = CC("my_module")
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature)(func)
            cc.export(func.__name__, signature)(func)
        cc.compile()
        exit()
    elif os.name == "posix":
        exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
        for func, _ in numba_config:
            globals()[func.__name__] = vars()[func.__name__]
    else:
        from numba import njit
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature, cache=True)(func)
        print("compiled!", file=sys.stderr)

import numpy as np

def solve_1bit(N, rps, cps, rv, cv):
    res = np.full((N, N), 2, dtype=np.uint64)
    if N == 1:
        res[0, 0] = rv[0]
        return res
    r_all = np.array([False, False])
    for i, (ps, v) in enumerate(zip(rps, rv)):
        if ps ^ v == 1:
            res[i, :] = v
            r_all[v] = True
    c_all = np.array([False, False])
    for i, (ps, v) in enumerate(zip(cps, cv)):
        if ps ^ v == 1:
            res[:, i] = v
            c_all[v] = True
    if (r_all[0] and c_all[1]) or (r_all[1] and c_all[0]):
        return res
    if r_all[0] and c_all[0]:
        return np.where(res==2, np.uint64(1), res)
    if r_all[1] and c_all[1]:
        return np.where(res==2, np.uint64(0), res)
    if np.all(r_all):
        for y in range(N):
            for x in range(N):
                if res[y, x] == 2:
                    res[y, x] = rv[y]
        return res
    if np.all(c_all):
        for y in range(N):
            for x in range(N):
                if res[y, x] == 2:
                    res[y, x] = cv[x]
        return res
    if r_all[0]:
        if (cv==0).any():
            x = (cv==0).nonzero()[0][0]
            res[:, x] = 0
            return np.where(res==2, np.uint64(1), res)
        x = 0
        for y in range(N):
            v = rv[y]
            if v == 0 and res[y, 0] == 2:
                res[y, x] = 0
                x = (x+1) % N
        return np.where(res==2, np.uint64(1), res)
    if r_all[1]:
        if (cv==1).any():
            x = (cv==1).nonzero()[0][0]
            res[:, x] = 1
            return np.where(res==2, np.uint64(0), res)
        x = 0
        for y in range(N):
            v = rv[y]
            if v == 1 and res[y, 0] == 2:
                res[y, x] = 1
                x = (x+1) % N
        return np.where(res==2, np.uint64(0), res)
    if c_all[0]:
        if (rv==0).any():
            y = (rv==0).nonzero()[0][0]
            res[y, :] = 0
            return np.where(res==2, np.uint64(1), res)
        y = 0
        for x in range(N):
            v = cv[x]
            if v == 0 and res[0, x] == 2:
                res[y, x] = 0
                y = (y+1) % N
        return np.where(res==2, np.uint64(1), res)
    if c_all[1]:
        if (rv==1).any():
            y = (rv==1).nonzero()[0][0]
            res[y, :] = 1
            return np.where(res==2, np.uint64(0), res)
        y = 0
        for x in range(N):
            v = cv[x]
            if v == 1 and res[0, x] == 2:
                res[y, x] = 1
                y = (y+1) % N
        return np.where(res==2, np.uint64(0), res)
    for y in range(N):
        for x in range(N):
            res[y, x] = (y^x)&1
    return res

def solve(N, row_prod_sum, col_prod_sum, row_val, col_val):
    res = np.zeros((N, N), dtype=np.uint64)
    for i in range(64):
        rps = row_prod_sum
        cps = col_prod_sum
        rv = row_val>>i&1
        cv = col_val>>i&1
        r = solve_1bit(N, rps, cps, rv, cv)
        res |= r<<i
    #print(res)
    prod = res[0].copy()
    sum_ = res[0].copy()
    for y in range(1, N):
        prod &= res[y]
        sum_ |= res[y]
    #print(prod, sum_)
    if (prod[col_prod_sum==0] != col_val[col_prod_sum==0]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    if (sum_[col_prod_sum==1] != col_val[col_prod_sum==1]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    prod = res[:, 0].copy()
    sum_ = res[:, 0].copy()
    for x in range(1, N):
        prod &= res[:, x]
        sum_ |= res[:, x]
    #print(prod, sum_)
    if (prod[row_prod_sum==0] != row_val[row_prod_sum==0]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    if (sum_[row_prod_sum==1] != row_val[row_prod_sum==1]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    return 1, res

numba_compile([
    [solve_1bit, "u8[:,:](i8,u8[:],u8[:],u8[:],u8[:])"],
])

def main():
    N = int(input())
    row_prod_sum = np.array(input().split(), dtype=np.uint64)
    col_prod_sum = np.array(input().split(), dtype=np.uint64)
    row_val = np.array(input().split(), dtype=np.uint64)
    col_val = np.array(input().split(), dtype=np.uint64)
    t, ans = solve(N, row_prod_sum, col_prod_sum, row_val, col_val)
    if t:
        for lst in ans.tolist():
            print(" ".join(map(str, lst)))
    else:
        print(-1)

main()

Score : <var>600</var> points

Problem Statement

Given are an integer <var>N</var> and arrays <var>S</var>, <var>T</var>, <var>U</var>, and <var>V</var>, each of length <var>N</var>.
Construct an <var>N×N</var> matrix <var>a</var> that satisfy the following conditions:

<var>a_{i,j}</var> is an integer.

<var>0 \leq a_{i,j}  \lt 2^{64}</var>.

If <var>S_{i} = 0</var>, the bitwise AND of the elements in the <var>i</var>-th row is <var>U_{i}</var>.

If <var>S_{i} = 1</var>, the bitwise OR of the elements in the <var>i</var>-th row is <var>U_{i}</var>.

If <var>T_{i} = 0</var>, the bitwise AND of the elements in the <var>i</var>-th column is <var>V_{i}</var>.

If <var>T_{i} = 1</var>, the bitwise OR of the elements in the <var>i</var>-th column is <var>V_{i}</var>.

However, there may be cases where no matrix satisfies the conditions.

Constraints

All values in input are integers.

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

<var> 0 \leq S_{i} \leq 1 </var>

<var> 0 \leq T_{i} \leq 1  </var>

<var> 0 \leq U_{i} \lt 2^{64}  </var>

<var> 0 \leq V_{i} \lt 2^{64}  </var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_{1}</var> <var>S_{2}</var> <var>...</var>  <var>S_{N}</var>
<var>T_{1}</var> <var>T_{2}</var> <var>...</var>  <var>T_{N}</var>
<var>U_{1}</var> <var>U_{2}</var> <var>...</var>  <var>U_{N}</var>
<var>V_{1}</var> <var>V_{2}</var> <var>...</var>  <var>V_{N}</var>

Output

If there exists a matrix that satisfies the conditions, print one such matrix in the following format:

<var>a_{1,1}</var> <var>...</var>  <var>a_{1,N}</var>
<var>:</var>
<var>a_{N,1}</var> <var>...</var>  <var>a_{N,N}</var>

Note that any matrix satisfying the conditions is accepted.

If no matrix satisfies the conditions, print <var>-1</var>.

Sample Input 1

2
0 1
1 0
1 1
1 0

Sample Output 1

1 1
1 0

In Sample Input <var>1</var>, we need to find a matrix such that:

the bitwise AND of the elements in the <var>1</var>-st row is <var>1</var>;

the bitwise OR of the elements in the <var>2</var>-nd row is <var>1</var>;

the bitwise OR of the elements in the <var>1</var>-st column is <var>1</var>;

the bitwise AND of the elements in the <var>2</var>-nd column is <var>0</var>.

Sample Input 2

2
1 1
1 0
15 15
15 11

Sample Output 2

15 11
15 11


import numpy as np

def solve_1bit(N, rps, cps, rv, cv):
    res = np.full((N, N), 2, dtype=np.uint64)
    if N == 1:
        res[0, 0] = rv[0]
        return res
    r_all = [False, False]
    for i, (ps, v) in enumerate(zip(rps, rv)):
        if ps ^ v == 1:
            res[i, :] = v
            r_all[v] = True
    c_all = [False, False]
    for i, (ps, v) in enumerate(zip(cps, cv)):
        if ps ^ v == 1:
            res[:, i] = v
            c_all[v] = True
    if (r_all[0] and c_all[1]) or (r_all[1] and c_all[0]):
        return res
    if r_all[0] and c_all[0]:
        return np.where(res==2, 1, res)
    if r_all[1] and c_all[1]:
        return np.where(res==2, 0, res)
    if all(r_all):
        for y in range(N):
            for x in range(N):
                if res[y, x] == 2:
                    res[y, x] = cv[x]
        return res
    if all(c_all):
        for y in range(N):
            for x in range(N):
                if res[y, x] == 2:
                    res[y, x] = rv[y]
        return res
    if r_all[0]:
        if (cv==0).any():
            x = (cv==0).nonzero()[0][0]
            res[:, x] = 0
            return np.where(res==2, 1, res)
        x = 0
        for y in range(N):
            v = rv[y]
            if v == 0 and res[y, 0] == 2:
                res[y, x] = 0
                x = (x+1) % N
        return np.where(res==2, 1, res)
    if r_all[1]:
        if (cv==1).any():
            x = (cv==1).nonzero()[0][0]
            res[:, x] = 1
            return np.where(res==2, 0, res)
        x = 0
        for y in range(N):
            v = rv[y]
            if v == 1 and res[y, 0] == 2:
                res[y, x] = 1
                x = (x+1) % N
        return np.where(res==2, 0, res)
    if c_all[0]:
        if (rv==0).any():
            y = (rv==0).nonzero()[0][0]
            res[y, :] = 0
            return np.where(res==2, 1, res)
        y = 0
        for x in range(N):
            v = cv[x]
            if v == 0 and res[0, x] == 2:
                res[y, x] = 0
                y = (y+1) % N
        return np.where(res==2, 1, res)
    if c_all[1]:
        if (rv==1).any():
            y = (rv==1).nonzero()[0][0]
            res[y, :] = 1
            return np.where(res==2, 0, res)
        y = 0
        for x in range(N):
            v = cv[x]
            if v == 1 and res[0, x] == 2:
                res[y, x] = 1
                y = (y+1) % N
        return np.where(res==2, 0, res)
    for y in range(N):
        for x in range(N):
            res[y, x] = (y^x)&1
    return res

def solve(N, row_prod_sum, col_prod_sum, row_val, col_val):
    res = np.zeros((N, N), dtype=np.uint64)
    for i in range(64):
        rps = row_prod_sum
        cps = col_prod_sum
        rv = row_val>>i&1
        cv = col_val>>i&1
        r = solve_1bit(N, rps, cps, rv, cv)
        res |= r<<i
    return 1, res
    #print(res)
    prod = res[0].copy()
    sum_ = res[0].copy()
    for y in range(1, N):
        prod &= res[y]
        sum_ |= res[y]
    #print(prod, sum_)
    if (prod[col_prod_sum==0] != col_val[col_prod_sum==0]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    if (sum_[col_prod_sum==1] != col_val[col_prod_sum==1]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    prod = res[:, 0].copy()
    sum_ = res[:, 0].copy()
    for x in range(1, N):
        prod &= res[:, x]
        sum_ |= res[:, x]
    #print(prod, sum_)
    if (prod[row_prod_sum==0] != row_val[row_prod_sum==0]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    if (sum_[row_prod_sum==1] != row_val[row_prod_sum==1]).any():
        return 0, np.array([[-1]], dtype=np.int64)
    return 1, res

N = int(input())
row_prod_sum = np.array(input().split(), dtype=np.uint64)
col_prod_sum = np.array(input().split(), dtype=np.uint64)
row_val = np.array(input().split(), dtype=np.uint64)
col_val = np.array(input().split(), dtype=np.uint64)
t, ans = solve(N, row_prod_sum, col_prod_sum, row_val, col_val)
if t:
    for lst in ans.tolist():
        print(" ".join(map(str, lst)))
else:
    print(-1)


n, m = map(int, input().split())
a = [int(s) for s in input().split()]
days = n - sum(a)
print(days) if days >= 0 else print(-1)

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

Score : <var>200</var> points

Problem Statement

Takahashi has <var>N</var> days of summer vacation.

His teacher gave him <var>M</var> summer assignments. It will take <var>A_i</var> days for him to do the <var>i</var>-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

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

<var>1 \leq M \leq 10^4</var>

<var>1 \leq A_i \leq 10^4</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>...</var> <var>A_M</var>

Output

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

Sample Input 1

41 2
5 6

Sample Output 1

30

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

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


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

if N - sum(A) > 0:
    print(N-sum(A))
else:
    print(-1)


def readinput():
    n=int(input())
    return n

def main(n):
    ans=0
    for i in range(1,n+1):
        if i%3==0 or i%5==0:
            continue
        else:
            ans+=i
    return ans

if __name__=='__main__':
    n=readinput()
    ans=main(n)
    print(ans)

N = int(input())

answer = 0

for i in range(1, N + 1):
    if i % 3 != 0 and i % 5 != 0:
        answer = answer + i

print(answer)

Score : <var>200</var> points

Problem Statement

Let us define the FizzBuzz sequence <var>a_1,a_2,...</var> as follows:

If both <var>3</var> and <var>5</var> divides <var>i</var>, <var>a_i=\mbox{FizzBuzz}</var>.

If the above does not hold but <var>3</var> divides <var>i</var>, <var>a_i=\mbox{Fizz}</var>.

If none of the above holds but <var>5</var> divides <var>i</var>, <var>a_i=\mbox{Buzz}</var>.

If none of the above holds, <var>a_i=i</var>.

Find the sum of all numbers among the first <var>N</var> terms of the FizzBuzz sequence.

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the sum of all numbers among the first <var>N</var> terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first <var>15</var> terms of the FizzBuzz sequence are:

<var>1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}</var>

Among them, numbers are <var>1,2,4,7,8,11,13,14</var>, and the sum of them is <var>60</var>.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


n=int(input())
a=[0]*n
for i in range(n):
    if i%3==0 or i%5==0:
        a[i]=0
    else:
        a[i]=i
print(sum(a))


N, K = map(int, input().split())
ans = N
a = ans // K
b = ans % K

if a > 0:
    ans = N - K * a
    a = ans // K
    b = ans % K

if a  == 0:
    if ans > abs(ans - K):
        print(abs(ans - K))
    else:
        print(ans)

Score : <var>300</var> points

Problem Statement

Given any integer <var>x</var>, Aoki can do the operation below.

Operation: Replace <var>x</var> with the absolute difference of <var>x</var> and <var>K</var>.

You are given the initial value of an integer <var>N</var>. Find the minimum possible value taken by <var>N</var> after Aoki does the operation zero or more times.

Constraints

<var>0 ≤ N ≤ 10^{18}</var>

<var>1 ≤ K ≤ 10^{18}</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

Print the minimum possible value taken by <var>N</var> after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, <var>N=7</var>.

After one operation, <var>N</var> becomes <var>|7-4| = 3</var>.

After two operations, <var>N</var> becomes <var>|3-4| = 1</var>, which is the minimum value taken by <var>N</var>.

Sample Input 2

2 6

Sample Output 2

2

<var>N=2</var> after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


n, k = map(int,input().split())
print(n%k)


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

m = 0
while True:
    m += 1
    if k**m > n:
        print(m)
        break

N,K=map(int,input().split())
ans=1
while N>1:
    N=N//K
    ans+=1
if N%K==0:
    ans-=1
print(ans)

Score : <var>200</var> points

Problem Statement

Given is an integer <var>N</var>. Find the number of digits that <var>N</var> has in base <var>K</var>.

Notes

For information on base-<var>K</var> representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

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

<var>2 \leq K \leq 10</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

Print the number of digits that <var>N</var> has in base <var>K</var>.

Sample Input 1

11 2

Sample Output 1

4

In binary, <var>11</var> is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


n,k = map(int,input().split())
i = 0
while k**i < n:
  i += 1
print(i)


n = int(input())
s = list(input() for _ in range(n))
d = {}
for i in range(n):
    if s[i] in d:
        d[s[i]] += 1
    else:
        d[s[i]] = 1
m = max(d.values())
for s in sorted(k for k in d if d[k] == m):
    print(s)

n = int(input())
s = list(input() for _ in range(n))
d = {}
for i in range(n):
    if s[i] in d:
        d[s[i]] += 1
    else:
        d[s[i]] = 1

m = max(d.values())
l=[]
for i in d:
    if d[i] == m:
        l.append(i)
for i in sorted(l):
    print(i)

Score: <var>300</var> points

Problem Statement

We have <var>N</var> voting papers. The <var>i</var>-th vote <var>(1 \leq i \leq N)</var> has the string <var>S_i</var> written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

<var>S_i</var> <var>(1 \leq i \leq N)</var> are strings consisting of lowercase English letters.

The length of <var>S_i</var> <var>(1 \leq i \leq N)</var> is between <var>1</var> and <var>10</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>:</var>
<var>S_N</var>

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


n = int(input())
s = list(input() for _ in range(n))
d = {}
for i in range(n):
    if s[i] in d:
        d[s[i]] += 1
    else:
        d[s[i]] = 1
m = d[max(d)]
for s in sorted(k for k in d if d[k] == m):
    print(s)


# coding: utf-8

def main():
    N, M = map(int, input().split())
    ans = [0, 0]
    A = [[0, 0] for _ in range(N)]

    for i in range(M):
        p, s = input().split()
        p = int(p)
        if s == 'AC':
            A[p - 1][1] = 1
        elif A[p - 1][1] == 0:
            A[p - 1][0] += 1

    for i, j in A:
        if j == 1:
            ans[0] += 1
            ans[1] += i

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

if __name__ == "__main__":
    main()

def resolve():
    n,m = map(int,input().split())
    ac_list = [0]*n
    wa_count = [0]*n
    ac = 0
    wa = 0
    for _ in range(m):
        p,s = input().split()
        if s == 'WA' and (ac_list[int(p)-1]==0):
            wa_count[int(p)-1] += 1
        elif s == 'AC' and (ac_list[int(p)-1]==0):
            ac += 1
            ac_list[int(p)-1] = 1
    for (i,j) in zip(wa_count,ac_list):
        if j: wa+=i
    print(f'{ac} {wa}')
resolve()

Score : <var>300</var> points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had <var>N</var> problems.

Takahashi made <var>M</var> submissions during the contest.

The <var>i</var>-th submission was made for the <var>p_i</var>-th problem and received the verdict <var>S_i</var> (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

<var>N</var>, <var>M</var>, and <var>p_i</var> are integers.

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

<var>0 \leq M \leq 10^5</var>

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

<var>S_i</var> is AC or WA.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>p_1</var> <var>S_1</var>
<var>:</var>
<var>p_M</var> <var>S_M</var>

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


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

AC = 0
WA = 0
AC_count = set()
num = set()

for _ in range(M):
    p, S = input().split()
    if not int(p) in num:
        num.add(int(p))
        if S == 'WA':
            WA += 1
        else:
            AC += 1
            AC_count.add(int(p))
    else:
        if S == 'AC' and not int(p) in AC_count:
            AC += 1
            AC_count.add(int(p))
        elif S == 'WA' and not  int(p) in AC_count:
            WA += 1

print(AC, WA)


h,w = map(int,input().split())
C = [list(input()) for i in range(h)]
startls = []

for i in range(h):
    for j in range(w):
        if C[i][j] == '.':
            startls.append([i,j])

dy_dx = [[1,0],[0,1],[-1,0],[0,-1]]
ans = 0
for start in startls:
    visited = [[-1 for i in range(w)] for i in range(h)]
    visited[start[0]][start[1]] = 0
    cost = 0
    queue = [start]
    while len(queue) > 0:
        now = queue.pop(0)
        cost = visited[now[0]][now[1]]+1
        for i in range(4):
            y = now[0]+dy_dx[i][0]
            x = now[1]+dy_dx[i][1]
            if 0 <= y < h and 0 <= x < w:
                if C[y][x] != '#' and visited[y][x] == -1:
                    visited[y][x] = cost
                    queue.append([y,x])
                    ans = max(ans,cost)
print(ans)

#!/usr/bin/env python3
def main():
    from collections import deque
    import numpy as np

    H, W = map(int, input().split())
    S = [list(input()) for _ in range(H)]

    move = ((0, 1), (0, -1), (1, 0), (-1, 0))
    seen = [[False] * W for _ in range(H)]
    ans = 0
    for sh in range(H):
        for sw in range(W):
            if S[sh][sw] == '#' or seen[sh][sw]:
                continue
            seen[sh][sw] = True
            queue = deque([(sh, sw)])
            # distance = np.zeros((H, W), dtype=np.int16)
            distance = np.full((H, W), -1, dtype=np.int16)
            distance[sh, sw] = 0
            while queue:
                h, w = queue.popleft()
                for dh, dw in move:
                    nh = h + dh
                    nw = w + dw
                    if (1
                            and 0 <= nh < H
                            and 0 <= nw < W
                            and S[nh][nw] == '.'
                            and distance[nh][nw] == -1):
                        distance[nh][nw] = distance[h][w] + 1
                        queue.append((nh, nw))
            ans = max(ans, distance.max())
    print(ans)

if __name__ == '__main__':
    main()

Score : <var>400</var> points

Problem Statement

Takahashi has a maze, which is a grid of <var>H \times W</var> squares with <var>H</var> horizontal rows and <var>W</var> vertical columns.

The square at the <var>i</var>-th row from the top and the <var>j</var>-th column is a "wall" square if <var>S_{ij}</var> is #, and a "road" square if <var>S_{ij}</var> is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

<var>1 \leq H,W \leq 20</var>

<var>S_{ij}</var> is . or #.

<var>S</var> contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>S_{11}</var><var>...</var><var>S_{1W}</var>
<var>:</var>
<var>S_{H1}</var><var>...</var><var>S_{HW}</var>

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


h,w = map(int,input().split())
C = [list(input()) for i in range(h)]
startls = []

for i in range(h):
    for j in range(w):
        if C[i][j] == '.':
            startls.append([i,j])

dy_dx = [[1,0],[0,1],[-1,0],[0,-1]]
ans = 0
for start in startls:
    visited = [[0 for i in range(w)] for i in range(h)]
    cost = 0
    queue = [start]
    while len(queue) > 0:
        now = queue.pop(0)
        cost = visited[now[0]][now[1]]+1
        for i in range(4):
            y = now[0]+dy_dx[i][0]
            x = now[1]+dy_dx[i][1]
            if 0 <= y < h and 0 <= x < w:
                if C[y][x] != '#' and visited[y][x] == 0:
                    visited[y][x] = cost
                    queue.append([y,x])
                    ans = max(ans,cost)
print(ans)


from itertools import accumulate

class Factorial:
    def __init__(self, n, mod=10**9+7):
        self.fac = [0] * (n+1)
        self.ifac = [0] * (n+1)
        self.fac[0] = 1
        self.ifac[0] = 1
        self.mod = mod
        modmod = self.mod - 2
        for i in range(n):
            self.fac[i+1] = self.fac[i] * (i+1) % self.mod
            self.ifac[i+1] = self.ifac[i] * pow(i+1, modmod, self.mod) % self.mod

    def comb(self, n, r):
        if n == 0 and r == 0:
            return 1
        if n < r or n < 0:
            return 0
        tmp =  self.ifac[n-r] * self.ifac[r] % self.mod
        return tmp * self.fac[n] % self.mod

    def perm(self, n, r):
        if n == 0 and r == 0:
            return 1
        if n < r or n < 0:
            return 0
        return (self.fac[n] * self.ifac[n-r]) % self.mod

def resolve():
    n, k = map(int, input().split())
    a = sorted(map(int, input().split()))
    mod = 10**9 + 7

    fact = Factorial(n + 1)
    lll = [fact.comb(i, k-1) for i in range(k-1, n)]
    # acc = list(accumulate(lll))

    ans = 0
    for i in range(n-k+1):
        # print(i, -1-i, f" --- {a[i]}, {a[-i-1]}, {lll[-i-1]}")
        ans = (ans + (a[-i-1] - a[i]) * lll[-i-1]) % mod
    print(ans)

if __name__ == "__main__":
    resolve()

class Enumerator:
    def __init__(self, N: int, MOD: int) -> None:
        self.fact = [1, 1]
        self.finv = [1, 1]
        self.invs = [0, 1]
        for i in range(2, N + 1):
            self.fact.append(self.fact[i - 1] * i % MOD)
            self.invs.append(-self.invs[MOD % i] * (MOD // i) % MOD)
            self.finv.append(self.finv[-1] * self.invs[-1] % MOD)
        self._MOD = MOD
        self._N = N

    def choose(self, n: int, k: int) -> int:
        if p := self.permutate(n, k):
            return p * self.finv[k] % self._MOD
        else:
            return 0

    def permutate(self, n: int, k: int) -> int:
        if n < k or n < 0 or k < 0:
            return 0
        assert n <= self._N and k <= self._N
        return self.fact[n] * self.finv[n - k] % self._MOD

    def choose_with_duplicates(self, n: int, k: int) -> int:
        return self.choose(n + k - 1, n)

N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 1_000_000_007
A.sort()
e = Enumerator(N, MOD)
nck = e.choose(N, K)
ans = 0
for i in range(N - 1):
    ci = nck - e.choose(i + 1, K) - e.choose(N - i - 1, K)
    ans += ci * (A[i + 1] - A[i])
    ans %= MOD
print(ans)

Score : <var>500</var> points

Problem Statement

For a finite set of integers <var>X</var>, let <var>f(X)=\max X - \min X</var>.

Given are <var>N</var> integers <var>A_1,...,A_N</var>.

We will choose <var>K</var> of them and let <var>S</var> be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are <var>{}_N C_K</var> ways to make this choice. Find the sum of <var>f(S)</var> over all those ways.

Since the answer can be enormous, print it <var>\bmod (10^9+7)</var>.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_1</var> <var>...</var> <var>A_N</var>

Output

Print the answer <var>\bmod (10^9+7)</var>.

Sample Input 1

4 2
1 1 3 4

Sample Output 1

11

There are six ways to choose <var>S</var>: <var>\{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\}</var> (we distinguish the two <var>1</var>s). The value of <var>f(S)</var> for these choices are <var>0,2,3,2,3,1</var>, respectively, for the total of <var>11</var>.

Sample Input 2

6 3
10 10 10 -10 -10 -10

Sample Output 2

360

There are <var>20</var> ways to choose <var>S</var>. In <var>18</var> of them, <var>f(S)=20</var>, and in <var>2</var> of them, <var>f(S)=0</var>.

Sample Input 3

3 1
1 1 1

Sample Output 3

0

Sample Input 4

10 6
1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0

Sample Output 4

999998537

Print the sum <var>\bmod (10^9+7)</var>.


n,k=map(int,input().split())
a=sorted(list(map(int,input().split())))
p=10**9+7

def fact(n,p):
    a=[[] for _ in range(n+1)]
    a[0]=1
    for i in range(n):
        a[i+1]=(a[i]*(i+1))%p
    return a
f=fact(n,p)
def com(n,r):
    return f[n]//(f[r]*f[n-r])
ans=0
for i in range(n-k+1):
    ans=ans+(a[-i-1]-a[i])*com(n-i-1,k-1)
print(ans%p)


#!/usr/bin/env python3
def main():
    N, K = map(int, input().split())
    R, S, P = map(int, input().split())
    T = input()

    command = [''] * N
    ans = 0
    for i, t in enumerate(T):
        if t == 'r':
            point = P
            command_candidate = 'p'
        elif t == 's':
            point = R
            command_candidate = 'r'
        else:
            point = S
            command_candidate = 's'

        if i >= K and command[i - K] == command_candidate:
            point = 0
            command_candidate = ''
        ans += point
        command[i] = command_candidate
    print(ans)

if __name__ == '__main__':
    main()

def rle(a):
    ll,l=[],1
    for i in range(len(a)-1):
        if a[i]==a[i+1]:
            l+=1
        else:
            ll.append([l,a[i]])
            l=1
    ll.append([l,a[-1]])
    return ll
n,k=map(int,input().split())
r,s,p=map(int,input().split())
t=input()
ans=0
w=[]
for i in range(k):
    j=i
    b=""
    while j<n:
        b+=t[j]
        j+=k
    w.append(b)
for i in t:
    if i=="r":
        ans+=p
    elif i=="s":
        ans+=r
    else:
        ans+=s
for x in w:
    st=rle(x)
    for i,j in st:
        if j=="r":
            ans-=(i//2)*p
        elif j=="s":
            ans-=(i//2)*r
        else:
            ans-=(i//2)*s
print(ans)

Score : <var>400</var> points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays <var>N</var> rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

<var>R</var> points for winning with Rock;

<var>S</var> points for winning with Scissors;

<var>P</var> points for winning with Paper.

However, in the <var>i</var>-th round, the player cannot use the hand he/she used in the <var>(i-K)</var>-th round. (In the first <var>K</var> rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string <var>T</var>. If the <var>i</var>-th character of <var>T</var> <var>(1 \leq i \leq N)</var> is r, the machine will play Rock in the <var>i</var>-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

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

<var>1 \leq K \leq N-1</var>

<var>1 \leq R,S,P \leq 10^4</var>

<var>N,K,R,S,</var> and <var>P</var> are all integers.

<var>|T| = N</var>

<var>T</var> consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>R</var> <var>S</var> <var>P</var>
<var>T</var>

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn <var>27</var> points.
We cannot earn more points, so the answer is <var>27</var>.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


#!/usr/bin/env python3
def main():
    N, K = map(int, input().split())
    R, S, P = map(int, input().split())
    T = input()

    win_hands = [0] * N
    for index, t in enumerate(T):
        if t == 'r':
            win_hands[index] = P
        elif t == 's':
            win_hands[index] = R
        else:
            win_hands[index] = S

    for i in range(K, N):
        if win_hands[i] == win_hands[i - K]:
            win_hands[i] = 0
    print(sum(win_hands))

if __name__ == '__main__':
    main()


Score : <var>900</var> points

Problem Statement

Let us consider a grid of squares with <var>N</var> rows and <var>N</var> columns. You want to put some domino pieces on this grid.
Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.

For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row.
We define the quality of each column similarly.

Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column,
or determine that such a placement doesn't exist.

Constraints

<var>2 \le N \le 1000</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If the required domino placement doesn't exist, print a single integer -1.

Otherwise, output your placement as <var>N</var> strings of <var>N</var> characters each.
If a square is not covered, the corresponding character must be . (a dot).
Otherwise, it must contain a lowercase English letter.
Squares covered by the same domino piece must contain the same letter.
If two squares have a common side but belong to different pieces, they must contain different letters.

Sample Input 1

6

Sample Output 1

aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b

The quality of every row and every column is 2.

Sample Input 2

2

Sample Output 2

-1


import sys
from itertools import accumulate, repeat, takewhile
from operator import mul

def main():
    N = int(next(sys.stdin.buffer))
    if N % 2:
        print(0)
        return
    print(sum(N // x for x in takewhile(lambda x: x <= N, accumulate(repeat(5), mul, initial=10))))

if __name__ == '__main__':
    main()

n = int(input())
cnt = 0
x = len(str(n))

if n % 2 == 1:
  print(0)
else:
  for i in range(1,26):
    cnt += n//((5**i)* 2)
  print(cnt)

Score : <var>500</var> points

Problem Statement

For an integer <var>n</var> not less than <var>0</var>, let us define <var>f(n)</var> as follows:

<var>f(n) = 1</var> (if <var>n < 2</var>)

<var>f(n) = n f(n-2)</var> (if <var>n \geq 2</var>)

Given is an integer <var>N</var>. Find the number of trailing zeros in the decimal notation of <var>f(N)</var>.

Constraints

<var>0 \leq N \leq 10^{18}</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of trailing zeros in the decimal notation of <var>f(N)</var>.

Sample Input 1

12

Sample Output 1

1

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

Sample Input 2

5

Sample Output 2

0

<var>f(5) = 5 × 3 × 1 = 15</var>, which has no trailing zeros.

Sample Input 3

1000000000000000000

Sample Output 3

124999999999999995


import sys
from itertools import accumulate, repeat, takewhile
from operator import mul

def main():
    N = int(next(sys.stdin.buffer))
    print(sum(N // x for x in takewhile(lambda x: x <= N, accumulate(repeat(5), mul, initial=10))))

if __name__ == '__main__':
    main()


### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

def resolve():
    readline=sys.stdin.readline
    mod=10**9+7
    n=int(readline())
    arr=list(map(int, readline().rstrip().split()))
    ans = 0
    x = 1
    for i in range(60):
        c = 0
        for j in range(n):
            if arr[j]&x != 0:
                c += 1
        ans += (c * (n-c)) * x
        ans %= mod
        x = x*2
    print(ans)
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで
### ----------------

import sys

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

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

    res = 0
    for mask in range(60):
        cnt1 = sum([1 if a & (1 << mask) else 0 for a in A])
        cnt0 = n - cnt1
        res += (pow(2, mask, mod) * cnt1 * cnt0) % mod
        res %= mod
    print(res)

if __name__ == '__main__':
    resolve()

Score : <var>400</var> points

Problem Statement

We have <var>N</var> integers. The <var>i</var>-th integer is <var>A_i</var>.

Find <var>\sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j)</var>, modulo <var>(10^9+7)</var>.

What is <var>\mbox{ XOR }</var>?

The XOR of integers <var>A</var> and <var>B</var>, <var>A \mbox{ XOR } B</var>, is defined as follows:

When <var>A \mbox{ XOR } B</var> is written in base two, the digit in the <var>2^k</var>'s place (<var>k \geq 0</var>) is <var>1</var> if either <var>A</var> or <var>B</var>, but not both, has <var>1</var> in the <var>2^k</var>'s place, and <var>0</var> otherwise.

For example, <var>3 \mbox{ XOR } 5 = 6</var>. (In base two: <var>011 \mbox{ XOR } 101 = 110</var>.)

Constraints

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

<var>0 \leq A_i < 2^{60}</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>A_2</var> <var>...</var> <var>A_N</var>

Output

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

Sample Input 1

3
1 2 3

Sample Output 1

6

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

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo <var>(10^9+7)</var>.


n = int(input())
n1 = n//2
s = input()
s1 = s[n1:]
s2 = s[:n1]
if n % 2 != 0:
    print('No')
else:
    if s1 == s2:
        print('Yes')
    else:
        print('No')

N = int(input())
S = input()
if(N % 2 == 1):
    print("No")
    exit()
m = N//2
for i in range(m):
    if(S[i] != S[i+m]):
        print("No")
        exit()
print("Yes")

Score : <var>200</var> points

Problem Statement

Given are a positive integer <var>N</var> and a string <var>S</var> of length <var>N</var> consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string <var>T</var> such that <var>S = T + T</var>.

Constraints

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

<var>S</var> consists of lowercase English letters.

<var>|S| = N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S</var>

Output

If <var>S</var> is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let <var>T = </var> abc, and <var>S = T + T</var>.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


N = int(input())
S = input()
if N%2!=0:
  print("No")
else:
  if S[:N//2]*2 == S:print("Ok")
  else : print("No")


import sys
X,Y = map(int,input().split())
if (X+Y)%3 != 0:
    print(0)
    sys.exit()
A = Y - (X+Y)//3
B = X - (X+Y)//3
if A<0 or B<0:
    print(0)
    sys.exit()
N = A+B
def cmb(n, r, mod):
    inv = [0,1]
    for i in range(2, N + 1):
        inv.append((-inv[mod % i] * (mod // i)) % mod)
    cmd = 1
    for i in range(1,min(r,n-r)+1):
        cmd = (cmd*(N-i+1)*inv[i])%mod
    return cmd

a = cmb(N,A,10**9+7)
print(a)

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

mod=pow(10, 9)+7

def comint(n, mod):
    fac = [0 for _ in range(n)]
    finv = [0 for _ in range(n)]
    inv = [0 for _ in range(n)]
    fac[0]=1
    fac[1]=1
    finv[0]=1
    finv[1]=1
    inv[1]=1

    for i in range(2, n):
        fac[i] = fac[i-1]*i%mod
        inv[i] = mod-inv[mod%i]*(mod//i)%mod
        finv[i] = finv[i-1]*inv[i]%mod
    return fac, finv

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

if (x+y)%3!=0:
    print(0)
else:
    n=(x+y)//3
    a=x-n
    b=y-n
    fac, finv = comint(a+b+1, mod)
    print(com(a+b,a,fac,finv,mod))

Score : <var>400</var> points

Problem Statement

There is a knight - the chess piece - at the origin <var>(0, 0)</var> of a two-dimensional grid.

When the knight is at the square <var>(i, j)</var>, it can be moved to either <var>(i+1,j+2)</var> or <var>(i+2, j+1)</var>.

In how many ways can the knight reach the square <var>(X, Y)</var>?

Find the number of ways modulo <var>10^9 + 7</var>.

Constraints

<var>1 \leq X \leq 10^6</var>

<var>1 \leq Y \leq 10^6</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>Y</var>

Output

Print the number of ways for the knight to reach <var>(X, Y)</var> from <var>(0, 0)</var>, modulo <var>10^9 + 7</var>.

Sample Input 1

3 3

Sample Output 1

2

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

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach <var>(2,2)</var>.

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo <var>10^9 + 7</var>.


p = 1000000007
def mcomb(n, k):
    if n == 0 and k == 0:
        return 1
    if n < k or k < 0:
        return 0
    return fac[n] * pow(fac[n - k], p - 2, p) * pow(fac[k], p - 2, p) % p

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

a = (2 * Y - X) / 3
b = (2 * X - Y) / 3

if a.is_integer()==False or b.is_integer()==False or a<0 or b<0:
    print(0)
else:
    a=int(a)
    b=int(b)
    n = a + b
    fac = [0] * (n + 1)
    fac[0] = 1
    for i in range(n):
        fac[i + 1] = fac[i] * (i + 1) % p
        print(mcomb(n, a))
#他者の解答を参考にした


N,M=map(int,input().split())
lrc = [tuple(map(int,input().split())) for _ in range(M)]
lrc = sorted(lrc)
INF=10**20

class SegTree:
    """ segment tree with point modification and range product. """
    # # https://yukicoder.me/submissions/452850
    def __init__(self, N, data_f = min, data_unit=1<<30):
        self.N = N
        self.data_f = data_f
        self.data_unit = data_unit
        self.data = [self.data_unit] * (N + N)

    def build(self, raw_data):
        data = self.data
        f = self.data_f
        N = self.N
        data[N:] = raw_data[:]
        for i in range(N - 1, 0, -1):
            data[i] = f(data[i << 1], data[i << 1 | 1])

    def set_val(self, i, x):
        data = self.data
        f = self.data_f
        i += self.N
        data[i] = x
        while i > 1:
            data[i >> 1] = f(data[i], data[i ^ 1])
            i >>= 1

    def fold(self, L, R):
        """ compute for [L, R) """
        vL = vR = self.data_unit
        data = self.data
        f = self.data_f
        L += self.N
        R += self.N
        while L < R:
            if L & 1:
                vL = f(vL, data[L])
                L += 1
            if R & 1:
                R -= 1
                vR = f(data[R], vR)
            L >>= 1
            R >>= 1
        return f(vL, vR)

seg = SegTree(N,min,INF)
seg.set_val(0,0)

for i in range(1,M+1):
  l,r,c = lrc[i-1]
  tmp = seg.fold(l-1,r-1)
  seg.set_val(r-1,min(tmp+c, seg.fold(r-1,r)))

ans = seg.fold(N-1,N)
if ans == INF:
  print(-1)
else:
  print(ans)

import sys
from collections import defaultdict
import networkx as nx

input = sys.stdin.buffer.readline

N, M = map(int, input().split())
LR_dict = defaultdict(lambda: 10 ** 9)
for _ in range(M):
    l, r, c = map(int, input().split())
    LR_dict[(l, r)] = min(LR_dict[(l, r)], c)

G = nx.DiGraph()
G.add_nodes_from(range(1, N + 1))
G.add_weighted_edges_from([(x + 1, x, 0) for x in range(1, N)])
G.add_weighted_edges_from((l, r, c) for (l, r), c in LR_dict.items())

try:
    print(nx.dijkstra_path_length(G, 1, N))
except nx.NetworkXNoPath:
    print(-1)

Score : <var>600</var> points

Problem Statement

We have <var>N</var> points numbered <var>1</var> to <var>N</var> arranged in a line in this order.

Takahashi decides to make an undirected graph, using these points as the vertices.
In the beginning, the graph has no edge. Takahashi will do <var>M</var> operations to add edges in this graph.
The <var>i</var>-th operation is as follows:

The operation uses integers <var>L_i</var> and <var>R_i</var> between <var>1</var> and <var>N</var> (inclusive), and a positive integer <var>C_i</var>. For every pair of integers <var>(s, t)</var> such that <var>L_i \leq s < t \leq R_i</var>, add an edge of length <var>C_i</var> between Vertex <var>s</var> and Vertex <var>t</var>.

The integers <var>L_1, ..., L_M</var>, <var>R_1, ..., R_M</var>, <var>C_1, ..., C_M</var> are all given as input.

Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex <var>1</var> to Vertex <var>N</var> in the final graph.

Constraints

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

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

<var>1 \leq L_i < R_i \leq N</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>L_1</var> <var>R_1</var> <var>C_1</var>
<var>:</var>
<var>L_M</var> <var>R_M</var> <var>C_M</var>

Output

Print the length of the shortest path from Vertex <var>1</var> to Vertex <var>N</var> in the final graph.
If there is no shortest path, print -1 instead.

Sample Input 1

4 3
1 3 2
2 4 3
1 4 6

Sample Output 1

5

We have an edge of length <var>2</var> between Vertex <var>1</var> and Vertex <var>2</var>, and an edge of length <var>3</var> between Vertex <var>2</var> and Vertex <var>4</var>, so there is a path of length <var>5</var> between Vertex <var>1</var> and Vertex <var>4</var>.

Sample Input 2

4 2
1 2 1
3 4 2

Sample Output 2

-1

Sample Input 3

10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3

Sample Output 3

28


n,m=map(int,input().split())
lrc=[list(map(int,input().split())) for _ in range(m)]
lrc.sort(key=lambda x:x[0])
#
inf=float('inf')
seen=[inf]*n
seen[0]=0
now=0
from heapq import heappop,heappush
from collections import deque
lrc=deque(lrc)
todo=[now]
while todo:
  v=heappop(todo)
  lst=[]
  while lrc and lrc[0][0]<=v+1:
    lst.append(lrc.popleft())
  for l,r,c in lst:
    if seen[r-1]>seen[v]+c:
      heappush(todo,r-1)
      seen[r-1]=seen[v]+c
if seen[-1]!=inf:
  print(seen[-1])
else:
  print(-1)
#print(seen)


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

if a <= b or a - (b * 2) <= 0:
    print("0")

else:
    print(a - (b * 2))

A,B = map(int,input().split())
if(A >= B * 2):
    print(A - B * 2)
else:
    print(0)

Score : <var>100</var> points

Problem Statement

The window of Takahashi's room has a width of <var>A</var>. There are two curtains hung over the window, each of which has a horizontal length of <var>B</var>. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

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

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

<var>A</var> and <var>B</var> are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

12 4

Sample Output 1

4

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

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print <var>0</var>.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


a, b = map(int, input().split())
print(a - (2 * b))


def divisors(M):#Mの約数列 O(n^(0.5+e))
    import math
    d=[]
    i=1
    while math.sqrt(M)>=i:
        if M%i==0:
            d.append(i)
            if i**2!=M:
                d.append(M//i)
        i=i+1
    d.sort()
    return d

def Ind(b,n):
    count=0
    while n%b==0:
        count+=1
        n//=b
    return count

N=int(input())
X=input()
x=0
for i in range(N):
    x=2*x+int(X[i])

a=Ind(2,N)
n=N//(2**a)
d=divisors(n)
data={i*2**(a+1):0 for i in d}
mod=998244353

for i in d:
    Q=((2**(i*2**a)+1)*(x+1))//(2**N+1)
    Q%=mod
    data[i*2**(a+1)]+=Q
    data[i*2**(a+1)]%=mod

for i in d:
    for j in d:
        if i>j and i%j==0:
            data[i*2**(a+1)]-=data[j*2**(a+1)]
            data[i*2**(a+1)]%=mod

ans=0
for i in data:
    ans+=data[i]*i
    ans%=mod
print(ans)

n = int(input())
s = input()
mod = 998244353
pr = []
for i in range(2,n+1):
  if n%i == 0:
    pr.append((i,n//i))
num = []
pr = pr[::-1]
for p,q in pr:
  if p%2 == 0:
    continue
  ntmp = 0
  x = s[:q]
  y = ""
  for i in x:
    if i == "0":
      y += "1"
    else:
      y += "0"
  for i in range(q):
    if x[i] == "1":
      ntmp = (ntmp+pow(2,q-1-i,mod))%mod
  k = (x+y)*((p-1)//2)+x
  if s >= k:
    ntmp += 1
  num.append((p,2*q,ntmp))
ans = 2*n
for i in range(n-1,-1,-1):
  if s[i] == "1":
    ans = (ans+pow(2,n-1-i,mod)*2*n)%mod
for i in range(len(num)):
  p1,x,number = num[i]
  for p2,y,number2 in num:
    if x == y:
      continue
    elif p2%p1 == 0 and (p2//p1)%2 == 1:
      number -= number2
  num[i] = p1,x,number
for p1,x,number in num:
  ans = (ans-(2*n-x)*number)%mod
print(ans)

Score : <var>800</var> points

Problem Statement

Given are integers <var>N</var> and <var>X</var>. For each integer <var>k</var> between <var>0</var> and <var>X</var> (inclusive), find the answer to the following question, then compute the sum of all those answers, modulo <var>998244353</var>.

Let us repeat the following operation on the integer <var>k</var>. Operation: if the integer is currently odd, subtract <var>1</var> from it and divide it by <var>2</var>; otherwise, divide it by <var>2</var> and add <var>2^{N-1}</var> to it. How many operations need to be performed until <var>k</var> returns to its original value? (The answer is considered to be <var>0</var> if <var>k</var> never returns to its original value.)

Constraints

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

<var>0 \leq X < 2^N</var>

<var>X</var> is given in binary and has exactly <var>N</var> digits. (In case <var>X</var> has less than <var>N</var> digits, it is given with leading zeroes.)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X</var>

Output

Print the sum of the answers to the questions for the integers between <var>0</var> and <var>X</var> (inclusive), modulo <var>998244353</var>.

Sample Input 1

3
111

Sample Output 1

40

For example, for <var>k=3</var>, the operation changes <var>k</var> as follows: <var>1,0,4,6,7,3</var>. Therefore the answer for <var>k=3</var> is <var>6</var>.

Sample Input 2

6
110101

Sample Output 2

616

Sample Input 3

30
001110011011011101010111011100

Sample Output 3

549320998


n = int(input())
s = input()
mod = 998244353
pr = []
for i in range(2,n+1):
  if n%i == 0:
    pr.append((i,n//i))
num = []
pr = pr[::-1]
for p,q in pr:
  if p%2 == 0:
    continue
  ntmp = 0
  x = s[:q]
  y = ""
  for i in x:
    if i == "0":
      y += "1"
    else:
      y += "0"
  for i in range(q):
    if x[i] == "1":
      ntmp = (ntmp+pow(2,q-1-i,mod))%mod
  k = (x+y)*((p-1)//2)+x
  if s >= k:
    ntmp += 1
  num.append((p,2*q,ntmp))
ans = 2*n
for i in range(n-1,-1,-1):
  if s[i] == "1":
    ans = (ans+pow(2,n-1-i,mod)*2*n)%mod
for p1,x,number in num:
  for p2,y,number2 in num:
    if x == y:
      continue
    elif p2%p1 == 0 and (p2//p1)%2 == 1:
      number -= number2
  ans -= (2*n-x)*number
print(ans%mod)


def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

H, W, A, B = getNM()

"""
0, ?の場合は対応可能

0 0 0 1 1
0 0 0 1 1
0 0 0 1 1
0 0 0 1 1
0 0 0 1 1

対応出来ないケース無さそう？
1, 2の場合は？

これは1, 2
1 1 1 1 0
1 1 1 1 0
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
"""

res = [[''] * W for i in range(H)]

for i in range(H):
    for j in range(W):
        if (i < B) ^ (j < A):
            res[i][j] = str(0)
        else:
            res[i][j] = str(1)
res = [''.join(i) for i in res]
for i in res:
    print(i)

def main():
    H, W, A, B = map(int, input().split())
    for _ in range(B):
        tmp = ['0']*A + ['1']*(W-A)
        print(''.join(tmp))

    for _ in range(H-B):
        tmp = ['1']*A + ['0']*(W-A)
        print(''.join(tmp))

if __name__ == "__main__":
    main()

Score : <var>300</var> points

Problem Statement

We have a square grid with <var>H</var> rows and <var>W</var> columns.
Snuke wants to write <var>0</var> or <var>1</var> in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is <var>A</var>: the number of <var>0</var>s contained in the row, and the number of <var>1</var>s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is <var>B</var>: the number of <var>0</var>s contained in the column, and the number of <var>1</var>s contained in the column.

Determine if these conditions can be satisfied by writing <var>0</var> or <var>1</var> in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

<var>1 \leq H,W \leq 1000</var>

<var>0 \leq A</var>

<var>2 \times A \leq W</var>

<var>0 \leq B</var>

<var>2 \times B \leq H</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>A</var> <var>B</var>

Output

If the conditions cannot be satisfied by writing <var>0</var> or <var>1</var> in each of the squares, print <var>-1</var>.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

<var>s_{11}s_{12}\cdots s_{1W}</var>
<var>s_{21}s_{22}\cdots s_{2W}</var>
<var>\vdots</var>
<var>s_{H1}s_{H2}\cdots s_{HW}</var>

Here <var>s_{ij}</var> is the digit written in the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two <var>0</var>s and one <var>1</var>, so the first condition is satisfied.
Also, every column contains two <var>0</var>s and one <var>1</var>, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


h,w,a,b=map(int,input().split())
c=[0 for i in range(w)]
d=[0 for i in range(w)]
for i in range(a):
    c[i]=1
for i in range(a,w):
    d[i]=1
for i in range(h):
    if i<b:
        print(*c)
    else:
        print(*d)