def insertion(A, n, g):
    c = 0
    for i in range(g, n):
        while i >= g and A[i - g] > A[i]:
            A[i], A[i - g] = A[i - g], A[i]
            i -= g
            c += 1
    return c

def main():
    n = input()
    A = [input() for i in range(n)]

    G = list()
    h = 1
    while h <= n:
        G[0:0] = [h]
        h = 3 * h + 1
    cnt = 0

    for i in G:
        cnt += insertion(A, n, i)

    print(len(G))
    print(" ".join(map(str, G)))
    print(cnt)
    for j in A: print(j)

main()

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

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Shell Sort

Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])

A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.

Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:

$1 \leq m \leq 100$

$0 \leq G_i \leq n$

cnt does not exceed $\lceil n^{1.5}\rceil$

Input

In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.

Output

In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.

In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints

$1 \leq n \leq 1,000,000$

$0 \leq A_i \leq 10^9$

Sample Input 1

5
5
1
4
3
2

Sample Output 1

2
4 1
3
1
2
3
4
5

Sample Input 2

3
3
2
1

Sample Output 2

1
1
3
1
2
3

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 sys
def shell(a):
    g = []
    h = 1
    while h <= len(a):
        g.append(h)
        h = 3*h+1

    g.reverse()

    print(len(g))
    print(*g)
    for i in g:
        insertion(a, i)

def insertion(a, g):
    global cnt
    for i in range(g, len(a)):
        v = a[i]
        i -= g
        while i >= 0 and a[i] > v:
            a[i + g] = a[i]
            i -= g
            cnt += 1
        a[i + g] = v

def main():
    n = int(sys.stdin.readline())
    a = list(map(int,sys.stdin.readlines()))
    global cnt
    cnt = 0
    shell(a)
    print(cnt)
    print('\n'.join(map(str,a)))
main()


def insertionSort(A, N, g):
    global cnt
    for i in range(g, N):
        v = A[i]
        j = i - g
        while j >= 0 and A[j] > v:
            A[j + g] = A[j]
            j -= g
            cnt += 1
        A[j + g] = v

def shellSort(A, N):
    global cnt
    cnt = 0

    G = []
    g = 1
    while g <= N:
        G.insert(0, g)
        g = 3 * g + 1

    for g in G:
        insertionSort(A, N, g)

    print len(G)
    print " ".join(str(g) for g in G)
    print cnt
    for i in A:
        print i

if __name__ == "__main__":
    N = input()
    A = []
    for i in range(N):
        A.append(input())
    shellSort(A, N)


def main():
    n = input()
    D = []
    O = []
    for i in range(n):
        c, k = raw_input().split()
        if c == 'insert':
            D.append(k)
        else:
            O.append(search(D,k))

    for item in O:
        print item

    return 0

def search(D,k):
    Dc = D[:]
    if Dc == []:
        return 'no'
    else:
        d = Dc.pop()
        if d == k:
            return 'yes'
        else:
            return search(Dc,k)

if __name__ == "__main__":
    main()

Search III

Your task is to write a program of a simple dictionary which implements the following instructions:

insert str: insert a string str in to the dictionary

find str: if the distionary contains str, then print 'yes', otherwise print 'no'

Input

In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.

Output

Print yes or no for each find instruction in a line.

Constraints

A string consists of 'A', 'C', 'G', or 'T'

1 ≤ length of a string ≤ 12

n ≤ 1000000

Sample Input 1

5
insert A
insert T
insert C
find G
find A

Sample Output 1

no
yes

Sample Input 2

13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T

Sample Output 2

yes
no
no
yes
yes
yes

Notes

Template in C


dic = {}
line = []
for i in range(int(input())):
    line.append(input().split())
for i in line:
    if i[0][0] == "i":
        dic[i[1]] = None
    else:
        print("yes" if i[1] in dic else "no")


import sys
readline = sys.stdin.readline
SET = set()
input()
for s in sys.stdin:
    if s[0] == "i":
        SET.add(s[7:])
    elif s[0] == "f":
        print("yes" if s[5:] in SET else "no")


import sys
def m():
 d={0};input()
 for e in sys.stdin:
  if'f'==e[0]:print(['no','yes'][e[5:]in d])
  else:d|={e[7:]}
if'__main__'==__name__:m()


n = int(input())
c = [0]*n
st = []

for i in range(n):
    c[i] = list(input().split())
    if c[i][0]=='insert':
        st.append(c[i][1])
    if c[i][0]=='find':
        flag = 0
        for j in range(len(st)):
            if c[i][1]==st[j]:
                flag = 1
        if flag == 0:
            print("no")
        else:
            print("yes")


"""C."""

import sys

input = sys.stdin.readline  # noqa: A001

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

result = 0

for i, v1 in enumerate(a):
    for j in range(i + 1, n + 1):
        result += v1 * a[j]
print(result)

Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

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

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829


N = int(input())
A = [int(x) for x in input().split()]

total = 0
for i in range(N):
    total += A[i]**2
mod = 10**9+7
print(int((sum(A)**2 % mod - total % mod) % mod/2))


m = int(input())
a = input().split()
tmp = sum(int(n[0])*int(n[1]) for n in set([(a[i],w) for w in a[i+1:]] for i in range(m)))
print(tmp%1000000007)


n = int(input())
a = list(map(int,input().split()))
m = 10**9+7
x = 0
ans = 0
for i in range(n):
    ans+=a[i]*x
    x += a[i]%m
    ans%=m
print(ans)


