S=input()
N=len(S)
left=0
right=0
ans=0
for left in range(N):
    while(right<N and (S[right] in ["A","C","G","T"])):
        right+=1
        ans=max(ans,right-left)
    if left==right:
        right+=1
print(ans)

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


s=input()
ans=0
cur=0
ACGT=set("A","C","G","T")
for ss in s:
  if ss in ACGT:
    cur+=1
  else:
    ans=max(cur,ans)
    cur=0
print(max(ans,cur))

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

Submitted source-code file size, in bytes.

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

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


cho,N = map(int,input().split())
moji = str(input())
moji_dict = []
flg = 0
##計算量は10**5
for i in range(cho):
    if flg == 1:
        flg = 0
    elif i != cho and moji[i] == "A" and moji[i+1] =="C":
        moji_dict.append(i + 1)
        flg = 1
##計算量は10**3　* 10 ** 5
for j in range(N):
    s,g = map(int,input().split())
    print(len([k for k in moji_dict if k >= s and k < g]))

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

li = []

for i in range(n-1):
    if s[i:i+2] == "AC":
        li.append(i)

for i in range(q):
    ans = 0
    a,b = map(int, input().split())
    data1 = list(filter(lambda x: a-1 <= x <=b-2, li))
    print(len(data1))


N,Q=map(int,input().split())
S=input()
l=[0]*Q
r=[0]*Q
for i in range(Q):
  l[i],r[i]=map(int,input().split())
counter=[0]*N
for i in range(len(S)-1):
  if S[i]=="A":
    counter[i]=(S[i+1]=="C")
  else:counter[i]=0
for j in range(Q):
  print(sum(counter[l[j]-1:r[j]-1]))


Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo 10^9+7.


def extgcd(a,b):
    r = [1,0,a]
    w = [0,1,b]
    while w[2]!=1:
        q = r[2]//w[2]
        r2 = w
        w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]]
        r = r2
        w = w2
        #[x,y]
        return [w[0],w[1]]

# aの逆元(mod m)を求める。(aとmは互いに素であることが前提)
def mod_inv(a,m):
    x = extgcd(a,m)[0]
    return (m+x%m)%m

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

ans=0
log=[0]*26
mod=10**9+7
for item in S:
    item=ord(item)-97
    if log[item]==0:
        log[item]+=1
        ans+=ans+1
    else:
        ans+=ans//2+1

print(ans)

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


import itertools
n = input()
N = int(n[0])

st = input()
S = list(st)

count = 0
for i, _ in enumerate(S, 1):
    for j in itertools.combinations(S, r=i):  # rには1、2、3と渡される
        seq = list(j)
        if len(seq) == len(set(seq)):
            count += 1
print(count)


H,W = map(int,input().split())
h,w = map(int,input().split())
allnum = H*W
delnum = h*W + w*H
addnum = h*w
print(allnum - delnum + addnum)

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


n,m,c=map(int, input().split())
b=list(map(int, input().split()))
tmp=0
cnt=0
a_i=[]
for _ in range(n):
    a=list(map(int, input().split()))
    tmp=0
    for i in range(m):

        tmp+=int(a[i])*int(b[i])

    if tmp+c>0:
        cnt+=1

print(cnt)

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


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

count = 0

for i in range(n):
  a = list(map(int, input().split()))
  sum = 0
  for j, xj in enumerate(a):
    sum += a[j] * b[j]

  if sum + c > 0:
    count += 1

print(count)


def solve(n, m, c, b_list, a_matrix):
    ans = 0
    for i in range(n):
        val = c
        for j in range(m):
            val += b_list[j] * a_matrix[i][j]
        if val > 0:
            ans += 1
    print(ans)

n, m, c = map(int, input().split())
b_list = list(map(int, input().split()))
a_matrix = []

for i in range(n):
    a_matrix.append(list(map(int, input().split())))

solve(n, m, c, b_list, a_matrix)


N, M, C = list(map(int, input().split()))
B = list(map(int, input().split()))
A = [list(map(int, input().split())) for i in range(N)]

Ans = 0
for i in range(N):
  t = C
  for j in range(M):
    t += A[i][j] * B[j]
  if t > 0:
    Ans += 1

print(Ans)


def energy_drink_collector(n,m,dic):
    count = 0
    v = 0
    stores = sorted(dic.keys())

    for i in range(n):
        c = stores[i]
        s = dic[c]
        v += s

        if v >= m:
            _s = s - (v - m)
            count += c * _s
            break
        else:
            count += c * s

    return count

if __name__ == '__main__':
    n,m = map(int,raw_input().split())
    a = [0]*n
    b = [0]*n
    dic = {}
    for i in range(n):
        a[i],b[i] = map(int,raw_input().split())
        dic[a[i]] = 0

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

    print energy_drink_collector(n,m,dic)

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


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

for i in range(1, a*b+1):
    if a % i == 0 and b % i == 0:
        ls.append(-i)

ls.sort()
print(-ls[k-1])

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


a, b, k = map(int, input().split())
c = []
if a < b:
    for i in range(a, 0, -1):
        if a % i == 0 and b % i == 0:
            c.append(i)
else:
    for i in range(b, 0, -1):
        if a % i == 0 and b % i == 0:
            c.append(i)

print(c[k-1])


a,b,k=map(int, input().split())
cnt=0
for i in range(1,max(a,b)+1):
    if a%i==0 and b%i==0:
        cnt+=1
        if cnt==k:
            print(i)
if cnt<k:
  print(1/0)


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

m = max(a,b)
c = 0;

for i in range(m+1,1,-1):
  if (a%i==0) and (b%i==0):
    c += 1
  if c == k:
    print(i)
    break


mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))

def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)

def solve():
    N, M = iip(False)

    AB = iipt(M)
    AB.reverse()
    uf = UfTree(N)

    benlist = [0]

    cur = 0
    for a, b in AB:
        a -= 1
        b -= 1
        c1 = uf.size(a)
        c2 = uf.size(b)
        uf.unite(a, b)
        if c2 != uf.size(a):
            cur += c1*c2
        benlist.append(cur)

    t = benlist.pop()
    benlist.reverse()
    #print(benlist)

    ans = [t - i for i in benlist]

    split_print_enter(ans)

