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


import math

a,b = map(str,input().split())
c = int(a)
d = float(b)
e = 100*d
e = int(e)
c *= e

c /= 100
print(math.floor(c))

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

Score : 300 points

Problem Statement

Compute A \times B, truncate its fractional part, and print the result as an integer.

Constraints

0 \leq A \leq 10^{15}

0 \leq B < 10

A is an integer.

B is a number with two digits after the decimal point.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the answer as an integer.

Sample Input 1

198 1.10

Sample Output 1

217

We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217.

Sample Input 2

1 0.01

Sample Output 2

0

Sample Input 3

1000000000000000 9.99

Sample Output 3

9990000000000000

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.


import math

ab = list(input().split())
a,b = int(ab[0]),float(ab[1])
print(a*b)
print(math.floor(a*b))


import math
input = input().split()
a = int(input[0])
b = float(input[1])
print(int(math.modf(a*b)[1]))


A,B = map(float, input().split())
print(int(A * B))


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


A, B = map(float, input().split())

BB = int(B*100)

C = BB * A /100

C =math.floor(C)


a, b = input().split()
a = float(a)
b = float(b)
import math
print(math.floor(a*b))


import math
A, B = input().split()

print(int(math.floor(round(int(A) * float(B), 10))))


import math

A, B = list(input().split())
A = int(A)
B = '{:.2f}'.format(B).replace('.', '')
B = int(B)

# A *= 100
# B = int(B * 100)

AB = A * B / 100
floored = int(math.floor(AB))
print(floored)

# AB = A * B
# AB = str(AB)
# AB = AB[0:-2]
# AB = 0 if AB == '' else AB
# print(AB)


li=input().split()
a = int(li[0])
b = float(li[1])
from decimal import Decimal, ROUND_HALF_UP
def remove_representation_error_in_float(x):
    x = Decimal(str(x)).quantize(Decimal('0.000000000000001'), rounding=ROUND_HALF_UP)
    x = float(str(x))
    return x
bb = remove_representation_error_in_float(b)
print(int(a*b))


/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main()
{
    ll a;
    double b;
    cin>>a>>b;
    double x=a*b;
    cout<<(ll)x<<endl;    //cout<<s;

    return 0;
}