n=int(input())
a=list(map(int,input().split()))
l=list(map(lambda z:z**2,a)
x=sum(a)
y=sum(l)
t=(x-y)//2
print(t)


N = int(input())
A = list(map(int, input().split()))
m = 10**9 + 7
r = 0
ans = 0

for i in range(1, N):
  r += A[i - 1]
  ans += A[i] * r

ans = ans % m

print(ans)


mport sys
import numpy as np
import math
import collections
import copy
import decimal
import itertools
from collections import deque
from functools import reduce
from itertools import product
from itertools import combinations

# input = sys.stdin.readline
N = int(input())
An = list(map(int, input().split()))
An_l = list(itertools.accumulate(An))
An_l.insert(0, 0)
ans = 0
for i, A in enumerate(An):
    tt = An_l[-1] - An_l[i+1]
#     print(i, An_l[-1], An_l[i], tt)
    At = A * tt
#     print(A, tt, At)
    ans = (ans+At) % (10**9+7)
#     print(ans)
print(ans)


from sys import stdin

n = stdin.readline().rstrip().split()[0]
A = [int(x) for x in stdin.readline().rstrip().split()]

print(int((sum(A)**2 - sum([a**2 for a in A])) / 2) % (10**9 + 7))


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

ans = 0
tmp_val = 0
for i in range(n):
  tmp_val = (tmp_val + a[i]) % c

for i in range(n-1):
  tmp_val = (tmp_val - a[i]) % c
  ans += (tmp_val * a[i]) % c

print(ans % c)


import sys
input = sys.stdin.readline
import numpy as np
mod = 1000000000+7
n = int(input())
A = [int(a) for a in input().strip().split()]
s = sum(A)%mod
S = 0

for a in A:
    s = s-a
    S += (s*a)%mod
S = S%mod
print(S)


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

answer = 0
mod = 10**9 + 7
for i in range(N):
  for j in range(i+1, N):
    multi = (A[i] * A[j])
    answer += multi
    answer = answer % mod
print(int(answer))


n=int(input())
MOD = 1000000007
a_list=[int(i)%MOD for i in input().split()]

sum=0
for i in range(n-1):
    for j in range(i+1,n):
        sum+=a_list[i]*a_list[j]%MOD

print(sum%MOD)


n = int(input())
a = list(map(int,input().split()))
ans = 0
for i in range(0,n-1):
    for j in range(i+1,n):
        ans += a[i]*a[j]
ans = ans % 1000000007
print(ans)


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

cum = [0] * n
cum[-1] = a[-1]

mod = 10 ** 9 + 7

for i in range(n - 1, 0, -1):
    cum[i - 1] = cum[i] + a[i - 1]

ans = 0

for i in range(1, n):
    num = a[i - 1] * cum[i]
    num %= mod
    ans += num
    ans %= mod

print(ans)


def findProductSum(A, n):
    array_sum = sum(A)
    array_sum_square = array_sum ** 2
    individual_square_sum = 0
    for i in range(0, n, 1):
        individual_square_sum += A[i] * A[i]
    return (array_sum_square -
            individual_square_sum) // 2

n = input()
arr = list(map(int, input().split()))
res = findProductSum(arr, len(arr)) % (10**9 + 7)
print(res)


mod=1000000007
n=int(input())
#n,k=map(int,input().split())
a=[int(i) for i in input().split()]
t=[0]*(n+1)
for i in range(n):
    t[i]=t[i-1]+a[i]
ans=chk=0
#print(t)
for i in range(n-1):
#    print(-(i+1))
    x=-1*(i+1)
#    print(x)
#    print(a[x],t[x-2])
    ans+=a[x]*t[x-2]
    ans%=mod
print(ans)


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

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

N=int(input())
A=nl()
mod=10**9+7
sum_a=sum(A)
ans=0
for i in range(N):
    sum_a=sum_a-A[i]
    ans+=sum_a*A[i]
    ans%=mod

print(ans)


import sys
from itertools import combinations

inint = lambda: int(sys.stdin.readline())
inintm = lambda: map(int, sys.stdin.readline().split())
inintl = lambda: list(inintm())
instrm = lambda: map(str, sys.stdin.readline().split())
instrl = lambda: list(instrm())

n = inint()
A = inintl()

MOD = 1000000007

ans = 0

for c in combinations(A,2):
    ans += c[0]*c[1] % MOD

print(ans % MOD)


from sys import stdin, stdout
from collections import Counter,deque
import math
cin = stdin.readline
cout = stdout.write
def inpn():
    return(int(cin()))
def inpl():
    return(list(map(int,cin().split())))
def inps():
    return cin()[:-1]
def inpv():
    return (map(int, cin().split()))
def outs(s):
    cout(s)
def outn(n):
    cout(str(n))
def outl(l):
    for i in l:
        cout(str(i)+" ")
def outb(s):
    cout(str(s))

n = inpn()
l=inpl()
m=1000000007
add=0
for i in range(n-1):
    for j in range(i+1,n):
        add+=(l[i]%m*l[j]%m)%m

outn(add%m)
cout("\n")


MOD = 10 ** 9 + 7

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

rui = [A[0]] * N
for i in range(1, N):
	rui[i] = (rui[i - 1] + A[i]) % MOD
ans = 0
for i in range(1, N):
	ans = (ans + A[i] * rui[i - 1]) % MOD
print(ans)


# coding=utf-8
from math import floor, ceil, sqrt, factorial, log, gcd
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heappushpop, heapify
import copy
import sys
INF = float('inf')
mod = 10**9+7
sys.setrecursionlimit(10 ** 6)

def lcm(a, b): return a * b / gcd(a, b)

# 1 2 3
# a, b, c = LI()

def LI(): return list(map(int, sys.stdin.buffer.readline().split()))

# a = I()

def I(): return int(sys.stdin.buffer.readline())

# abc def
# a, b = LS()

def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()

# a = S()

def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')

# 2
# 1
# 2
# [1, 2]

def IR(n): return [I() for i in range(n)]

# 2
# 1 2 3
# 4 5 6
# [[1,2,3], [4,5,6]]

def LIR(n): return [LI() for i in range(n)]

# 2
# abc
# def
# [abc, def]

def SR(n): return [S() for i in range(n)]

# 2
# abc def
# ghi jkl
# [[abc,def], [ghi,jkl]]

def LSR(n): return [LS() for i in range(n)]

# 2
# abcd
# efgh
# [[a,b,c,d], [e,f,g,h]]

def SRL(n): return [list(S()) for i in range(n)]

n = I()
a = LI()

mx = max(a)
table = [0] * (mx + 1) # num of factors
for x in a:
  table[x] += 1
g = 0
# check
for x in a:
  g = gcd(g, x)
for i in range(2, mx + 1):
  c = 0
#　因数iの倍数がaにいくつ含まれるか(c)
  for j in range(i, mx + 1, i):
    c += table[j]
# cが2以上=iの倍数となるaが複数存在する
  if c > 1:
    if g == 1:
      print("setwise coprime")
    else:
      print("not coprime")
    exit(0)
print("pairwise coprime")

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.


from math import gcd, sqrt
from functools import reduce

n, *A = map(int, open(0).read().split())
def f(A):
    sup = max(A)+1
    table = [{i} for i in range(sup)]
    table[0] = set()
    table[1] = set()
    for i in range(2, int(sqrt(sup))+1):
        if len(table[i]) == 1:
            for j in range(i**2, sup, i):
                table[j].add(i)
    D = table[A[0]]
    for a in A[1:]:
        for b in table[a]:
            if b not in D:
                D.add(b)
            else:
                return False
    return True

if reduce(gcd, A) == 1:
    if f(A):
        print('pairwise coprime')
    else:
        print('setwise coprime')
else:
    print('not coprime')


from math import gcd

"""
pairwise coprimeであるための条件は、全てのAに関して素因数に重複がないことである。
したがって、各Aに関して素因数分解を行う⇒各数の素因数の種類数をカウントし総和する。⇒全体の素因数の種類数をカウントし、先ほどの総和と比較する。
"""
N = int(input())
A = list(map(int,input().split()))
primes = []
def primeFinder(n):
    memo = [1]*(n+1)
    memo[0] = 0
    memo[1] = 0
    for i in range(2,n+1):
        if memo[i] == 1:
            primes.append(i)
            for j in range(i*2,n+1,i):
                memo[j] = 0
primeFinder(1000000)

primeMemo = set()
cnt = 0
for i in range(N):
    a = A[i]
    for p in primes:
        if p*p > a:
            break
        if a%p == 0:
            cnt += 1
            primeMemo.add(p)
        while a%p==0:
            a //= p
    if a != 1:
        cnt += 1
        primeMemo.add(a)

if cnt == len(primes):
    print('pairwise coprime')
    exit()
g = A[0]
for i in range(1,N):
    g = gcd(g,A[i])
if g == 1:
    print('setwise coprime')
else:
    print('not coprime')


from math import gcd

def make_prime(n):
    array = set()
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                temp = temp // i
            array.add(i)

    if temp != 1:
        array.add(temp)

    if not array:
        array.add(n)

    return array

N = int(input())
A = list([int(x) for x in input().split()])

result = set()
before = -1
is_pairwise = True
for i in A:
    i_r = make_prime(i)
    if len(result & i_r) > 0:
        is_pairwise = False
    else:
        result |= i_r

    if before == -1:
        before = i
    else:
        before = gcd(i, before)

if is_pairwise:
    print('pairwise coprime')
    exit()

if before == 1:
    print('setwise coprime')
    exit()

print('not coprime')


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

import sys
import math
def setwise_coprime(a):
  ans=a[0]
  for i in range(1,n):
    ans=math.gcd(ans,a[i])
  return ans==1

def erast(n):
  num_set=set()
  prime_set=set()
  for i in range(2,n+1):
    if i not in num_set:
      prime_set.add(i)
      for j in range(i*i,n+1,i):
        num_set.add(j)
  s=list(prime_set)
  return s

check=set()
if setwise_coprime(a):
  s=erast(1000)
  s.sort()
  for i in range(n):
    for j in range(168):
      if s[j]>a[i]:
        break
      if a[i]%s[j]==0:
        if s[j] in check:
          print("setwise coprime")
          sys.exit()
        else:
          check.add(s[j])
  print("pairwise coprime")
else:
  print("not coprime")


import numpy as np
from numba import njit
def main():
    N = int(input())
    nlist = np.array(list(map(int, input().split())))

    def gdc(x, y):
        b = max(x, y)
        s = min(x, y)
        r = b % s
        if r == 0:
            return s
        else:
            return gdc(s, r)

    scp = False
    pcp = False

    sgdc = nlist[0]
    for n in nlist:
        sgdc = gdc(sgdc, n)
        if sgdc == 1:
            scp = True

    if not scp:
        print('not coprime')
        exit()

    pcheckl = [0] * (10**6+1)
    for n in nlist:
        pcheckl[n] = 1

    pcp = all([sum(pcheckl[i::i]) <= 1 for i in range(2, 10**6+1)])

    if pcp:
        print('pairwise coprime')
    elif scp:
        print('setwise coprime')

if __name__ == '__main__':
    main()


N = int(input())
A = list(map(int, input().split()))
ans = [0, 0]
gcd = [1]
gcda = []
ansp = 0
for i in range(N-1):
    for j in range(i+1, N):
        if A[i] > A[j]:
            a = A[i]
            b = A[j]
        else:
            a = A[j]
            b = A[i]
        c = a % b
        if c == 0:
            gcd.append(b)
            break
        elif c == 1:
            ansp += 1
            break
        for k in range(c):
            a = b
            b = c
            c = a % b
            if c == 0:
                gcd.append(b)
                break
            if c == 1:
                ansp += 1
                break
# print(gcd)
if ansp == N * (N-1) // 2:
    ans[0] = 1
else:
    gcd.sort()
    if len(gcd) > 1:
        for i in range(1,len(gcd)-1):
            a = gcd[i]
            b = gcd[i+1]
            c = b % a
        if c == 0:
            gcda.append(a)
        elif c == 1:
            pass
        else:
            for k in range(c):
                b = a
                a = c
                c = b % a
            if c == 1:
                pass
            if c == 0:
                gcda.append(a)
    d = len(gcda)
    if d == 0:
        ans[1] = 1
    else:
        D = gcda[0]
        r = gcda.count(D)
        if r == d:
            pass
        else:
            ans[1] = 1

if ans[0] == 1:
    print("pairwise comprime")
elif ans[1] == 1:
    print("setwise comprime")
else:
    print("not comprime")


import math
N = int( input() )
A = sorted( list(map(int, input().split())))
ans = A[0]
L = []
mod = 10 ** 7 + 9

cnt = 0
for i in range(1, N):
    ans = math.gcd(ans, A[i])
    if ans == 1:
      break
    else:
      cnt += 1
if ans != 1:
  ret = "not coprime"
else:
  if cnt > 0:
    ret = "setwise coprime"
  else:
    product = 1
    for a in A:
      product = ( product * a ) % mod
    ret = "pairwise coprime"
    for a in A:
      ans = math.gcd(a, product // a)
      if ans != 1:
        ret = "setwise coprime"
        break
print( ret )


import time
A=time.time()
p=[1 for i in range(1001)]
p[0]=0
p[1]=0
for i in range(2,1001):
    if p[i]==1:
        for j in range(2,1001):
            if i*j<=1000:
                p[i*j]=0
#print(p[:25])
Prime=[]
for i in range(1001):
    if p[i]==1:
        Prime.append(i)

#print(Prime)
#print(len(Prime))
N=int(input())
L=list(map(int,input().split()))

def gcd(a,b):
    if b>a:
        a,b=b,a
    while a%b!=0:
        a,b=b,a%b
    return b

X=L[0]
for i in range(1,N):
    X=gcd(X,L[i])
    if X==1:
        break
if X>1:
    print("not coprime")
    exit()

D={}

for I in L:
    B=time.time()
    if B-A>1.9:
        print("pairwise coprime")
        exit()
    for j in Prime:
        if I%j==0:
            if j not in D:
                D[j]=1
            else:
                print("setwise coprime")
                exit()
            while I%j==0:
                I//=j
    if I!=1:
        if I not in D:
            D[I]=1
        else:
            print("setwise coprime")
            exit()
#print(D)

print("pairwise coprime")


from sys import stdin,stdout
from math import gcd
n=int(stdin.readline())
a=list(map(int,stdin.readline().split()))
s=set(a)
if len(s)!=n:
    print('not coprime')
    exit(0)
p=2;d={}
N=max(a)+2
primes=[1]*N;not_pairwise=0
while p*p<=N:
    if primes[p]:
        for mul in range(p,N,p):
            primes[mul]=0
            if mul in s:
                d[p]=d.get(p,0)+1
                if d[p]>=2:not_pairwise=1;break;
        if not_pairwise:break
    p+=1
g=a[0]
for v in a:
    g=gcd(g,v)
if not_pairwise==0:print('pairwise coprime')
elif g==1:print('setwise coprime')
else:print('not coprime')


N = int(input())
A = list(map(int, input().split()))
dictA = dict()
for a in A:
  if a in dictA.keys():
    dictA[a] += 1
  else:
    dictA[a] = 1

def get_prime(p):
  result = []
  if p==1:
    return result
  else:
    integers = [1 for _ in range(p+1)]
    integers[0] = 0
    integers[1] = 0
    for i in range(p+1):
      if integers[i] == 1:
        result.append(i)
        for j in range(i,p+1,i):
          integers[j] = 0
    return result

def count_coprime(p):
  count = 0
  for a,v in dictA.items():
    if a%p == 0:
      count += v
  return count

maxA = max(A)
answer = 'pairwise coprime'
if maxA > 1:
  if max(dictA.values()) == N:
    answer = 'not coprime'
    break
  if max(dictA.values()) >= 2:
    answer = 'setwise coprime'
  for p in get_prime(1001):
    count = count_coprime(p)
    if count == N:
      answer = 'not coprime'
      break
    elif count >= 2:
      answer = 'setwise coprime'

print(answer)


#!/usr/bin/env python3

import collections
import sys
input=sys.stdin.readline

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

def judge(n,arr):
    MAX=10**6
    table=[i for i in range(MAX+1)]
    for i in range(2,MAX+1):
        if table[i]<i:
            continue
        for j in range(i,MAX+1,i):
            table[j]=i
    cnt=collections.defaultdict(int)
    for val in arr:
        s=set()
        while val!=1:
            prime=table[val]
            s.add(prime)
            val//=prime
        for tmp in s:
            cnt[tmp]+=1
    for val in cnt.values():
        if val>=2:
            return False
    return True

n=int(input())
arr=list(map(int,input().split()))
tmp=arr[0]
for val in arr:
    tmp=gcd(tmp,val)
if tmp==1:
    is_setwise=True
else:
    is_setwise=False
is_pairwise=judge(n,arr)
if is_pairwise==True:
    print('pairwise coprime')
elif is_setwise==True:
    print('setwise coprime')
else:
    print('not coprime')


h,w,m=map(int,input().split())

dich={}
dicw={}
l=[]

for i in range(m):
  h,w=map(int,input().split())
  if h not in dich:
    dich[h]=1
  else:
    dich[h]+=1

  if w not in dicw:
    dicw[w]=1
  else:
    dicw[w]+=1

  l.append([h,w])

dicw=sorted(dicw.items(),key=lambda x:x[1],reverse=True)
dich=sorted(dich.items(),key=lambda x:x[1],reverse=True)

h_max=dich[0][1]
w_max=dicw[0][1]

ans=0
now=0
mae_h=h_max
mae_w=w_max

for i in range(len(dicw)):
  for j in range(len(dich)):
    nh=dich[j][1]
    nw=dicw[i][1]

    now=nh+nw
    if now<h_max+w_max:
      break

    if [dich[j][0],dicw[i][0]] in l:
      now-=1
    ans=max(ans,now)

    if h_max+w_max==ans:
      break

print(ans)

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

6


from collections import Counter

def solve():
    H, W, M = map(int, input().split())
    dh, dw = Counter(), Counter()
    used = set()

    for _ in range(M):
        h, w = map(int, input().split())
        dh[h] += 1
        dw[w] += 1
        used.add((h, w))

    ih = dh.most_common()
    iw = dw.most_common()

    h, counth = ih[0]
    w, countw = iw[0]
    ans = counth + countw - ((h, w) in used)

    for h, counth in ih:
        for w, countw in iw:
            b = counth + countw - ((h, w) in used)
            if b<ans:
                break
            ans = b
    print(ans)

solve()


H,W,M=map(int,input().split())
L=[]
bh=[0]*(H+1)
bw=[0]*(W+1)
mh,mw=[0,[]],[0,[]]
for _ in range(M):
    h,w=map(int,input().split())
    L.append((h,w))
    bh[h]+=1
    bw[w]+=1
    if bh[h]>mh[0]:
        mh=[bh[h],[h]]
        nh=1
    elif bh[h]==mh[0]:
        mh[1].append(h)
        nh+=1
    if bw[w]>mw[0]:
        mw=[bw[w],[w]]
        nw=1
    elif bw[w]==mw[0]:
        mw[1].append(w)
        nw+=1
ans=mh[0]+mw[0]
n=0
if nh*nw<=M:
    for h,w in L:
        if h in mh[1] and w in mw[1]:
            n+=1
if n==nh*nw:
    ans-=1
print(ans)


from collections import Counter
from collections import defaultdict
from collections import deque
from heapq import heapify
from heapq import heappop
from heapq import heappush

h,w,m=[int(x) for x in input().split()]

#defaultdictにすることにより後に使うmax関数のコストを削減
hcnt=defaultdict(int)
wcnt=defaultdict(int)
#存在チェックのアクセスがリストで持たせるより高速
#リストは突っ込めないので注意(hashabeのみOK)
bomb=defaultdict()
#O(H)
for _ in range(m):
    hi,wi=[int(x)-1 for x in input().split()]
    hcnt[hi]+=1
    wcnt[wi]+=1
    bomb[(hi,wi)]=True

#O(H)
hmax=max(hcnt.values())
wmax=max(wcnt.values())

#O(H)
hidx=[x for x,y in hcnt.items() if y==hmax]
widx=[x for x,y in wcnt.items() if y==wmax]

#O(H**2)
ofst=-1
for i in hidx:
    for j in widx:
        if not bomb.get((i,j)):
            ofst=0
            break

print(hmax+wmax+ofst)


#!/usr/bin/env python3

# from typing import Optional
from typing import List

# from typing import Dict
from typing import Tuple
from typing import Set

# from typing import Sequence

Cod = Tuple[int, int]

def main():
    args = input().split()
    H = int(args[0])
    W = int(args[1])
    M = int(args[2])

    codList: Set[int] = set()
    columnSumList: List[int] = [0] * W
    rowSumList: List[int] = [0] * H
    for i in range(M):
        h, w = map(lambda x: int(x), input().split())
        item = (h, w)
        codList.add(item)
        # codList.setdefault(h, {})
        # codList[h][w] = item
        columnSumList[w - 1] += 1
        rowSumList[h - 1] += 1

    maxColumnSum = max(columnSumList)
    maxColumIndexList = [i for i, x in enumerate(columnSumList) if x == maxColumnSum]
    maxRowSum = max(rowSumList)
    maxRowIndexList = [i for i, x in enumerate(rowSumList) if x == maxRowSum]

    result = maxColumnSum + maxRowSum
    for row in maxRowIndexList:
        for column in maxColumIndexList:
            if (row + 1, column + 1) in codList:
                continue
            else:
                print(result)
                return

    print(result - 1)

if __name__ == "__main__":
    main()


import numpy as np

H,W,N = [int(i) for i in input().split()]
varriers = [[int(i)-1 for i in input().split()] for i in range(N)]
board = np.array([[0 for _ in range(W)] for i in range(H)], dtype=int)

for varrier in varriers:
    for x in range(W):
        board[varrier[0]][x] += 1
    for y in range(H):
        if y == varrier[0]:
            continue
        board[y][varrier[1]] += 1

print(board.max())


import numpy as np
def main():
  H,W,m=map(int,input().split())
  h=np.zeros(H, dtype = int)
  w=np.zeros(W, dtype = int)
  hw={}
  for i in range(m):
    hi,wi=map(int,input().split())
    hi=hi-1
    wi=wi-1
    h[hi]+=1
    w[wi]+=1
    hw[(hi,wi)]=0
  yn=1
  hm=np.max(h)
  wm=np.max(w)
  #print(hw)
  for j in range(H):
    if h[j]==hm:
      #print(h)
      for k in range(W):
        if w[k]==wm:
          #print(k)
          #print(hw[3,k])
          if (j,k) not in hw:
            yn=0
            break
      else:
        continue
      break
  print(hm+wm-yn)
main()


import numpy as np

h, w, m = map(int, input().split())
bb = [[0] * w for _ in range(h)]
mx = 0
for _ in range(m):
    bh, bw = map(int, input().split())
    bb[bh - 1][bw - 1] = 1
smr = np.sum(bb,axis=1)
bb.pop(np.argmax(smr))
smc = np.sum(bb,axis=0)
print(max(smr) + max(smc))


import collections

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

h = []
w = []
point = []
for i in range(M):
    a, b = list(map(int, input().split()))

    h.append(a)
    w.append(b)
    point.append((a, b))

h_count = collections.Counter(h)
w_count = collections.Counter(w)

max = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        count = h_count[i] + w_count[j]

        if ((i, j) in point):
            count = count - 1

        if (count > max):
            max = count

print(max)


x=input().split()

m=int(x[2])
a=[]
b=[]
for i in range(m):
	y=input().split()

	a.append(int(y[0]))
	b.append(int(y[1]))

a1={}
b1={}

for i in range(m):
	a1.update({a[i]:a.count(a[i])})
	b1.update({b[i]:b.count(b[i])})

amax=max(a1, key=a1.get)
bmax=max(b1, key=b1.get)

counter=0

for i in range(m):
	if amax==a[i]: counter+=1
	if bmax==b[i]: counter+=1
	if amax==a[i] and bmax==b[i]: counter-=1

print(counter)


import sys
import math
import numpy as np

if __name__ == '__main__':
    H, W, M = list(map(lambda x: int(x), sys.stdin.readline().split()))

    dic = {}
    # h = [0 for i in range(H)]
    # w = [0 for i in range(W)]
    h = np.zeros(H, dtype=np.int64)
    w = np.zeros(W, dtype=np.int64)
    for i in range(M):
        # P.append(list(map(lambda x: int(x), sys.stdin.readline().split())))
        x, y = list(map(lambda x: int(x), sys.stdin.readline().split()))
        x -= 1
        y -= 1
        h[x] += 1
        w[y] += 1
        dic[x*H+y] = 1

    lh = np.where(h == h.max())
    lw = np.where(w == w.max())

    mx = np.max(h)
    my = np.max(w)
    # print(mx, my)

    # print(lh[0])
    # print(lw[0])

    tmp = mx + my
    for i in lh[0]:
        for j in lw[0]:
            if i*H+j not in dic:
                print(tmp)
                exit()
    print(tmp-1)
    exit()


from sys import stdin

input = stdin.readline

def solve():
    n = int(input())
    r = n % 1000
    res = 0 if r == 0 else 1000 - r
    print(res)

if __name__ == '__main__':
    solve()

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


money=int(input())
yen_bills=1000
if yen_bills>=money:
    print(yen_bills-money)
else:
    while yen_bills<money:
        yen_bills+=1000
    print(yen_bills-money)


n = int(input()) % 1000

if n > 0:
    print(1000 - n)
else:
    print(0)


N = int(input())
a = N // 1000
b = N % 1000

if b == 0:
    ans = 0
else:
    ans = N - a * 1000

print(ans)


N = int(input())
n=N%1000
if n==0:
    print(0)
else:
    print(1000-n)


n = input()
value = n[-3]+n[-2]+n[-1]
#print(value)
value_int = int(value)
if value == '000':
    print(0)
else:
    print(1000 - value_int)


from collections import deque

# for #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

# 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")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from bisect import bisect_left as bl
from math import log2,ceil
from heapq import heappush, heappop
from itertools import permutations
def main():
    # for t in range(int(input())):
        n = int(input())
        x = (n+1000)//1000*1000-n
        if x==1000:
            print(0)
        else:
            print(x)

            # heappush(h, l[i])

# endregion

if __name__ == "__main__":
    main()


import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]

def main():
    N = II()

    print(N%1000)

if __name__ == "__main__":
	main()


from copy import copy
from time import time
import random
t0 = time()
import math
import sys
input = sys.stdin.readline
D = int(input())
c = list(map(int,input().split()))
s = [list(map(int,input().split())) for _ in range(D)]
last = [0]*26
ans = [0]*D
score = 0
for i in range(D):
    ps = [0]*26
    for j in range(26):
        pl = copy(last)
        pl[j] = i+1
        ps[j] += s[i][j]
        for k in range(26):
            ps[j] -= c[k]*(i+1-pl[k])
    idx = ps.index(max(ps))
    last[idx] = i+1
    ans[i] = idx+1
    score += max(ps)
now = time()
lim = 1.85
T = 1000
while now-t0<lim:
    na = copy(ans)
    x = random.randint(1,365)
    y = random.randint(1,365)
    na[x-1] = na[y-1]
    last = [0]*26
    ns = 0
    for i in range(D):
        last[na[i]-1] = i+1
        ns += s[i][na[i]-1]
        for j in range(26):
            ns -= c[j]*(i+1-last[j])
    now = time()
    T = 1000+(-998)*(now-t0)/lim
    p = pow(math.e,-abs(ns-score)/T)
    if ns > score or random.random() < p:
        ans = na
        score = ns
for a in ans:
    print(a)

Problem Statement

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

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

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

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

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

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

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

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

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

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

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

Sample Input 1

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

Sample Output 1

1
17
13
14
13

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

Input generator, score calculator, and visualizer

Beginner's Guide

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


import sys
from time import time
from random import randint

def func(s, x):
    last = [0] * 26
    score = 0
    for i, v in enumerate(x, 1):
        last[v] = i
        c = 0
        for j in range(26):
            c += s[j] * (i - last[j])
        score += s[i * 26 + v] - c
    return score

def main():
    start = time()
    d, *s = map(int, sys.stdin.buffer.read().split())
    x = ([*range(26)] * 15)[:d]
    M = func(s, x)
    while time() - start < 1.8:
        y = x.copy()
        if randint(0, 1):
            y[randint(0, d - 1)] = randint(0, 25)
        elif randint(0, 1):
            i = randint(0, d - 16)
            j = randint(i + 1, i + 15)
            y[i], y[j] = y[j], y[i]
        else:
            i = randint(0, d - 15)
            j = randint(i + 1, i + 7)
            k = randint(j + 1, j + 7)
            if randint(0, 1):
                y[i], y[j], y[k] = y[j], y[k], y[i]
            else:
                y[i], y[j], y[k] = y[k], y[i], y[j]
        t = func(s, y)
        if t > M:
            M = t
            x = y
    for t in x:
        print(t + 1)

if __name__ == '__main__':
    main()


# 貪欲法 + 山登り法 + スワップ操作
import time
s__ = time.time()
limit = 1.9
#limit = 10

from numba import njit
import numpy as np

d = int(input())
cs = list(map(int, input().split()))
cs = np.array(cs, dtype=np.int64)
sm = [list(map(int, input().split())) for _ in range(d)]
sm = np.array(sm, dtype=np.int64)

@njit('i8(i8[:], i8)', cache=True)
def total_satisfaction(ts, d):
    ls = np.zeros(26, dtype=np.int64)
    s = 0
    for i in range(d):
        t = ts[i]
        t -= 1
        s += sm[i][t]
        ls[t] = i + 1

        dv = cs * ((i+1) - ls)
        s -= dv.sum()
    return s

@njit('i8[:]()', cache=True)
def greedy():
    ts = np.array([0] * d, dtype=np.int64)
    for i in range(d):
        mx = -1e10
        mxt = None
        for t in range(1, 26+1):
            ts[i] = t
            s = total_satisfaction(ts, i + 1)
            if s > mx:
                mx = s
                mxt = t
        ts[i] = mxt
    return ts

@njit('i8(i8, i8[:])', cache=True)
def loop(mxsc, ts):
    it = 50
    rds = np.random.randint(0, 4, (it,))
    rdd = np.random.randint(1, d, (it,))
    rdq = np.random.randint(1, 26, (it,))
    rdx = np.random.randint(1, 12, (it,))
    for i in range(it):
        bk1 = 0
        bk2 = 0
        if rds[0] == 0:
            # trailing
            di = rdd[i]
            qi = rdq[i]

            bk1 = ts[di]
            ts[di] = qi
        else:
            # swap
            di = rdd[i]
            xi = rdx[i]
            if di + xi >= d:
                xi = di - xi
            else:
                xi = xi + xi

            bk1 = ts[di]
            bk2 = ts[xi]
            ts[di] = bk2
            ts[xi] = bk1

        sc = total_satisfaction(ts, d)

        if sc > mxsc:
            #print(mxsc, '->', sc)
            mxsc = sc
        else:
            # 最大値を更新しなかったら戻す
            if rds[0] == 0:
                ts[di] = bk1
            else:
                ts[di] = bk1
                ts[xi] = bk2

    return mxsc

ts = greedy()
mxsc = total_satisfaction(ts, d)
mxbk = mxsc

s_ = time.time()
mxsc = loop(mxsc, ts)
e_ = time.time()

consume = s_ - s__
elapsed = e_ - s_
#print('consume:', consume)
#print('elapsed:', elapsed)

if consume < limit:
    lp = int((limit - consume)/ elapsed)
    #print('loop', lp)
    for _ in range(lp):
        mxsc = loop(mxsc, ts)

for t in ts:    print(t)
#print(mxbk, mxsc)
#print(time.time() - s__)


import sys

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

D = I()
c = [0] + LI()
s = [0] + [[0] + LI() for i in range(D)]

last = [[0]*27 for i in range(D+1)]

for i in range(1,D+1):
    r = 0
    manzokudo = 0
    for j in range(1,27):
        m = s[i][j]
        for k in range(1,27):
            if k != j:
                m -= c[k]*(i-last[i-1][k])
            else:
                continue
        if j == 1:
            r = 1
            manzokudo = m
        else:
            if manzokudo < m:
                manzokudo = m
                r = j
    print(r)
    for j in range(1,27):
        if j == r:
            last[i][j] = i
        else:
            last[i][j] = last[i-1][j]


import sys
import unittest
import random

T = 26

def solve(d, c, s):
    best = [0] * d
    last = [-1]*T

    for i in range(d):
        max_v = -float('inf')
        for j in range(T):
            v = s[i][j] + c[j] * (i - last[j])
            if max_v < v:
                max_v = v
                best[i] = j
        last[best[i]] = i

    score = get_score(d, c, s, best)
    for i in range(1900):
        a = random.randint(0, d-1)
        b = random.randint(0, T-1)
        old = best[a]
        best[a] = b
        t_score = get_score(d, c, s, best)
        if t_score > score:
            score = t_score
        else:
            best[a] = old
    return best

def get_score(d, c, s, t):
    last = [-1]*T
    total = 0
    for i in range(d):
        total += s[i][t[i]]
        last[t[i]] = i
        for j in range(T):
            total -= c[j] * (i - last[j])
    return total

def main():
    d = int(input())
    c = list(map(int, input().split()))
    s = [list(map(int, input().split())) for i in range(d)]
    t = solve(d, c, s)
    print(get_score(d, c, s, t), file=sys.stderr)
    for i in range(d):
        print(t[i]+1)

if __name__ == "__main__":
    main()

class Test(unittest.TestCase):
    def test_score(self):
        pass


D = int(input())
C = list(map(int, input().split()))

S = []
for _ in range(D):
  S.append(list(map(int, input().split())))

def solve():
  LastD = [0] * 26
  sc = 0
  for i in range(D):
    t = 0
    wk = -10000000000
    for tx in range(26):
      scwk = S[i][tx] + C[tx] * (i+1 - LastD[tx])
      if wk < scwk:
        wk = scwk
        t = tx
    sc += S[i][t]
    LastD[t] = i+1
    for j in range(26):
      sc -= C[j] * (i+1 - LastD[j])
    print(t+1)
  return sc

solve()


import numpy as np

d = int(input())

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

sd = np.zeros((d, 26), dtype=np.int)
for i in range(d):
  s = list(map(int, input().split()))
  s_array = np.array(s)
  sd[i, :] = s_array

pp = np.zeros(26, dtype=np.int)

for i in range(d):
  pp += c
  pp_max = np.argmax(pp)+1
  pp_max_val = np.max(pp)
  sd_max = np.argmax(sd[i,:])+1
  sd_max_val = np.max(sd[i,:])
  if pp_max_val >= sd_max_val:
    t = pp_max -1
    pp[pp_max-1] = 0
  else:
    t = sd_max
  print(t)


d=int(input())
c=list(map(int,input().split()))
s=[]
for i in range(d):
	r=list(map(int,input().split()))
	s.append(r)
for i in range(d):
	print(i%26+1)


import bisect

n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ra = [0] * (n + 1)
rb = [0] * (m + 1)
for i in range(n):
    ra[i + 1] = a[i] + ra[i]

for j in range(m):
    rb[j + 1] = b[j] + rb[j]

rai = max(bisect.bisect_right(ra, k) - 1, 0)
rbi = max(bisect.bisect_right(rb, k) - 1, 0)
if rai >= rbi:
    zan = k - ra[rai]
    rbz = bisect.bisect_right(rb, zan) - 1
    if rbz < 0:
        print(rai)
    else:
        print(rai + rbz)
else:
    zan = k - rb[rbi]
    raz = bisect.bisect_right(ra, zan) - 1
    if raz < 0:
        print(rbi)
    else:
        print(rbi + raz)

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.


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

a_c_sum = [0]*(n + 1)
for i in range(n):
  a_c_sum[i + 1] = a_c_sum[i] + a[i]
b_c_sum = [0]*(m + 1)
for i in range(m):
  b_c_sum[i + 1] = b_c_sum[i] + b[i]

ans, best_b = 0, m
for i in range(n + 1):
  if a_c_sum[i] > k:
    break
  else:
    while 1:
      if b_c_sum[best_b] + a_c_sum[i] <= k:
        ans = max(ans, i + best_b)
        break
      else:
        best_b -= 1
        if best_b == 0:
          break
print(ans)


n, m, k = map(int, input().split())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))
ans = [0]
time_sum = 0
i, j = 0, 0

