# coding: utf-8
import re
import math
import itertools
from copy import deepcopy
import random
from heapq import heappop,heappush
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
readline=sys.stdin.readline
sys.setrecursionlimit(2000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n

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

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

    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1

    def unite(self,x,y):
        self.link(self.find(x),self.find(y))

    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_power(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod_,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod_-2,mod_)*pow(fac[r],mod_-2,mod_))%mod_
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)
#################################### ########
# coding: utf-8
import re
import math
import itertools
from copy import deepcopy
import random
from heapq import heappop,heappush
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
readline=sys.stdin.readline
sys.setrecursionlimit(2000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n

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

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

    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1

    def unite(self,x,y):
        self.link(self.find(x),self.find(y))

    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_power(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def get_facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)
###################################################
def main():
    X,Y=map(int,input().split())
    if (X+Y)%3==0:
        n=(X+Y)//3
        X-=n
        Y-=n
        facs=get_facs(10**6+1,mod)
        if X<0 or Y<0:
            print(0)
            return
        ans=(facs[X+Y])*pow(facs[X]*facs[Y],mod-2,mod)
        print(ans)
    else:
        print(0)

main()

Score : 400 points

Problem Statement

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

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

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

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

Sample Input 1

3 3

Sample Output 1

2

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

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


def main():
    X,Y=map(int,input().split())
    a=X+Y
    if a%3==0:
        b=a//3
        c=10**9+7
        print(b%c)

if __name__=='__main__':
    main()

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

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 numpy import*
N,T,*L=int64(open(0).read().split())
d=zeros(1e4)
for w,v in sorted(zip(*[iter(L)]*2)):d[w:T+w]=maximum(d[w:T+w],d[:T]+v)
print(max(d))

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,T=map(int,input().split())
    AB=[tuple(map(int,input().split())) for _ in range(n)]
    AB.sort()

    dp=[0]*T
    ans=-INF
    for i in range(n):
        a,b=AB[i]
        ndp=dp[:]
        for t in range(T):
            if(t+a<T):
                ndp[t+a]=max(ndp[t+a],dp[t]+b)
            else:
                ans=max(ans,dp[t]+b)
        dp=ndp
    print(ans)
resolve()


n, t = [int(i) for i in input().split()]
ab = []
for _ in range(n):
    ab.append([int(i) for i in input().split()])
c = [0] * (t*2+1)
for i in ab:
    for j in range(t-1, -1, -1):
        k = c[j]
        l = i[0] + j+1
        if l >= 2*t+1:
            continue
        c[l] = max(c[l], c[j] + i[1])
print(max(c))


N, K = map(int, input().split())
H = list(map(int, [0] + input().split() + [0]))
d = [[10**18]*(K+1) for _ in range(N+2)]
for i in range(K+1):
    d[0][i] = 0
for hi in range(N+1):
    hi+=1
    h = H[hi]
    for i in range(min(K+1, hi)):
        for k in range(i+1):
            d[hi][i] = min(d[hi][i], d[hi-k-1][i-k] + max(H[hi-k-1]-h, 0))
print(min(d[-1]))

Score : 600 points

Problem Statement

We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns.

The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column.

Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive).

Different values can be chosen for different columns.

Then, you will create the modified artwork by repeating the following operation:

Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)

Find the minimum number of times you need to perform this operation.

Constraints

1 \leq N \leq 300

0 \leq K \leq N

0 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 H_2 ... H_N

Output

Print the minimum number of operations required.

Sample Input 1

4 1
2 3 4 1

Sample Output 1

3

For example, by changing the value of H_3 to 2, you can create the modified artwork by the following three operations:

Paint black the 1-st through 4-th squares from the left in the 1-st row from the bottom.

Paint black the 1-st through 3-rd squares from the left in the 2-nd row from the bottom.

Paint black the 2-nd square from the left in the 3-rd row from the bottom.

Sample Input 2

6 2
8 6 9 1 2 1

Sample Output 2

7

Sample Input 3

10 0
1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000

Sample Output 3

4999999996


#B
import collections

N = int(input())
D = list(map(int, input().split()))
is_first_zero = True
if D[0] != 0:
    is_first_zero = False
if is_first_zero:
    c = sorted(collections.Counter(D).items(), key=lambda x:x[0])
    if len(c) == 2:
        res = 1
    for index, i in enumerate(c):
        ind = i[0]
        num = i[1]
        if ind == 0:
            if num != 1:
                is_first_zero = False
                break
        else:
            if ind != pre_ind + 1:
                is_first_zero = False
                break
            else:
                if index == 2:
                    res = pre_num ** num
                elif index > 2:
                    res = res * (pre_num ** num)
                #print(res)
        pre_ind = ind
        pre_num = num

if is_first_zero:
    print(res % 998244353)
else:
    print("0")

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


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

a.sort()
b.sort()

i = 0
while i < N:
  if (b[i] - a[i] < 0):
    print('No')
    break
  i += 1
else:
  print('Yes')

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

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

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left

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

a = sorted(A)
b = sorted(B)

for i in range(N):
    if a[i] > b[i]:
        print("No")
        sys.exit()

for i in range(N):
    if A[i] <= B[i]:
        l = bisect_left(b,B[i])
        r = bisect_left(b,B[i]+1) - 1
        if a[l] <= A[i] <= a[r]:
            print("Yes")
            sys.exit()