#####################################################ライブラリ集ここから

def kiriage_warizan(a, b):
    return -(-a//b)

def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=False, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret

def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret

def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])

def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d

def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]

def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))

def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]

def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")

def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)

def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))

def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))

def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret

def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret

def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)

def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_

def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r

def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r

class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
# 同一の集合の判定
def same(x, y):
    if find(x) == find(y):
        return True
    else:
        return False
# 集合の併合
def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    if par[x] > par[y]:
        x, y = y, x
    par[x] += par[y]
    par[y] = x

# 集合の数
def uCnt(x):
    return -par[find(x)]

N, M = map(int, input().split())
par = [-1 for i in range(N)]
tmp = ((N * (N - 1)) // 2)
ab = [list(map(int, input().split())) for _ in range(M)]
ans = [0] * M
ans[M - 1] = tmp
index = M - 1
for i in range(M - 1, 1, -1):
    fa = find(ab[i][0] - 1)
    fb = find(ab[i][1] - 1)
    if fa != ab:
        ans[index - 1] = ans[index] - uCnt(fa) * uCnt(fb)
        unite(ab[i][0] - 1, ab[i][1] - 1)
    index -= 1

for i in ans:
    print(i)


import array
import time

class UnionFind :
    def __init__(self, n):
        self.par = array.array('i', range(n))
        self.sizes = array.array('i', [1]*n)

    def root(self, i):
        if i == self.par[i]:
            return i
        else:
            r = self.root(self.par[i])
            self.par[i] = r
            return r

    def unite(self, x, y):
        try:
            rx = self.root(x)
            ry = self.root(y)
        except:
            return
        if rx != ry:
            srx = self.sized(x)
            sry = self.sized(y)
            self.par[rx] = ry
            self.sizes[ry] = srx + sry

    def same(self, x, y) :
        try:
            px = self.root(x)
            py = self.root(y)
        except:
            return False
        if px == py :
            return True
        else:
            return False

    def sized(self, x):
        return self.sizes[self.root(x)]

    def debug(self):
        print(self.par)
        print(self.sizes)

def calsc(x):
    return (x * (x-1)) // 2

def main():
    (n,m) = map(int, input().split())
    ab = []
    for _ in range(m):
        (p,q) = map(int, input().split())
        ab.append((p-1,q-1))
    uf = UnionFind(n)
    res = []
    prev = 0
    while len(ab) > 0:
        (a,b) = ab.pop()
        #uf.debug()
        res.append(prev)
        score = prev
        if not uf.same(a,b):
            score = score - calsc(uf.sized(a)) - calsc(uf.sized(b))
            uf.unite(a,b)
            score = score + calsc(uf.sized(a))
        prev = score
    for i in range(len(res)):
        res[i] = calsc(n) - res[i]
    res = res[::-1]
    for r in res:
        print(r)

if __name__ == '__main__':
    main()


n,m = map(int,input().split())
ab = [[int(i) for i in input().split()]for j in range(m)][1:]
ans = [0]*(m-1)+[int(n*(n-1)/2)]
l = [i for i in range(1,n+1)]
s = {i:1 for i in range(1,n+1)}

def serch_l(num):
  if l[num]==num+1:
    return l[num]
  else:
    leader = serch_l(l[num]-1)
    l[num]=leader
    return leader

for k,i in enumerate(ab[::-1]):
  k = m-1-k

  if l[i[0]-1] == l[i[1]-1]:
    ans[k-1]=ans[k]
  else:
    l_a,l_b = serch_l(i[0]-1),serch_l(i[1]-1)
    s_a,s_b = s[l_a],s[l_b]

    if s_a > s_b:
      (s_a,s_b) = (s_b,s_a)
    c = s_a*s_b
    s[l_b]+=s_a
    s[l_a]=0
    l[l_a-1]=l_b
    ans[k-1]=ans[k]-c
for i in ans:
  print(i)


import sys
input = sys.stdin.readline
s=input()
month = s[5]+s[6]
day = s[8]+s[9]
if month[0] == '0':
    month = s[6]
if day[0] == '0':
    day = s[9]

if int(month) <= 4:
    print('Heisei')
else:
    print("TBD")

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


S = list(map(int, input().split('/')))

if S[0] < 2019:
    print('Heisei')
elif S[0] == 2019:
    if S[1] < 4:
        print('Heisei')
    elif S[1] == 4:
        if S[2] <= 30:
            print('Heisei')
    else:
        print('TBD')


n = int(input())

ans = 0
for _ in range(n):
	x, u = input().split()
	if u == 'JPY':
		ans += int(x)
	else:
		ans += float(x) * 380000

print(ans)

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


n=int(input())
for i in range(n):
  m, curr=input().split()
  m=float(m)
  curr=str(curr)
  a=0
  if curr=='BTC':
    a=a+m*380000
  else:
    a=a+m
print(a)


N=int(input())
xu=[list(input().split()) for _ in range(N)]
# print(xu)

ans=0
for i in range(N):
	if xu[i][1]=='JPY':
		ans+=float(xu[i][0])
	else:
		ans+=float(xu[i][0])*380000.0
print(ans)


inf = 1 << 60
N,A,B,C=map(int, input().split())
l = []
for i in range(N):
    l.append(int(input()))

def dfs(n, a, b, c):
    if n == N:
        if min(a,b,c) == 0:
            return inf
        return abs(A-a)+abs(B-b)+abs(C-c)-30

    a1 = dfs(n+1, a, b, c)
    a2 = dfs(n+1, a + l[n], b, c) + 10
    a3 = dfs(n+1, a, b + l[n], c) + 10
    a4 = dfs(n+1, a, b, c + l[n]) + 10
    return min(a1, a2, a3, a4)

ans = dfs(0, 0, 0, 0)
print(ans)

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


from bisect import bisect_left
A, B, Q = map(int, input().split())
S = sorted([int(input()) for i in range(A)])
T = sorted([int(input()) for i in range(B)])
X = [int(input()) for i in range(Q)]

for x in X:
  s_index = bisect_left(S, x)
  s_left = S[s_index - 1] if s_index > 0 else None
  s_right = S[s_index] if s_index < A else None
  t_index = bisect_left(T, x)
  t_left = T[t_index - 1] if t_index > 0 else None
  t_right = T[t_index] if t_index < B else None

  ans = float("inf")

  sl = [s_left, s_right]
  tl = [t_left, t_right]

  for s in sl:
    if not s: continue
    for t in tl:
      if not t: continue
      ans = min(ans, abs(x-s) + abs(t-s))

  for t in tl:
    if not t: continue
    for s in sl:
      if not s: continue
      ans = min(ans, abs(x-t) + abs(t-s))

  print(ans)

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

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

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


# %2
class AvlTree:  # std::set
    def __init__(self, values=None, sorted_=False):
        if values is None:
            self.left = [-1]
            self.right = [-1]
            self.values = [-float("inf")]
            self.diff = [0]  # left - right
            self.size_l = [0]
        else:
            n = len(values)
            self.left = [-1] * (n+1)
            self.right = [-1] * (n+1)
            self.values = [-float("inf")] + values
            self.diff = [0] * (n+1)  # left - right
            self.size_l = [0] * (n+1)
            if not sorted_:
                values.sort()

            st = [[1, n+1, 0]]
            while len(st) > 0:
                l, r, idx_par = st.pop()  # 半開区間
                c = (l+r) % 2
                if self.values[c] < self.values[idx_par]:
                    self.left[idx_par] = c
                else:
                    self.right[idx_par] = c
                siz = r - l
                if siz & -siz == siz and siz != 1:  # 2冪だったら
                    self.diff[c] = 1
                siz_l = c - l
                self.size_l[c] = siz_l
                if siz_l > 0:
                    st.append([l, c, c])
                    c1 = c + 1
                    if c1 < r:  # 左にノードがなければ右には必ず無いので
                        st.append([c1, r, c])

    # def print(self):
    #     print(f"left  ={self.left}")
    #     print(f"right ={self.right}")
    #     print(f"values={self.values}")
    #     print(f"diff  ={self.diff}")
    #     print(f"dixr_l={self.size_l}")

    def rotate_right(self, idx_par, lr):  # lr: 親の左なら 0
        idx = self.left[idx_par] if lr==0 else self.right[idx_par]
        idx_l = self.left[idx]
        assert idx_l != -1  # 左の子が存在する

        # 部分木の大きさの計算
        self.size_l[idx] -= self.size_l[idx_l] + 1

        # 高さの計算
        a = self.diff[idx]
        b = self.diff[idx_l]  # 左の子の高さの差
        if b >= 0:
            na = a - 1 - b
            if na >= 0:
                nb = b - 1
            else:
                nb = a - 2
        else:
            na = a - 1
            if na >= 0:
                nb = b - 1
            else:
                nb = a + b - 2
        self.diff[idx] = na
        self.diff[idx_l] = nb

        # 回転
        self.left[idx] = self.right[idx_l]
        self.right[idx_l] = idx
        if lr==0:
            self.left[idx_par] = idx_l
        else:
            self.right[idx_par] = idx_l

    def rotate_left(self, idx_par, lr):  # lr: 親の左なら 0
        idx = self.left[idx_par] if lr==0 else self.right[idx_par]
        idx_r = self.right[idx]
        assert idx_r != -1  # 右の子が存在する

        # 部分木の大きさの計算
        self.size_l[idx_r] += self.size_l[idx] + 1

        # 高さの計算
        a = self.diff[idx]
        b = self.diff[idx_r]  # 右の子の高さの差
        if b <= 0:
            na = a + 1 - b
            if na <= 0:
                nb = b + 1
            else:
                nb = a + 2
        else:
            na = a + 1
            if na <= 0:
                nb = b + 1
            else:
                nb = a + b + 2
        self.diff[idx] = na
        self.diff[idx_r] = nb

        # 回転
        self.right[idx] = self.left[idx_r]
        self.left[idx_r] = idx
        if lr == 0:
            self.left[idx_par] = idx_r
        else:
            self.right[idx_par] = idx_r

    def add(self, x):  # insert
        idx = 0
        path = []
        path_left = []
        while idx != -1:
            path.append(idx)
            value = self.values[idx]
            if x == value:
                return  # 重複を許さない
            elif x < value:
                path_left.append(idx)
                idx = self.left[idx]
            else:
                idx = self.right[idx]

        if x < value:
            self.left[path[-1]] = len(self.values)
        else:
            self.right[path[-1]] = len(self.values)
        self.left.append(-1)
        self.right.append(-1)
        self.values.append(x)
        self.diff.append(0)
        self.size_l.append(0)

        for idx_ in path_left:
            self.size_l[idx_] += 1

        self.diff[path[-1]] += 1 if x < value else -1
        for idx, idx_par in zip(path[:0:-1], path[-2::-1]):
            diff = self.diff[idx]
            if diff == 0:
                return
            elif diff == 2:  # 右回転
                idx_l = self.left[idx]  # 左の子
                if self.diff[idx_l] == -1:  # 左右のパターン
                    self.rotate_left(idx, 0)
                self.rotate_right(idx_par, self.right[idx_par]==idx)
                return
            elif diff == -2:  # 左回転
                idx_r = self.right[idx]  # 右の子
                if self.diff[idx_r] == 1:  # 右左のパターン
                    self.rotate_right(idx, 1)
                self.rotate_left(idx_par, self.right[idx_par]==idx)
                return
            else:
                self.diff[idx_par] += 1 if self.left[idx_par]==idx else -1

    def remove(self):  # erase
        raise NotImplementedError

    def __contains__(self, x):  # count
        raise NotImplementedError

    def bisect_left(self, x):  # lower_bound
        idx = self.right[0]
        res = 0
        while idx != -1:
            value = self.values[idx]
            if value == x:
                return res + self.size_l[idx]
            elif value < x:
                res += self.size_l[idx] + 1
                idx = self.right[idx]
            else:
                idx = self.left[idx]
        return res

    def bisect_right(self):  # upper_bound
        raise NotImplementedError

from bisect import bisect_left
import sys
input = sys.stdin.readline
A, B, Q = map(int, input().split())

S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
avl_S = AvlTree(S, True)
avl_T = AvlTree(T, True)

def f(x):
    if 0 <= x and A - 1 >= x:
        return True
    return False
def g(x):
    if 0 <= x and B - 1 >= x:
        return True
    return False

for i in range(Q):
    x = int(input())
    p = avl_S.bisect_left(x)
    m = avl_T.bisect_left(x)

    res = []
    if f(p) and g(m):
        res.append(max(T[m], S[p]) - x)
    if f(p) and g(m - 1):
        res.append(min(S[p] - x, x - T[m - 1]) + S[p] - T[m - 1])
    if f(p - 1) and g(m):
        res.append(T[m] - S[p - 1] + min(T[m] - x, x - S[p - 1]))
    if f(p - 1) and g(m - 1):
        res.append(x - min(T[m - 1], S[p - 1]))
    print(min(res))


n, m = map(int, input().split())
dic = {}

for i in range(m,1):
    dic[i] = 0

for _ in range(n):
    arr = list(map(int, input().split()))

    for item in arr[1:]:

        if item in dic:
            dic[item] += 1
        else:
            dic[item] = 1

ans = 0
for count in dic.values():
    if count == n:
        ans += 1

print(ans)

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


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

def gcd(x,y):
    if y > x:
        x,y = y,x
    if x%y == 0:
        return y
    else:
        return gcd(y,x%y)

from functools import reduce
ans = reduce(gcd,L)
print(ans)

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


def gcd(x,y):
  while y !=0:
    x,y = y, x%y
  return x

N = int(input())
ALL = sorted(list(map(int,input().split())))

while len(ALL) > 1:
  ALL.append(gcd(ALL[0],ALL[1]))
  del ALL[0]
  del ALL[0]

print(ALL[0])


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

def gozyo():
    global a
    for i in range(1,len(a)):
        a[i]%=a[0]
    a.sort()
    while a[0]==0:
        a.pop(0)

while len(a)>1:
    gozyo()
print(a[0])


n, k = map(int, input().split())
if 2 * k - 1 < n : print("Yes")
else : print("No")

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


a, b = map(int, input().split())
if a < b + 1:
    print("YES")
else:
    print("NO")


import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    K, A, B = MI()

    ans = 1
    if (B-A) <= 2:
        ans += K
    else:
        sa = A - ans
        K -= sa
        ans = A
        p, q = K // 2, K % 2
        ans += (B-A) * p + q
    print(ans)

if __name__ == '__main__':
    solve()

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


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

flag = True if sum(L[:-1]) > L[-1] else False

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

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''
N = int(input())
L = list(map(int, input().split()))

L.sort()
sum = 0

for i in range(0, N - 1):
	sum += L[i]

sum -= L[N - 1]
if sum > 0:
	print('Yes')
else:
	print('No')


n = int(input())

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

m = max(l)
s = sum(l) - m

if m < s:
    print("Yes")
else:
    print("No")


n,m = map(int,input().split())
lst = [int(i) for i in input().split()]
lst.sort()
dst = []

if n>=m:
    print(0)
    exit()

for i in range(1,m):
    dst.append(lst[i]-lst[i-1])
dst.sort()
ans = sum(dst[:-n+1])
print(ans)

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


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

if n >= m:
    print(0)
    exit()
xxx.sort()
ddd = [b - a for a, b in zip(xxx, xxx[1:])]
ddd.sort()
print(sum(ddd[:m - n]))


n,a,b=map(int,input().split())
x=a+b-n
if x>=0:
  x+=0
else:
  x=0

print(min(a,b),x)

Score : 100 points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the N respondents the following two questions:

Question 1: Are you subscribing to Newspaper X?

Question 2: Are you subscribing to Newspaper Y?

As the result, A respondents answered "yes" to Question 1, and B respondents answered "yes" to Question 2.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

1 \leq N \leq 100

0 \leq A \leq N

0 \leq B \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the 10 respondents, 3 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 3 and at least 0.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the 10 respondents, 7 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 5 and at least 2.

Sample Input 3

100 100 100

Sample Output 3

100 100


import sys
def input():
	return sys.stdin.buffer.readline()[:-1]
sys.setrecursionlimit(10 ** 6)

class UnionFind():
	def __init__(self, lis):
		self.table = [-1 for _ in range(len(lis))]
		self.size = [x for x in lis]

	def find(self, x):
		if self.table[x] < 0:
			return x
		else:
			self.table[x] = self.find(self.table[x])
			return self.table[x]

	def unite(self, x, y):
		s1 = self.find(x)
		s2 = self.find(y)
		if s1 != s2:
			if self.table[s1] > self.table[s2]:
				self.table[s2] = s1
				self.table[s1] -= 1
				self.size[s1] += self.size[s2]
				self.size[s2] = 0
			else:
				self.table[s1] = s2
				self.table[s2] -= 1
				self.size[s2] += self.size[s1]
				self.size[s1] = 0
		return

n, m = map(int, input().split())
x = list(map(int, input().split()))
adj = [[] for _ in range(n)]
e = []
for i in range(m):
	a, b, y = map(int, input().split())
	a, b = a-1, b-1
	e.append((y, a, b))

used = [False for _ in range(m)]
candidate = [False for _ in range(m)]
e.sort()
uf = UnionFind(x)
for i in range(m):
	y, a, b = e[i]
	adj[a].append((b, y, i))
	adj[b].append((a, y, i))
	uf.unite(a, b)
	if uf.size[uf.find(a)] >= y:
		candidate[i] = True

ans = 0
for i in range(m-1, -1, -1):
	if used[i]:
		continue
	if not candidate[i]:
		ans += 1
	else:
		used[i] = True
		y, a, b = e[i]
		stack = [a, b]
		while stack:
			l = stack.pop()
			for v, z, j in adj[l]:
				if used[j]:
					continue
				if z <= y:
					stack.append(v)
					used[j] = True

print(ans)

Score : 800 points

Problem Statement

There is a connected undirected graph with N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Also, each of these vertices and edges has a specified weight.
Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i.

We would like to remove zero or more edges so that the following condition is satisfied:

For each edge that is not removed, the sum of the weights of the vertices in the connected component containing that edge, is greater than or equal to the weight of that edge.

Find the minimum number of edges that need to be removed.

Constraints

1 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq X_i \leq 10^9

1 \leq A_i < B_i \leq N

1 \leq Y_i \leq 10^9

(A_i,B_i) \neq (A_j,B_j) (i \neq j)

The given graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_N
A_1 B_1 Y_1
A_2 B_2 Y_2
:
A_M B_M Y_M

Output

Find the minimum number of edges that need to be removed.

Sample Input 1

4 4
2 3 5 7
1 2 7
1 3 9
2 3 12
3 4 18

Sample Output 1

2

Assume that we removed Edge 3 and 4.
In this case, the connected component containing Edge 1 contains Vertex 1, 2 and 3, and the sum of the weights of these vertices is 2+3+5=10.
The weight of Edge 1 is 7, so the condition is satisfied for Edge 1.
Similarly, it can be seen that the condition is also satisfied for Edge 2.
Thus, a graph satisfying the condition can be obtained by removing two edges.

The condition cannot be satisfied by removing one or less edges, so the answer is 2.

Sample Input 2

6 10
4 4 1 1 1 7
3 5 19
2 5 20
4 5 8
1 6 16
2 3 9
3 6 16
3 4 1
2 6 20
2 4 19
1 2 9

Sample Output 2

4

Sample Input 3

10 9
81 16 73 7 2 61 86 38 90 28
6 8 725
3 10 12
1 4 558
4 9 615
5 6 942
8 9 918
2 7 720
4 7 292
7 10 414

Sample Output 3

8


# 2019-11-12 01:01:32(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np

def f(n):
    if n % 2 == 0:
        return n // 2
    else:
        return 3 * n + 1

def main():
    s = int(sys.stdin.readline().rstrip())

    a = []
    n = s
    m = 1
    while True:
        a.append(n)
        n = f(n)
        m +=1
        if n in a:
            print(m)
            break

if __name__ == "__main__":
    main()

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


s = int(input())

a = [s]

for i in range(1000000):
  n = a[-1]
  fn = 0

  if n % 2 == 0:
    fn = n / 2
  else:
    fn = 3*n + 1

  if fn in a:
    print(i+2)
    break
  else:
    a.append(fn)


s = list(map(int, input()))
for i in range(1000000):
    if s[i] % 2 == 0:
        next = s[i] / 2
    else:
        next = 3 * s[i] + 1
    if next in s:
        ans = i + 2
        print(ans)
        break
    s.append(next)


import heapq
from collections import defaultdict

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

D = defaultdict(int)
c = 1
hh = 0
for i in range(N):
	for j in range(M):
		if A[i] != B[j]:
			d = min(A[i], B[j])
			D[d] += 1
			hh += 1

ds = sorted(D.items())
X = []
for i in range(len(ds)):
	X += [ds[i][0]] * ds[i][1]

a = A[0]
for i in range(N - 1):
	if A[i + 1] == a:
		c = 0
		break
	a = A[i + 1]

b = B[0]
for i in range(M - 1):
	if B[i + 1] == b:
		c = 0
		break
	b = B[i + 1]

AA = []
BB = []
CC = []

for i in range(N):
	if A[i] in B:
		CC.append(A[i])
		B.remove(A[i])
	else:
		AA.append(A[i])

BB = B

xB = sorted(BB + CC)
xA = sorted(AA + CC)

for i in range(len(AA)):
	cc = 0
	for j in range(len(xB)):
		if xB[-1 - j] <= AA[i]:
			break
		else:
			cc += 1
	c = c * cc

for i in range(len(BB)):
	cc = 0
	for j in range(len(xA)):
		if xA[-1 - j] <= BB[i]:
			break
		else:
			cc += 1
	c = (c * cc) % 1000000007

if c != 0:
	if X != []:
		x = 0
	m = 0
	cnt = 0
	for i in range(hh):
		zzz = X[i]
		j = "G"
		if AA != []:
			if zzz == AA[0]:
				AA.remove(zzz)
				j = "N"
		if BB != []:
			if zzz == BB[0]:
				BB.remove(zzz)
				j = "N"

		if j == "G":
			if zzz != x:
				m += 1
			c = (c * (zzz - cnt - m)) % 1000000007
			cnt += 1
			x = zzz

print(c)

Score : 500 points

Problem Statement

Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates.
Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:

The largest among the values in the i-th row (1 \leq i \leq N) is A_i.

The largest among the values in the j-th column (1 \leq j \leq M) is B_j.

For him, find the number of ways to write the numbers under these conditions, modulo 10^9 + 7.

Constraints

1 \leq N \leq 1000

1 \leq M \leq 1000

1 \leq A_i \leq N \times M

1 \leq B_j \leq N \times M

A_i and B_j are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{M}

Output

Print the number of ways to write the numbers under the conditions, modulo 10^9 + 7.

Sample Input 1

2 2
4 3
3 4

Sample Output 1

2

(A_1, A_2) = (4, 3) and (B_1, B_2) = (3, 4). In this case, there are two ways to write the numbers, as follows:

1 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 2 in (2, 2).

2 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 1 in (2, 2).

Here, (i, j) denotes the square at the i-th row and the j-th column.

Sample Input 2

3 3
5 9 7
3 6 9

Sample Output 2

0

Since there is no way to write the numbers under the condition, 0 should be printed.

Sample Input 3

2 2
4 4
4 4

Sample Output 3

0

Sample Input 4

14 13
158 167 181 147 178 151 179 182 176 169 180 129 175 168
181 150 178 179 167 180 176 169 182 177 175 159 173

Sample Output 4

343772227


h,w=[int(j) for j in input().split()]
s=[input()for i in range(h)]
ans=0
def f(i,j,se):
    se.add((i,j))
    res=0
    b=True
    for x,y in [(1,0),(-1,0),(0,1),(0,-1)]:
        p,q=i+x,j+y
        if 0<=p<h and 0<=q<w:
            if s[p][q]!=s[i][j] and (p,q) not in se:
                b=False
                res+=f(p,q,se)
    if b:
        if s[i][j]==".":
            return 1
        else:
            return 0
    else:
        if s[i][j]==".":
            return res+1
        else:
            return res

for i in range(h):
    for j in range(w):
        if s[i][j]=="#":
            ans+=f(i,j,set())

print(ans)

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


def main():
    from collections import defaultdict
    import sys
    sys.setrecursionlimit(10 ** 9)

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

    Visited = [[0] * W for i in range(H)]
    direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]

    def dfs(ny, nx, color):
        for dy, dx in direction:
            if not ((0 <= ny + dy < H) and (0 <= nx + dx < W)):
                continue

            if G[ny + dy][nx + dx] == G[ny][nx]:
                continue

            if Visited[ny + dy][nx + dx] != 0:
                continue

            if G[ny + dy][nx + dx] == '#':
                Visited[ny + dy][nx + dx] = color
            else:
                Visited[ny + dy][nx + dx] = -color

            dfs(ny + dy, nx + dx, color)

    Color = 1
    for y in range(H):
        for x in range(W):
            if Visited[y][x] == 0:
                if G[y][x] == '#':
                    Visited[y][x] = Color
                else:
                    Visited[y][x] = -Color
                dfs(y, x, Color)
                Color += 1

    D = defaultdict(int)
    for i in range(1, Color + 1):
        D[i] = 0
        D[-i] = 0

    for row in Visited:
        for data in row:
            D[data] += 1

    ans = 0
    for key in D.keys():
        ans += D[key] * D[-key]

    print(ans // 2)

main()


N=int(input())
ABC=[]
for i in range(N):
	ABC+=[[int(i) for i in input().split()]]
DP=[[0,0,0] for i in range(N)]
for i in range(N):
	DP[i]=[ABC[i][0]+max(DP[i-1][1],DP[i-1][2]),ABC[i][1]+max(DP[i-1][0],DP[i-1][2]),ABC[i][2]+max(DP[i-1][1],DP[i-1][0])]
print(max(DP[N-1]))

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


n,w=[int(k) for k in input().split()]
li=[]

ans=0
for i in range(n):
    li.append([int(k) for k in input().split()])
dp=[[0 for i in range(10001)] for j in range(n+1)]
for i in range(1,10001):
    dp[0][i]=10**10
for a in range(1,n+1):
    for b in range(1,10001):
        if(li[a-1][1]<=b):
            x=li[a-1][0]+dp[a-1][b-li[a-1][1]]
            y=dp[a-1][b]
            dp[a][b]=min(x,y)
        else:
            dp[a][b]=dp[a-1][b]
        if dp[a][b]<=w:
          ans=max(ans,b)

print(ans)

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


h, w = map(int, input().split())
grid = [str(input()) for _ in range(h)]
dp = [[0 for _ in range(w)] for _ in range(h)]
mod = 10 ** 9 + 7
dp[0][0] = 1
for i in range(h):
    for j in range(w):
        if grid[i][j] == '#':
            continue
        if i >= 1:
            dp[i][j] += dp[i - 1][j]
        if j >= 1:
            dp[i][j] += dp[i][j - 1]
        dp[i][j] %= mod
print(dp[-1][-1])

Score : 100 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns.
Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.

For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}.
If a_{i, j} is ., Square (i, j) is an empty square; if a_{i, j} is #, Square (i, j) is a wall square.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square (1, 1) to (H, W).
As the answer can be extremely large, find the count modulo 10^9 + 7.