flag_a = True
flag_b = True
flag = False
for i in range(0, len(aa)+1):
    for j in range(0, len(bb)+1):
        asum, bsum = sum(aa[:i]), sum(bb[:j])
        if k < asum and k < bsum:
            flag = True
            break
        else:
            time_total = asum + bsum
            if time_total > k:
                break
            else:
                ans.append(i+j)
    if flag:
        break

print(max(ans))


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

count=0
k=0
i=0
j=0
while k<=K:
  if A[i]<=B[j]:
    k+=A[i]
    i+=1
    count+=1
  else:
    k+=B[j]
    j+=1
    count+=1

print(count-1)


N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
answer = 0

for x in range(N-1):
    A[x+1] += A[x]
    if A[x+1] > K:
        A = [0] + A[:x+1]
        break

for y in range(M-1):
    B[y+1] += B[y]
    if B[y+1] > K:
        B = [0] + B[:y+1]
        break

if A[-1] + B[-1] <= K:
    answer = len(A) + len(B)
    print(answer)

else:
    for i in range(len(A)):
        for j in range(len(B)):
            if A[i] + B[j] > K:
                if answer < i+j-1:
                    answer = i+j-1
                break
    print(answer)


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

  spendTime = 0
  cnt = 0
  indexA = 0
  indexB = 0

  while spendTime < K:
    if indexA == N and indexB == M:
      break
    elif indexA == N:
      spendTime += B[indexB]
      indexB += 1
      cnt += 1
      continue
    elif indexB == M:
      spendTime += A[indexA]
      indexA += 1
      cnt += 1
      continue

    if A[indexA] <= B[indexB]:
      spendTime += A[indexA]
      indexA += 1
      cnt += 1
    else:
      spendTime += B[indexB]
      indexB += 1
      cnt += 1

  if spendTime == K:
    print(cnt)
  else:
    print(cnt-1)