A,B = map(float, input().split())
print(int((A * B) // 1))


a,b = map(float, input().split())
a = round(a)
c = a*b

print(int(c))


import math
A, B = input().strip().split()
A=float(A)
B=float(B)
print(math.floor(A*B))


import math
import decimal
a, b = map(float, input().split())
a = decimal.Decimal(a)
b = decimal.Decimal(b)
print(math.floor(a*b))


a,b=map(float,input().split())
ans=a*b
temp=int(ans)
if abs(temp-ans)<0.999:
  print(temp)
else:
  print(temp+1)


#c
a,b=map(float, input().split())
import math
a = decimal.Decimal(a)
b = decimal.Decimal(b)
ans = a*b
print(ans)


from sys import stdin
import sys
import math
import random
from decimal import Decimal

s = input().split()
A = Decimal(s[0])
B = Decimal(s[1])
print(int(A*B))


# Code for C - Multiplication 3
# Use input() to fetch data from STDIN
from math import floor

[astr, bstr] = list(input().split())

a = int(astr)
[b1str, b2str] = bstr.split(".")

b1 = int(b1str) * 100
b2 = int(b2str)

print(floor(a * (b1 + b2) / 100))


import math

a,b = map(float,input().split())
ans = a*b
ans = math.floor(ans)
ans = int(ans)
print(ans)


nums = []
nums = input().split(" ")

print(int(int(nums[0])*float(nums[1])))


A,B = map(float, input().split())

print(int(A*B))


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

#a=198
#b=1.10

print(int(a*b))


import math

A, B = input().split()
A = int(A)
B = float(B)
print(math.floor(A * B))


from collections import Counter
import sys

sys.setrecursionlimit(10 ** 6)

mod = 1000000007
inf = int(1e18)

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

def inverse(a):
    return pow(a, mod - 2, mod)

def usearch(x, a):
    lft = 0
    rgt = len(a) + 1
    while rgt - lft > 1:
        mid = (rgt + lft) // 2
        if a[mid] <= x:
            lft = mid
        else:
            rgt = mid
    return lft

def main():
    a, b = input().split()
    a = int(a)
    b = b.split('.')
    if len(b) == 1:
        print(a * int(b[0]))
        return
    k = pow(10, len(b[1]))
    s = a * (int(b[0]) * k + int(b[1])) // k
    print(s)
main()


import math

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

ans = math.floor(a*b)
print(ans)


import math
A, B = map(float, input().split())
print(math.floor(A*B))


a,b=input().split()
a=int(a)
b=int(float(b)*100)
print(a*b//100)


N, K = map(int,input().split())
A = list(map(int,input().split()))
B = [0]
S = set([]);S.add(0)
now = 0
Flag = False
loop_start = -1
if K <= 2*pow(10,5)+10:
  for i in range(K):
    nxt = A[now]-1
    B.append(nxt)
    now = nxt
  #print(B)
  print(B[K]+1)
  exit()
for i in range(K*2):
  nxt = A[now]-1
  #print(now,nxt)
  if nxt in S:
    if Flag:
      if nxt == loop_start:
        #print(nxt,i)
        loop_cycle = i-loop_num
        break
    else:
      loop_start = nxt
      loop_num = i
      Flag = True
  else:
    B.append(nxt);S.add(nxt)
  now = nxt
#print(B,loop_start,loop_cycle,loop_num)
loc = (K-loop_start)%loop_cycle+loop_start
#print(loc)
print(B[loc]+1)

Score: 400 points

Problem Statement

The Kingdom of Takahashi has N towns, numbered 1 through N.

There is one teleporter in each town. The teleporter in Town i (1 \leq i \leq N) sends you to Town A_i.

Takahashi, the king, loves the positive integer K. The selfish king wonders what town he will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Help the king by writing a program that answers this question.

Constraints

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

1 \leq A_i \leq N

1 \leq K \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the integer representing the town the king will be in if he starts at Town 1 and uses a teleporter exactly K times from there.

Sample Input 1

4 5
3 2 4 1

Sample Output 1

4

If we start at Town 1 and use the teleporter 5 times, our travel will be as follows: 1 \to 3 \to 4 \to 1 \to 3 \to 4.

Sample Input 2

6 727202214173249351
6 5 2 5 3 2

Sample Output 2

2


import numpy as np
import sys

readline = sys.stdin.readline

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

# 愚直にやると計算量O(K)でTLEになる
# 同じ街にいったら操作打ち切りで配列を完結させる

# Teleport順の配列を作る
teleport = {1: True}
next_town = 1
for i in range(K):
    next_town = A[next_town - 1] # next_townがintで与えられる
    try: # 辞書を使用してO[1]で判定する
        teleport[next_town]
        dupulicate_town = next_town
        # 辞書をリストに変換
        teleport = list(teleport.keys())
        dupulicate_index = teleport.index(dupulicate_town)
        dupulicate_list = teleport[dupulicate_index:]
        break
    except KeyError:
        teleport[next_town] = True

if len(teleport) - 1 == K:
    print(teleport[-1])
else: # ループに入る場合
    consumption = len(teleport) - 1
    roop_num = K - consumption
    roop_index = roop_num % len(dupulicate_list)
    if roop_index == 0:
        print(dupulicate_list[-1])
    else:
        print(dupulicate_list[roop_index - 1])


n,k = map(int, input().split())
a = [0] + list(map(int, input().split()))

before=k
roop=1
cnt={}
nxt=1
mp = []
for i in range(1, k+1):
    mp.append(nxt)
    if nxt not in cnt:
        cnt[nxt] = i
        nxt = a[nxt]
    else:
        roop = i - cnt[nxt]
        before = cnt[nxt]-1
        break
print(mp[before + (k-before)%roop])


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

route = [1]
start = 1
duplicate = 0
while True:
  start = A[start]
  if start in route:
    route.append(start)
    duplicate = start
    break
  else:
  	route.append(start)
loop = len(route) - route.index(duplicate) - 1
bias = route.index(duplicate)

K -= bias
K = K % loop
route = route[route.index(duplicate):-1]

print(route[K])


n, k = map(int, input().split())
l = list(map(int, input().split()))
start = 1
seenl = [1]
seen = {1}
for i in range(k):
	start = l[start-1]
	if start in seen:
		loop_len = len(seenl) - seenl.index(start)
		r = (k-i-1)%loop_len
		goal = seenl[-loop_len:][r]
		break
	seenl.append(start)
	seen.add(start)
print(goal)


N, K = map(int, input().split())
A = list(map(int, input().split()))
#N=6
#K=1
#A=[6,5,2,5,3,2]
iti = 1
ex_A = []
basyo=0

for k in range(K):
    ex_A.append(iti)
    iti = A[iti-1]
    if iti in ex_A:
        basyo = ex_A.index(iti)
        maru = len(ex_A[:basyo])
        nokori = (K - maru) % len(ex_A[basyo:])
        break

if basyo:
    iti = ex_A[basyo+nokori]
#print(ex_A)
print(iti)


import numpy as np

def main():
    n, k = map(int, input().split())
    a = list(map(lambda x: int(x)-1, input().split()))
    foot = [0]
    is_loop = False
    ed = np.zeros([n], dtype=int)
    ed[0] = 1

    for i in range(1,k):
        go = a[foot[-1]]
        foot.append(go)
        if ed[go] == 1:
            st_i = foot.index(foot[-1])
            lo_size = len(foot)-1 - st_i

            k -= st_i
            k %= lo_size

            print(foot[st_i+k]+1)
            is_loop = True
            break
        ed[go] = 1

    if not is_loop:
        print(a[foot[-1]]+1)

if __name__ == '__main__':
    main()


n, k = map(int, input().split())
a = list(map(int, input().split()))
l = [1]
for i in range(n):
    if a[l[i] - 1] in l:
        res = l[:l.index(a[l[i] - 1])]
        cyc = l[l.index(a[l[i] - 1]):]
        break
    else:
        l += [a[l[i] - 1]]
print(cyc[(k - len(res)) % len(cyc)] if k > len(res) - 1 else res[k])


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

pos = 0
kiseki = [0] * (N+1)
for i in range(N):
    pos = A[pos] - 1
    kiseki[i+1] = pos

tail = kiseki.pop()
past = kiseki.index(tail)
print(kiseki[past + (K - past) % (N - past)] + 1)


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

isPassed = [False] * N
town = 0
#2度同じところに行きつくまで繰り返し、ループの枝元探す
while True:
    if isPassed[town]==False:
        isPassed[town] = True
        town = A[town]-1
    else:
        loopPoint = town
        break

#ループまでの長さを測る
onewayLen = 0
town = 0
while town!=loopPoint:
    town = A[town]-1
    onewayLen += 1

#ループ自体の長さを測る
loopLen = 1
town = A[loopPoint] - 1
while town!=loopPoint:
    town = A[town]-1
    loopLen += 1

#解
if K <= onewayLen:
    town = 0
    for i in range(K):
        town = A[town]-1
    print(town)
else:
    loopMod = (K-onewayLen) % loopLen
    town = loopPoint
    for i in range(loopMod):
        town = A[town]-1
    print(town+1)


n,k = map(int, input().split())
a = list(map(int, input().split()))
import numpy as np
link = set()
next = a[0]
link.add(1)
while next not in link:
    link.add(next)
    next = a[next-1]

link2 = set()
next2 = a[0]
link2.add(1)
while next not in link2:
    link2.add(next2)
    next2 = a[next2-1]

link2.remove(next)
ans = 0

rep = len(link)- len(link2)

if(k > len(link2)):
    p = (k-len(link2))%rep
    for i in range(p):
        next = a[next-1]
else:
    next = 0
    for i in range(k-1):
        next = a[next-1]

ans = next
print(ans)


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

ans = A[0]

d = {0:1, ans -1:1}
#移動する可能性がある街の個数uを出す
for i in range(2 * N):
  #print(ans)
  ans = A[ans - 1]
  if ans -1 not in d:
    d[ans -1] = 1
  else:
    d[ans - 1] += 1

#print("d", d, len(d))
u = len(d)

if d[0] == 1:
  a = (K - 1) % u
else:
  a = K % u
if a == 0:
  a = u

#print("a", a)
ans = A[A[0] - 1]
for i in range(a + 1):
  #print(i, ans)
  ans = A[ans - 1]
print(ans)


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

limit = K
now = 1
log = []

while limit > 0 and now not in log:
    if 1 not in log:
        log.append(1)
    #print("通過1",now,limit,log)
    now = A[now - 1]
    log.append(now)
    limit -= 1

if limit > 0:
    #print("通過2",now,limit,log)
    limit = limit % len(log[log.index(now) - 1:])

    while limit > 0:
        #print("通過3",now)
        now = A[now - 1]
        limit -= 1

now = A[now - 1]

print(now)


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

rireki = [0] * (n+10)
curr_c = 1
rireki[1] = 0

no_loop_count = k
loop_cnt = 1

mugen = False
for i in range(n):
    next_c = a_list[curr_c-1]
    # print(i, curr_c, next_c)
    # if next_c == curr_c:
    #     mugen = True
    if next_c == 1:
        no_loop_count = 0
        loop_cnt = i + 1
        break
    elif rireki[next_c] == 0:
        rireki[next_c] = i+1
    else:
        # print(next_c)
        no_loop_count = rireki[next_c] -1
        loop_cnt = i - no_loop_count
        break
    curr_c = next_c

if loop_cnt ==0:
    loop_cnt = 1

# if not mugen:
if k <= no_loop_count:
    ans = rireki.index(k)
else:
    # print('k',k)
    # print('no', no_loop_count)
    # print('lo', loop_cnt)
    ind = (k-1-no_loop_count)%loop_cnt +1
    rireki_fix = [i-no_loop_count for i in rireki]
    # print(ind, 'ind')
    ans = rireki_fix.index(ind)
    # print(rireki_fix)
    print(ans)


N, K = map(int, input().split())
MyList = input().split()

MyList = [int(n) for n in MyList]

ANS = 0
visted = []

def Myfunc(A):
    return MyList[A] - 1

for i in range(K):
    ANS = Myfunc(ANS)
    if ANS in visted:
        beANS = K % (len(visted) - visted.index(ANS))
        ANS = visted[beANS-1]
        print(ANS+1)
        break
    visted.append(ANS)
    if i +1 == K:
        print(ANS+1)


import sys

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

L = [1]
tmp = 1
ct = 0
check = 0
while True:
    x = A[tmp - 1]
    ct += 1
    if x in L or ct > k:
        check = x
        break
    else:
        L.append(x)
        tmp = x
if ct > k:
    print(L[k])
    sys.exit()
p = L.index(check)
l = len(L)
roop = l - p
if k < p:
    print(L[k])
else:
    k -= p
    k %= roop
    print(L[p + k])


n,k=map(int,input().split())
a=list(map(int,input().split()))
c=1
t=0
path=[]
s=set()
cycle=[]
while(c<=k):
    c+=1
    if a[t] in s:
        #print(path.index(a[t]),a[t])
        cycle=path[path.index(a[t]):]
        k-=c-1
        break
    path.append(a[t])
    s.add(a[t])
    t=a[t]-1
    #print(path,c)
#print(cycle)
print(cycle[k%len(cycle)])


import math
from collections import deque
import sys
sys.setrecursionlimit(10**9)

def main():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))

    graph = [0] * (N+1)
    for i in range(N+1): #1-indexed
        f = i
        t = A[i-1]
        graph[f] = t

    def solve():
        visited = []
        stack = deque([1])
        x = 1
        count = 0
        while len(stack) > 0:
            x = stack.pop()
            if x in visited:
                break

            visited.append(x)
            stack.append(graph[x])
            count += 1

            if count == K:
                print(stack.pop())
                exit()

        loop_head = x
        head_index = visited.index(loop_head)
        loop_len = len(visited) - head_index

        r = (K-head_index)%loop_len
        print(visited[head_index:][r])

    solve()

if __name__ == "__main__":
  main()


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


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

appeared = [False] * N
appeared[0] = True
path = [1]
for _ in range(N+10):
    next_A = As[path[-1] - 1]
    if appeared[next_A-1]:
        break
    else:
        path.append(next_A)
        appeared[next_A-1] = True

before_loop = path.index(next_A)
loop_len = len(path) - before_loop

if K <= before_loop:
    print(path[K])
else:
    print(path[(K - before_loop) % loop_len + before_loop])


A, B, C, D = map(int, input().split())
print("Yes" if (A+D-1)//D >= (C+B-1)//B else "No")

Score : 200 points

Problem Statement

Takahashi and Aoki will have a battle using their monsters.

The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively.

The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes 0 or below. The person with the monster whose health becomes 0 or below loses, and the other person wins.

If Takahashi will win, print Yes; if he will lose, print No.

Constraints

1 \leq A,B,C,D \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

If Takahashi will win, print Yes; if he will lose, print No.

Sample Input 1

10 9 10 10

Sample Output 1

No

First, Takahashi's monster attacks Aoki's monster, whose health is now 10-9=1.

Next, Aoki's monster attacks Takahashi's monster, whose health is now 10-10=0.

Takahashi's monster is the first to have 0 or less health, so Takahashi loses.

Sample Input 2

46 4 40 5

Sample Output 2

Yes


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

A = a[0]
B = a[1]
C = a[2]
D = a[3]

while B>0 and D>0:
  D = D - A
  if D <= 0:
    print("No")
    break
  B = B - D
  if B <= 0:
    print("Yes")
    break


# This Python file uses the following encoding: utf-8

# if __name__ == "__main__":
#     pass
a, b, c, d = map(int, input().split())
'''
while a > 0 and c > 0:
    c -= b
    a -= d
if c <= 0:
    print("Yes")
else:
    print("No")
'''
if  -(-c//b) <= -(-a//d):
    print("Yes")
else:
    print("No")


#入力
A, B, C, D = map(int, input().split())

#高橋の攻撃何発分か
if C % B == 0:
    aokiDeath = C // B
else:
    aokiDeath = C // B + 1

#青木の攻撃何回分か
if A % D == 0:
    takahashiDeath = A // D
else:
    takahashiDeath = A // D + 1

if aokiDeath <= takahashiDeath:
    print("Yes")
else:
    print("No")


a,b,c,d = list(map(int, input().split()))
q1 = a // d
q2 = c // b
if q1 < q2:
    print("Yes")
else:
    print("No")


A,B,C,D=map(int,input().split())
while A<=0 or C<=0:
  C-=B
  A-=D
if A>C:
  print('Yes')
else:
  print('No')


A, B, C, D = map(int, input().split())
while True:
    if C <= B:
        print("Yes")
        break
    if A <= D:
        print("No")
        break
    A -= D
    C -= B


import math
a,b,c,d = map(int,input().split())

x = math.floor(a/c)
y = math.floor(c/d)
if x > y:
    print('No')
else:
    print('Yes')


a,b,c,d=map(int,input().split())
for i in range(100):
    if i%2 == 0:
        c = c-b
        if c <= 0:
            print('Yes')
            break
    else:
        a = a-d
        if a <= 0:
            print('No')
            break


a, b, c, d = map(int, input().split())
while a > 0 or c > 0:
  a = a - d
  c = c - b

if a <= 0:
  print('No')
else:
  print('Yes')


a,b,c,d=[int(i) for i in input().split()]
if max(a,b)>max(c,d):
  print('Yes')
else:
  print('No')


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

def func(X,Y):
    if X%Y == 0:
        return X//Y
    else:
        return (X//Y)+1

if func(C,B) <= func(A,D):
    print('Yes')
else:
    print('No')


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

while True:
  C -= B

  if (C <= 0):
    print('Yes')
    return

  A -= D
  if (A <= 0):
    print('No')
    return


s = input()[::-1]

MOD = 2019

cum = 0
cnt = [0] * 2019
cnt[0] = 1

d = 1
for c in s:
    cum += int(c) * d
    cum %= MOD
    cnt[cum] += 1
    d *= 10
    d %= MOD

ans = 0
for v in cnt:
    ans += v * (v - 1) // 2

print(ans)

Score : 400 points

Problem Statement

Given is a string S consisting of digits from 1 through 9.

Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:

Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

Constraints

1 ≤ |S| ≤ 200000

S is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.


import sys
input=lambda: sys.stdin.readline().rstrip()
S=input()
import collections
D=collections.defaultdict(int)
cur=0
keta=0
ans=0
D[0]+=1
for s in S[::-1]:
  cur=(cur+int(s)*pow(10,keta))%2019
  ans+=D[cur]
  D[cur]+=1
  keta+=1
print(ans)


def main():
    import sys
    input = sys.stdin.readline
    from collections import defaultdict
    S = reversed(list(input().rstrip()))
    counter = defaultdict(int)
    mod = 2019
    counter[0] += 1
    num = 0
    for i, c in enumerate(S):
        num += int(c) * 10**(i)
        counter[num%mod] += 1
    ans = 0
    for v in counter.values():
        ans += (v * (v-1)) // 2
    print(ans)

if __name__ == '__main__':
    main()


#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

s=SI()
n=len(s)
beki=[0 for i in range(n+1)]
beki[0]=1
for i in range(n):
    beki[i+1]=(beki[i]*10)%2019
#print(beki)

#k=int(s)
dp=[0 for i in range(n)]
dp[-1]=int(s[-1])
#print(dp[3])
for i in range(n-1):
    j=n-i-1
    #print((dp[j]+int(s[j-1])*beki[i+1])%2019)
    dp[j-1]=(dp[j]+int(s[j-1])*beki[i+1])%2019

#print(dp)
ans=0
u=Counter(dp)
#print(u)
for i in u:
    if i==0:
        ans+=(u[i]*(u[i]+1))//2
    else:
        ans+=(u[i]*(u[i]-1))//2
print(ans)


S = str(input())
mojisu = len(S)
num = 0
for i in range(mojisu):
    for j in range(i, mojisu):
        mojisu2 = j-i+1
        taisho = 0
        for l in range(mojisu2):
            taisho += int(S[i+l]) * (10**(mojisu2-l-1))
        if taisho % 2019 == 0:
            num += 1
print(num)


s = list(input())

counter = 0

for i in range(len(s) + 1):
    for j in range(len(s) + 1):
        if i + j + 4 < len(s) + 1:
            a_str = s[i: i + j + 4]
            if(len(a_str) < 4):
                break
            a = int(''.join(map(str, a_str)))
            if(a % 2019 == 0):
                counter += 1
print(counter)


s = str(input())
L = len(s)
dict = {}
for i in range(L+1):
  amari = int(s[i:]) % 2019
  if not(amari in dict.keys()):
    dict[amari] = 1
  else:
    dict[amari] += 1
ans = 0
for key in dict.keys():
  ans += (dict[key]*(dict[key]-1))/2
print(int(ans))


s = input()
mod = 2019
l = [0]*mod
ans = 0

for i in range(len(s)):
    a = int(s[i:])%mod
    l[a] += 1
l[0] += 1

for i in range(2019):
    ans += l[i]*(l[i] - 1)//2

print(ans)


s=[int(j) for j in input()][::-1]
c=[0]*2019
tmp=0
c[0]+=1
t=1
import numpy as np
for i in s:
    tmp+=t*i
    c[tmp%2019]+=1
    t*=10
c=np.array(c)
ans=c*(c-1)//2
print(ans.sum())


# -*- coding: utf-8 -*-
import collections
s = (input())

"""
n = len(s)
ans = 0
for i in range(n-4):
    for j in range(i+4,n+1):
        if int(s[i:j]) % 2019 == 0:
            ans += 1
print(ans)
"""

n = len(s)
ans = 0
l = 0
#r = l
num = int(s)

tmp = [0 for _ in range(n+1)]
ten = [0 for _ in range(n)]
tmp1 = 0
val = 1
for i in range(0,n):
    ten[i] = val
    tmp1 += (int(s[n-i-1]) * val)
    tmp[i+1] = tmp1 % 2019
    val = (val * 10)
#print(tmp)

c = collections.Counter(tmp)
#print(c)
for i in range(0, 2020):
    if c[i] > 0:
        ans += ((2 * c[i] - 1) // 2)
print(ans)


s = str(input())
mod = 2019
li = [int(s[-1])]
for i in range(len(s) - 1):
    li.append((li[-1] + int(s[-(2 + i)]) * (10 ** (i + 1))) % mod)
import collections
A=collections.Counter(li)
ans=0
for u,v in A.items():
    ans+=v*(v-1)//2
    if u==0:
        ans+=v
print(ans)


s = input()
s_num = int(s)
len_s = len(s)
list=[0 for x in range(len_s+1)]
for i in range(len_s-1,-1,-1):
    for j in range(4,min(9,len_s-i+1)):
        if int(s[i:i+j])%2019==0:
            list[i]=list[i+j]+1
            break
print(sum(list))


s = str(input())

ans = 0
len_s = len(s)
ans_pos = []
str_pos = {}
end_pos = {}
for i in range(4,9):
    for j in range(len_s):
        if j+i > len_s :
            break
        if int(s[j:j+i]) % 2019 == 0:
            ans +=1
            str_pos[j] = 0
            end_pos[j+i-2]= 0
            #ans_pos.append([j,j+i-1])

for st in str_pos.keys():
    if st in end_pos.keys():
        ans += 1

print(ans)


#!/usr/bin/env python
import sys
S = input()
count = 0

for i in range(0,len(S)-3):
  for j in range(i+3,len(S)):
    if int(S[i:j+1])%3 == 0:
      if int(S[i:j+1])%673==0:
        count += 1
print(count)


from collections import deque

S = input()
N = len(S)
sub_s = ""

total = 0

for l in range(N):  # 200000
    if l % 2 == 0:
        # 左から右に伸ばしていく
        sub_s = S[l]

        if int(sub_s) % 2019 == 0:
            total += 1
        r = l + 1
        while r < N:  # 末尾N-1まで
            sub_s += S[r]
            if int(sub_s) % 2019 == 0:
                total += 1
                # print((l, r))
                # print(sub_s)
            r += 1
    else:
        # 右を縮めていく
        # r = N  # 末尾から
        r = 1
        # while r > l:
        while r < (N - l):
            # sub_s = S[l:r]  # ここが重いはず
            sub_s = sub_s[:-r] # ここが重いはず

            if not sub_s:
                break
            if int(sub_s) % 2019 == 0:
                total += 1
                # print((l, r))
                # print(sub_s)
            # r -= 1
            r += 1
    # print("--------")

ans = total

print(ans)


s = str(input())
if int(s) < 2019:
    print(0)
else:
#4桁事
    count = 0
    for i in range(len(s)-3):
        num = s[i] + s[i+1] + s[i+2] + s[i+3]
        if int(num) % 2019 == 0:
            count += 1

    for i in range(len(s) - 4):
        num = s[i] + s[i+1] + s[i+2] + s[i+3] + s[i + 4]
        if int(num) % 2019 == 0:
            count += 1

    for i in range(len(s) -5):

        num = s[i] + s[i+1] + s[i+2] + s[i+3] + s[i + 4] + s[i + 5]
        if int(num) % 2019 == 0:
            count += 1
    print(count)


s = int(input())
y=0
for i in range(len(str(s))-3):
    for j in range(i+3,len(str(s))):
        p=int(str(s)[i:j+1])
        if p%2019==0:
            y+=1
print(y)


#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m,s = LI()
    v = [[] for i in range(n)]
    M = 0
    for _ in range(m):
        x,y,a,b = LI()
        x -= 1
        y -= 1
        v[x].append((y,a,b))
        v[y].append((x,a,b))
        M += a
    g = LIR(n)
    d = defaultdict(lambda : float("inf"))
    d[(0,s)] = 0
    ans = [float("inf")]*n
    q = [(0,-s,0)]
    k = 0
    f = [0]*n
    f[0] = -s
    while q:
        dx,s,x = heappop(q)
        if f[x] < s:
            continue
        f[x] = s
        if ans[x] == float("inf"):
            k += 1
            ans[x] = dx
            if k >= n:
                break
        c,e = g[x]
        for y,a,b in v[x]:
            if a+s > 0:
                continue
            nd = dx+b
            ns = s+a
            if nd < d[(y,ns)]:
                d[(y,ns)] = nd
                heappush(q,(nd,ns,y))
        s -= c
        dx += e
        while M+s >= 0:
            for y,a,b in v[x]:
                if a+s > 0:
                    continue
                nd = dx+b
                ns = s+a
                if nd < d[(y,ns)]:
                    d[(y,ns)] = nd
                    heappush(q,(nd,ns,y))
            s -= c
            dx += e
    for i in ans[1:]:
        print(i)
    return

#Solve
if __name__ == "__main__":
    solve()

Score : 500 points

Problem Statement

There are N cities numbered 1 to N, connected by M railroads.

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

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

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

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

Constraints

2 \leq N \leq 50

N-1 \leq M \leq 100

0 \leq S \leq 10^9

1 \leq A_i \leq 50

1 \leq B_i,C_i,D_i \leq 10^9

1 \leq U_i < V_i \leq N

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

2
14

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

In this figure, each city is labeled as follows:

The first line: the ID number i of the city (i for City i)

The second line: C_i / D_i

Similarly, each railroad is labeled as follows:

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

The second line: A_i / B_i

You can travel from City 1 to City 2 in 2 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

You can travel from City 1 to City 3 in 14 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.

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

Use the 1-st railroad to move from City 2 to City 1 in 2 minutes.

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

Sample Input 2

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

Sample Output 2

5
5
7

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

You can travel from City 1 to City 4 in 7 minutes, as follows:

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

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

Use the 4-th railroad to move from City 3 to City 4 in 1 minutes.

Sample Input 3

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

Sample Output 3

1
9003
14606
16510
16576

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

You can travel from City 1 to City 6 in 16576 minutes, as follows:

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

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

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

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

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.

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

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

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

Use the 1-st railroad to move from City 2 to City 1 in 1 minute.

Use the 2-nd railroad to move from City 1 to City 3 in 1 minute.

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

At the exchange counter in City 5, exchange 63 gold coins for 63 silver coins in 63 minutes.

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

Use the 2-nd railroad to move from City 3 to City 1 in 1 minute.

Use the 5-th railroad to move from City 1 to City 6 in 1 minute.

Sample Input 4

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

Sample Output 4

1
3
5

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

Sample Input 5

2 1 0
1 2 1 1
1 1000000000
1 1

Sample Output 5

1000000001

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

You can travel from City 1 to City 2 in 1000000001 minutes, as follows:

At the exchange counter in City 1, exchange 1 gold coin for 1 silver coin in 1000000000 minutes.

Use the 1-st railroad to move from City 1 to City 2 in 1 minute.


Score : 100 points

Problem Statement

Print the circumference of a circle of radius R.

Constraints

1 \leq R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R

Output

Print the circumference of the circle.
Your output is considered correct if and only if its absolute or relative error from our answer is at most 10^{-2}.

Sample Input 1

1

Sample Output 1

6.28318530717958623200

Since we accept an absolute or relative error of at most 10^{-2}, 6.28 is also an acceptable output, but 6 is not.

Sample Input 2

73

Sample Output 2

458.67252742410977361942


from math import pi

r = int(input())
print(pi * r * 2)


R = float(input())
r = R * 2 * 3.14
print(r)


r=int(input())
from math import pi
print(2*r*pi)


import math
R=float(input())
L=2*math.pi*R


from collections import *
import sys
try: inp = raw_input
except: inp = input
def err(s):
    sys.stderr.write('{}\n'.format(s))

def ni():
    return int(inp())

def nl():
    return [int(_) for _ in inp().split()]

R = ni()
import math
print(math.pi*2*R)


from math import pi
r=int(input())
print(2*r*pi)


import math
r = int(input())
circle = r*2*math.pi
print(circle)


import math
R=int(input())
print(2*math.pi*R)


import math

R = int(input())
L = 2 * math.pi * R
print(L)


import math
r = int(input())
print(2 * r * math.pi)


import math
R = int(input())
print(2*math.pi*R)


import math

r = int(input())
print(2*math.pi*r)


N = input()
ans = 0
for i in range(3):
  if N[i] == '7':
    ans = 1
    break

if ans == 1:
  print('Yes')
else :
  print('No')

Score : 100 points

Problem Statement

Given is a three-digit integer N. Does N contain the digit 7?

If so, print Yes; otherwise, print No.

Constraints

100 \leq N \leq 999

Input

Input is given from Standard Input in the following format:

N

Output

If N contains the digit 7, print Yes; otherwise, print No.

Sample Input 1

117

Sample Output 1

Yes

117 contains 7 as its last digit.

Sample Input 2

123

Sample Output 2

No

123 does not contain the digit 7.

Sample Input 3

777

Sample Output 3

Yes


n = input()

flag = 0

for i in n:
  if i == "7":
    flag = 1
    break

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


num = input()
if "7" in str(num):
  print("Yes")
else:
  print("No")


N = input()
print("Yes" if N.count("7")>=1 else "No")


import sys
input = sys.stdin.readline

N = int(input())
I = input()

R =0
G =0
B =0
for i in range(N):
    if (I[i] == 'R'):
        R+=1
    if (I[i] == 'G'):
        G+=1
    if (I[i] == 'B'):
        B+=1

sum = R * G * B
count = 0

for i in range(N):
    for j in range(i+1,N):
        if I[i] != I[j]:
            k = j + j - i
            if k >= N:
                continue
            if I[i] != I[k] and I[j] != I[k]:
                count += 1

print(sum - count)


n = int(input())
s = str(input())
r, g, b = map(s.count, "RGB")
ans = r*g*b
for i in range(n):
    for j in range(i+1, n):
        k = 2*j - i
        if k<n and len(set([s[i], s[j], s[k]])) == 3:
            ans -= 1
print(ans)


text = input()
if "7" in text:
  print("Yes")
else:
  print("No")


import sys

for line in sys.stdin:
    print(line)


if "7" in input():
  print("Yes")

else:
  print("No")


n = input()
if '7' in n:
    print('Yes')
else:
    print('No')


N = input()
if "7" in N:
  print("Yes")
else:
  print("No")


N = list(input())

if '7' in N:
    print("Yes")
else:
    print("No")


list = list(str(input()))

YN_flag = 0

for i in list:
    if i == "7":
        print("Yes")
        YN_flag = 1
        break

if YN_flag == 0:
    print("No")


n=int(input())
if n[1]=='7':
  print('Yes')
if n[2]=='7':
   print('Yes')
if n[3]=='7':
   print('Yes')
else:
   print('No')


N = int(input())
N = str(N)
if "7" in N:
    print("Yes")
else:
    print("No")


N = input()
ret = 'No'
for c in N:
  if c == '7':
    ret = 'Yes'
print(ret)


S = input()

if '7' in S:
    print("Yes")
else:
    print("No")


lista=list(input())
if "7" in lista:
    print("Yes")
else:
    print("No")


s=input()
if('7' in s):
  print("Yes")
else:
  print("No")


import numpy
import math

K = int(input())

sum=0
for i in range(1, K+1):
    for j in range(1, K+1):
        for l in range(1, K+1):
            temp= math.gcd(i,j)
            sum += math.gcd(temp, l)

print(sum)

Score : 300 points

Problem Statement

Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.

Constraints

1 \leq K \leq 200

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the value of \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Sample Input 1

2

Sample Output 1

9

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)
+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)
=1+1+1+1+1+1+1+2=9

Thus, the answer is 9.

Sample Input 2

200

Sample Output 2

10813692


# abc162_c.py
# https://atcoder.jp/contests/abc162/tasks/abc162_c

# C - Sum of gcd of Tuples (Easy) /
# 実行時間制限: 2 sec / メモリ制限: 1024 MB
# 配点 : 300点

# 問題文
# K∑a=1K∑b=1K∑c=1gcd(a,b,c)を求めてください。
# ただし、gcd(a,b,c)は a,b,cの最大公約数を表します。

# 制約
#     1≤K≤200
#     Kは整数

# 入力
# 入力は以下の形式で標準入力から与えられる。
# K

# 出力
# K∑a=1K∑b=1K∑c=1gcd(a,b,c)の値を出力せよ。

# 入力例 1
# 2

# 出力例 1
# 9

# gcd(1,1,1)+gcd(1,1,2)+gcd(1,2,1)+gcd(1,2,2)+gcd(2,1,1)+gcd(2,1,2)+gcd(2,2,1)+gcd(2,2,2)
#  =1+1+1+1+1+1+1+2=9
# となるため、答えは 9です。

# 入力例 2
# 200

# 出力例 2
# 10813692

global FLAG_LOG
FLAG_LOG = False

def log(value):
    # FLAG_LOG = True
    # FLAG_LOG = False
    if FLAG_LOG:
        print(str(value))

def calculation(lines):
    # S = lines[0]
    K = int(lines[0])
    # N, M = list(map(int, lines[0].split()))
    # values = list(map(int, lines[1].split()))
    # values = list(map(int, lines[2].split()))
    # values = list()
    # for i in range(N):
    #     values.append(int(lines[i]))
    # valueses = list()
    # for i in range(N):
    #     valueses.append(list(map(int, lines[i+1].split())))

    import math

    dic = dict()
    for x in range(1, K):
        for y in range(x+1, K+1):
            dic[(x, y)] = math.gcd(x, y)

    su = 0
    for a in range(1, K+1):
        for b in range(1, K+1):
            for c in range(1, K+1):
                # ☆これだと5秒かかる
                # su += get_gcd(a, b, c)
                tmp = [a, b, c]
                tmp.sort()
                x, y, z = tmp
                # けど...速くしきらんかった...
                su += get_gcd_by_dic(dic, x, y, z)

    return [su]

# def get_gcd(a, b, c):
#     import math
#     return math.gcd(math.gcd(a, b), math.gcd(a, c))

def get_gcd_by_dic(dic, a, b, c):
    if a == b:
        x = a
    else:
        x = dic[(a, b)]
    if a == c:
        y = a
    else:
        y = dic[(a, c)]
    if x == y:
        ret = x
    elif x > y:
        ret = dic[(y, x)]
    else:
        ret = dic[(x, y)]
    return ret

# 引数を取得
def get_input_lines(lines_count):
    lines = list()
    for _ in range(lines_count):
        lines.append(input())
    return lines

# テストデータ
def get_testdata(pattern):
    if pattern == 1:
        lines_input = ['2']
        lines_export = [9]
    if pattern == 2:
        lines_input = ['200']
        lines_export = [10813692]
    return lines_input, lines_export

# 動作モード判別
def get_mode():
    import sys
    args = sys.argv
    global FLAG_LOG
    if len(args) == 1:
        mode = 0
        FLAG_LOG = False
    else:
        mode = int(args[1])
        FLAG_LOG = True
    return mode

# 主処理
def main():
    import time
    started = time.time()
    mode = get_mode()
    if mode == 0:
        lines_input = get_input_lines(1)
    else:
        lines_input, lines_export = get_testdata(mode)

    lines_result = calculation(lines_input)

    for line_result in lines_result:
        print(line_result)

    # if mode > 0:
    #     print(f'lines_input=[{lines_input}]')
    #     print(f'lines_export=[{lines_export}]')
    #     print(f'lines_result=[{lines_result}]')
    #     if lines_result == lines_export:
    #         print('OK')
    #     else:
    #         print('NG')
    # finished = time.time()
    # duration = finished - started
    # print(f'duration=[{duration}]')

# 起動処理
if __name__ == '__main__':
    main()


from math import gcd
K = int(input())
ans = 0
for a in range(1,K+1):
  for b in range(1,K+1):
    for c in range(1,K+1):
      ans += gcd(gcd(a,b),c)

print(ans)


K = int(input())
c = 0
import math
for i in range(1,K+1):
    for j in range(1,K+1):
        ab = math.gcd(i,j)
        for k in range(1,K+1):
            c += math.gcd(ab,k)

print(c)


from numba import njit
from sys import stdin

@njit(cache=True)
def gcd(x, y):
    if x % y == 0:
        return y
    return gcd(y, x % y)

@njit(cache=True)
def fact(x):
    if x == 1:
        return x
    return x * fact(x - 1)

def main():
    k = int(stdin.readline())

    ans = 0

    for a in range(1, k + 1):
        for b in range(a, k + 1):
            d = gcd(a, b)
            for c in range(b, k + 1):
                e = gcd(d, c)
                ans += e * fact(3) // fact(3 - len(set([a, b, c])) + 1)

    print(ans)

if __name__ == "__main__":
    main()


import math

t=0
n=int(input())
for i in range(n):
    for j in range(n):
        g=math.gcd(i+1,j+1)
        for k in range(n):
            t+=math.gcd(g,k+1)
print(t)


import math

K = int(input())

def gcd3(a, b, c):
    d = math.gcd(a, b)
    e = math.gcd(d, c)
    return e

ans = 0
for x in range(1, K + 1, 1):
    for y in range(1, K + 1, 1):
        tmp = list(map(lambda z: gcd3(x, y, z), range(1, K+1, 1)))
        ans = ans + sum(tmp)

print(ans)


from numba import jit

@jit
def gcd(a,b):
    if b == 0: return a
    else: return gcd(b, a % b)

K = int(input())

ans = 0
for i in range(1,K+1):
    for j in range(1,K+1):
        for k in range(1,K+1):
            ans += gcd(gcd(i,j),k)
print(ans)


import math
x=0;y=0
K=int(input())
for i in range(1,K+1):
  for j in range(1,K+1):
    y=math.gcd(i,j)
    for h in range(1,K+1):
      x=x+math.gcd(y,h)
print(x)


from math import gcd

K = int(input())
ans = 0

for i in range(1, K+1):
    for j in range(1, K+1):
        for k in range(1, K+1):
            ans += gcd(gcd(i, j), k)

print(ans)


import math
A = int(input())
def gcd(A):
    total = 0
    for i in range(1,A+1):
        for j in range(1,A+1):
            B = math.gcd(i,j)
            for k in range(1,A+1):
                total += math.gcd(B,k)
    return total
print(gcd(A))


#!/usr/bin/env python3
import sys
input = sys.stdin.readline
import math

k = int(input())
ret = 0
for i in range(1, k+1):
    for j in range(1, k+1):
        for k in range(1, k+1):
            ret += math.gcd(math.gcd(i, j), k)
print(ret)


from math import gcd
k = int(input())
うんち = 0
for デビ in range(1,k+1):
    for デビデ in range(1,k+1):
        for ビル in range(1,k+1):
            うんち += gcd(デビ,gcd(デビデ,ビル))
print(うんち)


import math
k = int(input())
x = 0
for a in range(1, k+1):
    for b in range(1, k+1):
        for c in range(1, k+1):
            x += math.gcd(math.gcd(a, b), c)
print(x)


import math
sum = 0
n = int(input())
for i in range(1,n+1):
    for j in range(1,n+1):
        for k in range(1,n+1):
            ans = math.gcd(i,j)
            ans = math.gcd(ans, k)
            sum += ans
print(sum)


import math
k=200
s=0
for p in range(k):
  for q in range(k):
    g=math.gcd(p+1,q+1)
    for i in range(k):
      r=math.gcd(g,i+1)
      s=s+r
print(s)


import math
from functools import reduce
answer=0

def gcd(*numbers):
    return reduce(math.gcd, numbers)

K=int(input())
for i in range(1,K+1):
    for j in range(1,K+1):
        for k in range(1,K+1):
            #print(i,j,k)
            answer+=gcd(i,j,k)

print(answer)


import math
from functools import reduce
K = int(input())
sum = 0
for a in range(1, K+1):
    for b in range(1, K+1):
        for c in range(1, K+1):
            nums = [a, b, c]
            gcd = reduce(math.gcd, nums)
            sum += gcd
print(sum)


import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

def gcd_list(numbers):
    return reduce(math.gcd, numbers)

k = int(input())

ret = 0

my_dict = dict()

for i in range(1, k+1):
    for j in range(1, i+1):
        for l in range(1, j+1):
            if i == j and j == l:
                ret += gcd_list([i, j, l])
            elif i != j and j != l:
                ret += 6 * gcd_list([i, j, l])
            else:
                ret += 3 * gcd_list([i, j, l])

print(ret)


import math

K = int(input())

sum = 0
for i in range(1, K + 1):
    for j in range(1, K + 1):
        for k in range(1, K + 1):
            a = math.gcd(math.gcd(i, j), k)
            # print(math.gcd(math.gcd(i, j), k))
            sum += a

print(sum)


N=int(input())
S=input()
ans = 0
for i in range(0,N):
  for j in range(i+1,N):
    if S[i] != S[j]:
      k = j+j-i
      if k < N:
        if S[i] != S[k] and S[j] != S[k]:
          #print(i,j,k)
          ans += 1
ans = (S.count('R') * S.count('G') * S.count('B')) - ans
print(ans)

Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800


N = int(input())
S = list(input())
ans = S.count('R') * S.count('G') * S.count('B')
for i in range(N-2):
    for j in range(i+1, N + (-(N-i-1)//2)):
        k = j+(j-i)
        if len(set([S[i], S[j], S[k]])) == 3:
            ans-=1
print(ans)


def solve(n, s):
    D = {"R": 0, "G": 0, "B": 0}
    for c in s:
        D[c] += 1
    ans = D["R"] * D["G"] * D["B"]
    for i in range(n):
        for j in range(i+1,(i+n+1)//2):
            k = 2*j - i
            if (s[i] != s[j]) and (s[j] != s[k]) and (s[k] != s[i]):
                ans -= 1
    return ans

n = int(input())
s = input()
print(solve(n, s))


def contains(n, s):
	r, g, b = 0, 0, 0
	for i in s:
		if i == 'R':
			r += 1
		if i == 'G':
			g += 1
		if i == 'B':
			b += 1
	ans = r * g * b
	for i in range(len(s)):
		for j in range(i + 1, len(s)):
			k = j - i + j
			if k < len(s):
				if (s[i] == 'R' or s[j] == 'R' or s[k] == 'R') and (s[i] == 'G' or s[j] == 'G' or s[k] == 'G') and (s[i] == 'B' or s[j] == 'B' or s[k] == 'B'):
					# print(i, j, k)
					ans -= 1
	return ans

n = int(input())
s = input()
print(contains(n, s))


# import numpy as np
# import math
# import copy
# from collections import deque
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10000)

def main():
    N = int(input())
    S = input().rstrip()

    R = set([])
    G = set([])
    B = set([])

    for i in range(N):
        temp = S[i]
        if temp == 'R':
            R.add(i)
        elif temp == 'G':
            G.add(i)
        else:
            B.add(i)

    all = [R,G,B]

    M = [len(R),len(G),len(B)]
    res = M[0] * M[1] * M[2]
    index = M.index(max(M))

    most = all.pop(index)
    first = all[0]
    second = all[1]

    count = 0

    for f in first:
        for s in second:
            temp1 = s * 2 - f
            temp2 = f * 2 - s
            temp3 = (f + s) // 2
            if (True) & (temp1 in most):
                count += 1
            if (True) & (temp2 in most):
                count += 1
            if (s + f) % 2 == 0:
                if temp3 in most:
                    count += 1

    res -= count
    print(res)

main()


N = int(input())
S = list(input())
f=0
ijk = [[i+1,j+1,k+1]for i in range(N) for j in range(N) for k in range(N)
        if i<j<k and S[i]!=S[j]!=S[k]]
# print(ijk)
for i in range(len(ijk)):
    if(ijk[i][1]-ijk[i][0] != ijk[i][2]-ijk[i][1]):
        f+=1
print(f)


n = int(input())
s = str(input())
count = 0
sum_RGB = s.count("R") * s.count("G") * s.count("B")
for i in range(n):
    for j in range(i, n):  # rangeをiからにすることでループ減らせる
        # for k in range(n): # sum_RGBから減らしていくのでｋがi,jで決まる
        k = 2*j - i
        if k < n:
            a = (s[i], s[j], s[k])
            # print(a)
            a_set = set(a)
            # print(a_set)
            if len(a_set) == 3:
                count += 1

print(sum_RGB - count)


def calc(N, S):
    id = {'R': 0, 'G': 1, 'B': 2}
    rgb = [[0, 0, 0] for _ in range(N)]
    rgb[0][id[S[0]]] = 1
    for i in range(1, N):
        for j in [0, 1, 2]:
            rgb[i][j] = rgb[i - 1][j]
            if j == id[S[i]]:
                rgb[i][j] += 1
    result = 0
    for i in range(N - 1, -1, -1):
        X = S[i]
        YZ = (['G', 'B'] if X == 'R' else ['R', 'B'] if X == 'G' else ['R', 'G'])
        j = i - 1
        while j > -1:
            if S[j] in YZ:
                result += rgb[j][3 - id[X] - id[S[j]]]
                if 2 * j - i > -1 and not S[2 * j - i] in [X, S[j]]:
                    result -=1
            j -= 1
    return result

N = int(input())
S = input()
print(calc(N, S))


n = int(input())
s_list = list(map(str,input()))
R_list=[];G_list=[];B_list=[];ans=0

for i in range(n):
    if s_list[i]=="R":
        R_list.append(i)
    elif s_list[i]=="G":
        G_list.append(i)
    else:
        B_list.append(i)

for a in R_list:
    for b in G_list:
        for c in B_list:
            if a+b==2*c or a+c==2*b or b+c==2*a:
                continue
            ans += 1
print(ans)


from sys import stdin
import sys

# A, B, C = [int(x) for x in stdin.readline().rstrip().split()]
# A,B = [int(x) for x in stdin.readline().rstrip().split()]
# U = input().split()
# A, B = [str(x) for x in stdin.readline().rstrip().split()]
N = int(input())
S = list(input())
r = []
g = []
b = []
for i in range(N):
    if S[i] == 'R':
        r.append(i+1)
    elif S[i] == 'G':
        g.append(i+1)
    else:
        b.append(i+1)
# print(r)
# print(g)
# print(b)
cnt = 0
for i in range(len(r)):
    for j in range(len(g)):
        for k in range(len(b)):
            x=min(r[i], g[j], b[k])
            y=max(r[i], g[j], b[k])
            if r[i] != x and r[i] != y:
                if r[i]-x != y-r[i]:
                    cnt += 1
            elif g[j] != x and g[j] != y:
                if g[j]-x != y-g[j]:
                    cnt += 1
            else:
                if b[k]-x != y-b[k]:
                    cnt += 1
print(cnt)


N = int(input())
S = input()
count = 0
for i, s_i in enumerate(S[:-2]):
    for j, s_j in enumerate(S[i + 1: -1]):
        if s_i == s_j:
            continue
        j += i + 1
        for k, s_k in enumerate(S[j + 1:]):
            k += j + 1
            if j - i != k - j:
                if s_i != s_k and s_j != s_k:
                    count += 1
print(count)


N=int(input())
S=input()
SS=[a for a in S]
SS.insert(0,0)
answer=0
for i in range(1,N-1):
    for j in range(i+1,N+1):
        if SS[i]==SS[j]:
            continue
        for k in range(j+1,N+1):
            if i+k==j*2:
                continue
            else:
                if SS[i]!=SS[j] and SS[j]!=SS[k] and SS[k]!=SS[i]:
                    answer+=1
print(answer)


N = int(input())
S = input()

r=0
ListR = []
g=0
ListG = []
b=0
ListB = []
for i in range(N):
    if S[i] == 'R':
        r = r+1
        ListR.append(i)
    elif S[i] == 'G':
        g = g+1
        ListG.append(i)
    else:
        b = b+1
        ListB.append(i)

n = (N+1)//2

remove = 0
for i in range(1,n+1):
    for j in range(N-2*i):
        if S[j] != S[j+i] and S[j+i] != S[j+2*i] and S[j] != S[j+2*i]:
            remove = remove+1

print(r*g*b-remove)


Score : 100 points

Problem Statement

We have three boxes A, B, and C, each of which contains an integer.

Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.

We will now do the operations below in order. Find the content of each box afterward.

Swap the contents of the boxes A and B

Swap the contents of the boxes A and C

Constraints

1 \leq X,Y,Z \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the integers contained in the boxes A, B, and C, in this order, with space in between.

Sample Input 1

1 2 3

Sample Output 1

3 1 2

After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.

Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.

Sample Input 2

100 100 100

Sample Output 2

100 100 100

Sample Input 3

41 59 31

Sample Output 3

31 41 59


a, b, c = input().split(' ')
print("{} {} {}".format(c, a, b))


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


arr= input().split()
ans_list =[]
ans_list.append(arr[2])
ans_list.append(arr[0])
ans_list.append(arr[1])

ans=' '.join(ans_list)
print(ans)


a,b,c=map(int, input().split())  #複数数値入力　「A B」みたいなスペース空いた入力のとき

#aとcの入れ替え
temp = b
b = a
a =temp

#aとcの入れ替え
temp = c
c = a
a =temp

#出力
print(a,b,c)


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

i = X
X = Y
Y = i

i = X
X = Z
Z = i

print(X,Y,Z)


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

print(z, x, y)


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


a,b,c = map(int, input().split())
print(str(c)+' '+str(a)+' '+str(b))


X, Y, Z = map(int, input().split())
tmp = 0

print("{} {} {}".format(Z,X,Y))


m,n = map(int, input().split())
a = list(map(int, input().split()))
res = 0
for c in a:
    if (c / sum(a)) >= (1 / (4 * m)):
        res += 1
if res >= n:
    print("Yes")
else:
    print("No")

Score : 200 points

Problem Statement

We have held a popularity poll for N items on sale. Item i received A_i votes.

From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.

If M popular items can be selected, print Yes; otherwise, print No.

Constraints

1 \leq M \leq N \leq 100

1 \leq A_i \leq 1000

A_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_N

Output

If M popular items can be selected, print Yes; otherwise, print No.

Sample Input 1

4 1
5 4 2 1

Sample Output 1

Yes

There were 12 votes in total. The most popular item received 5 votes, and we can select it.

Sample Input 2

3 2
380 19 1

Sample Output 2

No

There were 400 votes in total. The second and third most popular items received less than \dfrac{1}{4\times 2} of the total number of votes, so we cannot select them. Thus, we cannot select two popular items.

Sample Input 3

12 3
4 56 78 901 2 345 67 890 123 45 6 789

Sample Output 3

Yes


n, m = map(int,input().split())
lst = list(map(int,input().split()))
lst.sort()
lst.reverse()
x = sum(lst)
if (lst[m - 1] < x/4/m):
  print("No")
else:
  print("Yes")


n, m = map(int, input().split())
alst = list(map(int, input().split()))
alst.sort(reverse = True)
stand = sum(alst) / m / 4
if alst[m - 1] >= stand:
    print("Yes")
else:
    print("No")


#!/usr/bin/env python3
n, m, *a = map(int, open(0).read().split())
s = sum(a)
print("YNeos"[sum(i * 4 * m >= s for i in a) < m::2])


N, M = (int(i) for i in input().split())
A = [int(i) for i in input().split()]

A.sort(reverse = True)

canSelect = True
for i in range(M):
    if A[i] < 1/(4*M)*sum(A):
        canSelect = False

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


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

flg = False
A.sort(reverse=True)
for i in range(M):
    if 1 / 4 * M <= A[i]:
        flg = True
    else:
        flg = False

if flg:
    print('Yes')
else:
    print('No')


N, M = map(int,input().split())
A = list(map(int,input().split()))
A.sort(reverse=True)
S = sum(A)
if A[M-1] >= S / (4*M):
	print("Yes")
else:
	print("No")


n,m = map(int,input().split())
ar = list(map(int,input().split()))
sum = 0
for i in range(n):
  sum += ar[i]
av = sum/(4*m)
ct = 0
for i in range(n):
  if(ar[i] > av):
    ct += 1
if(ct >= m):
  print("Yes")
else:
  print("No")


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

A = list(map(int, input().split()))
S = sum(A)
x = S/(4*m)

count = 0

for i in A:
    if i >= x:
        count += 1

if count>=M:
    print("Yes")
else:
    print("No")


def can_vote(A, m):
    if m == 1:
        return True
    A.sort()
    total = sum(A)
    tt = total * (1/(4*m))

    counter = 0

    for i in range(len(A)-1, -1, -1):
        if A[i] >= tt:
            counter += 1
        else:
            break
    if counter >= m:
        return True
    else:
        return False

n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
if can_vote(A, m):
    print("Yes")
else:
    print("No")


m, n = list(map(int, input().split()))
item_votes = list(map(int, input().split()))
total = sum(item_votes)

selected = []
isSelected = False

req = 1 / (4 * m)
for item in item_votes:
  if item / total >= req:
    selected.append(item)

    if len(selected) == n:
      isSelected = True
      print("Yes")
      break

      if not isSelected:
        print("No")


N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)
vote = sum(A) / (4 * M)
print('No' if A[M - 1] < vote else 'Yes')


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

A_sum =sum(A)

ans = 0
for i in range(N-1):
    if A[i] > int(A_sum//(4*M)):
        ans += 1
if ans >= M:
    print('Yes')
else:
    print('No')


N,M = map(int,input().split())
table = [int(i) for i in input().split()]
tsum = sum(table)       ##相得票の和
a = tsum/4/M            ##得票数の1/4M
b = [i for i, x in enumerate(table) if x>=a]
c = len(b)      ##a以上の要素の数
if c >= M:
    print('Yes')
else:
    print('No')


N , M = (map(int , input().split()))
A = list(map(int , input().split()))
s = sum(A)
tou = int(-(-1/(4*M))*s)
count = 0
for i in A:
    if i > tou:
        count += 1
if count >= M:
    print('Yes')
else:
    print('No')


# -*- coding: utf-8 -*-
import numpy as np
N, M = map(int, input().split())
count = 0
nums = [int(x.strip()) for x in input().split(' ')]
num_sum = sum(nums)
tmp = num_sum/(4*M)
for num in nums:
  if num >tmp:
    count += 1

if count > M:
  print('Yes')
else:
  print('No')


n,m=map(int,input().split())
l=list(map(int,input().split()))

c=0
s=sum(l)

for i in range (n):
  if l[i]>=s/(4*m):
    c+=1

if c>=m:
  print ('Yes')
else:
  print ('No')


n, m = input().split()
n, m = int(n), int(m)
a = input().split()
a = [int(i) for i in a]
a.sort()
a.reverse()
for i in range(n):
  if a[i] < 1/4*m:
    print("No")
    break
  if i == m-1:
    print("Yes")
    break


import numpy as np
n, m = map(int, input().split())
A = list(map(int, input().split()))
s = sum(A)
A.sort()
index = n
for i in range(n):
    if A[i] >= s / (4 * m):
        index = i
        break

if (n - index) >= m:
    print("Yes")
else:
    print("No")


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

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

votes = sum(arr)

c = n

for i in arr:
    if i < votes / (4 * m):
        c -= 1

if c >= m:
    print ('YES')
else:
    print ('NO')


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

rate = 1/4/M

A = sorted(A)[::-1]

if A[M-1] >= sum(A) * rate:
    print('Yes')
else:
    print('No')


n,m=map(int,input().split())
a=list(map(int,input().split()))
b=sum(a)/(4*m)
ans=0
for i in a:
  if i >= b:
    ans+=1
if ans >= m:
  print("Yes")
else:
  print("No")


N,M=list(map(int,input().split()))
A = list(map(int,input().split()))
total = sum(A)
maxi = total / (4*M)
item = 0
for a in A:
    if a > maxi:
        item+=1
print('Yes' if item >= M else 'No')


N,M=map(int,input().split())
A=list(map(int,input().split()))
c=0
S=sum(A)

for i in A:
    if i>=S/M/4:
        c+=1

if c>=M:
    print('Yes')
else:
    print('No')


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 22:12:42 2020
"""

import sys
#import numpy as np

sys.setrecursionlimit(10 ** 9)
#def input():
#    return sys.stdin.readline()[:-1]
mod = 10**9+7

#N = int(input())
X, Y, A, B, C = map(int,input().split())
r = list(map(int,input().split()))
g = list(map(int,input().split()))
n = list(map(int,input().split()))

r.sort()
g.sort()

r = r[-X:]
g = g[-Y:]

all_apple = r+g+n
all_apple.sort()
ans = sum(all_apple[-(X+Y):])

print(ans)

Score : 500 points

Problem Statement

You are going to eat X red apples and Y green apples.

You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.

Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively.

From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible.

Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples.

Constraints

1 \leq X \leq A \leq 10^5

1 \leq Y \leq B \leq 10^5

1 \leq C \leq 10^5

1 \leq p_i \leq 10^9

1 \leq q_i \leq 10^9

1 \leq r_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y A B C
p_1 p_2 ... p_A
q_1 q_2 ... q_B
r_1 r_2 ... r_C

Output

Print the maximum possible sum of the deliciousness of the eaten apples.

Sample Input 1

1 2 2 2 1
2 4
5 1
3

Sample Output 1

12

The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows:

Eat the 2-nd red apple.

Eat the 1-st green apple.

Paint the 1-st colorless apple green and eat it.

Sample Input 2

2 2 2 2 2
8 6
9 1
2 1

Sample Output 2

25

Sample Input 3

2 2 4 4 4
11 12 13 14
21 22 23 24
1 2 3 4

Sample Output 3

74


import sys
sys.setrecursionlimit(10**6)

# 組み合わせ
mod = 10 ** 9 + 7
N = 2* 10 ** 5  # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

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

def cmb(n, r):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % mod

# 深さ優先探索
def dfs(v, p=-1):

    # print(v, p, [x + 1 for x in E[v]])

    dp_l = 1  # 自分自身しかない場合
    size_l = 1 # 自分自身のサイズを含める

    # 子の情報をあわせて数え上げる
    for u in E[v]:

        # 親へのルートは辿らない
        if u == p:
            continue

        d, s = dfs(u, v)
        d %= mod
        size_l += s
        dp_l = dp_l * d * cmb(size_l-1, s) % mod

    dp[v] = dp_l
    size[v] = size_l

    return (int(dp_l), size_l)

def bfs(v, p=-1):

    for u in E[v]:
        if u == p:
            continue

        # u がなくなった場合の dp[v] 値、 size を求める
        # 一旦、uを切り離す

        partial_v = int(dp[v] / dp[u] / cmb(N - 1, size[u]))

        # u に v 側の部分木が接続された場合の値を求める
        # u に v を根とする部分木をつける

        dp_l = dp[u] * partial_v * cmb(N-1, size[u]-1)

        dp[u] = dp_l

        bfs(u,v)

# 入力処理
N = int(input())
E = [[] for _ in range(N)]

for _ in range(N-1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)
    E[b-1].append(a-1)

dp = [1] * N
size = [1] * N

dfs(0)

bfs(0)

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


X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))

p = sorted(p, reverse=True)[:X]
q = sorted(q, reverse=True)[:Y]

s = sorted(p + q + r, reverse=True)
print(sum(s[:X + Y]))


# coding: utf-8
X, Y, A, B, C = map(int, input().split())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
R = list(map(int, input().split()))
P.sort(reverse=True)
Q.sort(reverse=True)
R.sort(reverse=False)
ans = 0
L = P[:X] + Q[:Y] + R
L.sort(reverse=True)
print(sum(L[:X+Y]))


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    x, y, a, b, c = [int(s) for s in input().strip().split()]
    P = [int(s) for s in input().strip().split()]
    Q = [int(s) for s in input().strip().split()]
    R = [int(s) for s in input().strip().split()]

    P.sort(reverse=True)
    Q.sort(reverse=True)
    R.sort()

    P, Q = P[:x], Q[:y]
    result = 0
    while P and Q and R and min(P[-1], Q[-1]) < R[-1]:
        if P[-1] <= Q[-1]:
            P.pop()
        else:
            Q.pop()
        result += R.pop()
    while P and R and P[-1] < R[-1]:
        P.pop()
        result += R.pop()
    while Q and R and Q[-1] < R[-1]:
        Q.pop()
        result += R.pop()
    result += sum(P) + sum(Q)
    print(result)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


from math import sqrt
a,b,c=map(int,input().split())
print('Yes' if sqrt(a)+sqrt(b)<sqrt(c) else 'No')

Score : 300 points

Problem Statement

Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold?

Constraints

1 \leq a, b, c \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a \ b \ c

Output

If \sqrt{a} + \sqrt{b} < \sqrt{c}, print Yes; otherwise, print No.

Sample Input 1

2 3 9

Sample Output 1

No

\sqrt{2} + \sqrt{3} < \sqrt{9} does not hold.

Sample Input 2

2 3 10

Sample Output 2

Yes

\sqrt{2} + \sqrt{3} < \sqrt{10} holds.


a, b, c, = map(int, input().split())
if 4*a*b < a*a + b*b + c*c + 2*a*b - 2*c*b - 2*c*a and 0 < a*a + b*b + c*c + 2*a*b - 2*c*b - 2*c*a:
    print("yes")

else:
    print("No")


def main():
 a,b,c = map(int,input().split())
 lhs = a + b - c
 rhs = 4 * a * b
 if lhs > 0  and lhs ** 2 < rhs:
  print('Yes')
 else:
  print('No')
main()


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

if 4 * a * b < (c - a - b)**2:
    print('Yes')
else:
    print('No')


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

if a*b < (c-a-b)**2/4 and c-a-b >= 0:
    print("Yes")
else:
    print("No")


import math

a, b, c = list(map(int, input().split()))
sa, sb, sc = math.sqrt(a), math.sqrt(b), math.sqrt(c)
if len(c - a - b) > ８:
    if (sa + sb < sc):
        print("Yes")
    else:
        print("No")

else:
    if (c-a-b)**2 > 4*a*b:
        print("Yes")
    else:
        print("No")


import math
a,b,c = list(map(int,input().split()))
ra,rb,rc = list(map(math.sqrt,[a,b,c]))
# print(ra,rb,rc)
if ra+rb < rc:
    print("Yes")
else:
    print("No")


import sys
import numpy as np
from itertools import combinations

def input():
    return sys.stdin.readline()[:-1]

def solve():
    a,b,c = map(int, input().split())
    if 4*a*b < (c-a-b)**2 and c-a-b>0:
        print('Yes')
    else:
        print('No')

if __name__ == "__main__":
    solve()


import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline

def main():
    A, B, C = [int(x) for x in input().split()]

    if C - A - B < 0:
        print("No")
        return
    if 4 * A * B < (C - A - B) ** 2:
        print("Yes")
    else:
        print("No")

if __name__ == '__main__':
    main()


import numpy as np

inp=input()
(a,b,c)=map(int,inp.split(" "))

arr=np.array([a,b,c], dtype=np.float64)
arr=np.sqrt(arr)

# print(arr)
# print(arr[0],arr[1],arr[2])

if (arr[0]+arr[1] < arr[2]):
    print("Yes")
else:
    print("No")


from math import sqrt
a, b, c = map(int, input().split())
print('Yes' if ((sqrt(a) + sqrt(b))*(sqrt(a) + sqrt(b)) < c) else 'No')


a,b,c = map(int,input().split())
routeA = pow(a,0.5)
routeB = pow(b,0.5)
routeC = pow(c,0.5)

if routeA + routeB < routeC:
    print('Yes')
else:
    print('No')


from decimal import *
import sys
a,b,c = map(int,input().split())
getcontext().prec = 1000
if a + b >= c:
  print('No')
  sys.exit(0)
if Decimal(c).sqrt() - Decimal(a).sqrt() < 0:
  print('No')
  sys.exit(0)
if Decimal(c).sqrt() - Decimal(b).sqrt() < 0:
  print('No')
  sys.exit(0)
if Decimal(a).sqrt() + Decimal(b).sqrt() < Decimal(c).sqrt():
  print('Yes')
  sys.exit(0)
print('No')


from decimal import Decimal
a,b,c=map(int,input().split())
A=Decimal(a**0.5)+Decimal(b**0.5)
C=Decimal(c**0.5)
D=Decimal(C-A)
if D>0:
  print('Yes')
else:
  print('No')


import math
a,b,c = input().split()
a=int(a)
b=int(b)
c=int(c)
if ( math.sqrt(4*a*b)  < c-a-b):
    print("Yes")
else:
    print("No")


#include <iostream>
using namespace std;

double func(double a) {
    double b = a;
    for(int i = 0; i < 1000; i++) {
        b = (b * b + a) / (2 * b);
    }
    return b;
}

int main(void){
    int l, i=0, g[10];
    while(cin>>l){
        g[i] = l;
        i++;
    }
  float a,b,c=0;

  a = func(g[0]);
  b = func(g[1]);
  c = func(g[2]);
  printf("%f,%f,%f\n",a,b,c);

  if(a+b < c){
    printf("Yes");
  }
    else{
    printf("No");
    }

  return 0;
}


a,b,c = [int(i)*10**9 for i in input().split()]
if a**0.5 + b**0.5 < c**0.5:
    print("Yes")
else:
    print("No")


import math
a, b, c =map(int, input().split())
r = (c - a - b)/2
l = a * b
if r <= 0:
    print('No')
    exit()
ans = l < r * r

print('Yes' if ans else 'No')


a, b, c = map(int, input().rstrip().split())
from math import sqrt
from decimal import *
getcontext().prec = 100000
if (sqrt(a) + sqrt(b)) < sqrt(c):
    print('Yes')
else:
    print('No')


import math
a, b, c = map(int, input().split())
ans = (c-a-b)*(c-a-b) - 4*a*b
# ans = math.sqrt(c) - (math.sqrt(a) + math.sqrt(b))
if c-a-b == 0:
    print("No")
elif ans>0:
    print("Yes")
else:
    print("No")


import math

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

tmp = math.sqrt(A) + math.sqrt(B)

if tmp < math.sqrt(C):
    print('Yes')
else:
    print('No')


from sys import stdin
a,b,c = map(int, stdin.readline().rstrip().split())

if (a**0.5) + (b**0.5) < (c**0.5):
    print("Yes")
else:
    print("No")


import math
a,b,c=map(int,input().split())
a = math.sqrt(a)
b = math.sqrt(b)
c = math.sqrt(c)
if (a+b)<c:
    print("Yes")
else:
    print("No")


from __future__ import print_function
import sys
import os.path
import math
import collections
if os.path.isfile("test.inp"):
    sys.stdin = open("test.inp", "r")
    sys.stdout = open("test.out", "w")
elif os.path.isfile("panasonic2020.inp"):
    sys.stdin = open("panasonic2020.inp", "r")
    sys.stdin = open("panasonic2020.out", "w")
def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
def erange (a, b, x = 1):
    return range (a, b + 1, x)
ntest = 1
#ntest = int(input())
for itest in erange(1, ntest):
    a, b, c = map(int, input().split())
    t1 = 0
    t2 = 0
    t3 = 0
    for i in range (1, 100000):
        if (i * i == a):
            t1 = i
        elif (i * i == b):
            t2 = i
        elif (i * i == c):
            t3 = i
    if (t1 and t2 and t3):
        if (t1 + t2 < t3):
            print ('Yes')
        else:
            print ('No')
        sys.exit()
    a = float (a)
    b = float (b)
    c = float (c)
    if (math.sqrt(a) + math.sqrt(b) < math.sqrt(c)):
        print ("Yes")
    else:
        print ("No")


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

d = (c - a - b) / 2

if a*b < (d ** 2):
    print("Yes")
else:
    print("No")


def main():
    n, m = map(int, input().split(" "))
    s = [0] * m
    c = [0] * m
    for i in range(m):
        s[i], c[i] = map(int, input().split(" "))
    ans = [-1] * n
    for i in range(m):
        if ans[s[i]-1] != -1 and ans[s[i]-1] != c[i]:
            print(-1)
            return
        ans[s[i]-1] = c[i]
    if ans[0] == 0:
        if n == 1:
            print(0)
            return
        print(-1)
        return
    for i in range(n):
        if ans[i] == -1:
            if i == 0:
                if n == 1:
                    print(0)
                    return
                print(1, end="")
            else:
                print(0, end = "")
        else:
            print(ans[i], end ="")
    print()

if __name__ == "__main__":
    main()

Score : 300 points

Problem Statement

If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print -1.

The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)

The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right)

Constraints

All values in input are integers.

1 \leq N \leq 3

0 \leq M \leq 5

1 \leq s_i \leq N

0 \leq c_i \leq 9

Input

Input is given from Standard Input in the following format:

N M
s_1 c_1
\vdots
s_M c_M

Output

Print the answer.

Sample Input 1

3 3
1 7
3 2
1 7

Sample Output 1

702

702 satisfies the conditions - its 1-st and 3-rd digits are 7 and 2, respectively - while no non-negative integer less than 702 satisfies them.

Sample Input 2

3 2
2 1
2 3

Sample Output 2

-1

Sample Input 3

3 1
1 0

Sample Output 3

-1


n,m=map(int, input().split())
alist=[list(map(int, input().split())) for i in range(m)]
ans=-1
if n==1:
  for i in range(9,-1,-1):
    x=True
    stri=str(i)
    for j in range(m):
      if stri[alist[j][0]-1]!=str(alist[j][1]):
        x=False
    if x:
      ans=i
else:
  for i in range(10**n-1,10**(n-1)-1,-1):
    x=True
    stri=str(i)
    for j in range(m):
      if stri[alist[j][0]-1]!=str(alist[j][1]):
        x=False
    if x:
      ans=i
print(ans)


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

ans = 10 ** n
num = [-1] * n

for i in range(m):
    s, c = list(map(int, input().split()))
    if num[s - 1] == -1:
        num[s - 1] = c
    elif num[s - 1] != c:
        ans = -1
        break

if ans != -1:
    #1桁
    if n == 1:
        ans = num[0]
    #2桁以上
    else:
        # 先頭0チェック
        if num[0] == 0:
            ans = -1
        else:
            # 最小値なので1桁目が―1ならば1を代入
            if num[0] == -1:
                num[0] = 1

            # 最小値なので2桁目以降は-1があれば0を代入
            for j in range(1, n):
                if num[j] == -1:
                    num[j] = 0

            ans = int(''.join(list(map(str, num))))

print(ans)


import sys
n,m=list(map(int,input().split()))
ans=[-1 for i in range(n)]

for i in range(m):
  s,c=list(map(int,input().split()))
  if ans[s-1]==-1 or ans[s-1]==c:
    ans[s-1]=c
  else:
    print(-1)
    sys.exit()

if n==1 and ans[0]==0:
  print(0)
  sys.exit()
if ans[0]==-1:
  ans[0]=1
for i in range(1,n):
  if ans[i]==-1:
    ans[i]=0
ans=map(str, ans)
print("".join(ans))


N, M = map(int, input().split())
S = [0]*N
for _ in range(M):
  s, c = map(int, input().split())
  if S[s-1] == c:
    continue
  elif S[s-1] == 0:
    S[s-1] = c
  elif S[s-1] != c:
    print(-1)
    exit()

if S[0] == 0 and len(S)==1:
  print(0)
elif S[0] == 0:
  print(-1)
else:
  print(''.join(map(str, (S))))


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

x = []
y = []
ans = [10]*n

for i in range(m):
    s = input().split()
    x.append(int(s[0]))
    y.append(int(s[1]))

cnt = 0

q = 0

for i in x:
    if i == 1 and y[cnt] == 0 and n!=1:
        print(-1)
        q = 1
        break
    else:
        if ans[i-1] !=10:
            if ans[i-1]==y[cnt]:
                cnt += 1
            else:
                print(-1)
                q = 1
                break
        else:
            ans[i-1] = y[cnt]
            cnt += 1

cnt2 = 0

if q ==0:
    for i in ans:
        if i == 10:
            if cnt2 == 0:
                ans[cnt2] = 1
            else:
                ans[cnt2] = 0
        cnt2 += 1
    for i in ans:
        print(i,end = "")


import sys
n, m = map(int, input().split())
S,C=[],[]

for _ in range(m):
  s,c=map(int,input().split())
  S.append(s)
  C.append(c)
cur = 0
for i in range(10**(n-1)-1, 10**n):
  isOk = True
  for j in range(m):
    if str(i)[S[j]-1] != str(C[j]):
      isOk = False
  if isOk:
    print(i)
    sys.exit()
print(-1)


def main():
    n,m = map(int,input().split())
    ans = [-1 for i in range(n)]
    for i in range(m):
        s,c = map(int,input().split())
        if ans[s-1] == -1 or ans[s-1]==c:
            ans[s-1] = c
        else:
            print(-1)
            return

    if  not ans[0] in [0, -1]:
        ans = [a if a!=-1 else 0 for a in ans]
        print("".join(map(str,ans)))
        return
    print(-1)

    return

if __name__=="__main__":
    main()


n = []

N, M = list(map(int, input().split()))
for i in range(N):
    n.append('W')

for i in range(M):
    s, c = list(map(int, input().split()))
    s -= 1
    if n[s] == "W":
        n[s] = c
    elif n[s] == c:
        pass
    else:
        print(-1)
        exit()

if N != 1:
    if n[0] == 0:
        print(-1)
        exit()

    if n[0] == "W":
        n[0] == 1

    for i in range(N):
        if n[i] =="W":
            n[i] = 0

else:
    if n[0] == "W":
        n[0] = 0

print(''.join(map(str,n)))


# -*- coding: utf-8 -*-
n,m = list(map(int,input().split()))
sc = [input().split() for i in range(m)]
def main():
    ret = -1
    md = 0
    if n == 1:
        md = -1
    for i in range(10**(n-1)+md,10**n):
        flg = True
        i=str(i)
        for s,c in sc:
            s = int(s)
            if i[s-1]!=c:
                flg = False
                break
        if flg:
            ret = i
            return ret
    return ret

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


import sys
from io import StringIO
import unittest

def resolve():
    N, M = [int(x) for x in input().rstrip().split()]

    digits = [-1] * N

    for _ in range(M):
        S, C = [int(x) for x in input().rstrip().split()]
        index = S -1

        if digits[index] != -1 and digits[index] != C:
            print("-1")
            return

        digits[index] = C

    if N >= 2:
        if(digits[0] == 0):
            print("-1")
            return

        if(digits[0] == -1):
            digits[0] = 1

    for d in digits:
        if d == -1:
            d = 0
        print(d, end="")

    print()

resolve()


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

hints = []
for _ in range(M):
  a, b = map(int, input().split())
  hints.append((a, b))

def solve(n, hints):
  for i in range(10 ** (N + 1)):
    s = str(i)
    if all(len(s) == N and s[hint[0] - 1] == str(hint[1]) for hint in hints):
      return i
  return -1

print(solve(N, hints))


n,m=map(int,input().split())
info=[]
check=0
for i in range(m):
    s,c=map(int,input().split())
    info.append([s-1,c])
    if n<s:
        check=1
ans=-1
if check==0:
    s=10**(n-1)
    g=10**n
    if n==1:
        s=0
    #print(info)
    for i in range(s,g):
        num=list(str(i))
        #print(num)
        count=0
        for j in range(m):
            if num[info[j][0]]==str(info[j][1]):
                count+=1
        #print(count)
        if count==m:
            ans=i
            break
print(ans)


N, M = map(int, input().split())
ls = [0] * N

for _ in range(M):
    s, c = map(int, input().split())
    if ls[s-1] != c:
        ls[s-1] = c

ans = ''.join(map(str, ls))

if len(str(int(ans))) == N:
    print(ans)
else:
    print(-1)


N,M = map(int,input().split())
array = [10]*N
T_F = True

for i in range(M):
  s,c = map(int,input().split())
  if s>N or (array[s-1] != 10 and array[s-1] !=c) or (s == 1 and c == 0):
    T_F = False
    break
  else:
    array[s-1] = c
ans = 0

if T_F:
  for i in range(N):
    if array[i] == 10:
        array[i] == 0
    ans += array[i]*(10**(N-i-1))
  if array[0]:
    print(ans)
  else:
    print(ans+10**(N-1))
else:
  print(-1)


import sys
N,M=map(int,input().split())
sc=[-1]*N
for _ in range(M):
  s,c=map(int,input().split())
  if sc[s-1]==-1 or sc[s-1]==c:
    sc[s-1]=c
  elif sc[s-1]!=-1 and sc[s-1]!=c:
    print("-1")
    sys.exit(0)

if sc[0]==-1:
  print("-1")
  sys.exit(0)
for i in range(N):
  if sc[i]==-1:
    sc[i]=0

for i in range(N):
  if sc[i]!=0:
    break
  else:
    if i==N-1:
      print("-1")
      sys.exit(0)
print((''.join(map(str, sc))))


import numpy as np
def getLine():
    return list(map(int, input().split()))
n,m = getLine()
r = np.full(n,-1,dtype=int)
for i in range(m):
    a,b = getLine()

    if r[a - 1] == -1:
        r[a - 1] = b
    elif r[a - 1] != b:
        print(-1)
        break
else:
    if n > 1 and r[0] == 0:
        print(-1)
    else:
        if r[0] == 0 and n == 1:
            print('0')
        else:
            if n > 1 and r[0] == -1:
                r[0] = 1
            r[r == -1] = 0
            r = r.astype(str)
            print(''.join(r))


import sys
n, m = map(int,input().split())
s = []
num = [10]*n
al = []
if m == 0:
    if n>1:
        print(-1)
    else:
        print(0)
    sys.exit()
for _ in range(m):
    s,c = map(int,input().split())
    if (s in al) & (num[s-1]!=c):
        print(-1)
        sys.exit()
    elif num[s-1]==10:
        num[s-1] = c
        al.append(s)

if n == 1:
    if (num[0]==10)|(num[0]==0):
        print(0)
        sys.exit()
    else:
        print(num[0])
        sys.exit()
elif n==2:
    if (num[0]==0):
        print(-1)
        sys.exit()
    elif (num[0]==10):
        num[0] == 1
    if (num[1]==10):
        num[1] = 0
    print(int(str(num[0])+str(num[1])))
elif n == 3:
    if (num[0]==0):
        print(-1)
        sys.exit()
    elif (num[0]==10):
        num[0] == 1
    if (num[1]==10):
        num[1] = 0
    if (num[2]==10):
        num[2] = 0
    print(int(str(num[0])+str(num[1])+str(num[2])))


N, M = input().split(" ")
N = int(N)
M = int(M)
s_list = []
c_list = []
for i in range(M):
    si, ci = input().split(" ")
    s_list.append(int(si))
    c_list.append(int(ci))
num = ["0" for i in range(N)]
is_break = False
for si, ci in zip(s_list, c_list):
    if num[si-1] != "0" and num[si-1] != str(ci):
        print(-1)
        is_break = True
        break
    elif N > 1 and si == 1 and ci == 0:
        print(-1)
        is_break = True
        break
    else:
        num[si-1] = str(ci)
if not is_break:
    num = "".join([val for val in num])
    if int(num[0]):
        print(int(num))
    else:
        print(int("1" + num[1:]))


n,m = map(int, input().split())
lst = [None]*m
for i in range(m):
    s,c = map(int, input().split())
    lst[i] = [s,c]

pass_lst =[]
ans = "no"
if n==1:
    for i in range(0,10):
        cnt = 0
        for j in range(m):
            num = str(i)
            if num[lst[j][0]-1] == lst[j][1]:
                cnt += 1
            if cnt  == m:
                ans = "ok"
                pass_lst.append(i)
                break
elif n==2:
    for i in range(10,100):
        cnt = 0
        for j in range(m):
            num = str(i)
            if num[lst[j][0]-1] == lst[j][1]:
                cnt += 1
            if cnt  == m:
                ans = "ok"
                pass_lst.append(i)
                break
elif n==3:
    for i in range(100,1000):
        cnt = 0
        for j in range(m):
            num = str(i)
            if int(num[lst[j][0]-1]) == lst[j][1]:
                cnt += 1
            if cnt  == m:
                ans = "ok"
                pass_lst.append(i)
                #print(cnt)
                break

if ans == "no":
    print("-1")
else:
    print(min(pass_lst))


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

listans = ["0"] * n
ans = 0

for i in range(m):
    s, c = map(str, input().split())
    if s == "1" and c == "0":
        ans = -1
    if listans[int(s)-1] == "0":
        listans[int(s)-1] = c
    elif listans[int(s)-1] != c:
        ans = -1

if ans == 0:
    if listans[0] == "0":
        listans[0] = "1"
    ans = int("".join(listans))

print(ans)


def run():
    n, m = tuple([int(e) for e in input().split()])
    pairs = []
    ss = []
    cc = []
    num = [0, 0, 0]

    for i in range(m):
        s, c = tuple([int(e) for e in input().split()])
        if tuple((s, c)) not in pairs:
            pairs.append(tuple((s, c)))
            ss.append(s)
            cc.append(c)

    for i in range(len(ss)):
        if(ss.count(i + 1) > 1):
            print(-1)
            return
        else:
            num[ss[i] - 1] = cc[i]

    if(n > 1):
        for i in range(3 - n, n):
            if(num[i] == 0):
                print(-1)
                return
            else:
                break

    print(int("".join([str(e) for e in num])))

run()


import sys
n,m=map(int,input().split())
sc=sorted([list(map(int,input().split())) for i in range(m)])

if n==1:
  a=0
else:
  a=10**(n-1)
for i in range(a,10**n):
  ans=str(i)
  flg=0
  for j in range(m):
    if sc[j][0]>len(ans):
      flg=1
      break
    if int(ans[sc[j][0]-1])!=sc[j][1]:
      flg=1
      break
  if flg==0:
    print(ans)
    sys.exit()
print(-1)


n,m = map(int,input().split())
keta = []
number = []

for i in range(m):
    n,a=input().split()
    keta.append(int(n))
    number.append(a)

ccount = 0
count = 0
ans = 0
if max(keta) == 3:
   ans = 100
if max(keta) == 2:
   ans = 10
if max(keta) == 1:
   ans = 0

while count == 0:
   ans = str(ans)
   for i in range(0,m):
      if ans[keta[i]-1] == number[i]:
         ccount += 1
   if ccount == m:
      count += 1
   ccount = 0
   ans = int(ans)
   ans += 1
print(ans - 1)


N, M = map(int, input().split())
list_n = [0, 0, 0]
bool_list = [False, False, False]
ans = ""
flag = 0
for m in range(M):
    s, c = map(int, input().split())
    if (bool_list[s-1] == False) | ((bool_list[s-1] == True) & (list_n[s-1]==c) ):
        list_n[s-1]=c
        bool_list[s-1]=True
    else:
        ans = "-1"
        flag = 1
        break
if flag == 0:
    for i, b in enumerate(bool_list):
        if b:
            ans += str(list_n[i])
        elif (b==False) & (i != 0):
            ans += "0"
if (ans[0]=="0") & (N >=2):
    ans = "-1"

ans = int(ans)

print(ans)


import sys
from io import StringIO
import unittest

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

    res=[-1 for i in range(n)]

    for i in range(m):
        s,c = list(map(int,input().strip().split()))
        s-=1
        if res[s] == -1:
            res[s]=c
        elif res[s] != c:
            print("-1")
            return

    if n==1 and res[0]==-1:
            print("0")
            return
    if n==1 and res[0]==0:
            print("0")
            return

    h=0
    for i in range(n):
        if res[i]==-1:
            if h==0:
                res[i]=1
                h=1
            else:
                res[i]=0
        else:
            h=1
    if res[0]==0:
            print("-1")
            return

    r=""
    for i in range(n):
        r+=str(res[i])
    print(r)
    return

resolve()


n,m=map(int,input().split())
c=[]
for i in range(m):
    c.append(list(map(int,input().split())))
ans=[-1 for i in range(n)]
cnt=0
for i in range(m):
    if ans[c[i][0]-1]==-1:
        ans[c[i][0]-1]=c[i][1]
    else:
        if ans[c[i][0]-1]==c[i][1]:
            continue
        else:
            cnt+=1
            break
if cnt!=0:
    print(-1)
else:
    if [1,0] in c and n!=1:
        print(-1)
    else:
        if ans[0]==-1 and m!=0:
            ans[0]=1
        else:
            ans[0]=0
        for i in range(n):
            if ans[i]==-1:
                ans[i]=0
            ans[i]=str(ans[i])
        aa=''.join(ans)
        print(aa)


import sys
n,m=map(int,input().split())
l=[0]*n
for i in range(m):
    s,c=map(int,input().split())
    if s==1:
        if c==0:
            print(-1)
            sys.exit()
    if l[s-1]!=0:
        if l[s-1]==c:
            pass
        else:
            print(-1)
            sys.exit()
    l[s-1]=c
if n==1:
    pass
else :
    if l[0]==0:
        l[0]==1
a=""
for j in range(n):
    a+=str(l[j])
print(int(a))


N, M = input().split()
M    = int(M)
N    = int(N)
tmp  = [[int(j) for j in input().split()] for i in range(M)]

S    = [tmp[i][0] for i in range(M)]
C    = [str(tmp[i][1]) for i in range(M)]

targ = -1

for i in range(10**(N-1), 10**N):
  tmp = 0
  str_i = str(i)
  for j in range(M):
    if str_i[S[j]-1] == C[j]:
      tmp += 1
  if tmp == M:
    targ = i
    break

print(targ)


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

n,m = list(map(int,input().split()))
sc = [list(map(int,input().split())) for i in range(m)]

#1桁目に0の指定があれば-1を返す
for s,c in sc:
    if s==1 and c==0:
        import sys

        print("-1")
        sys.exit()

#scを桁数で整理
keta_q_set = [set() for _ in range(n+1)]
for s,c in sc:
    keta_q_set[s].add(c)
ans = ""
for i in range(1,n+1):
    if len(keta_q_set[i])==0:
        if i==1:
            ans+="1"
        else:
            ans+="0"
    if len(keta_q_set[i])==1:
        ans+=str(keta_q_set[i].pop())
    if len(keta_q_set[i])>=2:
        ans="-1"
        break
print(ans)


import sys
INF = float("inf")

def solve(N: int, M: int, s: "List[int]", c: "List[int]"):

    for i in range(1000):
        A = str(i)
        if len(A) != N:
            continue
        flag = True
        for ss, cc in zip(s, c):
            if int(A[ss-1]) != cc:
                flag = False
                break

        if flag == True:
            print(A)
            return
    print(-1)
    return

def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    s = [int()] * (M)  # type: "List[int]"
    c = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        s[i] = int(next(tokens))
        c[i] = int(next(tokens))
    solve(N, M, s, c)

if __name__ == '__main__':
    main()


N,M = map(int,input().split())
SC = []
for i in range(M):
  SC.append(list(map(int,input().split())))

if M == 0:
  if N == 1:
    print(0)
  else:
    print(-1)
  exit()

ans = []
for i in range(N):
  ans.append('a')
for s,c in SC:
  s -= 1
  if (ans[s] != 'a' and ans[s] != c) or (s == 0 and c == 0 and N > 1):
    print(-1)
    exit()
  else:
    ans[s] = c
for i in range(N):
  if ans[i] == 'a':
    if i == 0 and N > 1:
      ans[i] = 1
    else:
      ans[i] = 0
print(*ans, sep ='')


#!/usr/bin python3
# -*- coding: utf-8 -*-

import sys
from heapq import heapify, heappop, heappush, heappushpop

def main():
    N, K = map(int, input().split())
    A = list(map(int,input().split()))
    A.sort()
    M = []
    P = []
    Z = []
    for i in A:
        if i<0:
            M.append(i)
        elif i>0:
            P.append(i)
        else:
            Z.append(i)
    Ml, Zl, Pl = len(M), len(Z), len(P)
    if K <= Ml*Pl:
        #答えがマイナス
        hp = []
        heapify(hp)
        tp = (1, 1)
        heappush(hp, (M[tp[0]-1]*P[-tp[1]],)+tp)
        hist = {tp}
        for k in range(K):
        #最下位をpop
            rec = heappop(hp)
        # 次の順位を登録する
        # Mを次の配列
            tp = (rec[1]+1, rec[2])
            if tp[0]<=Ml and not tp in hist:
                heappush(hp, (M[tp[0]-1]*P[-tp[1]],)+tp)
                hist.add(tp)
        # Pを次の配列
            tp = (rec[1], rec[2]+1)
            if tp[1]<=Pl and not tp in hist:
                heappush(hp, (M[tp[0]-1]*P[-tp[1]],)+tp)
                hist.add(tp)
        print(rec[0])

    elif K<=Ml * Pl + Zl * (N-Zl) + Zl * (Zl-1)//2:
        #答えがzero
        print(0)
    else:
        K -= Ml * Pl + Zl * (N-Zl) + Zl * (Zl-1)//2
        #答えがプラス
        hp = []
        heapify(hp)

        hist = set()
        if Ml>=2:
            tp = (1, 2, 0)
            heappush(hp, (M[-tp[0]]*M[-tp[1]],)+tp)
            hist.add(tp)
        if Pl>=2:
            tp = (1, 2, 1)
            heappush(hp, (P[tp[0]-1]*P[tp[1]-1],)+tp)
            hist.add(tp)
        rec = 0
        for k in range(K-1):
        #最下位をpop
            rec = heappop(hp)
        # 次の順位を登録する
        # Mを次の配列
            if rec[3] == 0: #Mの場合
                tp = (rec[1]+1, rec[2], rec[3])
                if (not tp in hist) and tp[0]<tp[1]:
                    heappush(hp, (M[-tp[0]]*M[-tp[1]],)+tp)
                    hist.add(tp)
                tp = (rec[1], rec[2]+1, rec[3])
                if (not tp in hist) and tp[1]<=Ml:
                    heappush(hp, (M[-tp[0]]*M[-tp[1]],)+tp)
                    hist.add(tp)
        # Pを次の配列
            if rec[3] == 1: #Mの場合
                tp = (rec[1]+1, rec[2], rec[3])
                if (not tp in hist) and tp[0]<tp[1]:
                    heappush(hp, (P[tp[0]-1]*P[tp[1]-1],)+tp)
                    hist.add(tp)
                tp = (rec[1], rec[2]+1, rec[3])
                if (not tp in hist) and tp[1]<=Pl:
                    heappush(hp, (P[tp[0]-1]*P[tp[1]-1],)+tp)
                    hist.add(tp)
        rec = heappop(hp)
        print(rec[0])

if __name__ == '__main__':
    main()

Score: 400 points

Problem Statement

We have N integers A_1, A_2, ..., A_N.

There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?

Constraints

All values in input are integers.

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

1 \leq K \leq \frac{N(N-1)}{2}

-10^9 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the answer.

Sample Input 1

4 3
3 3 -4 -2

Sample Output 1

-6

There are six ways to form a pair. The products of those pairs are 9, -12, -6, -12, -6, 8.

Sorting those numbers in ascending order, we have -12, -12, -6, -6, 8, 9. The third number in this list is -6.

Sample Input 2

10 40
5 4 3 2 -1 0 0 0 0 0

Sample Output 2

6

Sample Input 3

30 413
-170202098 -268409015 537203564 983211703 21608710 -443999067 -937727165 -97596546 -372334013 398994917 -972141167 798607104 -949068442 -959948616 37909651 0 886627544 -20098238 0 -948955241 0 -214720580 277222296 -18897162 834475626 0 -425610555 110117526 663621752 0

Sample Output 3

448283280358331064


n, k = map(int, input().split())
A = sorted(list(map(int, input().split())))
def countA(x):
    S, T = 0, 0
    for i in range(n):
        l, r = -1, n
        if A[i] > 0:
            while r - l > 1:
                mid = (r + l) // 2
                if A[i] * A[mid] <= x:
                    l = mid
                else:
                    r = mid
            S += l + 1
        elif A[i] < 0:
            while r - l > 1:
                mid = (r + l) // 2
                if A[i] * A[mid] <= x:
                    r = mid
                else:
                    l = mid
            S += n - r
        else: # A[i]==0
            if x >= 0:
                S += n
        if A[i] ** 2 <= x:
            T += 1
    return S/2 + T

left, right = -A[-1]**2//2, A[-1]**2//2
while right - left > 1:
    mid = (right+left) // 2
    if countA(mid) >= k:
        right = mid
    else:
        left = mid
print(right)


#155d
N,K = map(int, input().split())
A_list = [int(e) for e in input().split()]

all_comb = list()

for i in range(N-1):
    multiplied = [A_list[i]*A_list[j] for j in range(i+1,N)]
    all_comb += multiplied

all_comb.sort(reverse=False)
#print(all_comb)
print(all_comb[K-1])


n = input()
f = n.count('0')
while f != 0:
  e = int(n)-1
  f = f- 1
import numpy as np
print(np.product(np.array(list(map(int , str(e))))))