Constraints

H and W are integers.

2 \leq H, W \leq 1000

a_{i, j} is . or #.

Squares (1, 1) and (H, W) are empty squares.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W}

Output

Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5
..#..
.....
#...#
.....
..#..

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

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


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
if zz:
	input=sys.stdin.readline
else:
	sys.stdin=open('input.txt', 'r')
	sys.stdout=open('all.txt','w')
def li():
	return [int(x) for x in input().split()]
def fli():
	return [float(x) for x in input().split()]
def gi():
	return [x for x in input().split()]
def fi():
	return int(input())
def si():
	return list(input().rstrip())
def mi():
	return 	map(int,input().split())
def gh():
	sys.stdout.flush()
def graph(n,m):
	for i in range(m):
		x,y=mi()
		a[x].append(y)
		a[y].append(x)
def bo(i):
	return ord(i)-ord('a')

tt=1

while tt>0:
	tt-=1
	n=fi()
	a=fli()
	dp=[[0 for i in range(n+1)] for j in range(n+1)]
	for i in range(n):
		if i==0:
			dp[i][0]=1-a[i]
			dp[i][1]=a[i]
		else:
			for j in range(0,n+1):
				dp[i][j]=dp[i-1][j]*(1-a[i])+(dp[i-1][j-1]*a[i] if j>0 else 0)
	ans=0
	for i in range(n+1):
		if i>n-i:
			ans+=dp[n-1][i]
	print(ans)