main()


def main():
    n, m, k = map(int,input().split())
    A = list(map(int,input().split()))
    B = list(map(int,input().split()))
    C = []
    for x in range(1,n+1):
        sumA = sum(A[0:x])
        for y in range(1,m+1):
            sumB = sum(B[0:y])
            if sumA + sumB < k:
                C.append(sumA + sumB)
    print(max(C))
main()


n,m,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
time=0
ai=0
bi=0
la=len(a)
lb=len(b)
for i in range(200000):
    if bi<lb:
        if ai<la:
            if a[ai]<b[bi]:
                if time+a[ai]<=k:
                    time+=a[ai]
                    ai+=1
                else:
                    break
            else:
                if time+b[bi]<=k:
                    time+=b[bi]
                    bi+=1
                else:
                    break
        else:
            if time+b[bi]<=k:
                time+=b[bi]
                bi+=1
            else:
                break
    elif ai<la:
        if time+a[ai]<=k:
            time+=a[ai]
            ai+=1
        else:
            break
    else:
        break
print(ai+bi)


n,m,k = map(int,input().split())
A = [int(p) for p in input().split()]
B = [int(p) for p in input().split()]
a,b = [0],[0]

a_apnd = a.append
b_apnd = b.append
for i in range(n):
  a_apnd(a[i]+A[i])