print("No")


import sys
from collections import defaultdict as dd
input = sys.stdin.readline

N, M = map(int, input().split())
d = []

# N: 処理する区間の長さ

INF = 2**31-1

LV = (N).bit_length()
N0 = 2**LV
data = [INF]*(2*N0)
lazy = [None]*(2*N0)

# 伝搬対象の区間を求める
def gindex(l, r):
    L = (l + N0) >> 1; R = (r + N0) >> 1
    lc = 0 if l & 1 else (L & -L).bit_length()
    rc = 0 if r & 1 else (R & -R).bit_length()
    for i in range(LV):
        if rc <= i:
            yield R
        if L < R and lc <= i:
            yield L
        L >>= 1; R >>= 1

# 遅延伝搬処理
def propagates(*ids):
    for i in reversed(ids):
        v = lazy[i-1]
        if v is None:
            continue
        lazy[2*i-1] = data[2*i-1] = lazy[2*i] = data[2*i] = v
        lazy[i-1] = None

def query(l, r):
    propagates(*gindex(l, r))
    L = N0 + l; R = N0 + r

    s = INF
    while L < R:
        if R & 1:
            R -= 1
            s = min(s, data[R-1])
        if L & 1:
            s = min(s, data[L-1])
            L += 1
        L >>= 1; R >>= 1
    return s

# 区間[l, r)をxで更新
def update(l, r, x):
    *ids, = gindex(l, r)
    propagates(*ids)
    f = 0
    if l > 1:
      f = query(l, r)
    #print(f, l, r)
    L = N0 + l; R = N0 + r
    while L < R:
        if R & 1:
            R -= 1
            yl = INF
            if lazy[R-1] != None: yl = lazy[R-1]
            lazy[R-1] = data[R-1] = min(x + f, data[R-1] + x,yl)
        if L & 1:
            yl = INF
            if lazy[L-1] != None: yl = lazy[L-1]
            lazy[L-1] = data[L-1] = min(x + f, data[L-1] + x,yl)
            L += 1
        L >>= 1; R >>= 1
    #print(data)
    for i in ids:
        data[i-1] = min(data[2*i-1], data[2*i])

for _ in range(M):
  d.append(list(map(int, input().split())))
d.sort(key = lambda x: (x[0], x[1]))
#print(d)
for i in range(M):
  update(d[i][0], d[i][1] + 1, d[i][2])
  #print(d[i])
  #print(data)

res = query(N, N + 1)
if res != INF: print(res)
else: print(-1)

Score : 600 points

Problem Statement

We have N points numbered 1 to N arranged in a line in this order.

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

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

The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.

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

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i < R_i \leq N

1 \leq C_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 C_1
:
L_M R_M C_M

Output

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

Sample Input 1

4 3
1 3 2
2 4 3
1 4 6

Sample Output 1

5

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

Sample Input 2

4 2
1 2 1
3 4 2

Sample Output 2

-1

Sample Input 3

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

Sample Output 3

28


import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

# 解説AC
N, K = list(map(int, sys.stdin.readline().split()))
if 2 * K > N + 1:
    print(-1)
    exit()

ab = []
ai = 0
bi = N - 1
for _ in range(N):
    ab.append((ai, bi))
    ai = (ai + 2) % N
    bi = (bi - 1) % N
    if ai == 0:
        # もう選んだ
        ai += 1
c = max(K + 2 * N, ab[0][0] + ab[0][1] + 2 * K + N)
for ai, bi in ab:
    a = K + ai
    b = K + N + bi
    print(a, b, c)
    c += 1
    if c >= K + 3 * N:
        c -= N

Score : 700 points

Problem Statement

Given are positive integers N and K.

Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples.

For every integer i from 1 to N, a_i + b_i \leq c_i holds.

If the answer is yes, construct one such partition.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq 10^9

Input

Input is given from Standard Input in the following format:

N K

Output

If it is impossible to partition the integers satisfying the condition, print -1. If it is possible, print N triples in the following format:

a_1 b_1 c_1
:
a_N b_N c_N

Sample Input 1

1 1

Sample Output 1

1 2 3

Sample Input 2

3 3

Sample Output 2

-1


n = int(input())

for i in range(1, int(n**0.5)+1):
    if n%i == 0:
        x = i
        y = n/i

print(int(x+y-2))

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


# coding: utf-8
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    return divisors
N = int(input())
tmp = make_divisors(N)
print(sum(tmp[-2:]) - 2)


import math

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

if (s >= a * b / 2):
    print(math.atan2(2 * (a * b - s) / a, a) / math.pi * 180)
else:
    print(math.atan2(b, 2 * s / b) / math.pi * 180)

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


import math
a,b,x = map(int,input().split())
c = (2*x)/(a*b)
if c <= a:
    d_squared = b**2+c**2
    d = math.sqrt(b**2+c**2)
    cosB = (c**2+d_squared-b**2)/(2*c*d)
    acosB = math.degrees(math.acos(cosB))
    ans = acosB
else:
    c = 2*x/a**2-b
    c2 = b-c
    d_squared = a**2+c2**2
    d = math.sqrt(a**2+c2**2)
    cosA = (c2**2+d_squared-a**2)/(2*c2*d)
    acosA = math.degrees(math.acos(cosA))
    ans = acosA
    ans = 90-acosA
print(ans)


import math

def to_angle(x):
    return x * 180 / math.pi