Score : 100 points

Problem Statement

Let N be a positive odd number.

There are N coins, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.

Taro has tossed all the N coins.
Find the probability of having more heads than tails.

Constraints

N is an odd number.

1 \leq N \leq 2999

p_i is a real number and has two decimal places.

0 < p_i < 1

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 \ldots p_N

Output

Print the probability of having more heads than tails.
The output is considered correct when the absolute error is not greater than 10^{-9}.

Sample Input 1

3
0.30 0.60 0.80

Sample Output 1

0.612

The probability of each case where we have more heads than tails is as follows:

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Head) is 0.3 × 0.6 × 0.8 = 0.144;

The probability of having (Coin 1, Coin 2, Coin 3) = (Tail, Head, Head) is 0.7 × 0.6 × 0.8 = 0.336;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Tail, Head) is 0.3 × 0.4 × 0.8 = 0.096;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Tail) is 0.3 × 0.6 × 0.2 = 0.036.

Thus, the probability of having more heads than tails is 0.144 + 0.336 + 0.096 + 0.036 = 0.612.

Sample Input 2

1
0.50

Sample Output 2

0.5

Outputs such as 0.500, 0.500000001 and 0.499999999 are also considered correct.

Sample Input 3

5
0.42 0.01 0.42 0.99 0.42