for i in range(m):
  b_apnd(b[i]+B[i])

count = 0
for i in range(n+1):
  res = k-a[i]
  if res<0:
    break
  if res<b[1]:
    count = max(count,i)
    continue
  for t in range(m,-1,-1):
    if b[t] <= res:
      break
  count = max(count,i+t)

print(count)


n, m, k = map(int, input().split())
*A, = map(int, input().split())
*B, = map(int, input().split())
SA, SB = [0], [0]
for i in range(n):
    SA.append(SA[i] + A[i])
for j in range(m):
    SB.append(SB[j] + B[j])
ans, tmp = 0, m
for i in range(n + 1):
    if SA[i] > k:
        break
    for j in range(tmp + 1)[::-1]:
        if SA[i] + SB[j] <= k:
            break
    ans = max(ans, i + j)
    tmp = j
print(ans)


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

a_list = list(map(int, input().split()))
b_list = list(map(int, input().split()))

for i in range(1,n):
  a_list[i]=a_list[i-1]+a_list[i]
for i in range(1,m):
  b_list[i]=b_list[i-1]+b_list[i]

max_ = 0
for i in range(n):
  if k < a_list[n-i-1]:
    pass
  else:
    for j in range(m):
      if k-a_list[n-i-1] < b_list[m-j-1]:
        pass
      else:
        max_ = max(len(a_list[:n-i])+len(b_list[:m-j]), max_)
        break
print(max_)


from itertools import accumulate
from bisect import bisect_right

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

ans = 0
for i, a in enumerate(A):
    if a > K:
        break
    n = bisect_right(B, K-a)
    ans = max(ans, i+n+1)

print(ans)


from decimal import Decimal

def main():
  M, N, K = map(int, input().split())
  A = list(map(int, input().split()))
  B = list(map(int, input().split()))
  spent_time = 0
  count = 0
  AB = A + B
  AB.sort()

  while(True):
    if count == M + N:
      break
    temp = AB[count]
    #print(temp, spent_time)
    if spent_time + temp >= K:
      break
    spent_time = spent_time + temp
    count += 1

  #print('----')
  #print(spent_time)
  print(count)

main()


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

if sum(A) + sum(B) <= K:
    print(len(A)+len(B))
else:
    ans = 0
    count = 0
    j = 0
    for i in range(0,len(A)):
        if A[i] <= B[j]:
            ans += A[i]
            if ans >= K:
                break
            else:
                count += 1
        elif A[i] >= B[j]:
            ans += B[j] + A[i]
            j += 1
            if ans >= K:
                break
            else:
                count += 2
    print(count)


#input = raw_input

map_ = lambda x, y: list(map(x, y))

n, m, k = map_(int, input().split(" "))
As = map_(int, input().split(" "))
Bs = map_(int, input().split(" "))

ai = 0
bi = 0
cost = 0
flag = True
count = 0
a = As[ai]
b = Bs[bi]

cur = 0
a_cumsum = []
for i in range(n):
    cur += As[i]
    if cur > k:
        n = i
        break
    else:
        a_cumsum.append(cur)

cur = 0
b_cumsum = []
for i in range(m):
    cur += Bs[i]
    if cur > k:
        m = i
        break
    else:
        b_cumsum.append(cur)
#print("n", n)
#print("m", m)
#print(a_cumsum)
#print(b_cumsum)

out = 0
end = False
for i in reversed(range(n)):
    a_count = i +1
    cur = a_cumsum[i]
    cur_count = None

    for j in reversed(range(m)):
        b_count = j + 1
        cur2 = cur + b_cumsum[j]
        if cur2 <= k:
            if b_count == m:
                end = True
            cur_count = a_count + b_count
            #print(i, a_count, b_count)
            break

    if cur_count is None:
        cur_count = a_count
        #print(i, a_count, 0)
    out = max(out, cur_count)

    if end:
        break

print(out)


n,m,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
count = 0
i = 0
j = 0
while k >= a[i] or k >= b[j]:
    read = min(a[i],b[j])
    if read == a[i]:
        i += 1
        count += 1
        k -= read
        if i == n:
            a.append(10**10)
    else:
        j += 1
        count += 1
        k -= read
        if j == m:
            b.append(10**10)
print(count)


a=input()
b=input()
c=input()

N,M,K=map(int, a.split())
A = list(map(int, b.split()))
B = list(map(int, c.split()))

kotae=N
Kotae=0
m=0
wa=sum(A)
for i in range(N+1):

    n=N-i-1

    if wa<=K:
        while wa+B[m]<=K:
            wa+=B[m]
            m+=1
            kotae+=1

            if m==M:
                m-=1
                break
        if kotae>Kotae:
            Kotae=kotae
    wa-=A[n]
    kotae-=1
print(Kotae)


n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0
s = 0
b_count = 0
for i in range(m):
    if s + b[i] <= k:
        s += b[i]
        ans += 1
        b_count = i
    else:
        break
a_count = 0
while True:
    if a_count < n and s+a[a_count] <= k:
        s += a[a_count]
        a_count += 1
        ans += 1
    else:
        break
now = ans
for i in range(b_count, -1, -1):
    s -= b[i]
    now -= 1
    while True:
        if a_count < n and s +a[a_count] <= k:
            s += a[a_count]
            a_count += 1
            now += 1
        else:
            break
    ans = max(now, ans)
print(ans)


N,M,K=list(map(int,input().split()))
a_list = list(map(int,input().split()))
b_list = list(map(int,input().split()))
totalbook = 0
totaltime = 0
for a in a_list:
  if totaltime+a <= K:
    totaltime+=a
    totalbook+=1
  else:
    break
ans = totalbook
nowaind = totalbook-1 if totalbook > 0 else 0
nowbind = 0
for b in b_list:
  if totaltime+b<=K:
    totaltime+=b
    totalbook+=1
    nowbind+=1
  else:
    break
ans = max(ans,totalbook)
for b in range(nowbind,len(b_list)):
  while nowaind >= 0 and totaltime+b_list[b]>K:
    totalbook-=1
    totaltime-=a_list[nowaind]
    nowaind-=1
  totaltime+=b_list[b]
  if totaltime<=K:
    totalbook+=1

print(max(ans,totalbook))


N,M,K=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
a=[0]*N
b=[0]*M
a[0]=A[0]
b[0]=B[0]
for i in range(N-1):
    a[i+1]=a[i]+A[i]
for i in range(M-1):
    b[i+1]=b[i]+B[i]
diff=2*10**9
count=0
for i in range(N):
    for j in range(M):
        if 0<K-(a[i]+b[j])<diff:
            diff=K-(a[i]+b[j])
            count=(i+1)+(j+1)
print(count)


n, m, k = map(int, input().split()) #n->a, m->b, max:k
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt = 0
now = 0
while True:
    if len(a) <= 0 and len(b) <= 0:
        break
    elif len(a) <= 0:
        now += b.pop(0)
    elif len(b) <= 0:
        now += a.pop(0)
    elif a[0] <= b[0]:
        now += a.pop(0)
    else:
        now += b.pop(0)
    if k < now:
        break
    else:
        cnt += 1
print(cnt)


production = True

import sys, math, collections

