import sys

heights = []

for height in sys.stdin:
  heights.append(int(height.rstrip()))

heights.reverse()

for i in range(3):
  print heights[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.


Reverse Sequence

Write a program which reverses a given string str.

Input

str (the size of str ≤ 20) is given in a line.

Output

Print the reversed str in a line.

Sample Input

w32nimda

Output for the Sample Input

admin23w


import bisect

MAX = 50050

#エラトステネスの篩
is_prime = [True for _ in range(MAX)]
is_prime[0] = is_prime[1] = False
for i in range(2, int(MAX ** (1 / 2)) + 1):
  if is_prime[i]:
    for j in range(i ** 2, MAX, i):
      is_prime[j] = False

primes = [i for i in range(MAX) if is_prime[i]]

while True:
  try:
    n = int(input())
    ind = bisect.bisect_left(primes, n)
    if primes[ind] == n:
      print(primes[ind - 1], primes[ind + 1])
    else:
      print(primes[ind - 1], primes[ind])

  except EOFError:
    break

素数 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
arr = [1,0,0]
for line in sys.stdin:
    s = line.split(',')
    if s[0] == 'A':
        n = 0
    elif s[0] == 'B':
        n = 1
    else:
        n = 2
    if s[1] == 'A':
        m = 0
    elif s[1] == 'B':
        m = 1
    else:
        m = 2

    if arr[n] == 1 or arr[m] == 1:
        t = arr[n]
        arr[n] = arr[m]
        arr[m] = t

for i in range(len(arr)):
    if arr[i] == 1:
        if i == 0:
            print('A')
        elif i == 1:
            print('B')
        else:
            print('C')

カップゲーム

3 つのカップがふせて置かれています。カップの置かれている場所を、順に A,B,C と呼ぶことにします。最初は A に置かれているカップの中にボールが隠されているとします。カップの位置を入れ替えると、中に入っているボールも一緒に移動します。

入れ替える２つのカップの位置を読み込んで、最終的にどの場所のカップにボールが隠されているかを出力するプログラムを作成してください。

Input

入れ替える２つのカップの位置が順番に複数行にわたり与えられます。各行に、入れ替える２つのカップの位置を表す文字（A, B, または C）がカンマ区切りで与えられます。

入れ替える操作は 50 回を超えません。

Output

ボールが入っているカップの場所（A, B, または C）を１行に出力します。

Sample Input

B,C
A,C
C,B
A,B
C,B

Output for the Sample Input

A


d = {};
d["A"] = 0;
d["B"] = 0;
d["AB"] = 0;
d["O"] = 0;

while True:
 try:
  b = raw_input().strip().split(",")[1]
  d[b] += 1;
 except:
  break;

print d["A"]
print d["B"]
print d["AB"]
print d["O"]

血液型

ある学級の生徒の出席番号と ABO 血液型を保存したデータを読み込んで、おのおのの血液型の人数を出力するプログラムを作成してください。なお、ABO 血液型には、A 型、B 型、AB 型、O 型の４種類の血液型があります。

Input

カンマで区切られた出席番号と血液型の組が、複数行に渡って与えられます。出席番号は 1 以上 50 以下の整数、血液型は文字列 "A", "B", "AB" または "O" のいずれかです。生徒の人数は 50 を超えません。

Output

１行目に A 型の人数

２行目に B 型の人数

３行目に AB 型の人数

４行目に O 型の人数

を出力します。

Sample Input

1,B
2,A
3,B
4,AB
5,B
6,O
7,A
8,O
9,AB
10,A
11,A
12,B
13,AB
14,A

Output for the Sample Input

5
4
3
2


import sys

def solve(n):
    sum = n
    current_value = n
    for i in range(2, 11):
        if i%2 == 0:
            next_value = current_value * 2.0
        else:
            next_value = current_value / 3.0
        sum += next_value
        current_value = next_value
    return sum

if __name__ == '__main__':
    # ??????????????\?????¨???????????????
    for line in sys.stdin:
        n = float(line.strip())
        result = solve(n)
        print('{:.8f}'.format(result))

数列

次のように定義されている数列があります。

すべての偶数番目の項は一つ前の項に 2 を掛けたものと等しい数である。

すべての奇数番目の項は一つ前の項を 3 で割ったものと等しい数である。

この数列の初項 a を読み込み、初項から第 10 項までの和 s(10) を出力するプログラムを作成してください。

Input

入力は複数のテストケースからなります。各テストケースとして、数列の初項を表す実数 a (1.0 ≤ a ≤ 10.0) が１行に与えられます。

テストケースの数は 50 を超えません。

Output

テストケースごとに s(10) を１行に出力します。

出力は0.000001以下の誤差を含んでもよい。

Sample Input

1.0
2.0
3.0

Output for the Sample Input

7.81481481
15.62962963
23.44444444


def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break

teams = [0 for i in range(101)]
points = [False for i in range(31)]
while True:
    a,b = [int(i) for i in input().split(",")]
    if a == 0 and b == 0:
        break

    teams[a] = b
    points[b] = True

N = list(get_input())
for l in range(len(N)):
    q = int(N[l])
    p = teams[q]
    ans = 0
    for i in range(30,-1,-1):
        if points[i]:
            ans += 1
        if i == p:
            break
    print(ans)

Rank Checker

時は2020 年。パソコン甲子園 2020 の予選結果を保存したデータがあります。このデータには、各チームに振られる整理番号と正解数が保存されています。ここでは、正解数で順位を決定するものとし、正解数の多いほうから順に 1 位、2 位 ... と順位をつけていくこととします。

予選結果のデータと整理番号をキーボードから入力して、その番号のチームの順位を出力するプログラムを作成してください。

Input

入力データは２つの部分からなります。前半の部分は、予選結果のデータ、後半の部分は順位を知りたいチーム番号の問い合わせです。予選結果のデータの形式は以下の通りです。

p1,s1
p2,s2
...
...
0,0

pi (1 ≤ pi ≤ 100 )、 si (0 ≤ si ≤ 30) はそれぞれ i チーム目の整理番号と正解数を表す整数です。整理番号と正解数がともに 0 のときこのデータの入力が終わるものとします。

続いて後半の問い合わせが複数与えられます。問い合わせの形式は以下の通りです。

q1
q2
:

各問い合わせは１行に整理番号 qi (1 ≤ qi ≤ 30) が与えられます。これを入力の最後まで処理して下さい。問い合わせの数は 100 を超えません。

Output

各問い合わせについて、チームの順位を１行に出力して下さい。

Sample Input

1,20
2,20
3,30
4,10
5,10
6,20
0,0
1
2
4
5

Output for the Sample Input

2
2
3
3

Note

入力例のデータにおいて、チームを正解数順に整列すると：

3,30
1,20
2,20
6,20
4,10
5,10

となります。ここでは、正解数を基に順位を決定するため、30問正解チームを1位、20問正解チームを2位、10問正解チームを3位とします（上位のチーム数を考慮し、10問正解チームを5位とする通常の順位付けとは異なることに注意して下さい）。


import sys
##device
d = [1,4,1,4,1,2,1,2]

"""
dd = []
for i in range(8):
    dd = d[i:] + d[-8:i-8]
    print dd
"""
min = 10000
r = -1

for i in range(2):
    g = map(int,raw_input().split())
    for j in range(8):
        dd = d[j:] + d[-8:j-8]
        t = []
        for k in range(8):
            if dd[k] - g[k] > 0:
                t.append(dd[k] - g[k])
            else:
                t.append(g[k] - dd[k])
        if sum(t) < min:
            min = sum(t)
            r = j
    re = d[r:] + d[-8:r-8]
    print re

メリーゴーランド

遊園地にあるメリーゴーランドはご存じでしょう。大きな円盤の上に馬や馬車などの乗り物が固定されていて、円盤が回転すると同時に乗り物が上下に揺れる、定番の遊具です。ある遊園地のメリーゴーランドは、４人乗りの馬車が２台、２人乗りの車２台、１人乗りの馬が４台、計８台の乗り物が図１のような順序で備えられています。そして、遊園地においでのお客様は、図１に示す乗り場０〜７のどこかで待つようになっています。

この遊園地のメリーゴーランドは、かならず乗り物が乗り場にぴったりと合う位置に停止します。そして、０〜７のそれぞれで待っているお客さまは、目の前にとまった乗り物に乗ることになっています。急いで他の乗り場へ移動してそこから乗るということはできません。効率よく、お客さまにたのしんでいただくためには、メリーゴーランドの停止する位置をうまく調整して、乗れないお客さまをできるだけ少なくするようにしなければなりません。

乗り場０〜７で待っているお客さまの人数を読み込んで、どの位置にどの乗り物が来るように止めれば乗れないお客さまが最も少なくなるかを出力するプログラムを作成してください。

入力

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

p0 p1 p2 p3 p4 p5 p6 p7

乗り場 0, 1, ..., 7 で待っているお客様の人数を表す整数 p0, p1,... , p7 ( 0 ≤ pi ≤ 10,000) が空白区切りで１行に与えられます。

出力

メリーゴーランドの乗り物の馬車を 4、車を 2、馬を 1 で表すこととします。乗り場 0, 1, ... , 7 にとめる乗り物を、それぞれ c0, c1,..., c7 とします。データセットごとに、c0, c1,..., c7 を空白区切りで 1 行に出力します。

なお、乗れなくなるお客さまが最小となるとめ方が複数ある場合は、c0c1c2c3c4c5c6c7 を 8 桁の整数 V とみなし、V が最小となるとめ方を選ぶものとします。

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

Sample Input

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

Output for the Sample Input

1 4 1 4 1 2 1 2
4 1 4 1 2 1 2 1


n_drop, cloth = int(input()), [[int(i) for i in input().split()] for _ in range(10)]
n_stain = sum(sum(i) for i in cloth)
n = (n_stain - 5 * n_drop) // 4

drops_candidate = []
dl = 0
while 2 * dl <= n:
    dm = n - 2 * dl
    ds = n_drop - dm - dl
    if ds >= 0:
        drops_candidate.append([ds, dm, dl])
    dl += 1

dx = (0, -1, 1, 0, 0, -1, -1, 1, 1, -2, 2, 0, 0)
dy = (0, 0, 0, -1, 1, -1, 1, -1, 1, 0, 0, -2, 2)
dd = (5, 9, 13)

def find(cloth, drops, pointer):
    global dy, dx, dd
    for p in range(pointer, 100):
        if cloth[p // 10][p % 10]:
            break
        pointer += 1
    for d in range(3):
        if not drops[d]:
            continue
        dn = dd[d]
        mir = int(d == 2)
        mar = 9 - mir
        for i in range(dn):
            x, y = pointer % 10 + dx[i], pointer // 10 + dy[i]
            if not mir < x < mar or not mir < y < mar:
                continue
            for j in range(dn):
                if not cloth[y + dy[j]][x + dx[j]]:
                    break
            else:
                for j in range(dn):
                    cloth[y + dy[j]][x + dx[j]] -= 1
                drops[d] -= 1
                if sum(drops):
                    result = find(cloth, drops, pointer)
                    if result:
                        result.append((x, y, d + 1))
                        return result
                    for i in range(dn):
                        cloth[y + dy[i]][x + dx[i]] += 1
                    drops[d] += 1
                else:
                    return [(x, y, d + 1)]
    return False

for drops in drops_candidate:
    history = find(cloth, drops, 0)
    if history != False:
        for h in history:
            print(*h)
        break

Blur

図 1 のような 10×10 のマス目の「布」があり、（1，2）のようにX座標・Y座標の値の対でマス目を示すことにします。座標値は 0 から始まる整数とします。例えば、図 1 の◎の座標は (1, 2) です。
この「布」に染料を少しずつたらして染物を作ります。たらす染料の滴には「大」「中」「小」の 3 サイズがあり、染料の滴の落ちたマス目を中心に図 1 のように周囲も色がつきます。図 1 で☆が中心、○が色のにじむ範囲です。

「布」は、最初は「まっしろ」つまり、どのマス目も色の濃さを示す値が 0 とします。染料の滴が落ちるごとに値が 1 ずつ増えていきます。「小」が（1, 2）、「中」が（3, 2）に落ちた場合、各マス目の値は図 2 の左のようになります。染料がもったいないので、図 2 の右に示すようなにじむ範囲が布の外にはみ出すような染料の落とし方はしないことになっています。また、同じ場所に複数の染料をたらすこともあります。

このような作業を何回か繰り返した結果、布にすばらしい模様が浮かび上がりましたが、残念なことに、うっかり作業経過を記録し忘れてしまいました。どうにもさっぱり思い出せませんが、かろうじて、落とした染料の滴数は覚えていました。あなたは、すばらしい染物を再現しなければなりません。すばらしい染物のデータを読みこんで、どこに、どのような染料をたらしたかを出力するプログラムを作成してください。なお、落とした染料の滴数は 12 以下とします。

入力

入力の形式は以下のとおりです：

最初の 1 行に落とした染料の滴数 n が与えられます。次の行から 10 行に各座標の色の濃さが空白区切りで与えられます。

出力

出力は n 行からなります。染料の滴の「大」を 3、「中」を 2、「小」を 1 で表し、落とした染料ごとに、そのX座標、Y座標、滴の大きさを空白で区切って1行に出力してください。

染料のたらし方はどのような順番で出力しても良いものとします。

入力例1

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

出力例1

3 2 1
8 4 2

入力例2

6
0 0 1 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 0 0
0 0 1 1 1 3 1 1 0 0
0 0 1 1 3 1 1 1 0 0
0 0 1 1 1 1 1 1 1 0
0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 1 0 0

出力例2

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


有料道路通行料

20XX年に喜多方市熱塩加納町から南会津町までの6区間、総距離58kmの会津中央道路が完成し開通する予定です。

開通後、半年間は利用促進のため17時30分〜19時30分までに出発ICか到着ICを通過し、なおかつ走行距離が40km以下の車に対する通行料金は半額になります。ただし料金は50円単位とし、端数は切り上げます。下記の表は料金と距離の一覧表です。

例えば喜多方（２）から会津若松（４）までは料金が450円、距離が12kmとなります。半額時間帯であれば250円になります。

出発IC、出発IC通過時刻、到着IC、到着IC通過時刻を入力とし、料金を計算して出力するプログラムを作成してください。ただし、入力される時刻は24 時間表記の値とします。なお、17時30分および19時30分ちょうどに通過した場合も半額時間帯に含めます。

Input

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

d
hd md
a
ha ma

１行目に出発ICの番号 d (1 ≤ d ≤ 7)、２行目に出発ICの通過時刻の時間 hd (0 ≤ hd ≤ 23) と分 md (0 ≤ md ≤ 59) が与えられます。

3行目に到着ICの番号 a (1 ≤ a ≤ 7)、４行目に到着ICの通過時刻の時間 ha (0 ≤ ha ≤ 23) と分 ma (0 ≤ ma ≤ 59) が与えられます。

Output

データセットごとに通行料金（整数）を１行に出力します。

Sample Input

2
17 25
4
17 45
4
17 25
7
19 35
0

Output for the Sample Input

250
1300


def bisect(L,a):
    n = len(L)
    if n < 1 or L[n/2] == a:
        return 1
    if L[n/2] > a:
        return bisect(L[:n/2],a) + 1
    return bisect(L[n/2+1:],a) + 1

while True:
    n = input()
    if n == 0:
        break
    print bisect([input() for _ in xrange(n)],input())

探索

「探索」とは、たくさんの情報の中から望みの情報を得る操作のことです。身近な例では、合格発表の時の「たくさんの受験番号から自分の受験番号を見つける」ことや、電話帳から「会津太郎さんの電話番号を見つける」ときなどがあります。この探索という操作はコンピュータの分野でも広く用いられています。

探索の方法は沢山あります。探索の対象となるデータが、小さい順(または大きい順)に並べられている場合に使うことができる探索の方法を考えます。

小さい順(または大きい順)に並べられているデータ列の中央に位置する値と目的の値との大小関係を用いて、中央に位置する値から前半部分を探索範囲にするか後半部分を探索範囲にするかを決めることで、探索の範囲を絞っていく方法があります。手順は以下のようになります。

データの列の全体を探索の範囲とします。

探索の範囲の中央に位置する値を調べます。

目的の値と中央に位置する値が一致すれば探索を終了します。

目的の値と中央に位置する値よりも小さければ前半部分を探索の範囲とし、大きければ後半部分を探索の範囲として2.へ戻ります。

以下は上述した探索の方法の例です。この例での目的の値は51です。それぞれのデータには番号
(index)が振られており、この番号は0から始まっています。

ステップ1: 最初は番号0~6全体を探索の範囲とします。

ステップ2: 探索の範囲の中央に位置する値を調べます。ただし、「中央に位置する値」とは、(左側の番号+右側の番号)を2で割った番号の位置にある値とします。つまり、この場合、(0 + 6) ÷ 2 を計算し、番号3にある値(36)が中央に位置する値となります。

ステップ3:目的の値(51)と中央に位置する値(36)を比較します。

ステップ4:ステップ3の結果から、目的の値は中央に位置する値より大きいので、後半部分にあたる番号4 (中央に位置する値の隣)以降を探索の範囲とします。同様の手順で探索の範囲の中央に位置する値を調べ、目的の値が中央に位置する値より小さければ前半部分を探索の範囲とし、大きければ後半部分を探索の範囲として、探索の範囲を小さくしていきます。(ステップ2~ステップ4の繰り返し)目的の値が中央に位置する値と一致するか、探索の範囲がつきてしまった時に探索を終了します。

n 個の数値の配列を入力とし、目的の値と中央に位置する値を比較した回数を出力するプログラムを作成してください。ただし、中央に位置する値の番号を計算したとき、割り切れない場合は、小数点以下を切り捨てた値をその番号とすることとします。
与えられるデータ列は小さい順に整列されているものとします。

Input

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

n
a1
a2
:
an
k

1 行目に数値の数 n (1 ≤ n ≤ 100) 、続く n 行に i 個目の数値 ai (1 ≤ ai ≤ 100000, 整数) が与えられます。

続く行に探索する値 k (1 ≤ k ≤ 100000) が与えられます。

Output

データセット毎に探索が終わるまでの比較回数を１行に出力します。

Sample Input

7
11
15
23
36
51
61
86
51
4
1
2
3
5
4
0

Output for the Sample Input

3
3


def put_dif():
  a, b = map(int, input().split())
  print(a - b)

for _ in range(7):
  put_dif()

気温の差

選手の皆さん、パソコン甲子園にようこそ。イベントに参加するには体調管理が大切です。気温が大きく変動する季節の変わり目には体に負担がかかり、風邪をひきやすいと言われています。一番気を付けなければいけない日は、最高気温と最低気温の差が最も大きい日です。１日の最高気温と最低気温が７日分与えられたとき、それぞれの日について最高気温から最低気温を引いた値を出力するプログラムを作成してください。

入力

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

a1 b1
a2 b2
:
a7 b7

入力は7行からなり、i行目にはi日目の最高気温 ai(-40 ≤ ai ≤ 40)と最低気温 bi(-40 ≤ bi ≤ 40)を表す整数が与えられる。すべての日において、最高気温 ai は必ず最低気温 bi 以上となっている。

出力

7日分の気温の差を7行に出力する。

入力例

30 19
39 20
19 18
25 20
22 21
23 10
10 -10

出力例

11
19
1
5
1
13
20


from math import ceil
class sqrt_tree:
    def __init__(self,dat,f):
        self.dat = dat
        self.sq = int(len(dat) ** 0.5)
        self.f = f
        self.baqet = [self.f(dat[i * self.sq:(i + 1) * self.sq]) for i in range(self.sq)]

    #query
    def q(self,l,r):
        r += 1
        if ceil(l / self.sq) >= r // self.sq:
            return self.f(self.dat[l:r])
        ret = self.f(self.baqet[ceil(l / self.sq):r // self.sq])
        if l % self.sq:
            ret = self.f(ret,self.f(self.dat[l:l + self.sq]))
        if r % self.sq:
            ret = self.f(ret,self.f(self.dat[r - r % self.sq:r]))
        return ret

import sys
f = sys.stdin

_, d = map(int, f.readline().split())

x,y = {},{}
for line in f:
    xi, yi, bi = map(int, line.split())
    if bi not in x:
        x[bi],y[bi] = [],[]
    x[bi].append(xi)
    y[bi].append(yi)

b = sorted(x.keys())

xmax = sqrt_tree([max(x[bi]) for bi in b],max)
xmin = sqrt_tree([min(x[bi]) for bi in b],min)
ymax = sqrt_tree([max(y[bi]) for bi in b],max)
ymin = sqrt_tree([min(y[bi]) for bi in b],min)

def get_lr(b,d):
    l = r = 0
    while r < len(b) - 1:
        while b[l] + d < b[r]:
            l += 1
        for k in range(l,len(b)):
            if b[l] + d < b[k]:
                break
            r = k
        yield l,r
        r += 1
        l += 1

max_size = max((xmax.q(l,r) - xmin.q(l,r)) * (ymax.q(l,r) - ymin.q(l,r)) for l,r in get_lr(b,d))
print(max_size)

天体観測

ある晴れた夜の帰り道、空を見上げるとそこには無数の星。強く輝く星々、かすかに見える星々、いろ
いろな明るさの星々が夜空を彩っています。

あなたはふと思いました。この星空に自分の星座があったらどんなに素敵だろうと。そこであなたはひとつの基準を決め、部屋の窓から見える星々を適当につなげて自分の星座を作ることにしました。その基準とは、「どの２つの星を選んでも、それらの明るさの差がある定数 d 以下になるような星のグループを作り、その中で一番大きいものを自分の星座にしよう！」というものです。例えば、図のような窓から見える夜空を考えてみましょう（外側の長方形は窓枠です）。

この夜空には、明るさがそれぞれ 1，12, 2，4，1，8, 3，5，4 の９つの星がありますが、d = 2 とすると例えば以下のような３つの星座 A, B, C ができます。

大きさが 12 の星座 A

大きさが 10 の星座 B

大きさが 16 の星座 C

星座の大きさを次のように決めることにしました。ある星座の星をすべて含むような、窓枠に平行な辺からなる長方形のうち、面積が最も小さいものを選びます。この長方形の面積をその星座の大きさとします。例えば、上の夜空では星座 A, B, Cの大きさはそれぞれ12, 10, 16になるので、星座Cが最も大きい星座となります。

N 個の星の位置と明るさ、および整数 d が与えられたとき、一番大きい星座の面積を求めるプログラムを作成してください。星の位置は窓枠の左下隅を原点とした座標で与えられ、軸は図のような向きとします。星座を構成する星が１つの場合や、星々が軸に平行な直線上にある場合は、その星座の面積は 0 となることに注意してください。

入力

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

N d
x1 y1 b1
x2 y2 b2
:
xN yN bN

1 行目に星の数 N (1 ≤ N ≤ 200000) と整数 d (0 ≤ d ≤ 109) が与えられる。続く N 行に、i 番目の星の座標を表す整数 xi (0 ≤ xi ≤ 2000000) と yi (0 ≤ yi ≤ 2000000)、明るさを表す整数 bi (0 ≤ bi ≤ 109) が与えられる。入力される星の座標はすべて異なる。

出力

一番大きい星座の面積を１行に出力する。

入出力例

入力例

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

出力例

16


data = map(int, raw_input().split())
stars = data[0]
lightrange = data[1]
a = []
for i in range(stars):
    a.append(map(int, raw_input().split()))
a.sort(key=lambda x:x[2])
scale = 0
while(len(a)>1):
    minx=maxx=a[0][0]
    miny=maxy=a[0][1]
    l=1
    if (a[l][2] <= a[0][2] + lightrange):
        if(a[l][0]<minx):
            minx=a[l][0]
        if(a[l][0]>maxx):
            maxx=a[l][0]
        if(a[l][1]<miny):
            miny=a[l][1]
        if(a[l][1]>maxy):
            maxy=a[l][1]
    area = (maxx-minx)*(maxy-miny)
    if (area > scale):
        scale = area
    del a[0]
print scale


#!/usr/bin/env python
# -*- coding: utf-8 -*-

while True:
    dic = {}
    n = int(input())
    if n == 0:
        break

    for i in range(n):
        key, value = input().split()
        dic[key] = value

    ret = ''

    m = int(input())
    for i in range(m):
        s = input().strip()
        ret += dic.get(s, s)

    print(ret)

与えられた変換表にもとづき，データを変換するプログラムを作成しなさい．

データに使われている文字は英字か数字で，英字は大文字と小文字を区別する．変換表に現れる文字の順序に規則性はない．

変換表は空白をはさんで前と後ろの 2 つの文字がある(文字列ではない)．変換方法は，変換表のある行の前の文字がデータに現れたら，そのたびにその文字を後ろの文字に変換し出力する．変換は 1 度だけで，変換した文字がまた変換対象の文字になっても変換しない．変換表に現れない文字は変換せず，そのまま出力する．

入力ファイルには，変換表（最初の n + 1 行）に続き変換するデータ（n + 2 行目以降）が書いてある． 1 行目に変換表の行数 n，続く n 行の各行は，空白をはさんで 2 つの文字，さらに続けて， n + 2 行目に変換するデータの行数 m，続く m 行の各行は 1 文字である． m ≤ 105 とする．出力は，出力例のように途中に空白や改行は入れず 1 行とせよ．

入力例

3

A a

0 5

5 4

10

A

B

C

0

1

4

5

a

b

A

出力例

aBC5144aba

入力

入力は複数のデータセットからなる．n が 0 のとき入力が終了する．データセットの数は 5 を超えない．

出力

データセットごとに、変換後の文字列を１行に出力する．

入力例

3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0

出力例

aBC5144aba
aBC5144aba

各データセットの出力（変換後の文字列）の後に改行を入れること．

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


#! cat input | python3 main.py
def debug():
    for X in field[size//2:] + field[:size//2]:
        print(X[size//2:], X[:size//2])

dice_data = [[],
        [4, 2, 3, 5],
        [4, 6, 3, 1],
        [6, 5, 1, 2],
        [1, 5, 6, 2],
        [4, 1, 3, 6],
        [4, 5, 3, 2],
        ]
def dice(t, f):
    i = dice_data[t].index(f)
    return [dice_data[t][x%4] for x in range(i, i + 4)]

size = 6
move = [[-1, 0], [0, 1], [1, 0], [0, -1]]

def drop(t, f, nowl, nowr):
    target = list(map(lambda x: x > 3, dice(t, f)))
    now = [nowl, nowr]

    now_field = field[now[0]][now[1]]
    for i, tg in enumerate(target):
        if tg:
            nb_field = field[now[0] + move[i][0]][now[1] + move[i][1]]
            if nb_field[1] >= now_field[1]:
                target[i] = False
    for i, v in sorted(enumerate(dice(t, f)), key=lambda x: x[1], reverse=True):
        if target[i]:
            if i == 0:
                f = t
            elif i == 2:
                f = 7 - t
            t = 7 - v
            drop(t, f, now[0] + move[i][0], now[1] + move[i][1])
            break
    else:
        change = field[now[0]][now[1]]
        change[0] = t
        change[1] += 1

while True:
    n = int(input())
    if not n: break
    field = [[[0, 0] for i in range(size)] for j in range(size)]

    tfs = [list(map(int, input().split())) for x in range(n)]
    for t, f in tfs:
        drop(t, f, 0, 0)
    cnt = [0 for x in range(7)]
    for row in field:
        for cell in row:
            cnt[cell[0]] += 1
    print(*cnt[1:])

Biased Dice

Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice. His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane. The dice fall onto the plane or dice already there, without rotating, and may roll and fall according to their property. Then he observes and records the status of the stack formed on the plane, specifically, how many times each number appears on the faces visible from above. All the dice have the same size and their face numbering is identical, which we show in Figure C-1.

Figure C-1: Numbering of a die

The dice have very special properties, as in the following.

(1) Ordinary dice can roll in four directions, but the dice used in this experiment never roll in the directions of faces 1, 2 and 3; they can only roll in the directions of faces 4, 5 and 6. In the situation shown in Figure C-2, our die can only roll to one of two directions.

Figure C-2: An ordinary die and a biased die

(2) The die can only roll when it will fall down after rolling, as shown in Figure C-3. When multiple possibilities exist, the die rolls towards the face with the largest number among those directions it can roll to.

Figure C-3: A die can roll only when it can fall

(3) When a die rolls, it rolls exactly 90 degrees, and then falls straight down until its bottom face touches another die or the plane, as in the case [B] or [C] of Figure C-4.

(4) After rolling and falling, the die repeatedly does so according to the rules (1) to (3) above.

Figure C-4: Example stacking of biased dice

For example, when we drop four dice all in the same orientation, 6 at the top and 4 at the front, then a stack will be formed as shown in Figure C-4.

Figure C-5: Example records

After forming the stack, we count the numbers of faces with 1 through 6 visible from above and record them. For example, in the left case of Figure C-5, the record will be "0 2 1 0 0 0", and in the right case, "0 1 1 0 0 1".

Input

The input consists of several datasets each in the following format.

n

t1  f1

t2  f2

...

tn  fn

Here, n (1 ≤ n ≤ 100) is an integer and is the number of the dice to be dropped. ti and fi (1 ≤ ti, fi ≤ 6) are two integers separated by a space and represent the numbers on the top and the front faces of the i-th die, when it is released, respectively.

The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output six integers separated by a space. The integers represent the numbers of faces with 1 through 6 correspondingly, visible from above. There may not be any other characters in the output.

Sample Input

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

Output for the Sample Input

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


Problem C: Die Game

Life is not easy. Sometimes it is beyond your control. Now, as contestants of ACM ICPC, you might be just tasting the bitter of life. But don't worry! Do not look only on the dark side of life, but look also on the bright side. Life may be an enjoyable game of chance, like throwing dice. Do or die! Then, at last, you might be able to find the route to victory.

This problem comes from a game using a die. By the way, do you know a die? It has nothing to do with "death." A die is a cubic object with six faces, each of which represents a different number from one to six and is marked with the corresponding number of spots. Since it is usually used in pair, "a die" is rarely used word. You might have heard a famous phrase "the die is cast," though.

When a game starts, a die stands still on a flat table. During the game, the die is tumbled in all directions by the dealer. You will win the game if you can predict the number seen on the top face at the time when the die stops tumbling.

Now you are requested to write a program that simulates the rolling of a die. For simplicity, we assume that the die neither slip nor jumps but just rolls on the table in four directions, that is, north, east, south, and west. At the beginning of every game, the dealer puts the die at the center of the table and adjusts its direction so that the numbers one, two, and three are seen on the top, north, and west faces, respectively. For the other three faces, we do not explicitly specify anything but tell you the golden rule: the sum of the numbers on any pair of opposite faces is always seven.

Your program should accept a sequence of commands, each of which is either "north", "east", "south", or "west". A "north" command tumbles the die down to north, that is, the top face becomes the new north, the north becomes the new bottom, and so on. More precisely, the die is rotated around its north bottom edge to the north direction and the rotation angle is 9 degrees. Other commands also tumble the die accordingly to their own directions. Your program should calculate the number finally shown on the top after performing the commands in the sequence. Note that the table is sufficiently large and the die never falls off during the game.

Input

The input consists of one or more command sequences, each of which corresponds to a single game. The first line of a command sequence contains a positive integer, representing the number of the following command lines in the sequence. You may assume that this number is less than or equal to 1024. A line containing a zero indicates the end of the input. Each command line includes a command that is one of north, east, south, and west. You may assume that no white space occurs in any line.

Output

For each command sequence, output one line containing solely the number of the top face at the time when the game is finished.

Sample Input

1
north
3
north
east
south
0

Output for the Sample Input

5
1


while (True):
    s1=input()
    if (s1=="."):
        break
    s2=input()
    l1=s1.split("\"")
    l2=s2.split("\"")
   #print(l1,l2)
    if (len(l1)!=len(l2)):
        print("DIFFERENT")
        continue
    error=0
    for i in range(len(l1)):
        #print(l1,l2,i)
        if (l1[i]!=l2[i] and i%2==0):
            print("DIFFERENT")
            error=-1
            break
        if (len(l1[i])!=len(l2[i])):
            error+=1
        else:
            for j in range(min(len(l1[i]),len(l2[i]))):
            #   print(l1[i][j],l2[i][j])
                if (l1[i][j]!=l2[i][j]):
                    error+=1
                    break

    if (error==0):
        print("IDENTICAL")
    elif (error==1):
        print("CLOSE")
    elif(error>=2):
        print("DIFFERENT")

Almost Identical Programs

The programming contest named
Concours de Programmation Comtemporaine Interuniversitaire (CPCI)
has a judging system similar to that of ICPC;
contestants have to submit correct outputs for two different inputs
to be accepted as a correct solution.

Each of the submissions should include the program that generated
the output. A pair of submissions is judged to be a correct
solution when, in addition to the correctness of the outputs, they
include an identical program.

Many contestants, however, do not stop including a different version
of their programs in their second submissions, after modifying a
single string literal in their programs representing
the input file name, attempting to process different input.

The organizers of CPCI are exploring the possibility of showing a
special error message for such close submissions,
indicating contestants what's wrong with such submissions.

Your task is to detect such close submissions.

Input

The input consists of at most 100 datasets, each in the following format.

s1
s2

Each of s1 and s2 is
a string written in a line, with the length between 1 and 200, inclusive.
They are the first and the second submitted programs respectively.

A program consists of lowercase letters (a, b, ..., z), uppercase letters (A, B, ..., Z),
digits (0, 1, ..., 9), double quotes ("), and semicolons (;).
When double quotes occur in a program, there are always even number of them.

The end of the input is indicated by a line containing one '.' (period).

Output

For each dataset, print the judge result in a line.

If the given two programs are identical, print IDENTICAL.
If two programs differ with only one corresponding string literal, print CLOSE.
Otherwise, print DIFFERENT.

A string literal is a possibly empty sequence of characters between an
odd-numbered occurrence of a double quote and the next occurrence of
a double quote.

Sample Input

print"hello";print123
print"hello";print123
read"B1input";solve;output;
read"B2";solve;output;
read"C1";solve;output"C1ans";
read"C2";solve;output"C2ans";
""""""""
"""42"""""
slow"program"
fast"code"
"super"fast"program"
"super"faster"program"
X""
X
I"S""CREAM"
I"CE""CREAM"
11"22"11
1"33"111
.

Output for the Sample Input

IDENTICAL
CLOSE
DIFFERENT
CLOSE
DIFFERENT
DIFFERENT
DIFFERENT
CLOSE
DIFFERENT


from collections import defaultdict, Counter
from math import floor, ceil, log
from heapq import heapreplace, heappush
import time

class TreeIndex:

    class Node:
        __slots__ = ('level', 'keys', 'values', 'keylen', '_cache', '_cacheq')

        def __init__(self, level):
            self.level = level
            self.values = []
            self.keys = {}
            self.keylen = 2 ** self.level
            self._init_cache()

        def add(self, text, value):
            def _add(node, t):
                if len(t) == 0:
                    node.values.append(value)
                    return node

                pre = t[:node.keylen]
                post = t[node.keylen:]
                if pre not in node.keys:
                    node.keys[pre] = self.__class__(node.level+1)
                return _add(node.keys[pre], post)

            node = self._get_cache(text)
            if node is not None:
                _add(node, '')
            else:
                self._set_cache(text, _add(self, text))

        def index(self, text):
            def _index(node, t):
                if len(t) == 0:
                    return node

                pre = t[:node.keylen]
                post = t[node.keylen:]
                if pre in node.keys:
                    return _index(node.keys[pre], post)
                else:
                    return None

            node = self._get_cache(text)
            if node is not None:
                return node.values
            else:
                node = _index(self, text)
                if node is not None:
                    self._set_cache(text, node)
                    return node.values
                return []

        def __contains__(self, text):
            if len(text) > self.keylen:
                pre = text[:self.keylen]
                post = text[self.keylen:]
                return (pre in self.keys and post in self.keys[pre])
            else:
                return any(key.startswith(text) for key in self.keys)

        def _init_cache(self):
            self._cache = {}
            self._cacheq = []

        def _set_cache(self, text, node):
            if text not in self._cache:
                if len(self._cacheq) > 65535:
                    _, txt = heapreplace(self._cacheq, (time.clock(), text))
                    del self._cache[txt]
                else:
                    heappush(self._cacheq, (time.clock(), text))
                self._cache[text] = node

        def _get_cache(self, text):
            if text in self._cache:
                return self._cache[text]
            else:
                return None

        def __str__(self):
            return ('(' + ','.join(["{}->{}".format(k, v)
                                   for k, v in self.keys.items()]) + ')')

    def __init__(self, text):
        self._keylen(text)
        self._create_index(text)

    def _keylen(self, text):
        chars = Counter(list(text))
        ent = 0.0
        total = len(text)
        base = len(chars) + 1
        for c, cnt in chars.items():
            p = cnt / total
            ent -= p * log(p, base)
        self.keylen = max(2 ** ceil(10 * (1 - ent)) - 1, 15)

    def _create_index(self, text):
        tree = self.Node(0)
        length = len(text)
        for i in range(length):
            tree.add(text[i:i+self.keylen], i)
        self.tree = tree
        self.text = text

    def match(self, search_text):
        def _match_partial(lo, hi):
            split = self.keylen
            if search_text[lo+split:hi] in self.tree:
                for i in self.tree.index(search_text[lo:lo+split]):
                    if (self.text[i+split:i+hi-lo]
                            == search_text[lo+split:hi]):
                        yield i

        def _match(lo, hi):
            length = hi - lo

            if length == self.keylen:
                return (i for i in self.tree.index(search_text[lo:hi]))

            if length < self.keylen*2:
                return _match_partial(lo, hi)

            mid = lo + length // 2
            pre = _match(lo, mid)
            post = _match(mid, hi)

            return _merge(pre, post, mid-lo)

        def _merge(idx1, idx2, shift):
            i2 = next(idx2)
            for i1 in idx1:
                while i1 + shift > i2:
                    i2 = next(idx2)
                if i1 + shift == i2:
                    yield i1

        length = len(search_text)
        if length < self.keylen:
            return search_text in self.tree

        # align by key length
        k = floor(log(length/self.keylen, 2))
        b = self.keylen * 2**k
        if length - self.keylen < b < length and k > 0:
            b = self.keylen * 2**(k-1)

        try:
            if b + self.keylen < length:
                match = _merge(_match(0, b), _match(b, length), b)
            else:
                match = _match(0, length)
            next(match)
            return True
        except StopIteration:
            return False

def run():
    s1 = input()
    n = int(input())

    index = TreeIndex(s1)
    for _ in range(n):
        s2 = input()
        if index.match(s2):
            print(1)
        else:
            print(0)

if __name__ == '__main__':
    run()

String Search

Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.

Input

In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.

Output

For each question, print 1 if the text includes P_i, or print 0 otherwise.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P_i ≤ 1000

1 ≤ Q ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
4
aa
ba
bb
xyz

Sample Output 1

1
1
0
0


N = int(input())
seq = list(map(int, input().split()))
print(" ".join(map(str, seq)))
for i in range(1, N):
    key = seq[i]
    j = i-1
    while j >= 0 and seq[j] > key:
        seq[j+1] = seq[j]
        j -= 1
    seq[j+1] = key
    print(" ".join(map(str, seq)))

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


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

min_v = R[0]
max_v = R[1] - R[0]
for i in range(1, len(R)):
    if min_v > R[i - 1]:
        min_v = R[i - 1]
    if max_v < R[i] - min_v:
        max_v = R[i] - min_v
print(max_v)

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

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


n = int(input())
R = [int(input()) for i in range(n)]
profit= R[1] - R[0]
for i in range(n):
    for j in range(i+1,n):
        tmp = R[j]-R[i]
        if profit < tmp:
            profit = tmp

print(profit)


N = int(raw_input())
A = map(int, raw_input().split())
i = 0
flag = 1
while flag:
    flag = 0
    for j in range(N-1, 0, -1):
        if A[j] < A[j-1]:
            A_j = A[j]
            A[j] = A[j-1]
            A[j-1] = A_j
            flag = 1
            i += 1
print " ".join(map(str, A))
print i

Bubble Sort

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

BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]

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

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

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 spaces 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

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9


def babble_sort(n, data):
    __count = 0
    for i in range(n-1):
        for j in range(n-i-1):
            if data[j] > data[j+1]:
                tmp = data[j+1]
                data[j+1] = data[j]
                data[j] = tmp
                __count += 1
    return data, __count

def show(data, count):
    for i in range(len(data)):
        if i != (len(data)-1):
            print(data[i], end = " ")
        else:
            print(data[i])
    print(count)

if "__main__" == __name__:
    n = int(input())
    data = list(map(int, input().rsplit()))
    data, count = babble_sort(n, data)
    show(data, count)


def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    c = 0
    flag = 1
    while flag:
        flag = 0
        j = 0
        for i in range(n-1, j, -1):
            if a[i] < a[i-1]:
                a[i], a[i-1] = a[i-1], a[i]
                c += 1
                flag = 1
        j -= 1
    print(' '.join(map(str, a)))
    print(c)

if __name__ == '__main__':
    main()


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

count = 0
for i in range(n):
    minj = i
    for j in range(i,n):
        if (A[j] < A[minj]):
            minj = j

    if (minj != i):
        A[i],A[minj] = A[minj],A[i]
        count += 1

for k in range(n-1):
    print(str(A[k])+" ",end = "")
print(str(A[n-1]))
print(count)

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 binarySearch(t):
	left,right = 0,n
	while right > left+1:
		mid = (left+right) // 2
		if S[mid] == t:
			return True
		elif S[mid] > t:
			right = mid
		else:
			left = mid
	return False

n = int(input())
S = [int(s) for s in input().split()]
q = int(input())
T = [int(s) for s in input().split()]

print(sum([binarySearch(t) for t in T]))

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


def check(P):
    i = 0
    for j in range(k):
        s = 0
        while s + T[i] <= P:
            s += T[i]
            i += 1
            if i == n: return n
    return i

def solve():
    left, right = 0, 100000*10000
    while right - left > 1:
        mid = (left + right) / 2
        v = check(mid)
        if v >= n: right = mid
        else: left = mid
    return right

if __name__ == '__main__':
    T = []
    n, k = [int(x) for x in input().split()]
    for i in range(n): T.append(int(input()))
    print(int(solve()))

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.


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

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

def f(A, s, res):
  if res[0]:
    return
  if s == 0:
    res[0] = True
    return
  for i, a in enumerate(A):
    if a > s:
      break
    f(A[i+1:], s-a, res)

for mi in m:
  res = [False]
  f(A, mi, res)
  if res[0]:
    print("yes")
  else:
    print("no")

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


# -*- coding: utf-8 -*-

import sys
import os
import pprint

#fd = os.open('CGL_2_A.txt', os.O_RDONLY)
#os.dup2(fd, sys.stdin.fileno())

def judge(lst):
    x0, y0, x1, y1, x2, y2, x3, y3 = lst
    v0 = (x1 - x0, y1 - y0)
    v1 = (x3 - x2, y3 - y2)

    dot = v0[0] * v1[0] + v0[1] * v1[1]
    cross = v0[0] * v1[1] - v0[1] * v1[0]

    if dot == 0:
        print(1)
    elif cross == 0:
        print(2)
    else:
        print(0)

N = int(input())
for i in range(N):
    lst = list(map(int, input().split()))
    judge(lst)

Parallel/Orthogonal

For given two lines s1 and s2, print "2" if they are parallel, "1" if they are orthogonal, or "0" otherwise.

s1 crosses points p0 and p1, and
s2 crosses points p2 and p3.

Input

The entire input looks like:

q (the number of queries)
1st query
2nd query
...
qth query

Each query consists of integer coordinates of the points p0, p1, p2, p3 in the following format:

xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3

Output

For each query, print "2", "1" or "0".

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

Sample Input 1

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

Sample Output 1

2
1
0


n, m = map(int, input().strip().split())
d = [i for i in map(int, input().strip().split())]
assert len(d) == m

cands = sorted(d)
data = [i for i in range(n+1)]

for c in cands:
    for i in range(n+1):
        if i + c <= n and data[i+c] > data[i] + 1:
            data[i+c] = data[i] + 1
print(data[-1])

Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3


#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_A&lang=jp

class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    def __init__(self):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点数
                    - 頂点数が与えられたときは、すべての辺をINFで初期化する
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)

    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)  # prov_cost := 暫定的な最短距離
            # キューに格納されている暫定的な最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                """(1)遅い
                try:
                    self.edges[(v,i)]
                except KeyError:
                    continue
                """

                cost = self.edges.get((v,i), float("inf"))  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d

if __name__ == "__main__":
    V, E, s = list(map(int, input().split()))
    djk = Dijkstra()
    if V == 1:
        print(0)
        exit()

    if E == 0:
        for i in range(V-1):
            djk.add(i, i+1, float("INF"))
    else:
        for i in range(E):
            _from, to, cost = list(map(int, input().split()))
            djk.add(_from, to, cost)

        for i in range(V):
            # 入力に存在しない頂点があるとき、適当にINFの辺を作成する
            if not i in djk.v_set:
                djk.add(i, 0, float("inf"))

    d = djk.shortest_path(s)

    for i in range(V):
        if i >= len(d):
            print("INF")
            continue

        cost = d[i]
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

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 sys import stdin
from collections import deque

def read_graph(n, k):
    A = [ [] for _ in range(n) ]
    for _ in range(k):
        line = stdin.readline().strip().split()
        A[int(line[0])].append(int(line[1]))
    return A

def topological_sort(n, A):
    color = ["WHITE"] * n
    Q = deque([])
    out = []

    indeg = [0] * n
    for i in range(n):
        for j in A[i]:
            indeg[j] = indeg[j] + 1

    def bfs(s):
        nonlocal color
        nonlocal indeg
        nonlocal Q
        color[s] = "GRAY"
        Q.append(s)

        while Q:
            u = Q.popleft()
            out.append(u)

            for v in A[u]:
                indeg[v] = indeg[v] - 1
                if indeg[v] == 0 and color[v] == "WHITE":
                    color[v] = "GRAY"
                    Q.append(v)

    for i in range(n):
        if indeg[i] == 0 and color[i] == "WHITE":
            bfs(i)

    return out

n, k = [int(i) for i in input().split()]
A = read_graph(n, k)
B = topological_sort(n, A)
for i in B:
    print(i)

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

Topological Sort

A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obtain the proper sequence of all the tasks by a topological sort.

Given a DAG $G$, print the order of vertices after the topological sort.

Input

A directed graph $G$ is given in the following format:

$|V|\;|E|$

$s_0 \; t_0$

$s_1 \; t_1$

:

$s_{|E|-1} \; t_{|E|-1}$

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

$s_i$ and $t_i$ represent source and target nodes of $i$-th edge (directed).

Output

Print the vertices numbers in order. Print a number in a line.

If there are multiple possible solutions, print any one of them (the solution is judged by a special validator).

Constraints

$1 \leq |V| \leq 10,000$

$0 \leq |E| \leq 100,000$

There are no parallel edges in $G$

There are no self loops in $G$

Sample Input

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

Sample Output

0
3
1
4
5
2


import math

(x1, y1, x2, y2) = [float(i) for i in input().split()]

distance = math.hypot((x2 - x1), (y2 - y1))
print('{0:.5f}'.format(distance))

Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


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())

print(A*B,2*(A+B))

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(int,input().split())
print(a*b,(a+b)*2)


time = input()
time = int(time)
h = time//3600
remain = time%3600
m = remain//60
s= remain%60
print('{}:{}:{}'.format(h,m,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=map(int,input().split())
if a<b:
    print("a < b")
elif a>b:
    print("a > b")
elif a==b:
    print("a == b")

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


a,b,c = map(int, raw_input().split(' '))
print ' '.join(map(str, (sorted([a, b, c]))))

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


def check(in_list):
    flag = True
    for i in in_list:
        if 1 <= i <= 10000:
            continue
        flag = False
    return flag
a = list(map(int, input().split()))
if check(a):
    print(" ".join(map(str, sorted(a))))


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

if b > c:
    c,b = b,c

if a > b:
    b,a = a,b

print(a,b,c)


s = input()
sss = s.split()
sss.sort()
a = int(sss[0])
b = int(sss[1])
c = int(sss[2])
print(a,b,c)


#!usr/bin/env python3

def string_five_numbers_spliter():
    """Split a given space-separated five numbers in a string into integers

    Return five integer values from a given space-separated five integers in a string.

    Returns:
        Five integer values; namely, w, h, x, y and r
    """
    w, h, x, y, r = [int(i) for i in input().split()]
    return w, h, x, y, r

def main():
    # Given that there are a rectangle and a circle.
    # Let w, h, x, y and r be such that:
    # w = width of the rectangle
    # h = height of thek rectangle
    # x = x coordinate for the centre of the circle
    # y = y coordinate for the centre of the circle
    # r = diameter of the circle
    w, h, x, y, r = string_five_numbers_spliter()

    if (not (x < 0) and not (y < 0) and
        not (x + r < 0) and not (y + r < 0) and
        not (x + r > w) and not (y + r > h)):
        print('Yes')
    else:
        print('No')

if __name__ == '__main__':
    main()

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


for i in range(10000):
    x = input()
    if x == "0":
        break
    print("Case {}: {}".format(i, x))

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


while True:
  x,y = map(int,input().split())
  if x == 0 and y == 0:
    break
  if x > y:
    print(y,x)
  else:
    print(x,y)

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


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


import math
pi = math.pi
r = float(input())
print('%.6f %.6f' % (pi*r**2, 2*pi*r))

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


import math
r = float(input())
cc = r * r * math.pi
ab = (r + r) * math.pi
print("%.6f"%(cc), "%.6f"%(ab))


# coding: utf-8
# Your code here!
# ITP1_4_C

while(True):
    x,k,y=input().split()
    x=int(x)
    y=int(y)
    if k=='?':
        break
    else:
        if k=='+':
            print(x+y)
        elif k=='-':
            print(x-y)
        elif k=='*':
            print(x*y)
        elif k=='/':
            print(int(x/y))

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

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

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


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

a = min(nlist)
b = max(nlist)
c = sum(nlist)
print(a,b,c)

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


mina=+1000*1000;maxa=-1000*1000;suma=0
input()
for a in tuple(map(int,input().split())):
    mina=min(mina,a);maxa=max(maxa,a);suma+=a
print(mina,maxa,suma)


while(True):
    h, w = map(int, input().split())
    if(h == 0 and 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

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

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

##
##


i=0
while True:
    H,W=map(int,input().split())
    if H==0 and W==0:
        break
    for j in range(H):
        for k in range(W):
            if j==0 or j==(H-1) or k==0 or k==(W-1):
                print("#",end="")
            else:
                print(".",end="")
        print("\n",end="")
    print("\n",end="")
    i+=1

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

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

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

###
#.#
###


def even_line(w):
    s=''
    for i in range(0,w):
        if i%2 == 0:
            s=s+'#'
        else:
            s=s+'.'
    print(s)

def odd_line(w):
    s=''
    for i in range(0,w):
        if i%2 == 0:
            s=s+'.'
        else:
            s=s+'#'

    print(s)

if __name__ == '__main__':

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

    while (h != 0) and (w != 0):
        for i in range(0,h):
            if i%2==0:
                even_line(w)
            else:
                odd_line(w)
            print()
        h, w = map(int, input().split())

Print a Chessboard

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

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

Note that the top left corner should be drawn by '#'.

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 chessboard made of '#' and '.'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

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

Sample Output

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

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

#.#
.#.
#.#

#.
.#

#


import sys
try:
	while 1:
		N=input()
		i = 1
		while 1:
			if (i % 3) == 0 :
				sys.stdout.write(" ")
				sys.stdout.write("%d" % i)
			else:
				if (i % 10 ) == 3 or  (i/10)%10 == 3:
					sys.stdout.write(' ')
					sys.stdout.write("%d" % i)
			if i+1  >  N:
				sys.stdout.write('\n')
				raise Exception
			i += 1
except Exception:
	pass

Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;

cout << endl;
}

Input

An integer n is given in a line.

Output

Print the output result of the above program for given integer n.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

3 6 9 12 13 15 18 21 23 24 27 30

Put a single space character before each element.


n = int(input())
a = list(map(int, input().split()))
for i in range(n-1, -1, -1):
    if i == 0:
        print(a[i])
    else:
        print(a[i], 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

      解説


from sys import stdin
import copy

def output(string, lis):
    for num in lis:
        print(string, num)

n = int(stdin.readline())

#ナンバーリスト作成
slist = []
for i in range(1,14):
    slist.append(i)

hlist = copy.copy(slist)
clist = copy.copy(slist)
dlist = copy.copy(slist)

for _ in range(n):
    mark, number = map(str, stdin.readline().split())
    if mark == 'S':
        slist.remove(int(number))
    elif mark == 'H':
        hlist.remove(int(number))
    elif mark == 'C':
        clist.remove(int(number))
    elif mark == 'D':
        dlist.remove(int(number))

output('S', slist)
output('H', hlist)
output('C', clist)
output('D', dlist)

Finding Missing Cards

Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Input

In the first line, the number of cards n (n ≤ 52) is given.

In the following n lines, data of the n cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line.
Arrange the missing cards in the following priorities:

Print cards of spades, hearts, clubs and diamonds in this order.

If the suits are equal, print cards with lower ranks first.

Sample Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Sample Output

S 1
H 3
H 7
C 12
D 8

Note

      解説


#!/usr/bin/env python3

n = int(input())
matrix = []
while n > 0:
    values = [int(x) for x in input().split()]
    matrix.append(values)
    n -= 1

official_house = [[[0 for z in range(10)] for y in range(3)] for x in range(4)]

for b, f, r, v in matrix:
    official_house[b - 1][f - 1][r - 1] += v

for i in range(4):
    for j in range(3):
        print('',' '.join(str(x) for x in official_house[i][j]))
    print('#' * 20)

Official House

You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.

For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth floor at building b. If v is negative, it means that −v persons left.

Assume that initially no person lives in the building.

Input

In the first line, the number of notices n is given. In the following n lines, a set of four integers b, f, r and v which represents ith notice is given in a line.

Output

For each building, print the information of 1st, 2nd and 3rd floor in this order. For each floor information, print the number of tenants of 1st, 2nd, .. and 10th room in this order. Print a single space character before the number of tenants. Print "####################" (20 '#') between buildings.

Constraints

No incorrect building, floor and room numbers are given.

0 ≤ the number of tenants during the management ≤ 9

Sample Input

3
1 1 3 8
3 2 2 7
4 3 8 1

Sample Output

0 0 8 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 7 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0


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

A = []
b = []
total = 0

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

for i in range(m):
    b.append(int(input()))

for i in range(n):
    for j in range(m):
        total += A[i][j] * b[j]
    print(total)
    total = 0

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

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.

A column vector with m elements is represented by the following equation.

\[
b = \left(
\begin{array}{c}
b_1 \\
b_2 \\
: \\
b_m \\
\end{array}
\right)
\]

A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
A = \left(
\begin{array}{cccc}
a_{11} & a_{12} & ... & a_{1m} \\
a_{21} & a_{22} & ... & a_{2m} \\
: & : & : & : \\
a_{n1} & a_{n2} & ... & a_{nm} \\
\end{array}
\right)
\]

$i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$ $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

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

Sample Output

5
6
9


import sys

W = input().lower()
T = sys.stdin.read().lower()

print(T.split().count(W))

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())
listA = []
listB = []
pntA = pntB = 0

for i in range(n):
    A, B = map(str, input().split())
    listA.append(A)
    listB.append(B)

    if listA[i] > listB[i]:
        pntA += 3
    elif listA[i] == listB[i]:
        pntA += 1
        pntB += 1
    else:
        pntB += 3

print(str(pntA) + ' ' + str(pntB))

Card Game

Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card.
The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

n ≤ 1000

The length of the string ≤ 100

Output

Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7


def calc_gcd(x, y):

    if x < y:
        x, y = y, x

    while y > 0:
        x, y = y, x % y

    return x

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

gcd = calc_gcd(a, b)

x1 = 1
y1 = 0
z1 = a_prime = a / gcd

x2 = 0
y2 = 1
z2 = b_prime = b / gcd

while z2 != 1:
    q = (z1 - (z1 % z2)) / z2

    (x1, y1, z1), (x2, y2, z2) = (x2, y2, z2), (x1 - (q * x2), y1 - (q * y2), z1 - (q * z2))

t = 0
x = x2 + b_prime * t
y = y2 + a_prime * t

print(int(x), int(y))

Extended Euclid Algorithm

Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b.

Input

a b

Two positive integers a and b are given separated by a space in a line.

Output

Print two integers x and y separated by a space. If there are several pairs of such x and y, print that pair for which |x| + |y| is the minimal (primarily) and x ≤ y (secondarily).

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

4 12

Sample Output 1

1 0

Sample Input 2

3 8

Sample Output 2

3 -1


class UnionFind:
    pairs = {}
    def __init__(self, n):
        for i in range(n):
            self.pairs[i] = i

    def set(self, s, t):
        if s in self.pairs and self.pairs[s] == s:
            self.pairs[s] = self.root(t)
        else:
            self.pairs[t] = self.root(s)

    def root(self, x):
        if self.pairs[x] == x:
            return x
        self.pairs[x] = self.root(self.pairs[x])
        return self.pairs[x]

    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        if rx == ry :
            return
        self.pairs[rx] = ry
    def same(self, x, y ):
        rx = self.root(x)
        ry = self.root(y)
        if rx == ry:
            return True
        else:
            return False

def main():
    n, m = map(int, input().split())

    uf = UnionFind(n)
    pairs =[]
    for i in range(m):
        s, t = map(int,input().split())
        if uf.same(s-1, t-1) == False:
            uf.unite(s-1,t-1)
        #pairs.append([s-1,t-1])

    # pairs.sort()
    # for pair in pairs:
    #     uf.set(pair[0], pair[1])
    #
    # for pair in pairs:
    #     uf.set(pair[0], pair[1])

    root = []
    for i in range(n):
        root.append(uf.root(i))
 #       print(i, uf.root(i))
    single_root = set(root)

    print(len(single_root)-1)
main()

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


import sys
input = sys.stdin.readline

class Unionfind:

    def __init__(self,n):
        self.uf = [-1]*n

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

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

    def union(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.uf[x] > self.uf[y]:
            x,y = y,x
        self.uf[x] += self.uf[y]
        self.uf[y] = x
        return True

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

def main():
    n = int(input())
    xy = [list(map(int,input().split())) for i in range(n)]
    xy2 = [[x[0],x[1],i] for (i,x) in enumerate(xy)]
    xy2.sort()
    u = Unionfind(n)

    l = []
    for x,y,ind in xy2:
        M = y
        le = ind
        while l and xy[l[-1]][1] < y:
            v = l.pop()
            if M > xy[v][1]:
                M = xy[v][1]
                le = v
            u.union(ind,v)
        l.append(le)
    for i in range(n):
        print(u.size(i))

if __name__ == "__main__":
    main()

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

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

Sample Output 2

3
3
1
1
2
3
2


n = input()
if n[-1] == 's':
  print(n+'es')
else:
  print(n+'s')

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


N = int(input())

ans = 0
for i in range(1, N + 1):
    ans += (N - 1) // i

print(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


import math as mt

MAXN = 1000001

spf = [0 for i in range(MAXN)]

def sieve():
    spf[1] = 1
    for i in range(2, MAXN):

        spf[i] = i

    for i in range(4, MAXN, 2):
        spf[i] = 2

    for i in range(3, mt.ceil(mt.sqrt(MAXN))):

        if (spf[i] == i):

            for j in range(i * i, MAXN, i):

                if (spf[j] == j):
                    spf[j] = i

def getFactorization(x):
    ret = [0]*(x+1)
    while (x != 1):
        ret[spf[x]]+=1
        x = x // spf[x]

    return ret

sieve()
x = int(input())
ans = 0
for i in range(1,x):
    p = getFactorization(x-i)
    sumi=1
    for i in range(len(p)):
        sumi*=(1+p[i])
    ans+=sumi
print(ans)


import numpy as np

mod = 998244353
n, k = map(int, input().split())
left = []
right = []
for _ in range(k):
  l, r = map(int, input().split())
  left.append(l)
  right.append(r)
dp = np.zeros(n, dtype=np.int)
dp[0] = 1
for i in range(n-1):
  for j in range(k):
    dp[i + left[j] : i + right[j] + 1] += dp[i]
    dp[i + left[j] : i + right[j] + 1] %= mod
print(dp[-1])

Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

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

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


N,K=map(int,input().split(" "))
a=[]
d=[]
e=[]
for k in range(K):
    l,r=map(int,input().split(" "))
    d.append(l)
    e.append(r)
d.sort()
e.sort()
for k in range(K):
    a+=list(range(d[k],e[k]+1))
a.sort()
b=[0 for i in range(a[-1]-1)]
b.append(1)
for i in range(N-1):
    b.append(0)
    for j in a:
        b[-1]+=b[-j-1]
print(b[-1]%998244353)


Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


while True:
	x = input()
	if x == 1:
  		print(0)
   		break
	elif x ==0:
  		print(1)
        break
    else:
      continue


from sys import stdin
inp = lambda : stdin.readline().strip()

n = int(inp())
if n == 1:
    print(0)
else:
    print(1)


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

f=1
g=1
ans=1
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


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


from itertools import combinations
S = int(input())
n = S // 3
ans = -1
for k in range(n + 1):
  ans = ans + 1
print(ans)

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


# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 20:41:42 2020

@author: liang
"""
#E
N = int(input())
d = list()
for i in range(N):
    x, y = map(int,input().split())
    d.append((x,y))

d.sort(key=lambda x:x[0]+x[1])
#print(d)

ans1 = abs(d[0][0] - d[N-1][0]) + abs(d[0][1] - d[N-1][1])

d.sort(key=lambda x:x[0]-x[1])

ans2 = abs(d[0][0] - d[N-1][0]) + abs(d[0][1] - d[N-1][1])

ans = max(ans1, ans2)

print(ans)

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

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

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


def solve():
    N = int(input())
    P = []
    for _ in range(N):
        x, y = input().split()
        P.append((int(x), int(y)))
    ans = 0
    for i in range(N - 1):
        for j in range(i, N):
            ans = max(ans, abs(P[i][0] - P[j][0]) + abs(P[i][1] - P[j][1]))
    print(ans)

if __name__ == "__main__":
    solve()


class UnionFind:
    def __init__(self, N):
        """
        N:要素数
        root:各要素の親要素の番号を格納するリスト.
             ただし, root[x] < 0 ならその頂点が根で-root[x]が木の要素数.
        rank:ランク
        """
        self.N = N
        self.root = [-1] * N
        self.rank = [0] * N

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

    def find(self, x):
        """頂点xの根を見つける"""
        if self.root[x] < 0:
            return x
        else:
            while self.root[x] >= 0:
                x = self.root[x]
            return x

    def union(self, x, y):
        """x,yが属する木をunion"""
        # 根を比較する
        # すでに同じ木に属していた場合は何もしない.
        # 違う木に属していた場合はrankを見てくっつける方を決める.
        # rankが同じ時はrankを1増やす
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        elif self.rank[x] > self.rank[y]:
            self.root[x] += self.root[y]
            self.root[y] = x
        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def same(self, x, y):
        """xとyが同じグループに属するかどうか"""
        return self.find(x) == self.find(y)

    def count(self, x):
        """頂点xが属する木のサイズを返す"""
        return - self.root[self.find(x)]

    def members(self, x):
        """xが属する木の要素を列挙"""
        _root = self.find(x)
        return [i for i in range(self.N) if self.find == _root]

    def roots(self):
        """森の根を列挙"""
        return [i for i, x in enumerate(self.root) 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()}

import sys
input = sys.stdin.readline
n, q = map(int, input().split())
uf = UnionFind(n)
for i in range(q):
    t, u, v = map(int, input().split())
    if t:
        print(int(uf.same(u, v)))
    else:
        uf.union(u, v)

Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

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

Sample Output 1

0
1
0
1


import sys
input = sys.stdin.readline

class SegTree:
    def __init__(self, v, op, e) -> None:
        self._n = len(v)
        self.log = (self._n - 1).bit_length()
        self.size = 1 << self.log
        self.d = [e for _ in range(2 * self.size)]
        self.op = op
        self.e = e
        for i in range(self._n):
            self.d[self.size + i] = v[i]
        for i in reversed(range(1, self.size)):
            self.__update__(i)

    @classmethod
    def init_e(cls, n: int, op, e) -> 'SegTree':
        return cls([e for _ in range(n)], op, e)

    def set(self, p: int, x) -> None:
        p += self.size
        self.d[p] = x
        for i in range(1, self.log + 1):
            self.__update__(p >> i)

    def get(self, p: int):
        return self.d[p + self.size]

    def prod(self, l: int, r: int):
        sml = self.e
        smr = self.e
        l += self.size
        r += self.size

        while l < r:
            if l & 1:
                sml = self.op(sml, self.d[l])
                l += 1
            if r & 1:
                r -= 1
                smr = self.op(self.d[r], smr)
            l >>= 1
            r >>= 1
        return self.op(sml, smr)

    def all_prod(self):
        return self.d[1]

    def max_right(self, l: int, f):
        if l == self._n:
            return self._n
        l += self.size
        sm = self.e
        while True:
            while l & 1 == 0:
                l >>= 1
            if not f(self.op(sm, self.d[l])):
                while l < self.size:
                    l <<= 1
                    if f(self.op(sm, self.d[l])):
                        sm = self.op(sm, self.d[l])
                        l += 1
                return l - self.size
            sm = self.op(sm, self.d[l])
            l += 1
            if (l & -l) == l:
                return self._n

    def min_left(self, r: int, f):
        if r == 0:
            return 0
        r += self.size
        sm = self.e
        while True:
            r -= 1
            while r > 1 and r & 1:
                r >>= 1
            if not f(self.op(self.d[r], sm)):
                while r < self.size:
                    r = (r << 1) + 1
                    if f(self.op(self.d[r], sm)):
                        sm = self.op(self.d[r], sm)
                        r -= 1
                return r + 1 - self.size
            sm = self.op(self.d[r], sm)
            if (r & -r) == r:
                return 0

    def __update__(self, k: int) -> None:
        self.d[k] = self.op(self.d[k << 1], self.d[(k << 1) + 1])

n, q = map(int, input().split())
a = list(map(int, input().split()))
seg = SegTree(a, max, -1)

for _ in range(q):
    t, x, y = map(int, input().split())
    if t == 1:
        seg.set(x - 1, y)
    elif t == 2:
        print(seg.prod(x - 1, y))
    else:
        print(seg.max_right(x - 1, lambda v: v < y) + 1)

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.


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.