Sample Output 3

0.3821815872


import sys
from math import ceil
input = lambda: sys.stdin.readline().rstrip()
tdlist = lambda i, j, value=0: [[value] * j for _ in range(i)]

n = int(input())
p = list(map(float, input().split()))
dp = tdlist(n+1, n+1)
dp[0][0] = 1

for i in range(1, n+1):
    for j in range(n+1):
        if j > 0: dp[i][j] += dp[i-1][j-1] * p[i-1]
        dp[i][j] += dp[i-1][j] * (1 - p[i-1])

print(sum(dp[n][ceil(n/2):]))


from functools import lru_cache
N = int(input())
A = list(map(int, input().split()))

#import random
#N = 400
#A = [random.randint(1, 10**9) for _ in range(N)]
INF = 1.0e+100

@lru_cache(maxsize=None)
def f(l, r, xy):
  if l > r:
    return xy

  n = r - l
  if (N - n) % 2 == 0:
    s = -1
  else:
    s = 1

  lv = f(l+1, r, xy + s*A[l])
  rv = f(l, r-1, xy + s*A[r])

  if s*lv > s*rv:
    return lv
  else:
    return rv

print(f(0, N-1, 0))

Score : 100 points

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

The answer may not fit into a 32-bit integer type.

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


import numpy as np