def input(input_format = 0, multi = 0):

    if multi > 0: return [input(input_format) for i in range(multi)]
    else:
        next_line = sys.stdin.readline()[:-1]

        if input_format >= 10:
            use_list = False
            input_format = int(str(input_format)[-1])
        else: use_list = True

        if input_format == 0: formatted_input = [next_line]
        elif input_format == 1: formatted_input = list(map(int, next_line.split()))
        elif input_format == 2: formatted_input = list(map(float, next_line.split()))
        elif input_format == 3: formatted_input = list(next_line)
        elif input_format == 4: formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
        elif input_format == 5: formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
        elif input_format == 6: formatted_input = next_line.split()
        else: formatted_input = [next_line]

        return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format = 0, newline = True):

    formatted_output = ""

    if output_format == 0: formatted_output = str(output_line)
    elif output_format == 1: formatted_output = " ".join(map(str, output_line))
    elif output_format == 2: formatted_output = "\n".join(map(str, output_line))

    print(formatted_output, end = "\n" if newline else "")

def log(*args):
    if not production:
        print("$$$", end = "")
        print(*args)

enum = enumerate

#
#   >>>>>>>>>>>>>>> START OF SOLUTION <<<<<<<<<<<<<<
#

def solve():

    n, m, k = input(1)
    a = input(1)
    b = input(1)

    ap = [0]
    bp = [0]

    for i in a:
        ap.append(ap[-1] + i)

    for i in b:
        bp.append(bp[-1] + i)

    log(ap, bp)

    pa = 0

    while pa < len(ap) and ap[pa] <= k:
        pa += 1

    m = pa - 1
    pb = 1

    c = k - ap[pa - 1]

    for i in range(pa - 1, -1, -1):
        while pb < len(bp) and bp[pb] <= c:
            m = max(pa - 1 + pb, m)
            pb += 1
        pa -= 1
        c += a[pa - 1]

    out(m)

    return

#for i in range(input(11)): solve()
solve()

#
#   >>>>>>>>>>>>>>>> END OF SOLUTION <<<<<<<<<<<<<<<
#


import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
N,M,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
a = []
aa = 0
bb = 0
b = []
flag = 0
for i in range(N):
    aa += A[i]
    a.append(aa)
for i in range(M):
    bb += B[i]
    b.append(bb)
MAX = 0
for i in range(N):
    t = a[i]
    if t > K:
        break
    else:
        tt = K-t
        index = bisect_left(b,tt)
        if index == M:
            MAX = max(MAX,i+1+M)
        elif b[index] == tt:
            MAX = max(MAX,i+1+1+index)
        else:
            MAX = max(MAX,i+1+index)
for i in range(M):
    t = b[i]
    if t > K:
        break
    else:
        tt = K-t
        index = bisect_left(a,tt)
        if index == N:
            MAX = max(MAX,i+1+N)
        elif b[index] == tt:
            MAX = max(MAX,i+1+1+index)
        else:
            MAX = max(MAX,i+1+index)

print(MAX)


n,m,k = map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
x,y,c,h=0,0,0,0
while(c<k):
  if(x>=n):
    while(y<m and c+b[y]<=k):
      h+=1
      c+=b[y]
      y+=1
    break
  elif(y>=m):
    while(x<n and c+a[x]<=k):
      h+=1
      c+=a[x]
      x+=1
    break
  else:
    if(a[x]<b[y]):
      if(c+a[x]>k):
        break
      else:
        c+=a[x]
        x+=1
        h+=1
    else:
      if(c+b[y]>k):
        break
      else:
        c+=b[y]
        y+=1
        h+=1
print(h)


import sys
input = sys.stdin.readline

n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ia, ib = 0, 0
ca, cb = 0, 0
t = 0
cnt = 0
INF = 987654321

while True:
    if a:
        ca = a[0]
    else:
        ca = INF
    if b:
        cb = b[0]
    else:
        cb = INF

    if ca >= cb:
        t += cb
        b.pop()
    elif ca < cb:
        t += ca
        a.pop()

    if t > k:
        break

    cnt += 1

    if cnt == n+m:
        break

print(cnt)


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

aidx = 0
bidx = 0
time = 0
judge = True
cnt = 0
while judge:
    if aidx < N and bidx < M:
        if A[aidx] < B[bidx]:
            time += A[aidx]
            aidx += 1
        else:
            time += B[bidx]
            bidx += 1
    else:
        if aidx < N:
            time += A[aidx]
            aidx += 1
        elif bidx < M:
            time += B[bidx]
            bidx += 1
        else:
            break
    if time <= K:
        cnt += 1
    else:
        break

print(cnt)