def main():
    a, b, x = map(float, raw_input().split())
    v = a * a * b
    if v <= x * 2:
        print(to_angle(math.atan(2 * (v - x) / a ** 3)))
    else:
        print(to_angle(math.atan(b ** 3 / x * 0.5)))

main()


import numpy as np
N, K = map(int,input().split())
A = list(map(int,input().split()))
F = list(map(int,input().split()))

A_sort = sorted(A)
F_sort = sorted(F,reverse=True)
A_sort = np.array(A_sort)
F_sort = np.array(F_sort)
Asum = A_sort.sum()

l = -1
r = 0
for i in range(N):
    r = max(r,A_sort[i]*F_sort[i])

def judge(c):
    return Asum - np.minimum(A_sort,c//F_sort).sum() <= K

while r-l > 1:
    c = (l+r)//2
    if judge(c):
        r = c
    else:
        l = c
print(r)

Score: 500 points

Problem Statement

Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.

In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:

A team should assign one member to each food, and should not assign the same member to multiple foods.

It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.

The score of a team is the longest time it takes for an individual member to finish the food.

Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.

What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

Constraints

All values in input are integers.

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

0 \leq K \leq 10^{18}

1 \leq A_i \leq 10^6\ (1 \leq i \leq N)

1 \leq F_i \leq 10^6\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N
F_1 F_2 ... F_N

Output

Print the minimum possible score of the team.

Sample Input 1

3 5
4 2 1
2 3 1

Sample Output 1

2

They can achieve the score of 2, as follows:

Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.

Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.

Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.

They cannot achieve a score of less than 2, so the answer is 2.

Sample Input 2

3 8
4 2 1
2 3 1

Sample Output 2

0

They can choose not to do exactly K sets of training.

Sample Input 3

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

Sample Output 3

12


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

a.sort(reverse=True)
f.sort()

def check(x):
    red = [a[i] - x // f[i] for i in range(n) if a[i] * f[i] > x]
    red = sum(red)
    return (red <= k)

lb = -1  # false
ub = max([a[i] * f[i] for i in range(n)])  # true
while ub - lb > 1:
    mid = (ub + lb) // 2
    if check(mid):
        ub = mid
    else:
        lb = mid

print(ub)


print((lambda x:max(0, x[0]-2*x[1]))(list(map(int, input().split()))))

Score : 100 points

Problem Statement

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

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

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

12 4

Sample Output 1

4

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

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


N = int(input())
S = input()
for i in range(N-1):
    if S[i] == S[i+1]:
        i += 1
        N -= 1
print(N)


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

def q(k):
    if A[k] < A[i] + A[j]:
        return True
    else:
        return False

for i in range(n):
    for j in range(i + 1, n):
        l = j
        r = n
        while r - l > 1:
            mid = (l + r) // 2
            if q(mid):
                l = mid
            else:
                r = mid
        ans += (l - j)

print(ans)

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

3 \leq N \leq 2 \times 10^3

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


from copy import copy
from collections import deque
N = int(input())
L = list(map(int, input().split()))
L.sort(reverse=True)
first = deque(L)
count = 0
for i in range(N-2):
    l = first.popleft()
    second = copy(first)
    for j in range(1,N-i-1):
        m = second.popleft()
        n = len([i for i in second if i > l-m])
        if n > 0:
            count += n
        else:
            break
print(count)


# coding: utf-8
def binary_search(x, L2):
    l, r = 0, len(L2)-1
    mid = (r + l) // 2
    while r - l > 1:
        mid = (r + l) // 2
        if L2[mid] == x:
            return len(L2) - mid
        elif L2[mid] > x:
            l = mid
        elif L2[mid] < x:
            r = mid
    if L2[r] > c:
        return r
    else:
        return l

N = int(input())
L = list(map(int, input().split()))
L.sort()
L = L[::-1]
ans = 0
for i in range(N-2):
    a = L[i]
    for j in range(i+1, N-1):
        b = L[j]
        c = a - b
        r = binary_search(c, L)
        if r > j and L[r] > c:
            ans += r - j
print(ans)


import sys
import bisect
input = sys.stdin.readline

def main():
    N = int(input())
    L = list(map(int, input().split()))
    L.sort()

    ans = 0
    for i in range(N-1, -1, -1):
        a = L[i]
        for j in range(i-1, -1, -1):
            b = L[j]
            ci = bisect.bisect_right(L, a-b, lo=0, hi=j)
            ans += j - ci
    print(ans)

if __name__ == '__main__':
    main()


import bisect
n = int(input())
l = list(map(int, input().split()))
l.sort()
#print(l)
ans = 0
for x in range(n - 1):
    for y in range(x + 1, n):
        lx = l[x]
        ly = l[y]
        s = lx + ly
        pl = bisect.bisect_left(l, s)
        pr = bisect.bisect_right(l, s)
        c = l[y + 1:pr]
        #print("x:{} y:{}, lx:{}, ly:{} pl:{}, pr:{}, c:{}".format(x, y, lx, ly, pl, pr, c))
        for lz in c:
            if lx + ly > lz:
                if lx + lz > ly:
                    if ly + lz > lx:
                        #print("{} {} {}".format(lx, ly, lz))
                        ans += 1
print(ans)


import sys
from numpy import*
from scipy.sparse import*
def main():
  f=csgraph.floyd_warshall
  t=int32(sys.stdin.buffer.read().split())
  n,m,l=t[:3]
  t=t[3:]
  m*=3
  print('\n'.join(map(str,map(int,f(f(csr_matrix((t[2:m:3],(t[:m:3],t[1:m:3])),[n+1]*2),0)<=l)[t[m+1::2],t[m+2::2]].clip(0,n)%n-1))))
main()

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


N = int(input())
if N%2 == 0:
  print(0.5)
else:
  print((N+1)/2/N)

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


n = int(input())
odd = 0
for i in range(n):
    if (i + 1) % 2:
        odd += 1
print(odd / n)


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)
a, b = map(int, input().split())
n = gcd(a, b)
primes = []
MAX = 10 ** 6 + 10
is_prime = [False] * 2 + [True] * (MAX - 2)
for i in range(2, MAX):
    if is_prime[i]:
        primes.append(i)
        for j in range(i * i, MAX):
            is_prime[j] = False
cnt = 1
for p in primes:
    if n % p == 0:
        cnt += 1
        while n % p == 0:
            n /= p
if n != 1:
    cnt += 1
print(cnt)

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


a = str(input())

if a == "Sunny":
    print("Cloudy")
elif a == "Cloudy":
    print("Rainy")
else:
    print("Sunny")


S = input()
if S == 'Sunny':
    print('Cloudy')
elif S == 'Cloudy':
    print('Rainy')
else:
    print('Sunny')


s=input().split()
if s=='Sunny':
  print('Cloudy')
ifelse s=='Cloudy':
  print('Rainy')
else:
  print('Sunny')


s = input()

if s=='Sunny':
    print('Cloudy')
elif s=='Cloudy':
    print('Rainy')
else :
    print('Sunny')


def examA():
    W = {'Sunny':'Cloudy','Cloudy':'Rainy','Rainy':'Sunny'}
    S = SI()
    ans = W[S]
    print(ans)
    return

def examB():
    R = {"R","U","D"}
    L = {"L","U","D"}
    S = SI()
    ans = "Yes"
    for i,s in enumerate(S):
        if i%2==0 and s in R:
            continue
        if i%2==1 and s in L:
            continue
        ans = "No"
        break
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    # https://tjkendev.github.io/procon-library/python/string/z-algorithm.html
    def z_algo(S):
        N = len(S)
        A = [0] * N
        i = 1; j = 0
        A[0] = l = len(S)
        while i < l:
            while i + j < l and S[j] == S[i + j]:
                j += 1
            if not j:
                i += 1
                continue
            A[i] = j
            k = 1
            while l - i > k < j - A[k]:
                A[i + k] = A[k]
                k += 1
            i += k; j -= k
        return A
    N = I()
    S = SI()
    ans = 0
    for i in range(N):
        Z = z_algo(S[i:])
        for k,n in enumerate(Z[1:]):
            cur = min(k+1,n)
            ans = max(ans,cur)
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examB()

"""

"""

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

S is a string of length between 1 and 100 (inclusive).

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


s = input()
l = len(s)
count1 = 0
count2 = 0
for i in range(l//2 + l%2):
    if s[2*i] == "R" or s[2*i] == "U" or s[2*i] == "D":
        count1 += 1
for j in range(l//2):
    if s[2*j + 1] == "L" or s[2*j + 1] == "U" or s[2*j + 1] == "D":
        count2 += 1
if count1 == l//2 + l%2 and count2 == l//2:
    print("Yes")
else:
    print("No")


S=input()
y="Yes"
n="No"
for i in range(len(S)-1):
    if i%2==1:
        if S[i] in {"L","U","D"} and S[i-1] in {"R","U","D"} and S[len(S)-1] in {"R","U","D"}:
            ans=y
        else:
            ans=n
    else:
        continue
print(ans)


line=input()

a=['R','U','D']
b=['L','U','D']
flag=True

for i in range(len(line)):
  if (i+1)%2==1:
    if line[i] not in a:
      fline=input()

a=['R','U','D']
b=['L','U','D']
flag=True

for i in range(len(line)):
  if not flag:
    print(flag)
    break
  if (i+1)%2==1:
    if line[i] not in a:
      flag=False
      print('No')
  else:
    if line[i] not in b:
      flag=False
      print('No')
if flag==True:
  print('Yes') lag==False
      print('No')
      break
  else:
    if line[i] not in b:
      flag==False
      print('No')
      break

if flag:
  print('Yes')


S = list(input())
count = 0
for i in S:

  if count == 0:
    if i == "L":
      print("No")
      exit()
    count += 1
  else:
    if i == "R":
      print("No")
      exit()
    count -= 1
print("Yes")


S =  input()
flag = 0

for i in range(len(S)):
    if (i % 2) == 0:
        if S[i] == "L":
            flag = 1
    else:
        if S[i] == "R":
            flag = 1

if flag:
    print("No")
else:
    print("Yes")


n,k,q = map(int, input().split())
a = []
for _ in range(q):
    a.append(int(input()))
ans = [k-q for x in range(n)]

for i in range(q) :
  ans[a[i]-1] += 1

for i in range(n) :
  if ans[i] > 0 :
    print('Yes')
  else :
    print('No')

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


n = int(input())
a = []
a.append(10 ** 5)
b = input().split()
x = 0 #答え

for i in range(n-1):
  b[i] = int(b[i])
  if a[i] > b[i]:
    a[i] = b[i]
  a.append(b[i])

for i in range(n):
  x += a[i]

print(x)

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


N = int(input())
B = [int(i) for i in input().split()]
A = [B[0]]
A += B

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

print(sum(A))


import math
input = raw_input

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

n = A[0]
for i in range(1, N-1):
    n += min(A[i], A[i-1])
n += A[-1]
print(n)


"""別解
解説動画でやってること。

考察問題。

ランレングス法みたいな考え方をする。

LグループとRグループに分けて考える。

LグループとRグループの境目を選択して操作をすると、基本的に幸福な人の数を＋２できる

ただし、端っこの境目を選んだときのみ、＋１になる。

・入力例２を考える

## 初期状態
 L R R L R L R R L R L L R
   .         .         .     幸福な人：3人

## LグループとRグループの境目を選択して、操作をする

 L R R L R L R R L R L L R
  |___|

 L L L L R L R R L R L L R
   . . .     .         .     幸福な人：5人

## LグループとRグループの境目を選択して、操作をする

 L L L L R L R R L R L L R
        |_|

 L L L L L L R R L R L L R
   . . . . . .         .     幸福な人：7人

## LグループとRグループの境目を選択して、操作をする

 L L L L L L R R L R L L R
            |___|

 L L L L L L L L L R L L R
   . . . . . . . .     .     幸福な人：9人

## LグループとRグループの境目を選択して、操作をする

 L L L L L L L L L R L L R
                  |_|

 L L L L L L L L L L L L R
   . . . . . . . . . . .     幸福な人：11人

## LグループとRグループの境目を選択して、操作をする

 L L L L L L L L L L L L R
                        |_|

 L L L L L L L L L L L L L
   . . . . . . . . . . . .   幸福な人：12人

この考察からすると、初期状態の幸福な人の数を score とすると、

・K回操作して、初期状態の幸福な人に加えて 2*K 人を幸福にすることができたパターン = score + 2*K
・K回以下の操作で、すべての人を L(R) にすることができたパターン = N-1

のどちらかなので、最終的な幸福な人の数 ans は、

ans = min(score+2*K, N-1)

となる。

初期状態の幸福な人の数 score をO(N)で数えればよいだけなので、計算量はO(N)

"""
def solve2():
    N, K = list(map(int, input().split()))
    S = input()

    ans = 0
    for i in range(N-1):
        if S[i] == S[i+1]:
            ans += 1

    ans = min(ans + 2*K, N-1)
    print(ans)

if __name__ == "__main__":
    solve2()

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


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

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


s=list(input())
t=list(input())
cnt=0
for i in range(3):
    if(s[i]==t[i]):
        cnt+=1
print(cnt)


s = list(input())
t = list(input())
num = 0
for i in range(2):
    if s[i] == t[i]:
        num += 1
print(num)


S = input()
T = input()
cnt = 0

for i, s in enumerate(S):
  if s == T[i]:
    cnt += 1

print(cnt)


def main():
    A, B = map(int, input().split())

    if B == 1:
        print(0)
        exit()

    B -= A

    cnt = 1

    if B > 0:
        cnt += B // (A-1) + (1 if B % (A-1) > 0 else 0)

    print(cnt)

main()

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


import math

A,B = map(int,input().split())
print(math.ceil((B-1)/(A-1)))


import numpy as np
N = input()
N = int(N)
H_ = input().split()
H = np.zeros(N)

for i in range(N):
  H[i] = int(H_[N-i-1])
H = np.array(H)
out = []

num = 0
for i in range(N-1):
  if H[i] <= H[i+1]:
    num += 1
  else:
    out.append(num)
    num = 0

print(np.array(out).max())

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


n=int(input())
inf=10*10
h=list(map(int,input().split()))+[inf]
n=len(h)
length=[0]*n
cnt=[]
move=0
for i in range(n-1):
    if h[i]<h[i+1]:
        length[i+1]=1
        if i==0:
            length[i]=1
for i in range(1,n):
    if length[i]==0:
        move+=1
    else:
        cnt.append(move)
        move=0
if len(cnt)==0:
    print(0)
else:
    print(max(cnt))


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

now = h[0]
cnt = 0
max_cnt = 0

for i in range(n):
    # 次が同じかそれ以下なら
    # nowを更新しカウントアップ
    if i == 0:
        cnt = 0
    elif now >= h[i]:
        now = h[i]
        cnt = cnt + 1
    # それ以上なら最大カウントを超えてれば更新
    else:
        if max_cnt < cnt:
            max_cnt = cnt
        cnt = 0
        now = h[i]
    if i == n-1:
        if max_cnt < cnt:
            max_cnt = cnt

print(max_cnt)


Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

N is an integer satisfying 1 \leq N \leq 10^9.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


# coding: utf-8
# Your code here!
N = int(input())

if N % 2 != 0:
    print(int(N * (N - 1) / 2))
else:
    print(int(N * int((N - 1) / 2) + (N / 2)))


#!/usr/bin/env python3
N=int(input())
print(sum(range(N)))


import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    dq = [collections.deque(LI()) for _ in range(N)]

    ans = 0
    cnt = 0
    while cnt < N*(N-1)//2:
        ud = False
        used = [False] * N
        for i in range(N):
            if used[i] or not dq[i]: continue

            j = dq[i][0]-1
            if dq[j][0]-1 == i and not used[j]:
                used[i] = True
                used[j] = True
                dq[j].popleft()
                dq[i].popleft()
                cnt += 1
                ud = True
        if ud:
            ans += 1
            continue
        else:
            print(-1)
            return
    print(ans)

if __name__ == '__main__':
    main()

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


import sys
input = sys.stdin.readline

N = int(input())
A = [[int(i) - 1 for i in input().split()] for _ in range(N)]

cur = [0] * N

max_pairs = N * (N - 1)

pairs = 0
cnt = 1
for _ in range(max_pairs):
    visited = [False] * N
    for i, a in enumerate(A):
        if cur[i] >= N - 1:
            continue
        p = a[cur[i]]
        if A[p][cur[p]] == i:
            # print(cnt, p + 1, A[p][cur[p]] + 1, i + 1)
            visited[i] = True
            visited[a[cur[i]]] = True
            pairs += 1

    # print(pairs)
    if pairs == max_pairs:
        break
    if pairs > max_pairs:
        print(-1)
        quit()

    update = False
    for i, v in enumerate(visited):
        if v:
            cur[i] += 1
            update = True

    if not update:
        print(-1)
        quit()

    cnt += 1

print(cnt)


N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 10**9+7

p, q = [0]*N, [0]*N
for i in range(N):
    for j in range(i):
        if A[i] > A[j]:
            p[i] += 1
            q[i] += 1
    for j in range(i+1,N):
        if A[i] > A[j]:
            p[i] += 1

ans = 0
if K % 2 == 0:
    k = ((K//2)*(K+1)) % MOD
else:
    k = (K*((K+1)//2)) % MOD
for i in range(N):
    ans = (ans + (((k * p[i]) % MOD - (K*q[i]) % MOD) % MOD)) % MOD
print(ans)

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

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

Sample Output 3

185297239

Be sure to print the output modulo 10^9 + 7.


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

rev_sum = 0
for x in i:
  rev = 1/x
  rev_sum += rev
  ans = 1/rev_sum

print(float(ans))

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


n = int(input())
m = 0
for i in input().split():
    m += 1 / int(i)
m = 1 / m
if m == int(m):
    print(int(m))
else:
    print(m)


n = int(input())

sum = 0
for A in range(n):
    num = int(input())
    sum += 1/num
ans = 1/sum
print(ans)


N=int(input())
v=list(map(int,input().split()))
v_sort=sorted(v,reverse=False)
for i in range(N):
    v_sort=sorted(v_sort,reverse=False)
    v_sort.append((v_sort[0]+v_sort[1])/2)
    del v_sort[0]
    del v_sort[0]
    if len(v_sort)==1:
        break
print(*v_sort)

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


import bisect
from collections import defaultdict
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

S = input()[:-1]
T = input()[:-1]

# 作れない場合
if any(t not in S for t in T):
    print(-1)
    exit()

D = defaultdict(lambda: [])
min_D = defaultdict(lambda: len(S)+1)
for i, s in enumerate(S):
    D[s].append(i)
    min_D[s] = min(i, min_D[s])

for s in D.keys():
    D[s] = sorted(D[s])

cur_pos = 0
repeat = 0
for t in T:
    #print("cur->", cur_pos)
    ind = bisect.bisect_left(D[t], cur_pos)
    if ind >= len(D[t]):
        repeat += 1
        cur_pos = min_D[t]+1
    else:
        cur_pos = D[t][ind]+1

print(len(S)*repeat+cur_pos)

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


slist = input()
tlist = input()
scounter = 0
slength=len(slist)
slist=slist+slist
preposition=-1
for tchar in tlist:
    preposition=slist.find(tchar, preposition+1)
    if preposition==-1:
        scounter=-1
        break
    elif preposition>slength:
        scounter+=slength
        preposition-=slength
    # print(tchar, scounter, preposition)
if (scounter==-1):
    print(scounter)
else:
    print(scounter+preposition+1)


S=input()
b,d="",0
t=False
for c in S:
    if t:
        d+=1
        #print(b+c)
        b=b+c
        t=not t
    elif len(b) == 2:
        d+=1
        #print(c)
        b=c
    else:
        if b!=c:
            #print(c)
            d+=1
            b=c
        else:
            b=c
            t=True
print(d)

Score : 300 points

Problem Statement

Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:

There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).

Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.

Constraints

1 \leq |S| \leq 2 \times 10^5

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum positive integer K that satisfies the condition.

Sample Input 1

aabbaa

Sample Output 1

4

We can, for example, divide S into four strings aa, b, ba, and a.

Sample Input 2

aaaccacabaababc

Sample Output 2

12


s = list(input())
count = 0
check = 0
tem = str()

for i in range(0,len(s)):
    if check >0:
        check -= 1
        count += 1
    if check != 0:
        count -= 1
        continue
    if tem == "" or tem != s[i] :
        count += 1
        print(tem)
        tem = s[i]
    else:
        check = 2
        print(tem+s[i])
        tem = str()
print(count)


Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


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


m, n = map(int, input().split())
print(max(m + n, m - n, m * n))


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

print(*range(X-K+1, X+K))

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


k, x = map(int, input().split())
l = [i for i in range(x - k + 1, x + k)]
print(" ".join(map(str, l)))


n=int(input())
from collections import Counter
A=[]
for i in range(n):
  a=sorted(input())
  a="".join(a)
  A.append(a)
ans=0
for j in Counter(A).values():
  ans+=j*(j-1)//2
print(ans)

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


n=int(input())
s=[sorted(input()) for _ in range(n)]
cnt=0
for i in range(n):
  for j in range(n):
    if i>=j:
      continue
    if s[i]==s[j]:
      cnt+=1
print(cnt)


n=int(input())
l=list()
q=0
for k in range(n):
	st=input()
    l.append(st)
for i in range(n)[:-1]:
	f=l[i]
	for s in range(n)[i+1:]:
		a=[f[k] for k in range(10)]
        g=l[s]
        b=[g[c] for c in range(10)]
        q +=1 if sorted(a)==sorted(b)
print(q)


N = int(input())
s = [sorted(list(input())) for i in range(N)]

from itertools import combinations

a = 0
for i,j in combinations(s,2):
  if i == j:
    a+=1
print(a)


n,m=map(int,input().split())
ab=[]
ans=[]
for i in range(n):
    a,b=map(int,input().split())
    a=m-a
    ab.append((a,b))
ab.sort()
ab.sort(key=lambda x:x[1],reverse=True)
for i in range(n):
    a,b=ab[i][0],ab[i][1]
    if a>=len(ans):
        ans.append(b)
print(sum(ans))

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


import heapq # 優先度付きキュー(最小値取り出し)

inf = 10**15
mod = 10**9+7
n,m = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n)]
ab.sort(key = lambda x:x[0], reverse = True)
q = []
heapq.heapify(q)   # ヒープ化
ans = 0
for i in range(1,m+1): # m-i日目からスタートして間に合う仕事
    while ab and ab[-1][0] == i:
        _,val = ab.pop()
        heapq.heappush(q, (-1) * val)
    if q:
        ans += heapq.heappop(q) * (-1)

print(ans)


import bisect
n, m = [int(i) for i in input().split()]
d = []
for i in range(n):
    a, b = [int(_) for _ in input().split()]
    d.append([a, b])

d.sort(reverse=True)
l = [-1 for i in range(m+1)]
for i in range(n):
    if d[i][0] <= m and l[d[i][0]] == -1:
        l[d[i][0]] = i
ans = 0
cand = []
key = []
for i in range(1, m+1):
    idx = bisect.bisect_left(cand, d[l[i]][1])
    if l[i] != -1 and idx == len(cand):
        ans += d[l[i]][1]
        if l[i] + 1 < n and d[l[i]+1][0] == d[l[i]][0]:
            idx = bisect.bisect_left(cand, d[l[i]+1][1])
            cand.insert(idx, d[l[i]+1][1])
            key.insert(idx, i)
            l[i] += 1
    else:
        if len(cand) > 0:
            ans += cand[-1]
            if l[key[-1]] + 1 < n and d[l[key[-1]]+1][0] == d[l[key[-1]]][0]:
                idx = bisect.bisect_left(cand, d[l[key[-1]]+1][1])
                cand[-1] = d[l[key[-1]]+1][1]
                l[key[-1]] += 1
            else:
                del cand[-1]
                del key[-1]
        if l[i] != -1:
            idx = bisect.bisect_left(cand, d[l[i]][1])
            cand.insert(idx, d[l[i]][1])
            key.insert(idx, i)
print(ans)


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

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


A,B,C = map(int,input().split())

print(C-A+B if C-A+B > 0  else 0)


num=input("N:")
count=0

for i in range(1,int(num)+1,1):
    if len(str(i))%2==1:
        count+=1

print(count)

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


s = input()
r = []
for _ in range(s.count('LR')):
    idx = s.index('LR')+1
    tmp = s[:idx]
    s = s[idx:]
    r.append([tmp, tmp.index('RL'), tmp.count('R'), tmp.count('L')])
r.append([s, s.index('RL'), s.count('R'), s.count('L')])
print(r)
T = []
for  i, j, R, L in r:
    tmp = [0]*len(i)
    if len(i) % 2 == 0:
        tmp[j], tmp[j+1] = len(i) // 2, len(i) // 2
    else:
        if R > L:
            if (R-1) % 2 ==0:
                tmp[j] = R
                tmp[j+1] = L
            else:
                tmp[j] = L
                tmp[j+1] = R
        else:
            if (L-1) % 2 ==0:
                tmp[j] = R
                tmp[j+1] = L
            else:
                tmp[j] = L
                tmp[j+1] = R
    T += tmp
print(*T)

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

0 3 3 0 0 0 1 1 0 2 2 0

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


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

def divisors(num):
    """
    約数全列挙
    """
    divisors = []
    for i in range(1, int(num ** 0.5) + 1):
        if num % i == 0:
            divisors.append(i)
            if i != num // i:
                divisors.append(num // i)

    return divisors
sum_num = sum(a_list)
a_list.sort()
div = divisors(sum_num)
div.sort(reverse=True)
ans = 1
from itertools import accumulate
for d in div:
    mod = []
    if d == 1:
        break
    for a in a_list:
        mod.append(a % d)
    mod.sort()
    acc_m = list(accumulate(mod))
    modd = []
    for i in range(N):
        modd.append(d-mod[i])
    acc_p = list(accumulate(modd))
    flag = False
    for i in range(N-1):
        p_sum = acc_p[-1] - acc_p[i]
        n_sum = acc_m[i]
        if p_sum == n_sum and p_sum <= K:
            flag = True
    if flag:
        ans = d
        break

print(ans)

Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

You can perform the following operation between 0 and K times (inclusive):

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5


a, b = map(int, input().split())
if a % 2 == 0:
    if b % 2 == 0:
        print(int((a+b)/2))
    else:
        print("IMPOSSIBLE")
else:
    if b % 2 == 0:
        print("IMPOSSIBLE")
    else:
        print(int((a+b)/2))

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

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

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


a,b = (int(i) for i in input().split())
if (a+b)%2!=0:
    print("IMPOSSIBLE")
else:
    print((a+b)//2)


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

n_l = [i for i in range(1, n+1)]
n_l.reverse()

if (n_l == p) or (reversed(n_l) == p):
    print('YES')
else:
    for i in range(n):
        for j in range(n):
            p[i], p[j] = p[j], p[i]
            if (n_l == p) or (reversed(n_l) == p):
                print('YES')
                sys.exit()
            else:
                p[i], p[j] = p[j], p[i]

print('NO')

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


N = int(input())
Ps = [int(i) for i in input().split(" ")]
Qs = list(sorted(Ps))
cnt = 0
for i in range(N):
  if Ps[i] != Qs[i]:
    cnt += 1
if cnt == 0 or cnt == 2: print("YES")
else: print("NO")


n = int(input())
a = list(map(int, input().split()))  # 初期のモンスターの数
b = list(map(int, input().split()))  # 各勇者が倒せるモンスターの数
num = 0
for i in range(n):
    # 倒したモンスターの数をnumに追加
    num += min(a[i], b[i])
    if b[i] - a[i] > 0:  # モンスターが残っていないとき
        # 隣町の勇者が倒せるモンスターの数か，隣町のモンスター全てか．
        num += min(b[i] - a[i], a[i + 1])
        # 隣町のモンスター数は残っているか，全滅しているか．
        a[i + 1] = max(a[i+1]-(b[i] - a[i]), 0)
print(num)

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
num = 0
zan = 0
for i in range(N):
    if A[i] <= B[i]:
        zan = B[i] - A[i]
        num += A[i]
        if zan >= A[i + 1]:
            num += A[i + 1]
            zan = 0
        else:
            num += zan
            zan = 0
    else:
        num += B[i]
        zan = 0

num += min(A[N], zan)

print(num)


import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x,'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x,'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x,'x') # rev => int(res, 16)
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(n=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(n+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, n+1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## const ##
MOD=10**9+7
## libs ##
import itertools as it
import functools as ft
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def main():
    s = II()
    m = 10**9
    x3 = m-s%m
    y3 = (s+x3)//m
    print(0, 0, m, 1, x3, y3)

if __name__ == '__main__':
    main()

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


import math

N, D = map(int, input().split())
print(math.ceil(N / (D * 2 + 1)))

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


n, d = map(int, input().split())
ans = n/d
if d*2+1 >= n:
    print(1)
elif n%((d*2)+1) == 0:
    print(int(n/(d*2)))
else:
    print(int(n/(d*2))+1)


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

for i in range(N):
    x=A.pop(i)
    print(max(A))
    A.insert(i,x)

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


import copy
n=int(input())
l1=[int(input()) for i in range(n)]

for i in range(n):
  l2 = copy.copy(l1)
  del l2[i]
  print(max(l2))


# n = 3
n = int(input())

lg, slg = 0, 0

arr = [0]*n

for i in range(n):
	arr[i] = int(input())
	if i==0:
		lg = i
	elif arr[i] >= arr[lg]:
		slg = lg
		lg = i
	elif arr[i] >= arr[slg]:
		slg = i

for i in range(n):
	if i==lg:
		print(arr[slg])
	else:
		print(arr[lg])


n = int(input())
a = [0] + list(map(int, input().split()))
ans = [0] * (n+1)
for i in range(n,0,-1):
  SUM = 0
  for j in range(i,n+1,i):
    SUM += ans[j]
  ans[i] = (SUM + a[i]) % 2
m = 0
b = []
for key,i in enumerate(a):
  if i:
    m += 1
    b.append(key)
print(m)
print(*b)

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


n = int(input())
a = [0] + list(map(int, input().split()))
ans = set()
b = [0] * (n + 1)
for i in range(n, 0, - 1):
    cnt = 0
    for j in range(i + i, n + 1, i):
        cnt += a[j]
    cnt %= 2
    b[i] = (a[i] % 2) - cnt
    if b[i] :
        ans.add(i)
print(len(ans))
print(*ans)


import sys
from bisect import bisect_right as bi_r

inf = float('inf')

n, *A = map(int, sys.stdin.read().split())

def main():
    res = [inf] * n
    for a in A[::-1]:
        i = bi_r(res, a)
        res[i] = a

    for i in range(n):
        if res[i] == inf:
            return i
    return n

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

Score : 500 points

Problem Statement

You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If A_i and A_j (i < j) are painted with the same color, A_i < A_j.

Find the minimum number of colors required to satisfy the condition.

Constraints

1 \leq N \leq 10^5

0 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.


from bisect import *
n = int(input())
a = [int(input()) for i in range(n)]

color = [-a[0]]
for i in range(1,n):
    if -a[i] >= color[-1]:
        color.append(-a[i])
    else:
        idx = bisect_right(color,-a[i])
        color[idx] = -a[i]

print(len(color))