def main():
    N, K = map(int, input().split())
    mod = 10 ** 9 + 7
    A = [[int(x) for x in input().split()] for _ in range(N)]
    A = np.asarray(A, dtype=np.int64)
    ans = np.identity(N, dtype=np.int64)
    while K > 0:
        if K & 1:
            ans = np.mod(np.dot(ans, A), mod)
        A = np.mod(np.dot(A, A), mod)
        K >>= 1
    print(ans.sum() % mod)

if __name__ == '__main__':
    main()

Score : 100 points

Problem Statement

There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N.

For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j.
If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not.

Find the number of different directed paths of length K in G, modulo 10^9 + 7.
We will also count a path that traverses the same edge multiple times.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 10^{18}

a_{i, j} is 0 or 1.

a_{i, i} = 0

Input

Input is given from Standard Input in the following format:

N K
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of different directed paths of length K in G, modulo 10^9 + 7.

Sample Input 1

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

Sample Output 1

6

G is drawn in the figure below:

There are six directed paths of length 2:

1 → 2 → 3

1 → 2 → 4

2 → 3 → 4

2 → 4 → 1

3 → 4 → 1

4 → 1 → 2

Sample Input 2

3 3
0 1 0
1 0 1
0 0 0

Sample Output 2

3

G is drawn in the figure below:

