n = int(input())

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

ans = 0

for i in range(1, n):
    if a[i] < a[i - 1]:
        ans += a[i - 1] - a[i]
        a[i] = a[i - 1]

print(ans)

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

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

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


from collections import deque
import sys

INF = 10 ** 8

H, W = map(int,input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
MAP = []
for _ in range(H):
    MAP.append(list(input()))
d = [[INF for i in range(W)] for j in range(H)]
tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]
tx_y = [(i, j) for i in range(-2, 3) for j in range(-2, 3)]

Q = deque()
Q.append([C[0]-1, C[1]-1, 0])

while len(Q) != 0:
    x, y, cnt = Q.popleft()

    if x == D[0]-1 and y == D[1]-1:
        print(cnt)
        sys.exit()

    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < H and 0 <= ny < W and MAP[nx][ny] == "." and d[nx][ny] > cnt:
            d[nx][ny] = cnt
            Q.appendleft([nx, ny, cnt])

    for i, j in tx_y:
        nx = x + i
        ny = y + j
        if 0 <= nx < H and 0 <= ny < W and MAP[nx][ny] == "." and d[nx][ny] > cnt+1:
            d[nx][ny] = cnt+1
            Q.append([nx, ny, cnt+1])

print(-1)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

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

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(lambda x: int(x) - 1, input().split())
Dh, Dw = map(lambda x: int(x) - 1, input().split())
maze = [input() for _ in range(H)]

INF = 10 ** 12
path = [[INF] * W for _ in range(H)]

walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

q = deque()
path[Ch][Cw] = 0
q.append((Ch, Cw, 0))

while q:
    x, y, s = q.popleft()
    for dx, dy in walk:
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
            path[nx][ny] = s
            q.appendleft((nx, ny, s))
    for dx, dy in warp:
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
            path[nx][ny] = s + 1
            q.appendleft((nx, ny, s + 1))

ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)


import numpy as np
from numba import njit, i8, u1, void, b1
import heapq

@njit(void(i8,i8,i8,i8,b1[:,:]),cache=True)
def solve(ch,cw,dh,dw,road_map):

    h,w = road_map.shape

    queue = [[0,ch*w+cw]]
    used_map = np.full(h*w,-1,dtype=np.int64)
    goal = dh*w+dw

    #move walk

    while len(queue) != 0:
        dot = heapq.heappop(queue)
        tl,n = dot[0],dot[1]
        th,tw = divmod(n,w)
        used_map[n] = tl
        if n == goal:
            break

        for x in range(-2,3,1):
            for y in range(-2,3,1):
                if x == y == 0:
                    continue
                if abs(x)+abs(y) <= 1:
                    loop = tl
                else:
                    loop = tl+1
                tx = th + x
                ty = tw + y
                next_n  = (th+x)*w+tw+y
                if tx < 0 or ty < 0 or tx >= h or ty >= w or road_map[tx][ty] == True:
                    continue
                check = used_map[next_n]
                if check == -1 or check > loop:
                    heapq.heappush(queue,[loop,next_n])

    print(used_map[dh*w+dw])

h,w = map(int,input().split())
ch,cw = map(int,input().split())
ch,cw = ch-1,cw-1
dh,dw = map(int,input().split())
dh,dw = dh-1,dw-1
road_map = np.array([[c=="#" for c in input()] for _ in range(h)])

solve(ch,cw,dh,dw,road_map)


import copy

from collections import deque

H, W = [int(x) for x in input().split()]

Ch,Cw = map(int,input().split())

Ch,Cw = Ch-1,Cw-1

Dh,Dw = map(int,input().split())

Dh,Dw = Dh-1,Dw-1

cell = [list(input()) for i in range(H)]

dp = [[-1]*W for _ in range(H)]

copy_stack = []
copy_stack.append([Ch,Cw])

nstack = []

dp[Ch][Cw] = 0

def search(stack):
    while len(stack) > 0:
        h,w = stack.pop()
        for dy, dx in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
            nh = h + dy
            nw = w + dx
            if 0 <= nh < H and 0 <= nw < W and (dp[nh][nw] == -1 or dp[nh][nw] > dp[h][w]):
                if cell[nh][nw] == '.':
                    dp[nh][nw] = dp[h][w]
                    stack.append([nh,nw])
                    copy_stack.append([nh,nw])

while True:
    if len(copy_stack):
        nstack = copy.copy(copy_stack)
    else:
        copy_stack = copy.copy(nstack)
    search(nstack)
    #print(dp)
    if dp[Dh][Dw] == -1:
        while len(copy_stack)>0:
            h,w = copy_stack.pop()
            for ddy in range(-2,3):
                for ddx in range(-2,3):
                    if ddy==ddx==0:
                        continue
                    nnh = h + ddy
                    nnw = w + ddx
                    if 0 <= nnh < H and 0 <= nnw < W:
                        if cell[nnh][nnw] == '.' and dp[nnh][nnw] == -1:
                            dp[nnh][nnw] = dp[h][w] + 1
                            nstack.append([nnh,nnw])
        if len(nstack) == 0:
            break
    else:
        break

if dp[Dh][Dw] != -1:
    print(dp[Dh][Dw])
else:
    print(-1)


import sys
from io import StringIO
import unittest

def resolve():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = []
    for h in range(H):
        Sh =  list(input())
        S.append(Sh)

    que = {(Ch-1,Cw-1)}
    jump_que = set()
    goal = (Dh-1, Dw-1)
    # searched=set()
    searched = [[False for i in range(W)] for i in range(H)]
    jump =0

    while(True):
        while(len(que)):
            tmp = que.pop()
            if tmp ==goal:
                print(jump)

                return

            searched[tmp[0]][tmp[1]] = True
            nxts=get_around(S,H,W,tmp[0],tmp[1], searched)
            # print(f'nxts: {nxts}')
            que=que|nxts
            jump_nxts = get_jump_around(S, H, W, tmp[0], tmp[1], searched)
            # print(f'jump_nxts: {jump_nxts}')
            jump_que = jump_que | jump_nxts
            # print(f'jump_que: {jump_que}')

        jump=jump+1
        que=jump_que
        jump_que = set()
        if len(que)==0:
            print('-1')
            return

def get_around(S,H,W, h,w, searched):
    hm = h-1
    hp =h+1
    wm = w-1
    wp= w+1
    nxt=set()
    if hm>=0 and S[hm][w]=='.' and not searched[hm][w]:
        nxt.add((hm,w))

    if hp<H and S[hp][w]=='.'and not searched[hp][w]:

        nxt.add((hp,w))
    if wm>=0 and S[h][wm]=='.'and not searched[h][wm]:
        nxt.add((h,wm))

    if wp<W and S[h][wp]=='.'and not searched[h][wp]:
        nxt.add((h,wp))
    return nxt

