#coding: UTF-8

list = []
for i in range(0,10) :
    input = int(raw_input())
    list.append(input)

list.sort(reverse = True)

for i in range(0,3) :
    print list[i]

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

List of Top 3 Hills

There is a data which provides heights (in meter) of mountains. The data is only for ten mountains.

Write a program which prints heights of the top three mountains in descending order.

Input

Height of mountain 1
Height of mountain 2
Height of mountain 3
.
.
Height of mountain 10

Constraints

0 ≤ height of mountain (integer) ≤ 10,000

Output

Height of the 1st mountain
Height of the 2nd mountain
Height of the 3rd mountain

Sample Input 1

1819
2003
876
2840
1723
1673
3776
2848
1592
922

Output for the Sample Input 1

3776
2848
2840

Sample Input 2

100
200
300
400
500
600
700
800
900
900

Output for the Sample Input 2

900
900
800

Submitted source-code file size, in bytes.

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

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


import sys

array = []
for line in sys.stdin:
    array.append(map(int, line.split(' ')))

for a, b in array:
    digit = 0
    c = a + b
    while c > 0:
        c = int(c / 10)
        digit = digit + 1

    print(digit)

Digit Number

Write a program which computes the digit number of sum of two integers a and b.

Input

There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF.

Constraints

0 ≤ a, b ≤ 1,000,000

The number of datasets ≤ 200

Output

Print the number of digits of a + b for each data set.

Sample Input

5 7
1 99
1000 999

Output for the Sample Input

2
3
4


n = int(input())
for i in range(n):
    a = list(map(int,input().split()))
    a = sorted(a)
    if a[2]**2 == ((a[0]**2)+(a[1]**2)):
        print("YES")
    else:
        print("NO")

Is it a Right Triangle?

Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.

Input

Input consists of several data sets. In the first line, the number of data set, N is given. Then, N lines follow, each line corresponds to a data set. A data set consists of three integers separated by a single space.

Constraints

1 ≤ length of the side ≤ 1,000

N ≤ 1,000

Output

For each data set, print "YES" or "NO".

Sample Input

3
4 3 5
4 3 6
8 8 8

Output for the Sample Input

YES
NO
NO


n = input()
for i in xrange(n):
    x1, y1, x2, y2, x3, y3, x4, y4 = map(float, raw_input().split())
    Ax = x1 - x2
    Ay = y1 - y2
    Bx = x3 - x4
    By = y3 - y4
    if Ax == Bx == 0 or Ay == By == 0:
        print "YES"
    elif abs(Ay * Bx - By * Ax) < 1e-10:
        print "YES"
    else:
        print "NO"

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

Parallelism

There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO".

Input

Input consists of several datasets. In the first line, you are given the number of datasets $n$ ($n \leq 100$). There will be $n$ lines where each line correspondgs to each dataset. Each dataset consists of eight real numbers:

$x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_4$ $y_4$

You can assume that $-100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4 \leq 100$.
Each value is a real number with at most 5 digits after the decimal point.

Output

For each dataset, print "YES" or "NO" in a line.

Sample Input

2
0.0 0.0 1.0 1.0 1.0 0.0 2.0 1.0
3.0 2.0 9.0 6.0 13.0 5.0 7.0 9.0

Output for the Sample Input

YES
NO


cnt = []
for i in range(0, 101):
	cnt.append(0)

while True:
	try:
		n = int(raw_input())
		cnt[n] += 1
	except:
		break

tmp = 0
lst = []
for i in range(1, 101):
	if tmp < cnt[i]:
		tmp = cnt[i]
		lst = [i]
	elif tmp == cnt[i]:
		lst.append(i)

for i in range(0, len(lst)):
	print lst[i]

Mode Value

Your task is to write a program which reads a sequence of integers and prints mode values of the sequence.
The mode value is the element which occurs most frequently.

Input

A sequence of integers ai (1 ≤ ai ≤ 100). The number of integers is less than or equals to 100.

Output

Print the mode values. If there are several mode values, print them in ascending order.

Sample Input

5
6
3
5
8
7
5
3
9
7
3
4

Output for the Sample Input

3
5

For example, 3 and 5 respectively occur three times, 7 occurs two times, and others occur only one. So, the mode values are 3 and 5.


from itertools import combinations

while True:
    n, s = map(int, input().split())
    if n==s==0: break
    print([sum(c) for c in combinations(range(10), n)].count(s))

整数の和

0 から 9 の数字から異なる n 個の数を取り出して合計が s となる組み合わせの数を出力するプログラムを作成してください。n 個の数はおのおの 0 から 9 までとし、１つの組み合わせに同じ数字は使えません。たとえば、n が 3 で s が 6 のとき、3 個の数字の合計が 6 になる組み合わせは、

1 + 2 + 3 = 6

0 + 1 + 5 = 6

0 + 2 + 4 = 6

の 3 通りとなります。

Input

複数のデータセットが与えられます。各データセットに n (1 ≤ n ≤ 9) と s (0 ≤ s ≤ 100) が１つのスペースで区切られて１行に与えられます。n と s が共に 0 のとき入力の最後とします（この場合は処理せずにプログラムを終了する）。

データセットの数は 50 を超えません。

Output

各データセットに対して、n 個の整数の和が s になる組み合わせの数を１行に出力して下さい。

Sample Input

3 6
3 1
0 0

Output for the Sample Input

3
0


import math
def is_prime(q):
    q = abs(q)
    if q == 2: return True
    if q < 2 or q&1 == 0: return False
    return pow(2, q-1, q) == 1

def main():
    while True:
        try:
            value = int(input())
            for v in range(0,value):
                if is_prime(v):
                    prime_MAX = v
            for v in range(value+1,10000):
                if is_prime(v):
                    break
            print(str(prime_MAX)+" "+str(v))
        except EOFError:
            break

if __name__ == '__main__':
    main()

素数 II

素数というのは、1 よりも大きくそれ自身か 1 でしか割りきれない整数をいいます。例えば、2 は、2 と 1 でしか割り切れないので素数ですが、12 は、12 と 1 のほかに、2, 3, 4, 6 で割りきれる数なので素数ではありません。

整数 n を入力したとき、n より小さい素数のうち最も大きいものと、n より大きい素数のうち最も小さいものを出力するプログラムを作成してください。

Input

複数のデータセットが与えられます。各データセットに n (3 ≤ n ≤ 50,000) が１行に与えられます。

データセットの数は 50 を超えません。

Output

各データセットに対して、n より小さい素数のうち最大のものと、n より大きい素数のうち最小のものを１つのスペースで区切って１行に出力して下さい。

Sample Input

19
3517

Output for the Sample Input

17 23
3511 3527


import sys
from math import*
for e in sys.stdin:
 a,b,c,d,e,f=map(float,e.split(','))
 z,w,q=complex(a,b),complex(c,d),complex(e,f)
 w-=z
 z+=(w/abs(w))**2*(q-z).conjugate()
 print(z.real,z.imag)

線対称

平面上の異なる 3 点 P1(x1,y1), P2(x2,y2), Q(xq,yq) の座標の組を読み込んで、点 P1 点P2 を通る直線を対称軸として点 Q と線対称の位置にある点 R(x,y) を出力するプログラムを作成してください。なお、点 Q は、その対称軸上にないものとします。

入力

入力は複数のデータセットからなります。各データセットは以下の形式で与えられます。

x1,y1,x2,y2,xq,yq

x1, y1, x2, y2, xq, yq (-100 以上 100 以下の実数) がカンマ区切りで１行に与えられます。

データセットの数は 50 を超えない。

出力

データセットごとに、x, y を空白区切りで 1 行に出力する。出力は実数で 0.0001 以下の誤差を含んでもよい。

Sample Input

1.0,0.0,-1.0,0.0,1.0,1.0
1.0,0.0,0.0,-1.0,3.0,0.0
0.0,1.0,0.0,-1.0,1.0,1.0

Output for the Sample Input

1.000000 -1.000000
1.000000 2.000000
-1.000000 1.000000


import math

while True:
    d, w, h = [int(x) for x in input().split()]
    if d == w == h == 0:
        break
    dw = math.sqrt(d * d + w * w)
    dh = math.sqrt(d * d + h * h)
    wh = math.sqrt(w * w + h * h)
    min_ = min(dw, dh, wh)
    n = int(input())
    for i in range(n):
        r = int(input()) * 2
        if r > min_:
            print('OK')
        else:
            print('NA')

Carry a Cheese

Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A × B × C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you help Jerry to find suitable holes to be survive?

Your task is to create a program which estimates whether Jerry can trail the cheese via each hole.
The program should print "OK" if Jerry can trail the cheese via the corresponding hole (without touching it). Otherwise the program should print "NA".

You may assume that the number of holes is less than 10000.

Input

The input is a sequence of datasets. The end of input is indicated by a line containing three zeros. Each dataset is formatted as follows:

A B C
n
R1
R2

.
.
Rn

n indicates the number of holes (entrances) and Ri indicates the radius of i-th hole.

Output

For each datasets, the output should have n lines. Each line points the result of estimation of the corresponding hole.

Sample Input

10 6 8
5
4
8
6
2
5
0 0 0

Output for the Sample Input

NA
OK
OK
NA
NA


# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0120