There are three directed paths of length 3:

1 → 2 → 1 → 2

2 → 1 → 2 → 1

2 → 1 → 2 → 3

Sample Input 3

6 2
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0

Sample Output 3

1

G is drawn in the figure below:

There is one directed path of length 2:

4 → 5 → 6

Sample Input 4

1 1
0

Sample Output 4

0

Sample Input 5

10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0

Sample Output 5

957538352

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


MOD = 10**9 + 7
K = input()
D = int(input())
N = len(K)
dp0 = [[0] * D for _ in range(N+1)]
dp1 = [[0] * D for _ in range(N+1)]
dp0[0][0] = 1
for i, digit in enumerate(K, 1):
    digit = int(digit)
    for d in range(D):
        for k in range(10):
            dp1[i][(d + k) % D] += dp1[i-1][d]
            dp1[i][(d + k) % D] %= MOD
            if k < digit:
                dp1[i][(d + k) % D] += dp0[i-1][d]
                dp1[i][(d + k) % D] %= MOD
            elif k == digit:
                dp0[i][(d + k) % D] += dp0[i-1][d]
                dp0[i][(d + k) % D] %= MOD
print((dp0[N][0] + dp1[N][0] - 1) % MOD)

Score : 100 points

Problem Statement

Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:

The sum of the digits in base ten is a multiple of D.

Constraints

All values in input are integers.

1 \leq K < 10^{10000}

1 \leq D \leq 100

Input

Input is given from Standard Input in the following format:

K
D

Output

Print the number of integers satisfying the condition, modulo 10^9 + 7.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: 4, 8, 13, 17, 22 and 26.

Sample Input 2

1000000009
1

Sample Output 2

2

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

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


n = str(input())
cnt = 0
for i in n:
  if i == "2":
    cnt += 1
print(cnt)

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


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

def prime_factorize(num):
    """
    This function performs prime factorization on the input natural number.
    The result is returned in the form of a dictionary with the prime number as the key
    and its number as the value.
    :param num:
    :return prime_factor: Dictionary with the prime number as the key and its number as the value.
    """
    prime_factor = {}
    i = 2
    while i ** 2 <= num:
        while num % i == 0:
            num //= i
            if i in prime_factor.keys():
                prime_factor[i] += 1
            else:
                prime_factor[i] = 1
        i += 1
    if num > 1:
        prime_factor[num] = 1
    return prime_factor