def get_jump_around(S,H,W, h,w, searched):
    hm = max(h-2,0)
    hp =min(h+2,H-1)
    wm = max(w-2,0)
    wp= min(w+2,W-1)
    nxt=set()
    # print(hm,hp,wm,wp)
    for h in range(hm,hp+1):
        for w in range(wm, wp + 1):
            if S[h][w]=='.' and not searched[h][w]:
                nxt.add((h, w))

    return nxt

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(output,out)

    def test_入力例_1(self):
        input = """4 4
1 1
4 4
..#.
..#.
.#..
.#.."""
        output = """1"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """4 4
1 4
4 1
.##.
####
####
.##."""
        output = """-1"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """4 4
2 2
3 3
....
....
....
...."""
        output = """0"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """4 5
1 2
2 5
#.###
####.
#..##
#..##"""
        output = """2"""
        self.assertIO(input, output)

if __name__ == "__main__":
    resolve()


import sys
sys.setrecursionlimit(10**6)
from itertools import product
from collections import deque
import numpy as np
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)

    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y)

    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

X = iter(open(0).readlines())
h, w = map(int, next(X).split())
ch, cw = map(int, next(X).split())
dh, dw = map(int, next(X).split())
dp = Grid([x.strip() for x in X], function=lambda x: 10**6 if x == '.' else -1)

def dfs(stack):
    if not stack:
        return
    x, y, d = stack[0]
    dp[y, x] = d
    stack2 = []
    while stack:
        x, y, d = stack.pop()
        if dp[y, x] < d:
            continue
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            nx, ny = x+dx, y+dy
            if dp.is_valid_xy(nx, ny) and dp[ny, nx] > d:
                dp[ny, nx] = d
                stack.append((nx, ny, d))
        for dx, dy in product(range(-2, 3), repeat=2):
            if abs(dx) + abs(dy) < 2:
                continue
            nx, ny = x+dx, y+dy
            if dp.is_valid_xy(nx, ny) and dp[ny, nx] > d+1:
                dp[ny, nx] = d+1
                stack2.append((nx, ny, d+1))
    dfs(stack2)

dfs([(cw-1, ch-1, 0)])
if dp[dh-1, dw-1] == 10**6:
    print(-1)
else:
    print(dp[dh-1, dw-1])


#include <iostream>
#include <string>

using namespace std;

int main() {
	string s;
  	cin >> s;
  	int cnt{0}, res{0};
  	for (char c : s) {
    	if (c == 'S') {
        	cnt = 0;
        } else {
        	cnt++;
        }
      	res = max(res, cnt);
    }

  	cout << res << endl;
}

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

RRS

Sample Output 1

2

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

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


s = input()
r = s.count("RRR")
n = s.count("RR")

if r == 1:
    print(3)
elif n == 1:
    print(2)
else:
    if s.count("R")>0:
        print(1)
    else:
        print(0)


x, k ,d = map(int,input().split())
q = x // d
mod = x % d
time = k - q
if time >= 2:
  if time % 2 == 0:
    ans = abs(mod)
  else:
    ans = abs(mod) - d
else:
  x = abs(x) -  k * d
  ans = x
print(abs(ans))

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

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

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


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

if abs(x)//d>=k:
    print(abs(x)-k*d)
    exit()

s = x

while k>0:
    s = s-d
    print(s,x)
    if abs(s)>=abs(x):
        break
    x = s
    k -= 1

if k == 0:
    print(abs(s))
    exit()

if d%2 == 0:
    print(abs(s))
else:
    print(abs(x))


x,k,d=map(int,input().split())
x=abs(x)
if x>=k*d:
    print(x-k*d)
else:
    ans=x%d
    a=x//d
    if (k-a)%2==1:
        ans=d-ans
    print(ans)


import numpy as np
import math
import scipy as sp
import queue
import collections

MOD = 10 ** 9 + 7
INF = 10 ** 9