N = int(input())
print(sum(N//n*(N//n+1)*n//2 for n in range(1,1+N)))

Score : 400 points

Problem Statement

For a positive integer X, let f(X) be the number of positive divisors of X.

Given a positive integer N, find \sum_{K=1}^N K\times f(K).

Constraints

1 \leq N \leq 10^7

Input

Input is given from Standard Input in the following format:

N

Output

Print the value \sum_{K=1}^N K\times f(K).

Sample Input 1

4

Sample Output 1

23

We have f(1)=1, f(2)=2, f(3)=2, and f(4)=3, so the answer is 1\times 1 + 2\times 2 + 3\times 2 + 4\times 3 =23.

Sample Input 2

100

Sample Output 2

26879

Sample Input 3

10000000

Sample Output 3

838627288460105

Watch out for overflows.


n=int(input())
ans=0
for i in range(1,n+1):
    d=n//i
    ans+=i*d*(d+1)//2
print(ans)


import math

N = int(input())

def count_divisor(n):

    ans = 0

    i=1
    while i*i <= n:
        syou, amari = divmod(n,i)
        #print(syou, amari)
        if(amari == 0):
            ans += 1
            if( syou != i):
                ans += 1
        i+=1
    return ans

ans = 0
for i in range(1, N+1):
    ans += i*count_divisor(i)

print(ans)


#172D
#Sum of Divisors

N=int(input())
ans=0
for k in range(N):
    a=0
    for i in range(k+1):
        if (k+1)%(i+1)==0:
            a+=1
    ans+=(k+1)*a
print(ans)


def solve(n):
    ans=0
    for d in range(1,n+1):
        c=n//d
        ans+=(c+1)*c//2*d
    return ans

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


def divi(n):
    if n in prime: return 2
    sm=1
    for x in prime:
        token=0
        while n%x==0:
            n=n//x
            token+=1
        if token : sm*=(token+1)
        if n==1 : break
    return sm

n=int(input())
lst=[True for i in range(n+1)]
lst[0]=False
lst[1]=False

for i in range(2,n+1):
    if lst[i] :
        j=2*i
        while j<=n:
            lst[j]=False
            j+=i
prime=[i for i in range(n+1) if lst[i]]

sm=1
for i in range(2,n+1):
    sm+=i*divi(i)
print(sm)


n=int(input())

def m_div(n):
    ans=0
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            ans+=1
            if i != n // i:
                ans+=1

    return ans

ans=0
for i in range(1,n+1):
    ans+=(i*m_div(i))

print(ans)


t=0
n=int(input())
for i in range(1,n+1):
  k=n//i
  s=k*(k+1)//2
  t+=s*i
print(t)


def eratosthenes(A):
    data = A
    for d in data:
        for i in data:
            if i!=d and i%d == 0:
                data.remove(i)
    return data

N=int(input())
A=list(map(int,input().split()))
ans=list(eratosthenes(A))
print(len(ans))

Score : 400 points

Problem Statement

Given is a number sequence A of length N.

Find the number of integers i \left(1 \leq i \leq N\right) with the following property:

For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the answer.

Sample Input 1

5
24 11 8 3 16

Sample Output 1

3

The integers with the property are 2, 3, and 4.

Sample Input 2

4
5 5 5 5

Sample Output 2

0

Note that there can be multiple equal numbers.

Sample Input 3

10
33 18 45 28 8 19 89 86 2 4

Sample Output 3

5


def main():
    s = [input() for l in range(2)]
    N, A = int(s[0]), [int(x) for x in s[1].split()]
    results = []

    for i in range(0, (N), 1):
        flag = 0
        for j in range(0, (N), 1):
            if i == j:
                pass
            else:
                if A[i] % A[j] == 0:
                    flag = 1
                    break
                else:
                    pass
        if flag == 1:
            results.append(0)
        else:
            results.append(1)
    cnt = 0
    for x in results:
        if x == 1:
            cnt += 1
    print(cnt)

if __name__ == '__main__':
    main()


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

count_loop_num=0
for i in range(N):
    count_loop=True
    for j in range(N):
        if A[i]%A[j]==0 and i!=j:
            count_loop=False
            break
    if count_loop==True:
        count_loop_num+=1
print(count_loop_num)


from collections import defaultdict

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

def divisor(n):
    div_list = set()
    limit = int(n**0.5) + 1
    for div in range(1, limit):
        if n % div == 0:
            div2 = n // div
            div_list.add(div)
            div_list.add(div2)

    return list(div_list)

A_dict = defaultdict(int)
for a in A:
    A_dict[a] += 1

ans = n
for a in A:
    A_dict[a] -= 1
    divs = divisor(a)
    for div in divs:
        if A_dict[div] >= 1:
            ans -= 1
            break

    A_dict[a] += 1

print(ans)


import math
#import sys
#input = sys.stdin.readline

def MakeDivisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

def AddV2(v,w):
    return [v[0]+w[0],v[1]+w[1]]

dir4 = [[1,0],[0,1],[-1,0],[0,-1]]

def clamp(x,y,z):
    return max(y,min(z,x))

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

#
def Zaatsu(a):
    a.sort()
    now = a[0][0]
    od = 0
    for i in range(n):
        if(now==a[i][0]):
            a[i][0]=od
        else:
            now = a[i][0]
            od+=1
            a[i][0] = od

    a.sort(key = lambda x : x[1])
    return a

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

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

p = 2
N = 10 ** 6 + 2
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) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

def rl(x):
    return range(len(x))

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

#################################################
#################################################
#################################################
#################################################

#31-

n = int(input())

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

a.sort()

#print(a)
li = [0 for i in range(10**6+1)]
ans = 0
co = 0

taboo = [0]*n

if a[0]==2:
    for i in range(1,n):
        if(a[i]%2==0):
            taboo[i]=1
if a[0]==3:
    for i in range(1,n):
        if(a[i]%3==0):
            taboo[i]=1
if a[1]==3:
    for i in range(2,n):
        if(a[i]%3==0):
            taboo[i]=1
if a[0]==5:
    for i in range(1,n):
        if(a[i]%5==0):
            taboo[i]=1
if a[1]==5:
    for i in range(2,n):
        if(a[i]%5==0):
            taboo[i]=1
#print(a)
#print(taboo)

for i in a:
    #print(i)
    if(taboo[co]==1):
        co+=1
        continue
    t = MakeDivisors(i)
    #print(li[:30])
    #print(i,t,ans)
    ok=1

    if(co!=0):
        if(a[co-1]==i):
            ok=0
    if(co!=n-1):
        if(a[co+1]==i):
            ok=0
    for j in t:
        if(li[j]==1):
            ok=0
    ans+=ok
    #print(i,ok,ans)
    li[i]=1
    co+=1
print(ans)


n, *a = map(int, open(0).read().split())
a.sort()
am = a[-1] + 1
dp = [True] * am
ans = 0
dup = set()
for x in a:
    d = dp[x]
    if d:
        ans += 1
        for i in range(x, am, x):
            dp[i] = False
        dp[x] = None
    elif d == None:
        dup.add(x)

print(ans - len(dup))


n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
dp = [1 for i in range(10**6+10)]
for i in range(n):
    if dp[a[i]] == 1:
        dp[a[i]] = 2
        for j in range(2*a[i], 10**6+10, a[i]):
            dp[j] = 0
    elif dp[a[i]] == 2:
        dp[a[i]] = 0
res = 0
for i in range(n):
    if dp[a[i]] == 2:
        res += 1
print(res)


#D
N = int(input())
A = list(map(int,input().split()))
A.sort(reverse=True)
count = 0
K = sorted(A,reverse = True)
for p in range(N):
    if len(A) == 0:
        break
    else:
        pass
    i = A[0]
    for j in A[1:]:
        if i%j == 0:
            count = count-1
            break
        else:
            pass
    A = [x for x in A if x != i]
    count = count+1
print(count)


n=int(input())
a=list(map(int,input().split()))
ok = [1]*n
a.sort()

for i in range(n):
    if ok[i]==1:
        for g in range(i+1,n):
            if a[g]%a[i]==0:
                ok[g]=0
if sum(ok)==1:
    print(0)
else:
    print(sum(ok))


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

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

    A_dict = {}
    for a in A:
        if a in A_dict.keys():
            A_dict[a] += 1
        else:
            A_dict[a] = 1

    black_list = set()
    ans = 0
    for a in sorted(A_dict.keys()):
        for b in black_list:
            if a % b == 0:
                break
        else:
            if A_dict[a] == 1:
                ans += 1
            black_list.add(a)
    print(ans)
main()


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

import math
import bisect

ans = [True] * N
A.sort()

A_cnt = {}
for i, Ai in enumerate(A):
    A_cnt.setdefault(str(Ai), 0)
    A_cnt[str(Ai)] += 1

for i, Ai in enumerate(A):
    if A_cnt[str(Ai)] > 1: ans[i] = False

inA = [False] * (10 ** 6 + 1)
for i, Ai in enumerate(A):
    inA[Ai] = True

for i, Ai in enumerate(A):
    for p in range(1, int(math.sqrt(Ai)) + 1):
        if Ai % p == 0:
            if inA[p]:
                ans[i] = False
                break
            if p == 1: continue
            elif inA[Ai // p]:
                ans[i] = False
                break

ans = ans.count(True)
print(ans)


#!/usr/bin/env python3
import sys
from collections import defaultdict

def get_prime_factors(n):
    dd = defaultdict(lambda: 0)
    if n > 1:
        i = 2
        while i * i <= n:
            if n % i == 0:
                dd[i] += 1
                n /= i
                i = 2
            else:
                i += 1
        dd[n] += 1
    return dd

def solve(N: int, A: "List[int]"):
    A = sorted(list(set(A)))
    if len(A) == 1:
        print(0)
        return

    count = 0

    dd = defaultdict(lambda: (0, 10**6+1))

    for a in A:
        d = get_prime_factors(a)

        flag = True
        for prime, value in d.items():
            dd_val, dd_mn = dd[prime]

            if a % dd_mn==0:
                flag = False
                break

            dd[prime] = (dd_val + value, min(dd_mn, a))

        if flag:
            count+= 1

    print(count)
    return

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()


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

k = 0
b = 0
for l in range(n):
    if a[l] == 1:
        b = b + 1

if b == 0:
    for i in range(n):
        for j in range(n):
            if a[j] != 0:
                if i != j:
                    if a[i] % a[j] == 0:
                        a[i] = 0
                        break
            if j == n-1:
                k = k + 1
    print(k)
elif b == 1:
    print('1')
else:
    print('0')


from numba import njit, int32, int64
from numba.typed import Dict

@njit
def solve(B):
    A = Dict.empty(
        key_type=int64,
        value_type=int64)
    for b in B:
      A[b] = A.get(b, 0) + 1
    r = 0
    if 1 in A:
        if A[1] == 1:
            return 1
        return 0
    for a, v in A.items():
        if v > 1:
            continue
        i = 2
        while i * i <= a:
            if a % i == 0:
                if i in A:
                    break
                if a // i in A:
                    break
            i += 1
        else:
            r += 1
    return r

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

print(main())


n=int(input())
a=list(map(int,input().split()))
b=[0]*(2*10**6)
c=0
for i in a:
    b[i]+=1
for i in range(10**6):
    c+=1 if b[i]==1 else 0
    if b[i]==0:
        continue
    for j in range(1,10**6+10000):
        if i*j>=10**6+10000:
            break
        b[i*j]=0
print(c)


import sympy

n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
count = 0

for i in range(n-1):
    for j in range(1,n-i):
        if a[i]%a[i+j] == 0:
            count += 1
            break

print(n-count)


n=int(input())
a=list(map(int,input().split()))
M=max(a)
num=[0]*M
for x in a:
	num[x-1]+=1
for i in range(M):
	if num[i]>=2:
		num[i]=0
ret=[1]*M
for i in range(M):
	if num[i]:
		j=i+i+1
		while j<M:
			ret[j]=0
			j+=i+1
	else:
		ret[i]=0
print(ret.count(1))


N=int(input())
Alist=list(map(int,input().split()))
ans=0
for i in range(N):

    for j in range(N):
        if i==j:
            continue
        if Alist[i]%Alist[j]==int(0):
            #print(Alist[i])
            ans=ans+1
            break

print(N-ans)


import numpy as np

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

def main():
    ans = 0
    for i, ai in enumerate(A):
        ans += ((ai % np.delete(A, i)).min() != 0)
    print(ans)

main()


import sys
input = sys.stdin.readline

def slove():
    n = int(input())
    A = list(map(int,input().split()))
    A = sorted(A)
    ans = 0
    flag = False
    while len(A) != 0:
        ans += 1
        tmp = A.pop(0)
        #print(A)
        k = 0
        for i in range(len(A)):
            if A[i-k] % tmp == 0:
                if A[i-k] == tmp:
                    flag = True
                A.remove(A[i-k])
                k += 1
        if flag:
            ans -= 1
            flag = False

    print(ans)

if __name__ == "__main__":
    slove()


import numpy as np
n=int(input())
a = list(map(int,input().split()))
anp = np.array(a)
a_sort_idx = np.argsort(anp)
que = []
flg = []
for i in a_sort_idx:
    if len(que) == 0:
        que.append(a[i])
        flg.append(0)
    else:
        for j in range(len(que)):
            if a[i] == que[j]:
                flg[j] = 1
                break
            if a[i] % que[j] == 0:
                break
        else:
            que.append(a[i])
            flg.append(0)

print(len(que)-sum(flg))


from bisect import bisect_left
n = int(input())
a = [int(i) for i in input().split()]
from collections import Counter
a_cnt = Counter(a)
a = []
for k, v in a_cnt.items():
    if v == 1:
        a.append(k)
a.sort()
ans = 0
while a:
    min_a = a[0]
    b = []
    ans += 1
    index = bisect_left(a, min_a * 2)
    m_i = max(index, 1)
    for i in range(m_i, len(a)):
        if a[i] % min_a != 0:
            b.append(a[i])
    a = a[1:index] + b
print(ans)


input();ans,limit=1,10**18
for i in map(int,input().split()):
  ans*=i
print([ans,-1][ans>limit])

Score : 200 points

Problem Statement

Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.

However, if the result exceeds 10^{18}, print -1 instead.

Constraints

2 \leq N \leq 10^5

0 \leq A_i \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}.

Sample Input 1

2
1000000000 1000000000

Sample Output 1

1000000000000000000

We have 1000000000 \times 1000000000 = 1000000000000000000.

Sample Input 2

3
101 9901 999999000001

Sample Output 2

-1

We have 101 \times 9901 \times 999999000001 = 1000000000000000001, which exceeds 10^{18}, so we should print -1 instead.

Sample Input 3

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

Sample Output 3

0


n=int(input())
a=list(map(int ,input().split()))
myans=1
for i in range(0,n):
    myans*=a[i]
if(myans>10**18):
    print(-1)
else:
    print(myans)


n=int(input())
a=list(map(int,input().split()))
ans=1
for i in range(n):
    ans=ans*a[i]
if len(ans)>19:
    print("-1")
    exit()
print(ans)


N=int(input())
L = [int(i) for i in input().split()]
ANS=1
for i in range(len(L)):
    ANS=ANS*L[i]
if ANS>=100000000000000000:
    print(-1)
else:
    print(ANS)


s=input()
a=input()
a=a.split()
c=1
for x in a:
  c=c*int(x)
if c > 10**18:
  print("-1")
else:
  print(c)


import sys

N=int(input())
#print(N)
A=input().split()
A_int = [int(s) for s in A]
#print(A_int)
ans=1
for i in range(N):
  ans=ans*A_int[i]
  if(ans>10**18):
    ans=-1
    break

print(ans)


_LIMIT = 10**18

N = int(input())
result = 1
for i in range(N):
  ai = int(input())
  result *= ai

if result > _LIMIT: result = -1

print(result)


n = input()
s = 1
for i  in input().split():
  s = s * int(i)

if s > 1e+18:
  print(-1)
else:
  print(s)


import sys
input = sys.stdin.readline
import functools

def multiplication2(n,a):
    #acc = functools.reduce(lambda x,y:x*y, a)
    acc = 1
    for s in a:
        acc = acc*s
        if 10**18 < acc:
            acc = -1
            break
    return acc

if __name__ == "__main__":
    n = int(input())
    a = list(map(int,input().split()))
    print(multiplication2(n,a))


import numpy as np
n = int(input())
nums = map(int, input().split())
a = np.prod([i for i in list(nums)])
print(a if a<10**18 else -1)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
#from fractions import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
#vsInput()

n=Int()
a=array()
ans=1
if(0 in a):
    print(0)
    exit()
for i in a:
    ans*=i
    #print(ans)
    if(ans>10**18):
        ans=-1
        break
print(ans)


N = int(input())
A = list(map(int, input().split()))
tmp = 1
if 0 in A:
    print(0)
    exit()
for i in A:
    tmp *= i
    if tmp > 10**18:
        print(-1)
        exit()
    else:
        continue
print(tmp)


input()
s=1
for a in map(int,input().split()):
  if s>0:s*=a
  if s>1e18:s=-1
  if s==0:break
print(s)


def main():
    n = int(input())
    m = map(int, input().split())
    ans = 1
    for i in m:
        ans *= i
    print(ans) if ans <= 1000000000000000000 else print(-1)
if __name__ == "__main__":
    main()


n = int(input())
num_list = list(map(int,input().split()))
result = 1

for number in num_list:
    result = result * number

if result > 10 ** 18:
    result = -1

print(result)


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

ans = 1
flag = 1
flag2 = 0

for d in data:
  if d == 0:
    flag2 = 1

for d in data:
  ans = ans * d
  if ans > 1e18:
    flag = 0
    break

if(flag2):
  print(0)
elif(flag):
  print(ans)
else:
  print(-1)


N = int(input())
A = input().split()

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

if a>10**18:
  print(-1)
else:
  print(a)


import numpy as np
N = int(input())
A = list(input().split())
B = np.array(A,dtype='float64')
B = np.max(B)
if B>=2e18 :
    print("-1")
else:
    A=np.array(A,dtype='int64')
    ans=np.prod(A,dtype='int64')
    if ans >=np.int64(1e18) : flg = 1
    if ans<=np.int64(0)  : flg = 1
    if flg ==1:
        print(ans)
    else:
        print("-1")


def main():
    _ = input()
    a = sorted(list(map(int, input().split())), reverse=True)
    if a[-1] == 0:
        print(0)
        return
    x = 1
    m = 10 ** 18
    for i in a:
        if i < 2:
            continue
        x *= i
        if x > m:
            print(-1)
            return
    print(-1 if x > 10 ** 18 else x)

if __name__ == '__main__':
    main()


N = int(input())
A = [int(a) for a in input().split()]
s = 1
for a in A:
    s *= a
print(s if s <= 10 ** 18 else -1)


from sys import stdin
input = stdin.readline

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

cum = 1
over = False
for x in a:
    if x == 0:
        cum = 0
        break

    cum *= x
    if (cum > 1e18):
        over = True

print(-1) if (over and cum != 0) else print(cum)


N = int(input())
A = list(map(int, input().rstrip().rsplit()))
A_dict = {}

for val in A:
    A_dict[val] = A_dict.get(val, 0) + 1

limit = 10**18
ans = 1

if A_dict.get(0, 0) > 0:
    ans = 0
else:
    for val in A_dict:
        ans *= val ** A_dict[val]

        if ans > limit:
            ans = -1
            break

print(ans)


from operator import mul
from functools import reduce

n = int(input())
s = list(map(int, input().split()))
num = 1
for i in range(n):
  num = s[i-1] * num
if num > 10 ** 18:
  print(-1)
else:
  print(num)


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

ans = 1#np.prod(A)
for i in A:
  ans = ans * i
print(ans if ans <= 10**18 else -1)


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

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


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

l.sort(reverse = True)
ans = l[-1]
for i in range(n-1):
    ans *= l[i]
    if ans > 10**18:
      ans = -1
      break
    elif ans == 0:
      ans = 0
      break

print(ans)


N = int(input())
a = [int(x) for x in input().split()]

X = 1

for i in range(N):
    if a[i] == 0:
        X = 0
        break

if X != 0:
    if N > 70:
        X = -1
    else:
        for i in range(N):
            X = X * a[i]
        if X > 1000000000000000000:
            X = -1

print(X)


n = int(input())
k = 1
m = input()
m = m.split()
# m = list(m)
# print(m)
for i in range(n):
    # print(m[i])
    k = k*(int(m[i]))

if k > (10**18):
    print("-1")
else:
    print(k)


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

count = 1

if 0 in A:
    print(0)
    exit()

for i in A:
    count *= i
    if count > 10**18:
        print(-1)
        exit()

print(count)


n = int(input())
a = list(map(int,input().split()))
check = 10**18
ans = a[0]

for  i in range(1,n):
    ans = ans * a[i]
if ans <= check:
    print(ans)
else:
    print('-1')


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

answer = 1
for Ai in A:
    answer *= Ai

if answer >= 10 ** 18:
    answer = -1

print(answer)


n = int(input())
a = [int(e) for e in input().split()]
ans = 1
if 0 in a:
    print(0)
else:
for i in range(n):
    ans *= a[i]
    if ans > 10**18:
        print(-1)
        break
else:
    print(ans)


from sys import exit
N = int(input())
A = list(map(int,input().split()))
ans = 1
if 0 in A: print(0)
else:
    for i in A:
        ans *= i
    if ans > 10 ** 18:
        print(-1)
    else:
        print(ans)


n = int(input())
now = 1
fl = False
li = list(map(int,input().split()))
zero = False;
for i in li:
    if i == 0:
        zero = True
if zero == True:
    print(0)
else:
    for i in li:
        if fl == True:
            continue;
        now *= i
        if now > 1e18:
            print(-1)
            fl = True
    if fl == False:
        print(now)


import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

sys.setrecursionlimit(10**7)

ni = lambda: int(ns())
nin = lambda y: [ni() for _ in range(y)]
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda y: [na() for _ in range(y)]
nf = lambda: float(ns())
nfn = lambda y: [nf() for _ in range(y)]
nfa = lambda: list(map(float, stdin.readline().split()))
nfan = lambda y: [nfa() for _ in range(y)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda y: [ns() for _ in range(y)]
ncl = lambda y: [list(ns()) for _ in range(y)]
nas = lambda: stdin.readline().split()

n = ni()
a = na()
a.sort()

ans = 1
for i in range(n):
    if ans >= 1 and a[i] > 10 ** 18:
        print(-1)
        exit()
    ans *= a[i]
    if ans > 10 ** 18:
        print(-1)
        exit()

if ans > 10 ** 18:
    print(-1)
else:
    print(ans)


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

ans = 1

for i in a:
  ans = i *ans
  if ans > 1000000000000000000:
    print(-1)
    exit()

print(ans)


import sys

N = int(input())

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

result = 1
for i in range(N):
    result *= NList[i]

    if result > 10 ** 18:
        print('-1')
        sys.exit(1)

if result > 10 ** 18:
    print('-1')
    sys.exit(1)
else:
    print(result)


n = int(input())
a = list(map(int, input().split()))
ans = 1
ng = 0
if 0 in a:
    print(0)
    exit()
for i in a:
    ans *= i
    if ans > 10 ** 18:
        print(-1)
        exit()
print(ans)


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

ans = a[0]
if a.count(0) == 0:
    for i in range(1,n):
        ans *= a[i]
        if ans > 10**18:
            ans = -1
            break
print(ans)


N=int(input())
ans = 1
A = list(map(int,input().split(' ')))
if 0 in A:
    print(0)
    exit()
for i in A:
    ans *= i
    if ans > 10**18:
        print(-1)
        exit()
print(ans)


n = int(input())
alist = list(map(int, input().split(" ")))

result = 1
for i in alist:
  result *= i

if result > 10**18:
  print("-1")
else:
  print(result)


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

if 0 in a_lst:
    print(0)
    quit()
else:
    res = a_lst[0]
    for a in a_lst[1:]:
        res *= a
    if res > 10 ** 18:
        print(-1)
    else:
        print(res)


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

ans = a[0]
for i in range(1, len(a)):
    ans *= a[i]

if ans > 10**18:
    print("-1")
else:
    print(ans)


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

ans = 1
for i in range(n):
    ans *= a[i]

print(ans if ans < 1000000000000000000 else -1)


a, b = list(map(float,input().split()))

print(int(a * b))

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


import math

li = input().split()
a = int(li[0])
b = float(li[1])

print(math.floor(a*b))


import math

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


lst = [i for i in input().split()]
x = int(lst[0])
y = float(lst[1])
y *= 1000
y = int(y)
z = x * y
z = int(z)
z //= 1000
print(z)


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


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

from decimal import Decimal

Db = Decimal(B)
B100 = int(Db * 100)
ans = A * B100
print(int(ans // 100))


import math

num1= str(input()) #take input as a string
num2= str(input())

num1=str(num1)
num2=str(num2)

result= int(num1)*float(num2) #calculate the multiplication of inputs as integer and float
result= math.floor(result) #rounding down the output using floor function

print(result)


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


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


a,b=[i for i in input().split()]
a=int(a)
b=float(b)
print(int(a*b))


import math

pair = input().split()
num1 = int(pair[0])
num2 = int(float(pair[1])*100)
result = num1 * num2
print(math.floor(result/100))


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

print(int(A*B))


A, B = input().split()

A = int(A)
B = float(B)

B2 = int(B * 100)

ans = A * B2 / 100
ans = int(ans)
print(ans)


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


import math
a,b=input().split()
a=int(a)
b= int(b.replace(".",""))
print(a*b//100)


import math
a,b=input().split()
a=int(a)
b=int(b.replace(".",""))
print(a*b//100)


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


from decimal import Decimal

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

print(int(A * B))


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

ha = input()
kita = ha.split(" ")
a = int(kita[0])
b = int(kita[1].replace(".",""))
m = a*b
m = str(m)

c = kita[1].split(".")
try:
    co = len(c[1])
except:
    co = 0
print(m)
if a==0 or float(kita[1]) < 1:
    print("0")
elif co > 0:
    print(m[:-1*co])
else:
    print(m)


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


import math
a,b=input().split()
a=int(a)
b=float(b)
n=(a*b*100)/100
print(math.floor(n))


from decimal import Decimal
a,b = input().split()
c = int(a)*Decimal(b)
print(int(c))


import sys
import math
def input():
    return sys.stdin.readline().strip()

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

main()


A = list(map(float, input().split()))
print(int(A[0] * A[1]))


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


a, b = map(float, input().split())
b = float(b)*1000
b = int(b)
c = int(a)*b//1000

print (int(c))


A, B = input().split()
A = int(A)
B = float(B)
B = int(B * 1000)
C = A * B
C //= 100
print(C)


import decimal
# N = int(input())
A, B = [decimal.Decimal(i) for i in input().split()]
print(int(A*B))


a,b=map(str,input().split())
a=int(a)
b=float(b)
print(int(a*int(100*b+0.5)//100))


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


import math
X = input().split(" ")
A = int(X[0])
B = float(X[1])
ab = math.floor(A*B)
print(str(ab))


a, b = map(float, input().split())
times = 0
a = int(a)
b = int(100 * b // 1)
times = a * b
new_times = times / 100
print(new_times)


import math

A, B = [float(x) for x in input().split(" ")]
A = int(A)
print(math.floor(A * B))