prime_fac = prime_factorize(p)
counts = []
for k, v in prime_fac.items():
    if v >= n:
        counts.append(k**(v//n))

counts.sort(reverse=True)
#print(prime_fac)
#print(counts)
if len(counts) == 0:
    print(1)
elif n == 1:
    print(p)
else:
    r = 1
    num = 0
    for c in counts:
        if num >= n:
            break
        r *= c
        num += 1
    print(r)

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


S = input()
x = 0
y = 0
z = 0
for i in range(len(S)):
  if S[i]=="W":
    x += i+1
    y += 1
    z += y
print(x-z)

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

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

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


#!/mnt/c/Users/moiki/bash/env/bin/python
import copy
N = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
b = {}
for c in a:
    try:
        b[c] += 1
    except:
        b[c] = 1
pow2 = 1
while not pow2 > a[0]:
    pow2 *= 2

cnt = 0
for aa in a:
    while not aa >= (pow2//2):
        pow2 //= 2
    v = aa
    rem = pow2 - aa
    if (not v in b) or (not rem in b):
        continue

    if rem != v:
        hit = min(b[v], b[rem])
        # print("hit:not: ", hit)
        cnt += hit
        b[v] -= hit
        b[rem] -= hit
    else:
        hit = b[v] // 2
        # print("hit: ", hit)
        # print(a)
        cnt += int(hit)
        # a[a.index(v)] = a[a.index(v)] % 2
        b[v] /= 2

print(cnt)

# b = {}
# c = {}
# # print(a)
# for e,i in enumerate(a):
#     b[i] = (e, [(x[0]+e+1, x[1]) for x in enumerate(a[e+1:])])

# # print(b)
# for be in b: # (3, (0, [(1,5),...]) in [3,5,..]
#     for j in b[be][1]:
#         try:
#             if (not (b[be][0], j[0]) in c[be+j[1]]):
#                 # c[be + j[1]].append(b[be][0])
#                 # c[be + j[1]].append(j[0])
#                 c[be+j[1]].append((b[be][0], j[0]))
#         except:
#             c[be + j[1]]  = [(b[be][0], j[0])]
#             # c[be + j[1]].append(b[be][0])
#             # c[be + j[1]].append(j[0])

# # print("c: ", c)
# d= []

# twopowerlist = [2**p for p in range(30)]
# for n in twopowerlist:
#     try:
#         # print(n, c[n])
#         # d[n] = len(c[n])//2
#         d.append(c[n])
#     except:
#         pass
# d.sort(key=lambda x:len(x))
# d.reverse()

# for p in [x for y in d[0] for x in y]:
#     # print("p:",  p)
#     for e,q in enumerate(d[1:]):
#         for j in q:
#             if p in j:
#                 try:
#                     d.pop(e+1)
#                 except:
#                     pass

# # print(d)
# print(len(d[0]))

###########################3

# b = {}
# c = {}
# for e,i in enumerate(a):
#     b[i] = [copy.deepcopy(a)[e+1:], 1]
#     c[i] = 1

# for be in b:
#     for j in b[be][0]:
#         try:
#             c[j+be] += 1
#         except:
#             c[j+be] = 1

# sum = 0
# for n in twopowerlist:
#     try:
#         sum += c[n]
#     except:
#         pass
# print("list: ", c)
# print(sum)

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


n = int(input())
l = [int(i) for i in range(n)]
print(sum(l)-0.5*max(l))

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


n = int(input())
s =list()
for i in range(0,n):
  s.append(int(input()))
print(sum(s)-max(s)//2)


import sys
import os
import math
import string

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')

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

    N, K = il()
    H = [ii() for _ in range(N)]
    H = sorted(H, reverse=True)
    cnt = len(H)-K+1
    ret = [0]*cnt
    for i in range(cnt):
        ret[i] = max(H[i:i+K]) - min(H[i:i+K])
    print(min(ret))

if __name__ == '__main__':
    main()

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


N,X = map(int, input().split())
burger = [(1,0)]
prev = (1,0)
for i in range(N):
    burger.append((2*prev[0]+1, 2*prev[1]+2))
    prev = burger[-1]

lev = N
cur = X-1
ps = 0
for i in range(N+1):
    if lev == 0:
        ps += 1
        break

    if cur == 0:
        break
    elif cur == sum(burger[lev-1])+1:
        ps += burger[lev-1][0]+1
        break
    elif cur == sum(burger[lev])-1:
        ps += 2*burger[lev-1][0] + 1
        break

    if cur < sum(burger[lev])/2:
        cur -= 1
        lev -= 1
    else:
        ps += burger[lev-1][0] + 1
        cur -= sum(burger[lev-1]) + 2
        lev -= 1
print(ps)

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


allEatCache = {}
lenBurgerCache = {}

def nOfPatty(level, eat):
    if level == 0:
        return 1
    else:
        if level in allEatCache and eat >= lenBurger(level):
            return allEatCache[level]
        else:
            lenOfLowerLevel = lenBurger(level - 1)
            if eat <= 1:
                return 0
            if 2 <= eat <= 1 + lenOfLowerLevel:
                return nOfPatty(level - 1, eat - 1)
            if eat == 1 + lenOfLowerLevel + 1:
                return nOfPatty(level - 1, eat - 1) + 1
            else:
                tmp = nOfPatty(level - 1, eat - 1) + 1
                tmp += nOfPatty(level - 1, eat - 1 - lenOfLowerLevel - 1)
                allEatCache[level] = tmp
                return tmp

def lenBurger(level):
    if level == 0:
        return 1
    else:
        if level in lenBurgerCache:
            return lenBurgerCache[level]
        else:
            return 3 + lenBurger(level - 1) * 2

str = input().split()
n = int(str[0])
x = int(str[1])

print(nOfPatty(n, x))


X = input()
X = int(X)
if X == 7 or X == 5 or X == 3:
    print('YES')
else:
    print('NO')

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


S = input()
diff = 1000
for i in range(len(S)-2):
    num = int(S[i:i+3])
    temp = abs(num - 753)
    if diff > temp:
        diff = temp

print(diff)

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

S is a string of length between 4 and 10 (inclusive).

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


N = input().strip()

maxn = ()
base = set(['357', '375', '537', '573', '735', '753'])

if int(N) < 357:
  print(0)
else:
  for n in range(len(N) - 3):
    newb = set()
    for b in base:
      new3b = set([b[:i] + '3' + b[i:] for i in range(len(b) + 1)])
      new5b = set([b[:i] + '5' + b[i:] for i in range(len(b) + 1)])
      new7b = set([b[:i] + '7' + b[i:] for i in range(len(b) + 1)])
      newb |= new3b | new5b | new7b
    base |= newb
  print(len([i for i in base if int(i) <= int(N)]))

Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484


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

beauty = []
for i in range(N-1):
    for j in range(i, N):
        beauty.append(sum(A[i:j+1]))

beauty = sorted(beauty, reverse=True, key=lambda x: (len(bin(x)), bin(x)[2:].count('1')))
beauty_bin = [len(bin(b)[2:]) for b in beauty]

ans_list = []
for j in range(N-K):
    k = beauty[j:j+K]
    ans = k[0]
    for i in range(1, K):
        ans = ans & k[i]
    ans_list.append(ans)

print(max(ans_list))

Score : 400 points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N.
He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

1 \leq K \leq N(N+1)/2

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are 10 nonempty contiguous subsequences of a. Let us enumerate them:

contiguous subsequences starting from the first element: \{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}

contiguous subsequences starting from the second element: \{5\}, \{5, 2\}, \{5, 2, 5\}

contiguous subsequences starting from the third element: \{2\}, \{2, 5\}

contiguous subsequences starting from the fourth element: \{5\}

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is 12.
This can be achieved by choosing \{5, 2, 5\} (with beauty 12) and \{2, 5, 2, 5\} (with beauty 14).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31