"""
import sys
from sys import stdin
input = stdin.readline

def calc_width(cakes):
    # ??±????????????????????????(?????????????????????????????????????????????????¨??????????)
    if len(cakes) == 1:
        return cakes[0]*2

    prev_r = cakes[0]
    width = prev_r

    for r in cakes[1:]:
        h_diff = abs(prev_r - r)
        if h_diff == 0:
            width += prev_r
            width += r
        else:
            w = ((prev_r + r)**2 - h_diff**2)**0.5
            width += w
        prev_r = r
    width += cakes[-1]

    return width

def main(args):
    for line in sys.stdin:
        data = [int(x) for x in line.split()]
        box_size = data[0]
        temp = data[1:]
        temp.sort()
        cakes = []

        head = True
        while temp:
            if head:
                cakes.append(temp[0])
                temp = temp[1:]
                head = False
            else:
                cakes.append(temp[-1])
                temp = temp[:-1]
                head = True
        result = calc_width(cakes)
        if result <= box_size:
            print('OK')
        else:
            print('NA')

if __name__ == '__main__':
    main(sys.argv[1:])

パティシエ

ケーキ屋さんが、まちまちな大きさのロールケーキをたくさん作りました。あなたは、このケーキを箱に並べる仕事を任されました。

ロールケーキはとてもやわらかいので、他のロールケーキが上に乗るとつぶれてしまいます。ですから、図(a) のように全てのロールケーキは必ず箱の底面に接しているように並べなければなりません。並べ替えると必要な幅も変わります。

図(a)

図(b)

n 個のロールケーキの半径 r1, r2, ..., rn と箱の長さを読み込み、それぞれについて、箱の中にうまく収まるかどうか判定し、並べる順番を工夫すると箱に入る場合は "OK"、どう並べても入らない場合には "NA"を出力するプログラムを作成してください。

ロールケーキの断面は円であり、箱の壁の高さは十分に高いものとします。 ただし、ロールケーキの半径は 3 以上 10 以下の整数とします。つまり、ケーキの半径に極端な差はなく、図(b) のように大きなケーキの間に小さなケーキがはまり込んでしまうことはありません。

Input

入力は複数のデータセットからなります。各データセットは以下の形式で与えられます。

W r1 r2 ... rn

最初に箱の長さを表す整数 W (1 ≤ W ≤ 1,000) が与えられます。 続いて、空白区切りで各ロールケーキの半径を表す整数 ri (3 ≤ ri ≤ 10) が与えられます。ケーキの個数 n は 12 以下です。

データセットの数は 50 を超えません。

Output

データセットごとに OK または NA を１行に出力してください。

Sample Input

30 4 5 6
30 5 5 5
50 3 3 3 10 10
49 3 3 3 10 10

Output for the Sample Input

OK
OK
OK
NA


from collections import Counter

SQUARE_NUM = [item ** 2 for item in range(1, 10001)]

while True:
    num = int(input())

    if num == 0:
        break

    half_num = num // 2

    mod = [item % num for item in SQUARE_NUM[:num - 1]]
    unique_mod = list(set(mod))

    counter = Counter()

    for index, item in enumerate(unique_mod):
        for item2 in unique_mod[index + 1:]:

            subtract = item - item2

            if subtract < 0:
                subtract += num
            if half_num < subtract:
                subtract = num - subtract

            counter[subtract] += 2

    output = [counter[index] for index in range(1, half_num + 1)]
    output = map(lambda item: str(item), output)
    print("\n".join(output))

素数の性質

4 で割ると 3 あまる素数 n (11、19、23 など) には、面白い性質があります。1 以上 n 未満の自然数 (1, 2,... , n - 1) を 2 乗したものを n で割ったあまりを計算した結果を並べると、同じ数になるものがあるため、互いに異なった数の個数は、(n - 1)/2 になります。

この様にして得られた数の集合には、特別な性質があります。得られた数の集合から、互いに異なる 2 つ a と b を選んでその差を計算します。差が負になったときは、その差に n を足します。さらに結果が (n - 1)/2 より大きいときは、その差を n から引きます。

例えば、n = 11 のとき 1 と 9 の差は、1 − 9 = −8 → −8 + n = −8 + 11 = 3 になります。9 と 1 の差も 9 −1 = 8 → n − 8 = 11 − 8 = 3 で、同じ値 3 になります。この差は、円周上に 0, 1, ・・・, n - 1 を書いて、二つの数字の間の短い方の円弧を考えるとわかりやすくなります。(下図参照)

こうして得られた数の「差」は、1, 2, . . ., (n - 1)/2 のいずれかであり、同じ回数出現します。

【例】 n = 11 の時は、以下のようになります。

1 から n-1 までの数を 2 乗したものを n で割った余りを計算します。

12 = 1 → 1
22 = 4 → 4
32 = 9 → 9
42 = 16 → 5
52 = 25 → 3
62 = 36 → 3
72 = 49 → 5
82 = 64 → 9
92 = 81 → 4
102 = 100 → 1

a, b の「差」の計算

1 で得られた 1, 3, 4, 5, 9 について異なる数同士の差を計算します。

計算結果が負の場合、n = 11 を加算します。

さらに、計算結果が (n-1)/2 = 5 より大きい場合 n = 11 から減算します。

出現回数を求める

計算結果 1, 2, 3, 4, 5 の出現回数をそれぞれ数え上げます。

これらの計算結果から 1, 2, 3, 4, 5 の出現回数が 4 回であることがわかります。この性質は 4 で割ると 3 あまる素数特有の性質であり 4 で割ると 1 あまる素数ではこのようなことはおきません。このことを確認するため、10000 以下の奇数 n を入力とし、例題にあるような計算 (n で割ったあまりの 2 乗の差の頻度を求める)を実行し、その出現回数を出力するプログラムを作成してください。

Input

複数のデータセットが与えられます。各データセットとして１つの整数 n　(n ≤ 10000) が１行に与えられます。入力は 0 を１つ含む行でおわります。

Output

各データセットについて、出現頻度を以下の形式で出力してください。

剰余の平方の差が 1 である(a, b)の出現個数(整数)
剰余の平方の差が 2 である(a, b)の出現個数(整数)
:
:
剰余の平方の差が (n-1)/2 である(a, b)の出現個数(整数)

Sample Input

11
15
0

Output for the Sample Input

4
4
4
4
4
2
2
4
2
4
4
2


ans = []
readline = open(0).readline
writelines = open(1, 'w').writelines

while 1:
    N = int(readline())
    if N == 0:
        break
    items = [map(int, readline().split()) for i in range(N)]
    P, Q, R, C = map(int, readline().split())
    c = 0
    for s, p, q, r in items:
        if p <= P and q <= Q and r <= R and 4*p+9*q+4*r <= C:
            ans.append("%d\n" % s)
            c += 1
    if not c:
        ans.append("NA\n")
writelines(ans)

カロリー計算

食べ物には3大栄養素と呼ばれる「たんぱく質」「脂質」「炭水化物」の３つの栄養素が含まれています。１g（グラム）あたりたんぱく質と炭水化物は 4 kcal（キロカロリー）、脂質は 9 kcal と計算されます。たとえば、下の表によると番号１のケーキにはタンパク質 7 g、脂質 14 g、炭水化物 47 g が含まれています。これをもとに含まれるカロリーを計算すると、4 × 7 + 9 × 14 + 4 × 47 = 342 kcal となります。その他も同様に計算されています。

番号

名前

たんぱく質(g)

脂質(g)

炭水化物(g)

カロリー(kcal)

1

ケーキ

7

14

47

342

2

ポテトチップス

5

35

55

555

3

どら焼き

6

3

59

287

4

プリン

6

5

15

129

分類の対象となるお菓子の個数 n と各お菓子の情報、制限の情報を入力とし、そのお菓子一つだけなら制限を超えることがない（食べてもよい）お菓子の一覧を出力するプログラムを作成してください。

お菓子の情報は、お菓子の番号 s、そのお菓子に含まれるたんぱく質の重量 p、脂質の重量 q、炭水化物の重量 r から構成されています。制限の情報には、含むことができる最大のたんぱく質の重量 P、脂質の重量 Q、炭水化物の重量 R、および摂取することができる最大のカロリー C からなっており、タンパク質、脂質、炭水化物、カロリーのいずれかの一つでも超えると制限違反となり、「食べてはいけないお菓子」と判断されます。

食べてもよいお菓子の一覧は、食べてもよいお菓子の番号を入力順に出力してください。なお、食べてもよいお菓子がなければ”NA”と出力してください。
上の表にある4個のお菓子について、P = 10, Q = 15, R = 50, C = 400 という制限の場合、ケーキとプリンはそれぞれの栄養素及びカロリーが制限値以下なので食べてもよいお菓子に分類されますが、ポテトチップスは炭水化物とカロリー、どら焼きは炭水化物の量が制限値を超えているため食べてはいけないお菓子に分類されます。

入力

複数のデータセットの並びが与えられます。入力の終わりはゼロひとつの行で示されます。各データセットは以下の形式で与えられます。

n
s1 p1 q1 r1
s2 p2 q2 r2
:
sn pn qn rn
P Q R C

1行目にお菓子の数 n (1 ≤ n ≤ 1000)が与えられます。続く n 行に第 i のお菓子の番号 si (1 ≤ si ≤ 1000)、各栄養素の重量を表す整数 pi, qi, ri (0 ≤ pi, qi, ri ≤ 100) が与えられます。

続く行に各栄養素及びカロリーの制限値を表す整数 P, Q, R (0 ≤ P, Q, R ≤ 100), C (0 ≤ C ≤ 1700) が与えられます。

データセットの数は 100 を超えません。

出力

データセットごとに、食べてもよいお菓子の番号または ”NA” を出力します。

入力例

4
1 7 14 47
2 5 35 55
3 6 3 59
4 6 5 15
10 15 50 400
2
1 8 10 78
2 4 18 33
10 10 50 300
0

出力例

1
4
NA


お財布メタボ診断

４月に消費税が８％になってから、お財布が硬貨でパンパンになっていませんか。同じ金額を持ち歩くなら硬貨の枚数を少なくしたいですよね。硬貨の合計が１０００円以上なら、硬貨をお札に両替して、お財布のメタボ状態を解消できます。

お財布の中の硬貨の枚数が種類ごとに与えられたとき、硬貨をお札に両替できるかどうかを判定するプログラムを作成してください。

入力

入力は以下の形式で与えられる。

c1 c5 c10 c50 c100 c500

入力は１行からなる。c1、c5、c10、c50、c100、c500 (0 ≤ c1, c5, c10, c50, c100, c500 ≤ 50) は、それぞれ、1円、5円、10円、50円、100円、500円硬貨の枚数を表す。

出力

硬貨をお札に両替できるなら1 を、そうでなければ 0 を１行に出力する。

入出力例

入力例１

3 1 4 0 4 1

出力例１

0

入力例２

2 1 4 3 2 3

出力例２

1

入力例３

21 5 9 3 1 1

出力例３

0

入力例４

2 4 3 3 3 1

出力例４

1

入力例５

50 50 50 4 0 0

出力例５

1


x = int(input())
l = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
print(l[(x-4)%7])

Day of Week

The 9th day of September 2017 is Saturday. Then, what day of the week is the X-th of September 2017?

Given a day in September 2017, write a program to report what day of the week it is.

Input

The input is given in the following format.

X

The input line specifies a day X (1 ≤ X ≤ 30) in September 2017.

Output

Output what day of the week it is in a line. Use the following conventions in your output: "mon" for Monday, "tue" for Tuesday, "wed" for Wednesday, "thu" for Thursday, "fri" for Friday, "sat" for Saturday, and "sun" for Sunday.

Sample Input 1

1

Sample Output 1

fri

Sample Input 2

9

Sample Output 2

sat

Sample Input 3

30

Sample Output 3

sat


check = True
cnt = 0

n = int(input())
stamps = input()

while len(stamps)>1:
    if check:
        if stamps[:2] in ["XO", "OX"]:
            cnt += 1
            check = False
    else:
        check = True
    stamps = stamps[1:]

print(cnt)

マルバツスタンプ (Circle Cross Stamps)

問題文

JOI 君はマルスタンプ，バツスタンプ，マルバツスタンプの3種類のスタンプをそれぞれ 0 個以上持っている．これらはマルやバツのマークを紙に印字することができるスタンプである．

マルスタンプを使うとマルが 1 つ印字され，バツスタンプを使うとバツが 1 つ印字される．マルバツスタンプを使うとマルとバツが横一列に 1 つずつ印字され，スタンプの向きを変えることで，マルの右にバツが来るようにも，バツの右にマルが来るようにも印字できる．

JOI 君は，持っているスタンプをそれぞれちょうど 1 回ずつ適当な順番で使い，紙に横一列にマルとバツを印字した．印字されたマルとバツの列は文字列 S で表される．S は O と X から構成された長さ N の文字列であり，S_i = O ならば JOI 君が印字したマークのうち左から i 番目のものがマルであることを表し，S_i = X ならばそれがバツであることを表す (1 ≦ i ≦ N)．

あなたは，JOI 君が持っているスタンプの個数は分からないが，JOI 君が印字したマルとバツの列は知っている．印字されたマルとバツの列から，JOI 君が持っているマルバツスタンプの個数としてあり得るもののうち最大値を求めよ．

制約

1 ≦ N ≦ 100000 (= 10^5)

S は長さ N の文字列である．

S の各文字は O か X である．

入力・出力

入力

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

N

S

出力

JOI 君が持っているマルバツスタンプの個数としてあり得るもののうち最大値を出力せよ．

入出力例

入力例 1

5
OXXOX

出力例 1

2

JOI 君が印字したマークは，左から順に，マル，バツ，バツ，マル，バツである．JOI 君がマルスタンプ，バツスタンプ，マルバツスタンプをそれぞれ 0, 1, 2 個持っているとすると，以下の順番でスタンプを使えば，そのようにマークを印字することができる．

1 つ目のマルバツスタンプを使ってマルとバツをこの順に印字する．

この右に，2 つ目のマルバツスタンプを使ってバツとマルをこの順に印字する．

最後に，この右に，バツスタンプを使ってバツを印字する．

マルバツスタンプを 3 個以上持っているケースは考えられないので，2 を出力する．

入力例 2

14
OXOXOXOXXOXOXO

出力例 2

7

入力例 3

10
OOOOOOOOOO

出力例 3

0

情報オリンピック日本委員会作 『第 18 回日本情報オリンピック JOI 2018/2019 予選競技課題』


import bisect

while(1):
    N=int(raw_input())
    if N==0: break
    D={}
    for i in range(N):
        inp=raw_input().split()
        inp[1:]=map(int, inp[1:])
        stt=inp[1]*24*60+inp[2]/100*60+inp[2]%100
        D[inp[0]]=stt
    P=int(raw_input())
    Tlist=[-99999999,999999999]
    for i in range(P):
        f=raw_input()
        Tlist.append(D.pop(f))
    Tlist.sort()
    for i in range(P+1):
        if Tlist[i+1]<Tlist[i]+30:
            print -1
            break
    else:
        ans=P
        E=sorted(D.values())
        for st in E:
            if (st - Tlist[ bisect.bisect(Tlist, st)-1])>= 30 and (Tlist[ bisect.bisect(Tlist, st)] - st ) >= 30:
                ans+=1
                bisect.insort(Tlist, st)
        print ans

Problem B: Watchin' TVA

Animation is one of methods for making movies and in Japan, it is popular to broadcast as a television program or perform as a movie. Many people, especially the young, love one. And here is an anime lover called Jack. We say he is an mysterious guy with uncertain age. He likes anime which are broadcasted in midnight and early morning especially.

In his room, there is a huge piece of paper on the wall. He writes a timetable of TV anime on it. In his house, he can watch all Japanese TV anime programs that are broadcasted in Japan using a secret and countrywide live system. However he can not watch all anime and must give up to watch some programs because they are "broadcasted at the same time" in a season. Here, programs are "broadcasted at the same time" means that two or more programs have one or more common minutes in broadcasting time. Increasing the number of anime programs in recent makes him nervous. Actually, some people buy DVDs after the program series ends or visit a web site called vhefoo. Anyway, he loves to watch programs on his live system. Of course, he is not able to watch two or more programs at the same time. However, as described above, he must give up some programs broadcasted at the same time. Therefore, he has a set of programs F and he watches programs in a set F absolutely.

Your task is to write a program that reads a timetable and outputs the maximum number of watchable programs, keeping that Jack watches all programs in the set F. Of course, there are multiple choices of programs, so we want the number of programs he can watch. If two or more programs in a set F are broadcasted at the same time, you must give Jack an unfortunate announcement. In this case, your program outputs -1. In addition, each anime program is a program of 30 minutes.

Input

Input consists of multiple datasets.

A dataset is given in a following format.

N
PROGRAM1
PROGRAM2
...
PROGRAMN
P
FAV1
FAV2
...
FAVP

N is the number of programs in a season.

PROGRAMi(1≤i≤N)is a string which has the following format.

name weekday start

name is a program name. This is a a string having between 1 and 32 characters and these names do not overlap each other program. A name consists of alphanumeric characters and '_'(underscore).

weekday is a broadcasting weekday about the corresponding program. This is an integer. 0 means Sunday and 1 is Monday and so on (2:Tuesday, 3:Wednesday, 4:Thursday, 5:Friday, 6:Saturday).

start is a starting time of the program broadcasting. This is an integer between 600 and 2929. First one or two digits represent hour and the last two digits represent minute. If the hour has one digit it will be a representation "900" for example. Note: a program may have an integer more than or equal to 2400 as start, if the program begins the next day. For example, a program begins from 2500 on Monday should be interpreted as a program begins from 0100 on Tuesday. There are no input the minute of start exceeds 59. And when the hour of start is equal to 29, there are no input the minute of start exceeds 29.

P is an integer and represents the number of elements in the set F. And FAVi(1≤i≤P≤N) is a string for a program name which Jack watches absolutely. You can assume names which are not given in program descriptions will not appear in the set F.

The last line contains a single 0 which represents the end of input.

Constraints

The number of datasets is less than or equal to 400.

1≤N≤500

Output

For each dataset, output an integer S that represents maximum number of programs Jack can watch in the following format.

S

Sample Input

1
galaxy_angel 0 600
1
galaxy_angel
11
A 0 600
B 0 610
C 0 610
D 0 610
E 0 640
EE 0 700
F 0 710
G 0 710
H 0 710
I 0 740
J 0 750
2
B
H
42
nchj 6 2620
anhnnnmewbktthsrn 4 2515
gntmdsh 1 1800
achnnl 4 2540
hnskirh 0 2200
aonexrcst 0 1700
dgdys 6 2330
hdnnara 4 2525
dnpaonntssotk 4 2555
ddmnwndrlnd 6 2500
C 4 2445
astrttnomch 0 2330
seknnqasr 1 2630
sftnt 4 2630
stnsgt 2 2605
drrnenmknmrmr 4 2610
hnzm 6 2713
yndmsoazzlsn 6 2658
mrahlcalv 4 2615
hshzrhkkrhs 1 900
ortchntsbshni 0 2430
kmnmzshrski 1 2530
sktdnc 4 1800
gykkybrkjhkirkhn 2 2459
trk 0 900
30zzsinhkntiik 3 2700
sngkotmmmirprdx 1 2600
yran 2 2529
tntissygntinybu 1 2614
skiichhtki 5 2505
tgrbnny 6 2558
dnbrsnki 3 1927
yugozxl 1 1930
frbllchrmn 1 1928
fjrg 1 1955
shwmngtr 0 2200
xmn 5 2200
rngnkkrskitikihn 0 2100
szysz 0 1254
prttyrythmaulrdrm 6 1000
sckiesfrntrqst 5 1820
mshdr 1 2255
1
mrahlcalv
0

Output for the Sample Input

1
4
31

Hint

Second dataset: He can watch program E after watching B. Then he can choose a program either I or J after watching H. Therefore he can watch maximum 4 programs.


def rec(s):
    ans = int(1e8)
    c_list = []
    st = []
    n = len(s)
    l = 0
    r = len(s)-1
    if s[0]!='[':
        return 1+int(s)//2
    for i in range(n):
        _s = s[i]
        if _s=='[':
            if len(st)==0:
                l = i+1
            st.append(_s)
        elif _s==']':
            st = st[:-1]
            if len(st)==0:
                r = i
                c_list.append(rec(s[l:r]))
    c_list.sort()
    return sum( c_list[:1+len(c_list)//2] )

N = int(input())
for _ in range(N):
    s = input()
    print(rec(s))

Hierarchical Democracy

The presidential election in Republic of Democratia is carried out through multiple stages as follows.

There are exactly two presidential candidates.

At the first stage, eligible voters go to the polls of his/her electoral district.
The winner of the district is the candidate who takes a majority of the votes.
Voters cast their ballots only at this first stage.

A district of the k-th stage (k > 1) consists of multiple districts of the (k − 1)-th stage. In contrast, a district of the (k − 1)-th stage is a sub-district of one and only one district of the k-th stage. The winner of a district of the k-th stage is the candidate who wins in a majority of its sub-districts of the (k − 1)-th stage.

The final stage has just one nation-wide district. The winner of the final stage is chosen as the president.

You can assume the following about the presidential election of this country.

Every eligible voter casts a vote.

The number of the eligible voters of each electoral district of the first stage is odd.

The number of the sub-districts of the (k − 1)-th stage that constitute a district of the k-th stage (k > 1) is also odd.

This means that each district of every stage has its winner (there is no tie).

Your mission is to write a program that finds a way to win the presidential election with the minimum number of votes.
Suppose, for instance, that the district of the final stage has three sub-districts of the first stage and that the numbers of the eligible voters of the sub-districts are 123, 4567, and 89, respectively.
The minimum number of votes required to be the winner is 107, that is, 62 from the first district and 45 from the third.
In this case, even if the other candidate were given all the 4567 votes in the second district, s/he would inevitably be the loser.
Although you might consider this election system unfair, you should accept it as a reality.

Input

The entire input looks like:

the number of datasets (=n)

1st dataset

2nd dataset

…

n-th dataset

The number of datasets, n, is no more than 100.

The number of the eligible voters of each district and the part-whole relations among districts are denoted as follows.

An electoral district of the first stage is denoted as [c], where c is the number of the eligible voters of the district.

A district of the k-th stage (k > 1) is denoted as [d1d2…dm], where d1, d2, …, dm denote its sub-districts of the (k − 1)-th stage in this notation.

For instance, an electoral district of the first stage that has 123 eligible voters is denoted as [123].
A district of the second stage consisting of three sub-districts of the first stage that have 123, 4567, and 89 eligible voters, respectively, is denoted as [[123][4567][89]].

Each dataset is a line that contains the character string denoting the district of the final stage in the aforementioned notation.
You can assume the following.

The character string in each dataset does not include any characters except digits ('0', '1', …, '9') and square brackets ('[', ']'), and its length is between 11 and 10000, inclusive.

The number of the eligible voters of each electoral district of the first stage is between 3 and 9999, inclusive.

The number of stages is a nation-wide constant.
So, for instance, [[[9][9][9]][9][9]] never appears in the input.
[[[[9]]]] may not appear either since each district of the second or later stage must have multiple sub-districts of the previous stage.

Output

For each dataset, print the minimum number of votes required to be the winner of the presidential election in a line.
No output line may include any characters except the digits with which the number is written.

Sample Input

6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]

Output for the Sample Input

107
7
175
95
21
3599


while True:
    N, T, L, B = [int(_) for _ in raw_input().split()]
    if N == T == L == B:
        break
    loses = {int(raw_input()) for _ in xrange(L)}
    backs = {int(raw_input()) for _ in xrange(B)}

    probs = [[0.0] * (N + 1) for _ in xrange(T + 1)]
    for t in xrange(T + 1):
        probs[t][N] = 1.0

    for t in xrange(1, T + 1):
        for x in xrange(N + 1):
            if x in loses:
                dt = 2
                if t == 1:
                    continue
            else:
                dt = 1
            for dx in xrange(1, 7):
                if x + dx <= N:
                    probs[t][x] += probs[t - dt][x + dx] / 6.0
                if x < N < x + dx:  # excess
                    probs[t][x] += probs[t - dt][2 * N - (x + dx)] / 6.0
        for x in backs:
            probs[t][x] = probs[t - 1][0]

    print(probs[T][0])

Problem C: Minimal Backgammon

Here is a very simple variation of the game backgammon, named “Minimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player).

The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker is placed on the start (square 0). The aim of the game is to bring the checker to the goal (square N). The checker proceeds as many squares as the roll of the dice. The dice generates six integers from 1 to 6 with equal probability.

The checker should not go beyond the goal. If the roll of the dice would bring the checker beyond the goal, the checker retreats from the goal as many squares as the excess. For example, if the checker is placed at the square (N - 3), the roll "5" brings the checker to the square (N - 2), because the excess beyond the goal is 2. At the next turn, the checker proceeds toward the goal
as usual.

Each square, except the start and the goal, may be given one of the following two special instructions.

Lose one turn (labeled "L" in Figure 2) If the checker stops here, you cannot move the checker in the next turn.

Go back to the start (labeled "B" in Figure 2)
If the checker stops here, the checker is brought back to the start.

Figure 2: An example game

Given a game board configuration (the size N, and the placement of the special instructions), you are requested to compute the probability with which the game succeeds within a given number of turns.

Input

The input consists of multiple datasets, each containing integers in the following format.

N T L B
Lose1
...
LoseL
Back1
...
BackB

N is the index of the goal, which satisfies 5 ≤ N ≤ 100. T is the number of turns. You are requested to compute the probability of success within T turns. T satisfies 1 ≤ T ≤ 100. L is the number of squares marked “Lose one turn”, which satisfies 0 ≤ L ≤ N - 1. B is the number of squares marked “Go back to the start”, which satisfies 0 ≤ B ≤ N - 1. They are separated by a space.

Losei's are the indexes of the squares marked “Lose one turn”, which satisfy 1 ≤ Losei ≤ N - 1. All Losei's are distinct, and sorted in ascending order. Backi's are the indexes of the squares marked “Go back to the start”, which satisfy 1 ≤ Backi ≤ N - 1. All Backi's are distinct, and sorted in ascending order. No numbers occur both in Losei's and Backi's.

The end of the input is indicated by a line containing four zeros separated by a space.

Output

For each dataset, you should answer the probability with which the game succeeds within the
given number of turns. The output should not contain an error greater than 0.00001.

Sample Input

6 1 0 0
7 1 0 0
7 2 0 0
6 6 1 1
2
5
7 10 0 6
1
2
3
4
5
6
0 0 0 0

Output for the Sample Input

0.166667
0.000000
0.166667
0.619642
0.000000


if __name__ == '__main__':
    while 1:
        n = int(input())
        if n ==0 :break
        line = list(map(int,input().strip().split()))
        diff = 1000000
        for i in range(n-1):
            for j in range(i+1,n):
                if diff > abs(line[i] - line[j]):diff = abs(line[i]-line[j])
        print(diff)

Selection of Participants of an Experiment

Dr. Tsukuba has devised a new method of programming training.
In order to evaluate the effectiveness of this method,
he plans to carry out a control experiment.
Having two students as the participants of the experiment,
one of them will be trained under the conventional method
and the other under his new method.
Comparing the final scores of these two,
he will be able to judge the effectiveness of his method.

It is important to select two students having the closest possible scores,
for making the comparison fair.
He has a list of the scores of all students
who can participate in the experiment.
You are asked to write a program which selects two of them
having the smallest difference in their scores.

Input

The input consists of multiple datasets, each in the following format.

n

a1 a2 … an

A dataset consists of two lines.
The number of students n is given in the first line.
n is an integer satisfying 2 ≤ n ≤ 1000.
The second line gives scores of n students.
ai (1 ≤ i ≤ n) is the score of the i-th student, which is a non-negative integer not greater than 1,000,000.

The end of the input is indicated by a line containing a zero.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, select two students with the smallest difference in their scores,
and output in a line (the absolute value of) the difference.

Sample Input

5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0

Output for the Sample Input

0
1
5


# coding: utf-8
# Your code here!
import itertools

def main():
    while True:
        n, m = map(int, input().split())
        if n == 0 : break
        ns = list(map(int, input().split()))
        ans = -1
        for p in itertools.permutations(ns, 2):
            if sum(p) <= m:
                ans = max(ans, sum(p))
        if ans == -1:
            print('NONE')
        else:
            print(ans)
main()

Taro's Shopping

Mammy decided to give Taro his first shopping experience.
Mammy tells him to choose any two items he wants from those
listed in the shopping catalogue,
but Taro cannot decide which two, as all the items look attractive.
Thus he plans to buy the pair of two items with
the highest price sum, not exceeding the amount Mammy allows.
As getting two of the same item is boring, he wants two different items.

You are asked to help Taro select the two items.
The price list for all of the items is given.
Among pairs of two items in the list,
find the pair with the highest price sum
not exceeding the allowed amount,
and report the sum.
Taro is buying two items, not one, nor three, nor more.
Note that, two or more items in the list may be priced equally.

Input

The input consists of multiple datasets, each in the following format.

n m
a1 a2 ... an

A dataset consists of two lines.
In the first line, the number of items n and the maximum
payment allowed m are given.
n is an integer satisfying 2 ≤ n ≤ 1000.
m is an integer satisfying 2 ≤ m ≤ 2,000,000.
In the second line, prices of n items are given.
ai (1 ≤ i ≤ n) is the price
of the i-th item.
This value is an integer greater than or equal to 1 and
less than or equal to 1,000,000.

The end of the input is indicated by a line containing two zeros.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, find the pair with the highest price sum
not exceeding the allowed amount m
and output the sum in a line.
If the price sum of every pair of items exceeds m,
output NONE instead.

Sample Input

3 45
10 20 30
6 10
1 2 5 8 9 11
7 100
11 34 83 47 59 29 70
4 100
80 70 60 50
4 20
10 5 10 16
0 0

Output for the Sample Input

40
10
99
NONE
20


n = int(input())
for i in range(n):
    a,b = map(int, input().split())
    coor = [[0for i in range(b+1)]for i in range(a+1)]
    p = int(input())
    prob = {}
    for k in range(p):
        z,x,c,v = map(int, input().split())
        if (z == c):
            r = max(x,v)
            if ((z,r) in prob.keys()):  ## list는 dictionary의 key가 안되지만 tuple은 가능
                prob[(z,r)] = 'xy'      ## (tuple의 불변성 때문인걸로 기억남)
            else:
                prob[(z,r)] = 'y'
        if (x == v):
            r = max(z,c)
            if ((r,x) in prob.keys()):
                prob[(r,x)] = 'xy'
            else:
                prob[(r,x)] = 'x'
    for k in range(a+1):
        for l in range(b+1):
            if (p == 0):
                if (k == 0 or l == 0):
                    coor[k][l] = 1
                else:
                    coor[k][l] = coor[k-1][l] + coor[k][l-1]
            elif (k == 0 and l == 0):
                coor[0][0] = 1
            elif (k == 0):
                if ((k,l) in prob.keys()):
                    coor[0][l] = 0
                else:
                    coor[0][l] = coor[0][l-1]
            elif (l == 0):
                if ((k,l) in prob.keys()):
                    coor[k][0] = 0
                else:
                    coor[k][0] = coor[k-1][0]
            elif ((k,l) in prob.keys() and prob[(k,l)] == 'x'):
                coor[k][l] = coor[k][l-1]
            elif ((k,l) in prob.keys() and prob[(k,l)] == 'y'):
                coor[k][l] = coor[k-1][l]
            elif ((k,l) in prob.keys() and prob[(k,l)] == 'xy'):
                coor[k][l] = 0
            else:
                coor[k][l] = coor[k-1][l] + coor[k][l-1]
    co = coor[-1][-1]
    if (co == 0):
        print('Miserable Hokusai!')
    else:
        print(co)

Problem B: 平安京ウォーキング

平安京は、道が格子状になっている町として知られている。

平安京に住んでいるねこのホクサイは、パトロールのために毎日自宅から町はずれの秘密の場所まで行かなければならない。しかし、毎日同じ道を通るのは飽きるし、後を付けられる危険もあるので、ホクサイはできるだけ毎日異なる経路を使いたい。その一方で、ホクサイは面倒臭がりなので、目的地から遠ざかるような道は通りたくない。

平安京のあちこちの道にはマタタビが落ちていて、ホクサイはマタタビが落ちている道を通ることができない。そのような道を通るとめろめろになってしまうからである。幸いなことに、交差点にはマタタビは落ちていない。

ホクサイは、自宅から秘密の場所までの可能な経路の数を知りたい。ここで、ホクサイの自宅は (0, 0) にあり、秘密の場所は(gx, gy)にある。道は x = i (i は整数), y = j (j は整数) に格子状に敷かれている。

Input

入力の1行目には、秘密の場所の座標 (gx, gy) が与えられる。これらはいずれも1以上15以下の整数で、空白1個で区切られて与えられる。 2行目にはマタタビが落ちている区間の数 p (0 ≤ p ≤ 100) が与えられ、続くp行にはマタタビが落ちている区間が1行に1区間ずつ与えられる。 p個の区間は互いに異なる。 1区間は x1 y1 x2 y2 の形で表され、(x1, y1) と (x2, y2) を端点とする、x軸またはy軸に平行な長さ1の線分である。 x1, x2 は [0, gx] の範囲にあり、y1, y2 は [0, gy] の範囲にある。

Output

可能な経路の数を出力せよ。可能な経路が1つもない場合は "Miserable Hokusai!" と1行に出力せよ。

Notes on Submission

上記形式で複数のデータセットが与えられます。入力データの 1 行目にデータセットの数が与えられます。各データセットに対する出力を上記形式で順番に出力するプログラムを作成して下さい。

Sample Input

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

Output for the Sample Input

6
Miserable Hokusai!
5
155117520


T = input()
P = input()
for i in range(len(T)):
  if T[i:].startswith(P):
    print(i)

Naive String Search

Find places where a string P is found within a text T.

Print all indices of T where P found. The indices of T start with 0.

Input

In the first line, a text T is given. In the second line, a string P is given.

output

Print an index of T where P found in a line. Print the indices in ascending order.

Constraints

1 ≤ length of T ≤ 1000

1 ≤ length of P ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output3

The ouput should be empty.


#coding:utf-8

def PS(A,B,H,W,R,C):
    for i in range(H):
        for j in range(W):
            if A[i][j]==B[0][0]:
                ans=0
                for k in range(R):
                    for l in range(C):
                        if i+k<H and j+l<W and A[i+k][j+l]==B[k][l]:
                            ans+=1
                if ans==R*C:
                    print(i,j)

if __name__=="__main__":
    H,W=map(int,input().split(" "))
    A=[]
    for i in range(H):
        A.append(list(input()))
    R,C=map(int,input().split(" "))
    B=[]
    for i in range(R):
        B.append(list(input()))
    PS(A,B,H,W,R,C)

Pattern Search

Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.

Input

In the first line, two integers H and W are given. In the following H lines, i-th lines of the region are given.

In the next line, two integers R and C are given. In the following R lines, i-th lines of the pattern are given.

output

For each sub-region found, print a coordinate i and j separated by a space character in a line. Print the coordinates in ascending order of the row numbers (i), or the column numbers (j) in case of a tie.

Constraints

1 ≤ H, W ≤ 1000

1 ≤ R, C ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

4 5
00010
00101
00010
00100
3 2
10
01
10

Sample Output 1

0 3
1 2


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

print(A)
for i in range(1, n):
    v = A[i]
    j = i - 1
    while j >= 0 and A[j] > v:
        A[j + 1] = A[j]
        j -= 1
    A[j + 1] = v
    print(*A)

Insertion Sort

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

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

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


num = int(input())
arr = list(map(int,input().split()))
print(" ".join(list(map(str,arr))))
def isn(A,N):
    for i in range(1,N):
        v = A[i]
        j = i-1
        while j >= 0 and A[j] >v:
            A[j+1] = A[j]
            j -=1
        A[j+1] = v
        print(" ".join(list(map(str,arr))))

isn(arr,num)


import math
n=int(input())
A=[0]*n
cnt=0
for i in range(0,n):
    A[i]=int(input())
for i in range(0,n):
    if A[i]<2: pass
    elif A[i]==2 or A[i]==3 or A[i]==5 or A[i]==7:
        cnt+=1
    else:
        x=int(math.sqrt(A[i])+1)
        for j in range(2,x):
            if A[i]%j==0:
                break
            else: pass
            if j==x-1:
                cnt+=1
            else: pass
print(cnt)

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


def selection_sort(a):
    res = 0
    for i in range(len(a)):
        m = i
        for j in range(i, len(a)):
            if a[m] > a[j]:
                m = j
        if m != i:
            res += 1
            a[i], a[m] = a[m], a[i]
    return res

def main():
    n = int(input())
    a = list(map(int, input().split()))
    ans = selection_sort(a)
    print(' '.join(map(str, a)))
    print(ans)

if __name__ == '__main__':
    main()

Selection Sort

Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

SelectionSort(A)
1 for i = 0 to A.length-1
2 mini = i
3 for j = i to A.length-1
4 if A[j] < A[mini]
5 mini = j
6 swap A[i] and A[mini]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 6 of the pseudocode in the case where i ≠ mini.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by space characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 6 4 2 1 3

Sample Output 1

1 2 3 4 5 6
4

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
3


def search_down_index(index, depthes, L):
    "index?????????????§??????????????????¨?????????????????????"
    for i in range(index, L - 1):
        if depthes[i] > depthes[i + 1]:
            return i
    return None

def search_down_index_reverse(index, depthes, L):
    "index?????????????§??????????????????¨?????????????????????"
    for i in range(index, -1, -1):
        if depthes[i] > depthes[i - 1]:
            return i
    return None

def search_up_index(index, depthes, L):
    "index?????????????§??????????????????¨?????????????????????"
    for i in range(index, L - 1):
        if depthes[i] < depthes[i + 1]:
            return i
    return None

def search_up_index(index, depthes, L):
    "index?????????????§??????????????????¨?????????????????????"
    for i in range(index, -1, -1):
        if depthes[i] < depthes[i + 1]:
            return i
    return None

def search_index_by_depth(index, depth, depthes, L):
    for i in range(index, L):
        if depthes[i] == depth:
            return i
    return None

def search_index_by_depth_reverse(index, depth, depthes, L):
    for i in range(index, -1, -1):
        if depthes[i] == depth:
            return i
    return None

def calc_area(begin_index, end_index, depthes):
    init_depth = depthes[begin_index]
    area = 0
    for i in range(begin_index, end_index):
        d1 = depthes[i]
        d2 = depthes[i + 1]
        if d1 > d2:
            area += (init_depth - d2 - 0.5)
        elif d1 == d2:
            area += init_depth - d1
        else:
            area += (init_depth - d1 - 0.5)
    return area

depthes = []
depth = 0
depthes.append(0)
for c in input():
    if c == "/":
        depth += 1
    elif c == "?\" or c == "\\":
        depth += -1
    depthes.append(depth)

L = len(depthes)
pond_ranges = []
stack = []
left_begin_index = search_down_index(0, depthes, L)
right_begin_index = search_down_index_reverse(L - 1, depthes, L)
while left_begin_index != None and right_begin_index != None and left_begin_index < right_begin_index:
    dl = depthes[left_begin_index]
    dr = depthes[right_begin_index]
    if dl < dr:
        left_end_index = search_index_by_depth(left_begin_index + 1, dl, depthes, L)
        pond_ranges.append((left_begin_index, left_end_index))
        left_begin_index = search_down_index(left_end_index, depthes, L)
    else:
        right_end_index = search_index_by_depth_reverse(right_begin_index - 1, dr, depthes, L)
        pond_ranges.append((right_end_index, right_begin_index))
        right_begin_index = search_down_index_reverse(right_end_index, depthes, L)

pond_ranges.sort()

k = len(pond_ranges)
areas = []
for r in pond_ranges:
    areas.append(int(calc_area(r[0], r[1], depthes)))
print(sum(areas))
print(str(k), " ".join(map(str, areas)))

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

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

For a given cross-section diagram, reports areas of flooded sections.

Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

In the first line, print the total area $A$ of created floods.

In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9


s1 = []
s2 = []
a = 0
s = input()
for i in range(len(s)):
    if s[i] == "\\":
        s1.append(i)
    elif s[i] == "/" and len(s1)>0:
        j = s1.pop()#position of nearest \
        a += i-j
        a_splt = i-j
        while(len(s2) > 0 and s2[-1][0] > j):
            a_splt += s2.pop()[1]
        s2.append([j, a_splt])

print(a)
ans = ""
ans += str(len(s2))
for area in s2:
    ans += " " + str(area[1])
print(ans)


#coding:UTF-8
def Check(P,k,w):
    i=0
    for j in range(k):
        s=0
        while s+w[i]<=P:
            s+=w[i]
            i+=1
            if i==n:
                return n
    return i

def Allocation(n,k,w):
    left=0
    right=100000000000000
    while right-left > 1:
        mid=int((left+right)/2)
        v=Check(mid,k,w)
        if v>=n:
            right=mid
        else:
            left=mid
    print(right)

if __name__=="__main__":
    a=input()
    n=int(a.split(" ")[0])
    k=int(a.split(" ")[1])
    w=[]
    for i in range(n):
        w.append(int(input()))
    Allocation(n,k,w)

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

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


def merge(A,left,mid,right):
    n1=mid-left
    n2=right-mid
    L=[0]*(n1+1)
    R=[0]*(n2+1)
    for i in range(n1):
        L[i]=A[left+i]
    for i in range(n2):
        R[i]=A[mid+i]
    L[n1]=float("inf")
    R[n2]=float("inf")
    i=0
    j=0
    global cnt
    cnt += (right-left)
    for k in range(left,right):
#        cnt+=1
        if L[i]<=R[j]:
            A[k]=L[i]
            i=i+1
        else:
            A[k]=R[j]
            j=j+1

def mergeSort(A,left,right):
    if left+2<right:
        mid=(left+right)//2
        mergeSort(A,left,mid)
        mergeSort(A,mid,right)
        merge(A,left,mid,right)
    elif left+1<right:
        mid =left+1
        merge(A,left,mid,right)

n=int(input())
S=list(input().split())
for i in range(n):
    S[i]=int(S[i])
cnt=0
mergeSort(S,0,n)
for i in range(n):
    if i==n-1:
        print(S[i])
    else:
        print(S[i],end=" ")
print(cnt)

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


n = int(input())
lis = list(map(int,input().split()))
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    # ここで分割を行う
    left = arr[:mid]
    right = arr[mid:]

    # 再帰的に分割を行う
    left = merge_sort(left)
    right = merge_sort(right)

    # returnが返ってきたら、結合を行い、結合したものを次に渡す
    return merge(left, right)

def merge(left, right):
    global ans
    merged = []
    l_i, r_i = 0, 0

    # ソート済み配列をマージするため、それぞれ左から見ていくだけで良い
    while l_i < len(left) and r_i < len(right):
        # ここで=をつけることで安定性を保っている
        if left[l_i] <= right[r_i]:
            merged.append(left[l_i])
            l_i += 1
        else:
            merged.append(right[r_i])
            r_i += 1
            ans += (len(left) - l_i)

    # 上のwhile文のどちらかがFalseになった場合終了するため、あまりをextendする
    if l_i < len(left):
        merged.extend(left[l_i:])
    if r_i < len(right):
        merged.extend(right[r_i:])
    return merged

ans = 0
merge_sort(lis)
print(ans)

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

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


def find(x):
    if tree[x] < 0:
        return x
    tree[x] = find(tree[x])
    return tree[x]

def unite(x, y):
    x_position = find(x)
    y_position = find(y)
    if x_position == y_position:
        return True
    if y_position < x_position:
        x_position, y_position = y_position, x_position
    tree[x_position] += tree[y_position]
    tree[y_position] = x_position
    return False

def same(x, y):
    if find(x) == find(y):
        print(1)
    else:
        print(0)

n, q = map(int, input().split())
tree = [-1] * n
for i in range(q):
    com, x, y = map(int, input().split())
    if com == 0:
        unite(x, y)
    if com == 1:
        same(x, y)

Disjoint Set

Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.

First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.

Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations:

unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set.

same(x, y): determine whether x and y are in the same set.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation.

Output

For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line.

Constraints

1 ≤ n ≤ 10000

1 ≤ q ≤ 100000

x ≠ y

Sample Input

5 12
0 1 4
0 2 3
1 1 2
1 3 4
1 1 4
1 3 2
0 1 3
1 2 4
1 3 0
0 0 4
1 0 2
1 3 0

Sample Output

0
0
1
1
1
0
1
1


import heapq
def dijkstra_heap(s,edge):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    for i,j in enumerate(used):
        if j:
            d[i]=-1
    return d

n,w,r = map(int,input().split()) #n:頂点数　w:辺の数
edge = [[] for i in range(n)]
#edge[i] : iから出る道の[重み,行先]の配列
for i in range(w):
    x,y,z = map(int,input().split())
    edge[x].append([z,y])
for i in dijkstra_heap(r,edge):
    if i==-1:
        print('INF')
    else:
        print(i)

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF


from enum import Enum
import sys
import math

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001

while True:
    N = int(input())
    if N == 0:
        break
    table = list(map(int,input().split()))

    tmp_sum = 0
    for i in range(len(table)):
        tmp_sum += table[i]
    B = tmp_sum/len(table) #平均

    squared_sum = 0
    for i in range(len(table)):
        squared_sum += table[i]*table[i]
    A = squared_sum/len(table)

    print("%.10f"%(math.sqrt(A-B*B)))

Standard Deviation

You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.

The variance α2 is defined by

α2 = (∑ni=1(si - m)2)/n

where m is an average of si.

The standard deviation of the scores is the square root of their variance.

Input

The input consists of multiple datasets. Each dataset is given in the following format:

n
s1 s2 ... sn

The input ends with single zero for n.

Output

For each dataset, print the standard deviation in a line. The output should not contain an absolute error greater than 10-4.

Constraints

n ≤ 1000

0 ≤ si ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000


X Cubic

Write a program which calculates the cube of a given integer x.

Input

An integer x is given in a line.

Output

Print the cube of x in a line.

Constraints

1 ≤ x ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27


a, b = map(int, input().split(" "))
area = a*b
perimeter = 2*(a+b)
print(area, perimeter)

Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

The length a and breadth b of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

1 ≤ a, b ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16


a,b = map(float, input().split())
A = a*b
C = a*2+b*2

print(int(A), int(C))


s = int(input())
m = 0
h = 0

if s >= 60:
    m = int(s / 60)
    s = s % 60

if m >= 60:
    h = int(m / 60)
    m = m % 60

print(h,end = ":")
print(m,end = ":")
print(s)

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

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


a,b,c=[int(x) for x in input().split()]
print("Yes" if a<b<c else "No")

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


nums = input().split()
nums.sort
print(nums, end='')

Sorting Three Numbers

Write a program which reads three integers, and prints them in ascending order.

Input

Three integers separated by a single space are given in a line.

Output

Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8


x=input().split()
x=list(map(int, x))
W,H,x,y,r = x[0],x[1], x[2], x[3],x[4]
if x-r < 0:
    print("No")
elif x+r > W :
    print("No")
elif y+r > H:
    print("No")
elif y-r < 0:
    print("No")
else:
    print("Yes")

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

Circle in a Rectangle

Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100 \leq x, y \leq 100$

$ 0 < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No


W,H,x,y,r = map(int,raw_input().split())
if r <= x <= W-r and r <= y <= H-r:
	print "Yes"
else:
	print "No"


import sys

while 1:
  str = sys.stdin.readline().strip()
  a , b = sorted(str.split(" "), key=int)
  if a == b == "0":
    break
  print(a,b)

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


while True:
  x,y=map(int,input().split())

  if x<y:
    print(x,y)

  elif y<x:
    print(y,x)

  elif x==y==0:
    break


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

How Many Divisors?

Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.

Input

Three integers a, b and c are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


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


[a,b]=raw_input().split()
x=long(a)
y=long(b)
z=float(a)
w=float(b)
d=x/y
r=x%y
f=1.0000*z/y
print d,r,f

A/B Problem

Write a program which reads two integers a and b, and calculates the following values:

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


a, b = map(int, input().split())
d=int(a/b)
r=int(a%b)
f=a/b
print(f"{d} {r} {f:.5f}")


z = input()
a,b = [ int(x) for x in z.split() ]
d = a // b
r = a % b
f = float(a) / b
f = round( f , 5 )
print (str(d) + " " + str(r) + " " + str(f))


import math
r = float(input())

pi =math.pi

print('%.10f %.10f'%(r*r*pi,2*r*pi))

Circle

Write a program which calculates the area and circumference of a circle for given radius r.

Input

A real number r is given.

Output

Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-5.

Constraints

0 < r < 10000

Sample Input 1

2

Sample Output 1

12.566371 12.566371

Sample Input 2

3

Sample Output 2

28.274334 18.849556


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

print("{} {} {}".format(min(array), max(array), sum(array)))

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

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


_ = input()
n = list(map(int, input().split()))
print("{} {} {}".format(min(n), max(n), sum(n)))


while True:
    H,W = map(int,input().split())
    if H==W==0:
        break
    for _ in range(H):
        print('#'*W)
    print()

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

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

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

##
##


while True:
    (H, W) = [int(x) for x in input().split()]
    if H == W == 0:
        break

    for hc in range(H):
        if hc == 0 or hc == H -1:
            print('#' * W)
        else:
            print('#' + '.' * (W -2) + '#')
    print()

Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

##########
#........#
#........#
#........#
#........#
##########

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Constraints

3 ≤ H ≤ 300

3 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
0 0

Sample Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###


while True:
    h,w = map(int, input().split())
    if h == 0 and w == 0: break
    for j in range(h):
        for i in range(w):
            if i == 0 or j == 0 or i == w-1 or j == h-1:
                print("#", end="")
            else:
                print(".", end="")
        print()
    print()


count = int(input())
array = [int(i) for i in input().split(" ")]

for n in range( len(array) - 1, -1, -1):
    print(array[n], end = " ")

Reversing Numbers

Write a program which reads a sequence and prints it in the reverse order.

Input

The input is given in the following format:

n
a1 a2 . . . an

n is the size of the sequence and ai is the ith element of the sequence.

Output

Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).

Constraints

n ≤ 100

0 ≤ ai < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説


n = int(input())

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

print(' '.join(a[::-1]))


r,c = map(int, input().split())
matrix = [[0 for i in range(c+1)] for j in range(r+1)]
for i in range(r):
  l = list(map(int, input().split()))
  for j in range(c):
    matrix[i][j] += l[j]
    matrix[i][c] += matrix[i][j]
    matrix[r][j] += matrix[i][j]
    matrix[r][c] += matrix[i][j]
  print(" ".join(map(str, matrix[i])))
print(" ".join(map(str, matrix[r])))

Spreadsheet

Your task is to perform a simple table calculation.

Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.

Input

In the first line, two integers r and c are given. Next, the table is given by r lines, each of which consists of c integers separated by space characters.

Output

Print the new table of (r+1) × (c+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56


def main(N, M, L, a, b):
    results = [[0]*L for i in range(N)]
    for n in range(N):
        for l in range(L):
            for m in range(M):
                results[n][l] += a[n][m]*b[m][l]
    results = [" ".join(map(str, i)) for i in results]
    return '\n'.join(map(str, results))

if __name__ == "__main__":
    N, M, L = map(int, input().split())
    a = [list(map(int, input().split())) for i in range(N)]
    b = [list(map(int, input().split())) for j in range(M)]
    print(main(N, M, L, a, b))

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

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


n, m, l = map(int, input().split())
a = [0 for i in range(n)]
b = [0 for i in range(m)]

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

s = 0
for i in range(n):
  for j in range(l):
    for k in range(m):
      s = s + a[i][k] * b[k][j]
    if k == (m-1):
      print(s, end="")
      s = 0
      if j == (l-1):
        print("")
      else:
        print("", "", end="")


while True:
  a = input()
  if a == "0":
    break
  s = 0
  for i in a:
    s += int(i)
  print(s)

Sum of Numbers

Write a program which reads an integer and prints sum of its digits.

Input

The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.

The input ends with a line including single zero. Your program should not process for this terminal symbol.

Output

For each dataset, print the sum of digits in x.

Sample Input

123
55
1000
0

Sample Output

6
10
1


target = input()

count = 0
while True:
    line = input()
    if line == 'END_OF_TEXT':
        break

    for word in line.split():
        if word.lower() == target.lower():
            count += 1

print(count)

Finding a Word

Write a program which reads a word W and a text T, and prints the number of word W which appears in text T

T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.

Constraints

The length of W ≤ 10

W consists of lower case letters

The length of T in a line ≤ 1000

Input

In the first line, the word W is given. In the following lines, the text T is given separated by space characters and newlines.

"END_OF_TEXT" indicates the end of the text.

Output

Print the number of W in the text.

Sample Input

computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT

Sample Output

3


n = int(input())

# n<= 10**9なので、高速化する
# 約数列挙でroot N に抑えるか？
def prime_divide(n):
    res = []
    i = 2
    while True:
        if n % i == 0:
            res.append(i)
            n //= i
        else:
            i += 1
            if i > n ** (0.5):
                break
    if n != 1:
        res.append(n)
    return res

print(n, end="")
print(":", *prime_divide(n))

Prime Factorization

Factorize a given integer n.

Input

n

An integer n is given in a line.

Output

Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.

Constraints

2 ≤ n ≤ 109

Sample Input 1

12

Sample Output 1

12: 2 2 3

Sample Input 2

126

Sample Output 2

126: 2 3 3 7


def smallest_factor(integer):
    j = 2
    while j :
        if j ** 2 > integer:
            return integer
        elif integer % j == 0:
            return j
        else:
            j += 1

n = int(input())
start = str(n)
prime_factors = []
while n >= 2:
    prime_factors.append(str(smallest_factor(n)))
    n //= smallest_factor(n)

print(start +  ': '+ ' '.join(prime_factors))


def factrize(x):
    # 試し割りによるxの素因数分解
    f = {}
    tmp = x
    i = 2
    while i**2 <= tmp:
        cnt = 0
        while tmp % i == 0:
            cnt += 1
            tmp = tmp // i
        if cnt > 0:
            f[i] = cnt
        i += 1
    if tmp != 1 or f == {}:
        f[tmp] = 1
    return f

n = int(input())
f = factrize(n)
ans = 1
for p in f:
    ans *= p**(f[p] - 1) * (p - 1)
print(ans)

Euler's Phi Function

For given integer n, count the totatives of n, that is, the positive integers less than or equal to n that are relatively prime to n.

Input

n

An integer n (1 ≤ n ≤ 1000000000).

Output

The number of totatives in a line.

Sample Input 1

6

Sample Output 1

2

Sample Input 2

1000000

Sample Output 2

400000


for _ in range(int(input())):
  print("ACL",end="")
print("")

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


class SegmentTree:
    def __init__(self, iterable, op, e):
        n = len(iterable)
        self._op = op
        self._e = e
        self._size = n
        t = 1 << (n - 1).bit_length()
        self._offset = t - 1
        self._data = [e] * (t * 2 - 1)
        self._data[self._offset:self._offset + self._size] = iterable
        for i in range(self._offset - 1, -1, -1):
            self._data[i] = op(self._data[i * 2 + 1], self._data[i * 2 + 2])

    def __getitem__(self, key):
        return self._data[self._offset + key]

    def __setitem__(self, key, value):
        op = self._op
        data = self._data
        i = self._offset + key
        data[i] = value
        while i >= 1:
            i = (i - 1) // 2
            data[i] = op(data[i * 2 + 1], data[i * 2 + 2])

    def query(self, start, end):
        op = self._op
        res = self._e
        l = self._offset + start
        r = self._offset + end
        while l < r:
            if l & 1 == 0:
                res = op(res, self._data[l])
            if r & 1 == 0:
                res = op(res, self._data[r - 1])
            l = l // 2
            r = (r-1) // 2
        return res

    def getTop(self):
        return self._data[0]

N,K=map(int,input().split())
A = []
for i in range(N):
  a = int(input())-1
  A.append(a)

A_MAX = 303030
dp = [0]*A_MAX

st = SegmentTree(dp,max,0)

for i in range(N):
  s = max(A[i]-K, 0)
  e = min(A[i]+K+1, A_MAX+1)
  st[A[i]] = st.query(s, e) + 1
print(st.getTop())

Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values 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

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

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.


N = int(input())

ans = [0] * N

for A in range(1, N):
    ans[A] = (N - 1) // A

print(sum(ans))

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


n = int(input())
targetlist = [i+1 for i in range(n)]
cnt=0
import itertools
for i in itertools.product(targetlist,targetlist,targetlist):
    if (i[0]*i[1])+i[2] == n:
        cnt+=1
print(cnt)


N, X, M = [int(i) for i in input().split()]
mods = [X]
start = None
for i in range(N-1):
  X = X*X % M
  if X not in mods:
    mods.append(X)
  else:
    start = mods.index(X)
    break
spec, period = mods[:start], mods[start::]
N -= len(spec)
S = sum(spec)
S += sum(period)*(int(N/len(period))) + sum(period[:N%len(period):])
print(S)

Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507


def main():
    n, x, m = map(int, input().split())
    a = x
    s = a
    seen = {a}
    seq = [a]
    for i in range(n - 1):
        if a == pow(a, 2, m):
            print(s + a * (n - i - 1))
            return
        else:
            a = pow(a, 2, m)
            if a in seen:
                si = seq.index(a)
                sl = i - si + 1
                ps = s - sum(seq[:si])
                ln = (n - i - 1) // sl
                lm = (n - i - 1) % sl
                print(s + ps * ln + sum(seq[si:si + lm]))
                return
            s += a
            seen.add(a)
            seq.append(a)
    print(s)

if __name__ == '__main__':
    main()


a, b, c, d = list(map(int, input().split()))
print(max(a*c, a*d, b*c, b*d))

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


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

print(max(a*c,a*d,b*c,c*d))


import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

a,b,c,d = MI()
print(max(a*c,a*d,b*c,b*d))


Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


#!/usr/bin/env pypy3

MODULUS = 10**9+7

N = int(input())

ret = pow(10, N, MODULUS)
ret -= 2*pow(9, N, MODULUS)
ret += pow(8, N, MODULUS)

print(ret)


def main():
    S=int(input())

    mod=10**9+7
    all=pow(2,S-1,mod)
    for i in range(S-2,1,-1):
        all=all-pow(2,i,mod)
    if S%3==0:
        print(all)
    elif S%3==1:
        print(all+1)
    else:
        print(all+2)
if __name__=="__main__":
    main()

Score : 400 points

Problem Statement

Given is an integer S.
Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S.
The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq S \leq 2000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

7

Sample Output 1

3

3 sequences satisfy the condition: \{3,4\}, \{4,3\} and \{7\}.

Sample Input 2

2

Sample Output 2

0

There are no sequences that satisfy the condition.

Sample Input 3

1729

Sample Output 3

294867501


class RMaxQ:

    __slots__ = ["n", "data"]

    def __init__(self, li):
        self.n = len(li)
        self.data = li*2
        for i in range(self.n - 1, 0, -1):
            self.data[i] = max(self.data[2*i], self.data[2*i+1])

    def update(self, i, a):
        i += self.n
        self.data[i] = a
        while i > 1:
            i //= 2
            self.data[i] = max(self.data[2*i], self.data[2*i+1])

    def add(self, i, a):
        i += self.n
        self.data[i] += a
        while i > 1:
            i //= 2
            self.data[i] = max(self.data[2*i], self.data[2*i+1])

    def fold(self, l, r):
        l += self.n
        r += self.n
        res = 0
        while l < r:
            if l % 2:
                res = max(self.data[l], res)
                l += 1
            if r % 2:
                r -= 1
                res = max(res, self.data[r])
            l //= 2
            r //= 2
        return res

import sys
input = sys.stdin.readline
n, q = map(int, input().split())
A = list(map(int, input().split()))
seg = RMaxQ(A)
for _ in range(q):
    t, x, v = map(int, input().split())
    x -= 1
    if t == 1:
        seg.update(x, v)
    elif t == 2:
        print(seg.fold(x, v))
    else:
        ng = x
        ok = n+1
        while ok - ng > 1:
            mid = (ok+ng)//2
            if seg.fold(x, mid) >= v:
                ok = mid
            else:
                ng = mid
        print(ok)

Score : 100 points

Problem Statement

You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.

The type of i-th query is represented by T_i.

T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.

T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.

T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.

Constraints

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

0 \leq A_i \leq 10^9

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

1 \leq T_i \leq 3

1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)

1 \leq L_i \leq R_i \leq N (T_i=2)

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query

Each query is given in the following format:

If T_i=1,3,

T_i X_i V_i

If T_i=2,

T_i L_i R_i

Output

For each query with T_i=2, 3, print the answer.

Sample Input 1

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

Sample Output 1

3
3
2
6

First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).

Second query: Since 3>A_2, j=2 does not satisfy the condition．Since 3 \leq A_3, print j=3.

Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).

Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).

Fifth query: Since there is no j that satisfies the condition, print j=N+1=6.


import sys
readline = sys.stdin.readline
from operator import xor
class Lazysegtree:
    def __init__(self, A, fx, ex, fm, em, fa, initialize = True):
        #fa(operator, idx)の形にしている、data[idx]の長さに依存する場合などのため
        self.N = len(A)
        self.N0 = 2**(self.N-1).bit_length()
        """
        self.fx = fx
        self.fa =
        """
        self.fm = fm

        self.ex = ex
        self.em = em
        self.lazy = [em]*(2*self.N0)
        if initialize:
            self.data = [self.ex]*self.N0 + A + [self.ex]*(self.N0 - self.N)
            for i in range(self.N0-1, -1, -1):
                self.data[i] = self.fx(self.data[2*i], self.data[2*i+1])
        else:
            self.data = [self.ex]*(2*self.N0)
    def fx(self, x, y):
        return (x[0]+y[0], x[1]+y[1], x[2]+y[2]+x[1]*y[0])
    def fa(self, ope, idx):
        """
        TO WRITE
        """
        if ope == 0:
            return self.data[idx]
        zero, one, t = self.data[idx]
        return (one, zero, (one+zero)*(one+zero-1)//2 - one*(one-1)//2 - zero*(zero-1)//2 - t)

    def __repr__(self):
        s = 'data'
        l = 'lazy'
        cnt = 1
        for i in range(self.N0.bit_length()):
            s = '\n'.join((s, ' '.join(map(str, self.data[cnt:cnt+(1<<i)]))))
            l = '\n'.join((l, ' '.join(map(str, self.lazy[cnt:cnt+(1<<i)]))))
            cnt += 1<<i
        return '\n'.join((s, l))

    def _ascend(self, k):
        k = k >> 1
        c = k.bit_length()
        for j in range(c):
            idx = k >> j
            self.data[idx] = self.fx(self.data[2*idx], self.data[2*idx+1])

    def _descend(self, k):
        k = k >> 1
        idx = 1
        c = k.bit_length()
        for j in range(1, c+1):
            idx = k >> (c - j)
            if self.lazy[idx] == self.em:
                continue
            self.data[2*idx] = self.fa(self.lazy[idx], 2*idx)
            self.data[2*idx+1] = self.fa(self.lazy[idx], 2*idx+1)
            self.lazy[2*idx] = self.fm(self.lazy[idx], self.lazy[2*idx])
            self.lazy[2*idx+1] = self.fm(self.lazy[idx], self.lazy[2*idx+1])
            self.lazy[idx] = self.em

    def query(self, l, r):
        L = l+self.N0
        R = r+self.N0
        self._descend(L//(L & -L))
        self._descend(R//(R & -R)-1)

        sl = self.ex
        sr = self.ex

        while L < R:
            if R & 1:
                R -= 1
                sr = self.fx(self.data[R], sr)
            if L & 1:
                sl = self.fx(sl, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return self.fx(sl, sr)

    def operate(self, l, r, x):
        L = l+self.N0
        R = r+self.N0

        Li = L//(L & -L)
        Ri = R//(R & -R)
        self._descend(Li)
        self._descend(Ri-1)

        while L < R :
            if R & 1:
                R -= 1
                self.data[R] = self.fa(x, R)
                self.lazy[R] = self.fm(x, self.lazy[R])
            if L & 1:
                self.data[L] = self.fa(x, L)
                self.lazy[L] = self.fm(x, self.lazy[L])
                L += 1
            L >>= 1
            R >>= 1

        self._ascend(Li)
        self._ascend(Ri-1)

MOD = 998244353
mask = (1<<32) - 1

N, Q = map(int, readline().split())
A = list(map(int, readline().split()))
A = [(0, 1, 0) if a == 1 else (1, 0, 0) for a in A]
T = Lazysegtree(A, None, (0, 0, 0), xor, 0, None, initialize = True)

Ans = []
for _ in range(Q):
    t, *s = readline().split()
    if t == '1':
        l, r = map(int, s)
        T.operate(l-1, r, 1)
    else:
        l, r = map(int, s)
        Ans.append(T.query(l-1, r)[2])

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

Score : 100 points

Problem Statement

You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N.

Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i.

T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i.

T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}．

Note：The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.

Constraints

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

0 \leq A_i \leq 1

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

1 \leq T_i \leq 2

1 \leq L_i \leq R_i \leq N

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
A_1 A_2 \cdots A_N
T_1 L_1 R_1
T_2 L_2 R_2
\vdots
T_Q L_Q R_Q

Output

For each query with T_i=2, print the answer.

Sample Input 1

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

Sample Output 1

2
0
1

First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).

Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.

Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).

Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.

Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0).


D, T, S = map(int,input().split())
if D/S<=T:
    print("Yes")
else:
    print("NO")

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


data=list(map(int,input().split()))
if data[0]/data[1]<=data[2]:
    print('Yes')
else:
    print('No')


import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

d,t,s = map(int, readline().split())

print('Yes' if d <= t*s else 'No')


import sys
# sys.stdin  = open("input.txt")
s=input()
t=input()
lol=float('inf')
for i in range(len(s)-len(t)+1):
    ch=0
    # print(i)
    for j in range(len(t)):
        # if i+j==(len(s)-1):
        #     print("yey")
        if s[i+j]!=t[j]:
            ch+=1
    lol=min(lol,ch)
print(lol)

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def main():
    N, M = map(int, input().split())
    AB = [list(map(int, input().split())) for _ in range(M)]

    uf = UnionFind(N)

    for ab in AB:
        uf.union(ab[0]-1, ab[1]-1)

    g = uf.all_group_members()

    ans = 0
    for gg in g:
        if len(g[gg]) > ans:
            ans = len(g[gg])

    print(ans)

if __name__ == "__main__":
    main()

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

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

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


n, x, t = input().split()
n = int(n)
x = int(x)
t = int(t)

if n % x == 0:
  print((n/x)*t)
else:
  print((n//x)*t)

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.