def main(kwargs):
    x = kwargs["x"]
    k = kwargs["k"]
    d = kwargs["d"]
    if k * d < abs(x):
        res = abs(x) - k * d
    else:
        res_1 = abs(x) % d
        res_2 = res_1 - k * (abs(x) // d % 2)
        res = abs(res_2)

    return res

if __name__ == "__main__":
    kwargs = {}

    cin = input().split()
    kwargs["x"], kwargs["k"], kwargs["d"] = [int(i) for i in cin]

    cout = main(kwargs)
    print(cout)


n,k = map(int,input().split())
next_map = list(map(int, input().split()))
score_ls = list(map(int, input().split()))
for i in range(n):
    next_map[i] -= 1

def max_of_the_start(start):
    # 同じますにたどり着くまで
    max1 = -float('inf')
    now_place = start
    # 一回も動かない可能性あるのでここ修正
    now_score = 0
    done_ls = [0] * n
    place_score = [0] * n
    place_times = [0] * n
    t = 0
    while True:
        # きたところの処理
        if done_ls[now_place]:
            break
        done_ls[now_place] = 1
        place_score[now_place] = now_score
        place_times[now_place] = t

        # 次の移動
        now_place = next_map[now_place]
        t += 1
        now_score += score_ls[now_place]
        max1 = max(now_score, max1)
        if t == k:
            return max1
    score_per_loop = now_score - place_score[now_place]
    times_per_loop = t - place_times[now_place]
    remain = k - t
    # ここまでが最初に同じところにたどり着くまで

    # ループでのポイントがプラスなら、最大限ループする
    if score_per_loop >= 0:
        q,remain = divmod(remain, times_per_loop)
        now_score += score_per_loop*q
    max2 = now_score

    # 余った回数
    while remain > 0:
        now_place = next_map[now_place]
        now_score += score_ls[now_place]
        max2 = max(max2,now_score)
        remain -= 1

    return max(max1,max2)

ans = -float('inf')
for i in range(n):
    ans = max(ans, max_of_the_start(i))
print(ans)

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

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

Sample Input 1

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

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


from sys import stdin

def main():
    readline = stdin.readline
    N, K = map(int, readline().split())
    P = list(map(int, readline().split()))
    C = list(map(int, readline().split()))
    P = [i-1 for i in P]
    Position_list=[P]
    Score_list=[[0 for i in range(N)]]

    for j in range(K):
        Updated_Position=[]
        Updated_Score=[]
        Current_Position=Position_list[j]
        Current_Score=Score_list[j]
        for i in range(N):
            Updated_Position.append(Current_Position[P[i]])
            Updated_Score.append(Current_Score[i]+C[Current_Position[i]])
        Position_list.append(Updated_Position)
        Score_list.append(Updated_Score)
    print(max(max(i) for i in Score_list))
main()


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

def solve(start):
    loop = []
    llen = 0
    lsum = 0
    reach = [0]*n

    now = start
    while True:
        nxt = P[now]-1
        loop.append(now)
        llen += 1
        lsum += C[now]
        reach[now] = 1
        if reach[nxt]:
            break
        now = nxt

    if lsum <= 0 or llen >= k:
        res = -10 ** 20
        s = 0
        now = start
        for i in range(min(llen, k)):
            s += C[now]
            res = max(res, s)
            now = P[now]-1
        return res
    else:
        s = lsum * (k // llen)
        now = start
        for i in range(k % llen):
            s += C[now]
            now = P[now]-1
        j = loop.index(now)
        res = -10**20
        for i in range(llen):
            j -= 1
            res = max(res, s)
            s -= C[loop[j]]
        return res

def solver():
    ans = -10 ** 20
    for i in range(n):
        ans = max(ans, solve(i))
    return ans

print(solver())


import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline

def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    for i in range(N):
        next = P[i] - 1
        cnt = 0
        tmp = 0

        f = False
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if next == i:
                break
            if cnt == K or next == i:
                f = True
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

        q, r = divmod(K, cnt)
        next = P[i] - 1
        tmp *= q
        cnt = 0
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == r:
                break
            next = P[next] - 1
    print(ans)

if __name__ == '__main__':
    main()


N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for k in range(N):
  P[k] -= 1
scorelist = []
roop = []
now = 0
visited = [-1 for _ in range(N)]
for k in range(N):
  now = k
  if visited[now] == -1:
    roop.append([])
    scorelist.append([])
    start = 0 + now
    while visited[start] == -1:
      roop[-1].append(start)
      visited[start] = 1
      start = P[start]
      scorelist[-1].append(C[start])
    scorelist[-1] = scorelist[-1] + scorelist[-1] + scorelist[-1]

#print(roop)
#print(scorelist)

ans = - float('inf')
for l in range(len(roop)):
  #print(scorelist[l][:len(roop[l])])
  Q = K // len(roop[l])
  R = K % len(roop[l])
  if Q > 0:
    Q -= 1
    R += len(roop[l])
  #print(Q, R)
  if sum(scorelist[l][:len(roop[l])]) > 0:
    basis = sum(scorelist[l][:len(roop[l])])*Q
  else:
    basis = 0
  #print(basis)
  advlist = -float('inf')
  for k in range(len(roop[l])):
    adv = 0
    for j in range(k, k + R):
      adv += scorelist[l][j]
      advlist  = max(advlist, adv)
  ans = max(ans, basis + advlist)

print(ans)


import numpy as np
(r,c,_),*d = [list(map(int, s.split())) for s in open(0)]

v = dict()
for dd in d:
    v[dd[0]-1, dd[1]-1] = dd[2]

dp = np.zeros([r,4], dtype=int)
for i in range(c):
    for j in range(r):
        if j > 0:
            dp[j][0] = max(dp[j][0], max(dp[j-1]))
        dp[j][1:] = np.maximum(dp[j][1:], dp[j][:-1] + v.get((j,i), 0))
print(np.max(dp))

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

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

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

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

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142


x=int(input())
if(x>=30):
  print("Yes")
else:
  print("No")

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

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

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


T = input()

if T >= 30:
    print("Yes")
else:
    print("No")


x = int(input())
if x>= 30:
  print("Yes")
else:
  print("No")


n, d = input().split()
n = int(n)
d = int(d)
xy = [map(int, input().split()) for _ in range(n)]
x, y = [list(i) for i in zip(*xy)]
c = 0

for i in range(n):
  if x[i]*x[i]+y[i]*y[i] <= d*d:
    c +=1

print(c)


def main():
    x = int(input())
    if x >=30:
        print('Yes')
    else:
        print('No')
if __name__ == "__main__":
    main()


X = int(input())
print('Yes' if X >= 30 else 'No')


K=int(input())
amari_list = []
amari = 7%K
amari_list.append(amari)
for i in range(1,K):
    amari = (amari * 10 + 7)% K
    if amari == 0:
        print(i+1)
        break
    if amari in amari_list:a
        print(-1)
        break
    if i == (K-1):
        print(-1)
    else:
        amari_list.append(amari)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

101

Sample Output 1

4

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

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


import sys
import  math
import fractions
from collections import defaultdict
import copy
stdin = sys.stdin

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

K=int(input())
mod_l=[0]*(K*10)
mod_l[0]=7%K
mod_k=7%K
ans=1
for i in range(10*K-1):
    if(mod_l[i]==0):
        print(ans)
        sys.exit(0)
    mod_k=(mod_k*10)%K
    if(mod_k==0):
        print("-1")
        sys.exit(0)
    mod_l[i+1]=(mod_l[i]+mod_k)%K
    ans+=1

print("-1")


k = int(input())
dic = dict()
cnt = 1
num1 = 7 % k
num2 = 70 % k
while True:
    if dic.get(num1):break
    if (num1) == 0:
        print(cnt)
        exit()

    dic[num1] = 1
    num1 = (num1 + num2) %k
    num2 = (num2 * 10) %k
    cnt += 1
    #print(num1, num2)
print(-1)


from sys import stdin
from sys import setrecursionlimit
from collections import Counter, deque, defaultdict
from math import floor, ceil
from bisect import bisect_left
from fractions import Fraction
from itertools import combinations
from math import gcd
setrecursionlimit(100000)

INF = int(1e10)
MOD = int(1e9 + 7)

def main():
    from builtins import int, map
    K = int(input())
    ss = set({})
    mod = 7 % K
    count = 1
    while True:
        if mod == 0:
            print(count)
            exit()
        if mod in ss:
            print(-1)
            exit()
        ss.add(mod)
        mod = (mod * 10 + 7) % K
        count += 1

if __name__ == '__main__':
    main()


def main():
    k = int(input())
    a = 7
    c = 1
    b = 7
    if k == 2 or k == 5:
        print(-1)
        exit()
    while True:
        if a%k== 0:
            print(c)
            break
        else:
            b = (b*10)%k
            a = b+a
            a = a %k
            c += 1
            if c > k:
                print(-1)
                exit()

main()


from collections import Counter

N = int(input())
C = list(input())
C1 = Counter(C)
ans = 0
for i in range(C1["R"]):
    if C[i] == "W":
        ans += 1
print(ans)

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


n = int(input())
C = list(input())
# print(n)
# print(C)
l = 0
r = n-1
c = 0
while l < r:
    # print('l {} r {}'.format(l,r))
    # print('C[l] {} C[r] {}'.format(C[l],C[r]))

    if C[l]=='W' and C[r]=='R':
        C[l],C[r] = C[r],C[l]
        l += 1
        r -= 1
        c += 1
        # print('C {}'.format(C))

    elif C[l]!='W':
        l += 1
    elif C[r]!='R':
        r -= 1

print(c)


import sys
from collections import Counter

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

e = Counter()
A = [None] * (N + 1)
A[0] = e | e
for i, c in enumerate(C):
    A[i + 1] = A[i] + Counter({c: 1})

for i in range(Q):
    l, r = map(int, sys.stdin.readline().split())
    print(len(A[r] - A[l - 1]))

Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

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

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3


X = int(split())

Rating = 10 - (X // 200)

print(Rating + "級")

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


def magic(a,b,c,k):
	for i in range(k):
		if(a>=b):
			b*=2
		elif(b>=c):
			c*=2
	if(a < b and b < c):
		print("Yes")
	else:
		print("No")
d,e,f = map(int,input().split())
j = int(input())
magic(d,e,f,j)

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


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

while n > 0:
    if flg == 0:
        b = b * 2
        n = n - 1
        #print(a,b,c)
        if a < b:
            flg = 1
            if b < c:
                print('Yes')
                exit()
    else:
        c = c * 2
        n = n - 1
        #print(a,b,c)
        if b < c:
            print('Yes')
            exit()

print('No')


n,k=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n-k):
  if a[k+i]>a[i]:
    print("Yes")
  else:
    print("No")

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


N=int(input())
P=[list(map(int,input().split())) for _ in range(N)]
ans=0
for i in range(N):
  ans+=min(abs(P[i][0]),abs(P[i][1]))*P[i][2]
print(ans)
if N==1:
  exit()
x=[0]
y=[0]
z=[]
for l in range(N):
  cns=10**12
  for i in range(N):
    if i in z:
      continue
    for j in range(2):
      bns=0
      for k in range(N):
        if i==k:
          continue
        s=10**5
        for u in x:
          s=min(abs(u-P[k][0]),s)
        s=min(s,abs(P[k][j]-P[i][j]))
        for v in y:
          s=min(abs(v-P[k][1]),s)
        bns+=s*P[k][2]
      if bns<cns:
        cns=bns
        a=i
  x.append(P[a][0])
  y.append(P[a][1])
  z.append(a)
  print(cns)

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


n = int(input())
from collections import defaultdict
import bisect
xd=defaultdict(list)
yd=defaultdict(list)
addd=defaultdict(list)
subd=defaultdict(list)

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    bisect.insort(xd[(x,u)],y)
    bisect.insort(yd[(y,u)],x)
    addd[x+y].append(u)
    addd[abs(x-y)].append(u)

tmp=float('inf')
for x in range(200001):
    for d in xd[(x,'D')]:
        ind=bisect.bisect_left(xd[(x,'U')], d)
        if ind!=0:
            u=xd[(x,'U')][ind-1]
            tmp=min((d-u)*10//2,tmp)

for y in range(200001):
    for l in yd[(y,'L')]:
        ind=bisect.bisect_left(yd[(y,'R')], l)
        if ind!=0:
            r=yd[(y,'R')][ind-1]
            tmp=min((r-l)*10//2,tmp)

if tmp!=float('inf'):
    print(tmp)
else: print('SAFE')

Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100


a,b,c = map(int, input().split())
d = 0
for i in range(a,b+1):
  if i%c==0:
    d+=1
print(d)

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


l,r,d=map(int,input().split())
cnt=0
for i in range(l,r+1):
    if i%d==0:
        cnt+=1
print(cnt)


import math
N = int(input())
ans = [0]*N
l = int(math.sqrt(N-3))

for i in range(1,l):
    for j in range(1,l):
        for k in range(1,l):
            if (i+j+k)**2-(i*j+j*k+k*i) <= N:
                ans[(i+j+k)**2-(i*j+j*k+k*i)-1] += 1

s = '\n'.join([str(n) for n in ans])
print(s)

# print(ans, sep='\n')

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


#c
import numpy
N = int(input())
cou = 0

for i in range(1,N+1):
    cou = 0
    for x in range(1,i+1):
        for y in range(1,i+1):
            for z in range(1,i+1):
                if x**2+y**2+z**2+x*y+y*z+z*x == i:
                    cou += 1
    print(cou)


n = int(input())

for i in range(1,n+1):
    count = 0
    for x in range(1,i):
        if x ** 2 + x > i:
            continue
        for y in range(1, i):
            if x ** 2 + x * y + y ** 2 > i:
                continue
            for z in range(1,n - x ** 2 - y ** 2 - x * y):
                if x ** 2 + y ** 2 + z ** 2 + x * y + y * z + z * x > i:
                    break
                elif x ** 2 + y ** 2 + z ** 2 + x * y + y * z + z * x == i:
                    count += 1
    print(count)


Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

1 \leq N \leq 2 \times 10^5

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

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

Sample Input 1

3
011

Sample Output 1

2
1
1

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

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

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

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()

cnt1 = sum( i=='1' for i in x )
x10 = int(x,2)

if cnt1 > 1:
  x10mod_m = x10 % (cnt1-1)
  x10mod_p = x10 % (cnt1+1)
else:
  x10mod_m = 0
  x10mod_p = 0

ans = []
for i in range(n):
  if x[i] == '1':
    if cnt1 == 1:
      print(0)
      continue
    mod = x10mod_m
    cntx = cnt1-1
  else:
    mod = x10mod_p
    cntx = cnt1+1
  mod += (1<<i) % cntx
  cnt = 1
  mod = format(mod, 'b')

  while True:
    if mod == '0':
      break
    one_cnt = sum( j=='1' for j in mod )
    mod_10 = int(mod,10)
    mod = format( mod_10 % one_cnt, 'b')
    cnt += 1
  print(cnt)


from collections import defaultdict
N = int(input())
X = list(input())
d = defaultdict(int)

for i in range(1, N):
    c = 0
    k = format(i, "b")
    for j in k:
        if j == "1":
            c += 1
    d[i] = i % c

n = 0
for i in X:
    if i == "1":
        n += 1

p = 1
total1 = 0
total2 = 0
for i in X[::-1]:
    if i == "1":
        total1 += p % (n+1)
        total2 += p % (n-1)
    p *= 2

total1 %= (n+1)
total2 %= (n-1)
Ans = []
p = 1
for i in X[::-1]:
    c = 1
    if i == "0":
        start = total1
        start += p % (n+1)
        start %= (n+1)
    else:
        start = total2
        start -= p % (n-1)
        start += n - 1
        start %= (n-1)
    if start == 0:
        Ans.append(c)
    else:
        while(True):
            start = d[start]
            c += 1
            if start == 0:
                break
        Ans.append(c)
    p *= 2

for i in Ans[::-1]:
    print(i)


def g(n):
    c = 0
    while n > 0:
        p = 0
        n2 = n
        while n2 > 0:
            if n2%2 == 1:
                p += 1

            n2 //= 2

        n %= p
        c += 1

    return c

def h(b, m):
    x = 1
    for _ in range(b):
        x = x*2%m

    return x

def f(N, X):
    b = sum(1 if x == '1' else 0 for x in X)

    Xplus = 0
    Xminus = 0

    for x in X:
        Xplus = (Xplus*2 + (1 if x == '1' else 0))%(b+1)

        if b > 1:
            Xminus = (Xminus*2 + (1 if x == '1' else 0))%(b-1)

    for i in range(N):
        if X[i] == '0':
            X2 = (Xplus + h(N-i-1, b+1))%(b+1)
            print(g(X2) + 1)
        elif b > 1:
            X2 = (Xminus - h(N-i-1, b-1))%(b-1)
            print(g(X2) + 1)
        else:
            print(0)

N = int(input())
X = input()
f(N, X)


N = int(input())
A = 0
T = 0
R = 0
W = 0
for i in range(N):
    S = input()
    if S == 'AC':
        A += 1
    elif S == 'WA':
        W += 1
    elif S == 'TLE':
        T += 1
    elif S == 'RE':
        R += 1

print('AC x',A)
print('WA x',W)
print('TLE x',T)
print('RE x',R)

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

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

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

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

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


n = int(input())
s = []
for i in range(n):
    s.append(input())
ac = 0
wa = 0
tle = 0
re = 0

for i in range(n):
    if s[i] == 'AC':
        ac += 1
    elif s[i] == 'WA':
        wa += 1
    elif s[i] == 'TLE':
        tle += 1
    elif s[i] == 'RE':
        re += 1

print('AC x {}'.format(ac))
print('WA x {}'.format(wa))
print('TLE x {}'.format(tle))
print('RE x {}'.format(re))


from sys import stdin

def main():
    cnt = [0] * 4
    n = int(input())
    for i in range(n):
        res = input()
        if res == "AC":
            cnt[0] += 1
        elif res == "WA":
            cnt[1] += 1
        elif res == "TLE":
            cnt[2] += 1
        elif res == "RE":
            cnt[3] += 1
    print("AC x "+str(cnt[0]))
    print("WA x "+str(cnt[1]))
    print("TLE x "+str(cnt[2]))
    print("RE x "+str(cnt[3]))

if __name__ == "__main__":
    main()


def nth_element(array, will):
    will -= 1
    n = len(array)
    left = 0
    right = n-1
    while right > left:
        i = left-1
        j = right
        v = array[right]
        while True:
            i += 1
            j -= 1
            while array[i]<v:i+=1
            while array[j]>v:j-=1
            if i>=j:break
            array[i],array[j] = array[j],array[i]
        array[i],array[right] = array[right],array[i]
        if i == will:break
        if i > will:
            right = i-1
        else:
            left = i+1
    return array

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

k = 1 + (n-1)//2

nth_element(A,n-k+1)

ans = 0
for i in range(n-1):
    ans += A[n - (i+1)//2 - 1]
print(ans)

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

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

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

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


n = int(input())
la = [int(w) for w in input().split()]
la.sort(reverse=True)

ans = la[0]
cnt = n - 2
for a in la[1:]:
    if cnt >= 2:
        cnt -= 2
        ans += a * 2
    elif cnt == 1:
        cnt -= 1
        ans += a
    else:
        break
print(ans)


def make_set_list(array,valid):
    new_array = []
    for i in range(len(array)//2):
        new_array.append(array[2*i]*array[2*i+1])
    if len(array)%2 == 1 and valid == 1:
        new_array.append(array[len(array)-1])
    return new_array

N, K = list(map(int,input().split()))
As = list(map(int,input().split()))
p_nums = []
n_nums = []
for i in range(N):
    n = As[i]
    if n < 0:
        n_nums.append(n)
    else:
        p_nums.append(n)
As.sort(key = abs)
n_nums.sort()
p_nums.sort(reverse = True)
if len(p_nums) > 0:
    if N > K:
        ok = True
    elif len(n_nums) % 2 == 0:
        ok = True
    else:
        ok = False
elif K % 2 == 0:
    ok = True
else:
    ok = False

ans = 1

if ok:
    if K % 2 == 0:
        set_p_num = make_set_list(p_nums,1)
        set_n_num = make_set_list(n_nums,0)
        set_num = set_p_num + set_n_num
        set_num.sort(reverse = True)
        for i in range(K//2):
            ans = (ans*(set_num[i]%(10**9+7)))%(10**9+7)
    else:
        ans = p_nums.pop(0)
        set_p_num = make_set_list(p_nums,1)
        set_n_num = make_set_list(n_nums,0)
        set_num = set_p_num + set_n_num
        set_num.sort(reverse = True)
        for i in range(K//2):
            ans = (ans*(set_num[i]%(10**9+7)))%(10**9+7)
else:
    for i in range(K):
        ans = (ans*(As[i]%(10**9+7)))%(10**9+7)

print(ans)

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

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

Constraints

1 \leq K \leq N \leq 2\times 10^5

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

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

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

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

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


n, k = map(int, input().split())
al = list(map(int, input().split()))
al_abs = []
al_p = []
al_m = []
zero_cnt = 0
MOD = 10**9+7

if n == 1 and k == 1:
    print(al[0]%MOD)
    exit()

if n == k:
    ans = 1
    for a in al:
        ans *= a
        ans %= MOD
    print(ans)
    exit()

for a in al:
    if a == 0:
        zero_cnt+=1
    else:
        if a > 0:
            al_abs.append((abs(a),1))
            al_p.append(a)
        elif a < 0:
            al_abs.append((abs(a),-1))

al_abs.sort(reverse=True)
if len(al_abs) < k:
    print(0)
    exit()

if len(al_abs) == k:
    ans = 1
    m_cnt = 0
    for a,s in al_abs:
        if s == -1: m_cnt += 1
        ans *= a
        ans %= MOD
    if m_cnt%2 == 0:
        print(ans)
    else:
        print(0)
    exit()

if not al_p:
    if k%2 == 1 and zero_cnt > 0:
        print(0)
    else:
        if k%2 == 1:
            al_abs.sort()
        ans = 1
        for a,s in al_abs[:k]:
            ans *= (a*(-1))
            ans %= MOD
        print(ans)
    exit()

val = 1
m_cnt = 0
last_m = 0
last_p = 0
for i in range(k):
    v,sig = al_abs[i]
    val *= v
    val %= MOD
    if sig == -1:
        m_cnt += 1
        last_m = v
    else:
        last_p = v

if m_cnt %2 == 0:
    print(val)
    exit()

# minus -> plus

## search next p
next_p = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == 1:
        next_p = v
        break

## search next m
next_m = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == -1:
        next_m = v
        break

# print(next_m, next_p)

if next_p == 0 and next_m == 0:
    print(0)
    exit()

# last_m -> next_p
if next_p*last_p >= next_m*last_m or last_p == 0:
# if next_p > 0 and next_m == 0:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_m and sig == -1:
            ans *= next_p
            skip_flag = True
        else:
            ans *= v
        # print(ans)
        ans %= MOD
    print(ans)
    exit()

# last_p -> next_m
# if next_p == 0 and next_m > 0:
elif next_p*last_p <= next_m*last_m:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_p and sig == 1:
            ans *= next_m
            skip_flag = True
        else:
            ans *= v
        ans %= MOD
    print(ans)
    exit()


mod = 1000000007
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
ans = 1
# 負になってしまう時
if A[-1] < 0 and K%2 == 1:
    for i in range(K):
        ans = ans * (A[-i-1]%mod) % mod
else:
    n = 0
    p = -1
    # Kが奇数の時、正の候補の最大値をあらかじめ消費しておき、偶数の時と同様に処理できるようにする。
    if K%2 == 1:
        ans = ans * (A[p]%mod) % mod
        p -= 1
    # 正/負の候補から２つずつ消費していく
    for _ in range(K//2):
        if A[n]*A[n+1] > A[p]*A[p-1]:
            ans = ans * (A[n]%mod) % mod
            ans = ans * (A[n+1]%mod) % mod
            n += 2
        else:
            ans = ans * (A[p]%mod) % mod
            ans = ans * (A[p-1]%mod) % mod
            p -= 2

print(ans)


N=int(input())
P=0
for i in range(N):
  P+=(i+2)*(i+1)//2
u,v=0,0
for i in range(N-1):
  u,v=map(int,input().split())
  if u>v:
    u,v=v,u
  P-=u*(N-v+1)
print(P)

Score : 600 points

Problem Statement

We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.

For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:

Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.

Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq u_i, v_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

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

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs (L, R) as follows:

For L = 1, R = 1, S = \{1\} and we have 1 connected component.

For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.

For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.

For L = 2, R = 2, S = \{2\} and we have 1 connected component.

For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.

For L = 3, R = 3, S = \{3\} and we have 1 connected component.

The sum of these is 7.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113


import sys
input = sys.stdin.readline

def scoring():
    last = [0] * 26
    res = 0
    penalty = 0
    for i in range(D):
        t = out[i]
        res += S[i][t]
        penalty += SC - (i + 1 - last[t]) * C[t]
        res -= penalty
        last[t] = i
    return res

D = int(input())
C = list(map(int, input().split()))
S = [list(map(int, input().split())) for _ in range(D)]
out = [int(input()) - 1 for _ in range(D)]
SC = sum(C)
M = int(input())
for _ in range(M):
    d, q = map(int, input().split())
    out[d-1] = q - 1
    print(scoring())

(Please read problem A first. The maximum score you can get by solving this problem C is 1, which will have almost no effect on your ranking.)

Beginner's Guide

"Local search" is a powerful method for finding a high-quality solution.
In this method, instead of constructing a solution from scratch, we try to find a better solution by slightly modifying the already found solution.
If the solution gets better, update it, and if it gets worse, restore it.
By repeating this process, the quality of the solution is gradually improved over time.
The pseudo-code is as follows.

solution = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
slightly modify the solution (randomly)
if the solution gets worse:
restore the solution

For example, in this problem, we can use the following modification: pick the date d and contest type q at random and change the type of contest to be held on day d to q.
The pseudo-code is as follows.

t[1..D] = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
pick d and q at random
old = t[d] # Remember the original value so that we can restore it later
t[d] = q
if the solution gets worse:
t[d] = old

The most important thing when using the local search method is the design of how to modify solutions.

If the amount of modification is too small, we will soon fall into a dead-end (local optimum) and, conversely, if the amount of modification is too large, the probability of finding an improving move becomes extremely small.

In order to increase the number of iterations, it is desirable to be able to quickly calculate the score after applying a modification.

In this problem C, we focus on the second point.
The score after the modification can, of course, be obtained by calculating the score from scratch.
However, by focusing on only the parts that have been modified, it may be possible to quickly compute the difference between the scores before and after the modification.
From another viewpoint, the impossibility of such a fast incremental calculation implies that a small modification to the solution affects a majority of the score calculation.
In such a case, we may need to redesign how to modify solutions, or there is a high possibility that the problem is not suitable for local search.
Let's implement fast incremental score computation.
It's time to demonstrate the skills of algorithms and data structures you have developed in ABC and ARC!

In this kind of contest, where the objective is to find a better solution instead of the optimal one, a bug in a program does not result in a wrong answer, which may delay the discovery of the bug.
For early detection of bugs, it is a good idea to unit test functions you implemented complicated routines.
For example, if you implement fast incremental score calculation, it is a good idea to test that the scores computed by the fast implementation match the scores computed from scratch, as we will do in this problem C.

Problem Statement

You will be given a contest schedule for D days and M queries of schedule modification.
In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule.
Note that we do not revert each query. That is, the i-th query is applied to the new schedule obtained by the (i-1)-th query.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A and the queries.

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}
t_1
t_2
\vdots
t_D
M
d_1 q_1
d_2 q_2
\vdots
d_M q_M

The constraints and generation methods for the input part are the same as those for Problem A.

For each d=1,\ldots,D, t_d is an integer generated independently and uniformly at random from {1,2,\ldots,26}.

The number of queries M is an integer satisfying 1\leq M\leq 10^5.

For each i=1,\ldots,M, d_i is an integer generated independently and uniformly at random from {1,2,\ldots,D}.

For each i=1,\ldots,26, q_i is an integer satisfying 1\leq q_i\leq 26 generated uniformly at random from the 25 values that differ from the type of contest on day d_i.

Output

Let v_i be the final satisfaction at the end of day D on the schedule after applying the i-th query.
Print M integers v_i to Standard Output in the following format:

v_1
v_2
\vdots
v_M

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
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19

Sample Output 1

72882
56634
38425
27930
42884

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case.

Next Step

Let's go back to Problem A and implement the local search algorithm by utilizing the incremental score calculator you just implemented!
For this problem, the current modification "pick the date d and contest type q at random and change the type of contest to be held on day d to q" is actually not so good. By considering why it is not good, let's improve the modification operation.
One of the most powerful and widely used variant of the local search method is "Simulated Annealing (SA)", which makes it easier to reach a better solution by stochastically accepting worsening moves.
For more information about SA and other local search techniques, please refer to the editorial that will be published after the contest.


a = int(input())

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

a = int(input())

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

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

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

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


s=str(input())
t=str(input())
ans=0
for i in range(len(s)):
    if s[i]!=t[i]:
        ans+=1
print(ans)

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


a = list(input())
b = list(input())
ans = 0
for _ in range(len(a)):
    x = a.pop()
    y = b.pop()
    if x != y:
        ans += 1
print(ans)


S = input()
T = input()

x = zip(S, T)
same = []
diff = []
for i, j in x:
    if i == j:
        same.append(i)
    else:
        diff.append(j)

print(len(diff))


def ext_euc(a, b):
    if b == 0:
        return 1, 0, a
    y, x, v = ext_euc(b, a % b)
    y -= (a // b) * x
    return x, y, v

def mod_inv(a, mod):
    ret, _, _ = ext_euc(a, mod)
    return ret % mod

def main():
    MOD = 10 ** 9 + 7
    N, M = list(map(int, input().split(' ')))
    comb = [1 for _ in range(N + 1)]  # N_C_k
    perm_1 = [1 for _ in range(N + 1)]  # M_P_k
    perm_2 = [1 for _ in range(N + 1)]  # (M-k)_P_(N-k)
    for k in range(1, N + 1):
        c = comb[k - 1] * (N - k + 1) * mod_inv(k, MOD)
        c %= MOD
        comb[k] = c
        p = perm_1[k - 1] * (M - k + 1)
        p %= MOD
        perm_1[k] = p
        p = perm_2[k - 1] * (M - N + k)
        p %= MOD
        perm_2[k] = p
    perm_2.reverse()
    ans = 0
    for k in range(N + 1):
        v = (-1) ** (k % 2)
        v *= comb[k]
        v %= MOD
        v *= perm_1[k]
        v %= MOD
        v *= perm_2[k]
        v %= MOD
        v *= perm_2[k]
        v %= MOD
        ans += v
        ans %= MOD
    print(ans)

if __name__ == '__main__':
    main()

Score : 500 points

Problem Statement

Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:

A_i \neq B_i, for every i such that 1\leq i\leq N.

A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.

Since the count can be enormous, print it modulo (10^9+7).

Constraints

1\leq N \leq M \leq 5\times10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

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

Sample Input 1

2 2

Sample Output 1

2

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

Sample Input 2

2 3

Sample Output 2

18

Sample Input 3

141421 356237

Sample Output 3

881613484


import sys
from io import StringIO
import unittest
from itertools import combinations

def resolve():
	n, k = map(int, input().split())
	seq = map(int, input().split())
	ans = float('inf')
	for r in combinations(seq, k):
		ans = min(ans, sum(r))
	print(ans)
resolve()

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

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

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


n = int(input())
ans = ''
while n:
  n -= 1
  ans += chr(ord('a') + n % 26)
  n //= 26
print(ans[::-1])

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


n = int(input())
names = []

while 26 < n:
    syo, jyoyo = divmod(n, 26)
    names.insert(0, chr(96+jyoyo))
     # print(chr(64+jyoyo))
    n = syo
else:
    names.insert(0, chr(96+n))

print("".join(names))


import string
n = int(input())

ans = ''
while n>0:
  n -= 1
  ans = chr(ord('a')+n%26) + ans
  n //= 26

print(ans)


import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(map(int,input().split()))
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
INF = 10**9
mod = 10**9+7

N = i()
A = [26**i for i in range(1,100)]
A = [0]+list(itertools.accumulate(A))
cnt = 0
for i in range(N):
    if A[i] >= N:
        p = cnt
        break
    cnt += 1
if p == 1:
    print(chr(N+96))
    exit()
s = []
if N in A:
    print('z'*p)
    exit()
for i in range(p):
    m = chr(N%26+96)
    if m == '`':
        m = 'a'
    s.append(m)
    N = N//26
s.reverse()
print(''.join(s))


num = int(input())
ans = ''
while num > 26:
    num, rest = divmod(num, 26)
    ans += s[rest - 1]
    #print(ans)
ans += s[num - 1]
print(ans[::-1])


def num2alpha(num):
    if num<=26:
        return chr(64+num)
    elif num%26==0:
        return num2alpha(num//26-1)+chr(90)
    else:
        return num2alpha(num//26)+chr(64+num%26)
N=int(input())
ans=num2alpha(N)
ans=ans.lower()
ans=ans.replace("'","")
print(ans)


from collections import defaultdict as d
n=int(input())
a=list(map(int,input().split()))
p=d(int)
l=0
for i in a:
    p[i]+=1
    l+=i
for i in range(int(input())):
    b,c=map(int,input().split())
    l+=p[b]*(c-b)
    p[c]+=p[b]
    p[b]=0
    print(l)

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

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

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


n=int(input())
s=str(input())
q=int(input())

for i in range(q):
 x,y=map(str, input().split())
 s.replace(x,y)
 ans=0
 s_list=list(s.split())
 for j in range(q+1):
  ans+=int(s_list[j])
  print(ans)


import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()

def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]

#隣接リスト 1-order
def make_adjlist_d(n, edges):
    res = [[] for _ in range(n + 1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
        res[edge[1]].append(edge[0])
    return res

def make_adjlist_nond(n, edges):
    res = [[] for _ in range(n + 1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
    return res

#nCr
def cmb(n, r):
    return math.factorial(n) // math.factorial(r) // math.factorial(n - r)

def main():
    N = NI()
    A = NLI()
    all_xor = 0
    for a in A:
        all_xor ^= a
    L = list(map(lambda x: x^all_xor, A))
    print(" ".join(map(str, L)))

if __name__ == "__main__":
    main()

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.


k = int(input())
s = input()
MOD = 10**9+7

FAC = [1]
INV = [1]
for i in range(1,len(s)+k+1):
  FAC.append((FAC[i-1]*i) % MOD)
  INV.append(pow(FAC[-1],MOD-2,MOD))

def nCr(n,r):
  return FAC[n]*INV[n-r]*INV[r]

ans = 0
for i in range(len(s),len(s)+k+1):
  tmp = nCr(i-1,len(s)-1)*pow(25,i-len(s),MOD)
  tmp %= MOD
  tmp *= pow(26,len(s)+k-i,MOD)
  tmp %= MOD
  ans +=tmp
  ans %= MOD
print(ans)

Score: 600 points

Problem Statement

How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?

The answer can be enormous, so print it modulo (10^9+7).

Constraints

K is an integer between 1 and 10^6 (inclusive).

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

Input

Input is given from Standard Input in the following format:

K
S

Output

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

Sample Input 1

5
oof

Sample Output 1

575111451

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

Sample Input 2

37564
whydidyoudesertme

Sample Output 2

318008117


n=int(input())
for i in range(1,360+1):
  if n*i%360==0:
    print(i)

Score : 200 points

Problem Statement

Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:

Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.

Constraints

1 \leq X \leq 179

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of times Takahashi will do the action before he is at the starting position again.

Sample Input 1

90

Sample Output 1

4

Takahashi's path is a square.

Sample Input 2

1

Sample Output 2

360


str = input()

data = str.strip().split()

for i in range(5):
    if data[i] == "0":
        print(i+1)

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

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

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

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

Sample Input 1

0 2 3 4 5

Sample Output 1

1

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

Sample Input 2

1 2 0 4 5

Sample Output 2

3


x  = list(map(int, input().split()))
print(x.index(0) + 1)


a = list(map(int, input().split()))
answer = 0
for i in range(len(a)):
  if (a[i] == 0):
    answer = 0
    break
print(i+1)


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


import collections

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

ans = "No"
for i in range(2**X):
    count = collections.Counter(bin(i)[2:].zfill(X))
    num = count["0"]*2 + count["1"]*4
    if num == Y:
        ans = "Yes"
        break
    elif num > Y:
        ans = "No"
        break

print(ans)

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

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

Sample Input 1

3 8

Sample Output 1

Yes

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

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


X, Y = map(int,input().split())
m = X*4
m = m-Y
if m%2==0:
  print('Yes')
else:
  print( 'No')


X,Y=map(int, input().split())
ans = 'No'
for a in range(X + 1):
  b=X-a
  if 2 * a + 4 * b == Y:
    ans = 'Yes'
print(ans)


import sys
import math

l=list(map(int,input().split()))
if l[0]*2<=l[1]<=l[0]*4 and l[1]%2==0:
    print("Yes")
else:
    print("No")


x, n = map(int, input().split())
p = list(map(int, input().split()))

for i in range(x+1):
    if x-i not in p:
        print(x-i)
        break
    elif x+i not in p:
        print(x+i)
        break

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

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

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


a = input().split()
b = int(a[0])
c = int(a[1])
d = [int(i) for i in input().split()]
e = sorted(d)

f = int(e[0]-1)
g = int(e[-1]+1)

h = int(g-f)

X = []
for I in range(int(h+1)):
    J = int(f+I)
    if e.count(J) == 0:
        X.append(J)

Y = len(X)
H = []
for S in range(Y):
    Q = X[S]
    if Q>=b:
        g = Q-b
        H.append(g)
    else:
        g = b-Q
        H.append(g)
P = sorted(H)
F = P[0]
O = H.index(F)
print(X[O])


x,n = map(int, input().split())
if n ==0:
  print(x)
if n != 0:
  i = list(map(int, input().split()))

  if x not in i:
    print(x)

  else:
    p = 1
    while True:
      z = x - p
      if z not in i:
        print(z)
        break

      z = x + p
      if z not in i:
        print(z)
        break

      p = p +1


X, N = map(int, input().split())
P = list(map(int, input().split()))

lis = [1] * (100+1)
for p in P: lis[p-1] -= 1

for i in range(100):
    up = X+i
    down = X-i
    if lis[down-1] == 1 and down >= 0 :
        print(down)
        exit()
    elif lis[up-1] == 1 and up <= 100:
        print(up)
        exit()


Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


A,V =map(int,input().split())
B,W =map(int,input().split())
T   =int(input())
D =[]

for i in range(T):
    A = A + V
    B = B + W

    if A == B:
        D.append(1)

#print(D)

if len(D) >= 1:
    print("YES")

else:
    print("NO")

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

-10^9 \leq A,B \leq 10^9

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


import sys
from collections import deque
import copy
def main():
    A, V = map(int, input().split())
    B, W = map(int, input().split())
    T = int(input())
    can_A = V * T
    can_B = W * T
    if A < B:
        B += can_B
        A += can_A
        if A >= B:
            print('YES')
        else:
            print('NO')
    else:
        B -= can_B
        A -= can_A
        if A <= B:
            print('YES')
        else:
            print('NO')

if __name__ == '__main__':
    main()


import math

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

for i in range(min(41, K)):
  B = [0] * N
  for n, A_n in enumerate(A):
    B_min = max(0, n-A_n)
    b_max = min(N-1, n+A_n)
    B[B_min] += 1
    if b_max+1 < N:
      B[b_max+1] -= 1

  sum = 0
  for n in range(len(A)):
    sum += B[n]
    A[n] = sum

print(" ".join(list(map(str, A))))

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq K \leq 2 \times 10^5

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


a = input()
b = input().split()
result = 1
for i in range(int(a)):
    result = result * int(b[i])
if result > 1000000000000000000:
    print(-1)
else:
    print(result)

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


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


import math

def prime_factrization(n):
    factor = []
    tmp = int(math.sqrt(n)) + 1
    for num in range(2,tmp):
        while n % num == 0:
            n //= num
            factor.append(num)

    if not factor:
        return 0 # 素因数分解ができなければ0を返す
    else:
        if n != 1:
            factor.append(n)
        return list(factor)

ans = 0
N = int(input())
factor = prime_factrization(N)

if factor == 0:
    print(0)
else:
    for i in list(set(factor)):
        num = factor.count(i)
        j = 1
        a = 1
        while j <= num:
            ans += 1
            a += 1
            j = j + a
    print(ans)

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7