$MAX_DAY = 3_652_425

def main
  n,q = gets.chomp.split(' ').map(&:to_i)
  days = Array.new($MAX_DAY + 1, 0)
  consum = Array.new($MAX_DAY + 1, 0)
  final_index = 0
  no_consum_index = 0

  n.times do
    w,t,x = gets.chomp.split(' ').map(&:to_i)
    recover_day = -1
    if consum[final_index] + final_index >= w
      recover_day = final_index
    else
      (final_index+1).upto($MAX_DAY) do |i|
        consum[i] = days[i] + consum[i-1]
        if consum[i] + i >= w
          final_index = i
          recover_day = i
          break
        end
      end
    end

    if recover_day == -1
      puts 'Many years later'
      next
    end

    puts recover_day

    index = 0
    x.times do |i|
      index = recover_day + 1 + i
      break if index > $MAX_DAY
      days[index] += (i+1) ** t
    end
    no_consum_index = [no_consum_index, index].max
  end

  (final_index+1).upto(no_consum_index) do |i|
    consum[i] = days[i] + consum[i-1]
  end
  final_index = no_consum_index

  q.times do
    target = gets.chomp.to_i
    if target <= final_index
      puts target + consum[target]
    else
      puts target + consum[final_index]
    end
  end
end

main

F - Acceleration of Network

インターネットと言う広大な海は少しずつ黒く塗りつぶされていった。

ボットの反乱、DDOS攻撃の嵐、ウィルスの蔓延、

何度も何度も繰り返されたクラッカーとの戦争で、人もインターネットもボロボロになった。

人の手では、インターネットはどうにもならない。

だから人は、とんでもない時間をかけて

インターネットを復旧できる「少女」を造った。

少女は、インターネットの手当をはじめた。

果てしなく広いインターネットの世界をどうにかしようと頑張った。

まだ少女ひとりでは撚り対線を織る事くらいしかできないけど、

長い長い時がすぎてインターネットが少し復旧すれば、

みんなと一緒に頑張れるだろうという期待をこめて。

問題文

少女はかつてインターネットに存在した N 個のサービスを復旧するために日々頑張っている．
現在を 0 日目とする．
インターネットがどの程度復旧しているかを復旧度という指標で表し，現在の復旧度は 0 であるとする．
少女は毎日作業をし，復旧度を 1 日につき 1 ずつ上げていく．
任意のまだ復旧していないサービス i は，復旧度が wi 以上になると自動的に復旧する．
サービス i が復旧すると，みんなが手伝ってくれることにより，復旧した次の日から xi 日間だけ作業がはかどり，復旧度の増加が加速する．
サービスには 3 つの種類があり，種類によって復旧度がどの程度増加するのかが異なる．
サービスの種類を 0, 1, 2 の番号で表すとする．
サービス i の種類を ti (∈ {0, 1, 2}) とすると，
サービス i が復旧してから d-1 日目から d 日目にかけて (1 ≤ d ≤ xi)，
ti=0 の場合は 1，
ti=1 の場合は d，
そして ti=2 の場合は d2 だけ，少女の作業とは別に復旧度が増加する．
また，同時に複数のサービスが復旧している場合，それぞれのサービスは独立に並行して復旧度を増加させる．

少女はサービスが復旧するまでにとんでもない時間がかかると思ったので，現在から何日目にサービスが復旧するか調べることにした．
またある日にち yj に復旧度がいくらになっているかも気になったので，それも Q 日分だけ調べることにした．

入力形式

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

N Q
w1 t1 x1
...
wN tN xN
y1
...
yQ

出力形式

最初に N 行出力し，i 行目にはサービス i の復旧する日にちを出力せよ．次に Q 行出力し，j 行目には yj 日目に復旧度がいくらになっているかを出力せよ．
サービスが復旧する日にちが 3,652,425 を超える場合はMany years laterと出力せよ．

制約

0 ≤ N ≤ 105

1 ≤ Q ≤ 105

0 ≤ wi < 260

wi ≤ wi+1 (1 ≤ i < N)

ti ∈ {0, 1, 2}

1 ≤ xi ≤ 104

0 ≤ yj ≤ 3,652,425

yj < yj+1 (1 ≤ j < Q)

入力値はすべて整数である．

この問題の判定には，15 点分のテストケースのグループが設定されている．このグループに含まれるテストケースは上記の制約に加えて下記の制約も満たす．

N,Q,wi,yj ≤ 1,000

注意

0 日目の復旧度は 0 である．

wi=0 の時，サービス i は 0 日目に復旧する．

入出力例

入力例1

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

出力例1

1
3
4
0
1
3
5
7
11
19
29
46
47
48

入力例2

5 5
10000 0 20
10000 1 30
10000 0 40
10000 2 70
30000 2 10000
5000
10000
15000
20000
25000

出力例2

10000
10000
10000
10000
10039
5000
10000
40711690801
329498273301
333383477320

入力例3

2 2
3652425 0 1
3652426 2 10000
3652424
3652425

出力例3

3652425
Many years later
3652424
3652425

2つ目のサービスは復旧する日にちが 3,652,425 日を超えているのでMany years laterと出力している．

Writer : 森槙悟
Tester : 田村和範


def warshall_floyd(dist_matrix)
	dist = dist_matrix
	n = dist.size
	raise "dist_matrix is not square" if dist.any?{|row| row.size != n}

	next_dist = (1..n).map{ Array.new(n) }
	(0..n-1).each{|k|
		dist_k = dist[k]
		(0..n-1).each{|i|
			dist_i = dist[i]
			next_dist_i = next_dist[i]
			(0..n-1).each{|j|
				x = dist_i[j]
				y = dist_i[k] + dist_k[j]
				next_dist_i[j] = (x < y ? x : y)
			}
		}
		dist = next_dist
	}
	dist
end

loop do
	n, m, l, s, t = gets.split.map(&:to_i)
	break if n == 0

	adj_mat = (0..n).map { (0..n).map { Float::INFINITY } }
	m.times do
		a, b, c = gets.split.map(&:to_i)
		adj_mat[a][b] = adj_mat[b][a] = c
	end
	dist = warshall_floyd(adj_mat)

	siros = [[s, 0]] + (1..l).map { gets.split.map(&:to_i) }
	siros.each do |j, e|
		dist.each {|to_dist| to_dist[j] += e}
	end
	dist = siros.map {|j, e| dist[j]}
	dist.map! {|to_dist| siros.map {|j, e| to_dist[j]}}

	max_num = 0
	hash = { 0 => {0 => 0} }
	(1..2**l-1).each do |visited|
		(1..l).each do |last_idx|
			next if visited[last_idx-1] == 0
			min = Float::INFINITY
			hash[visited - (1 << last_idx-1)].each do |k, d|
				new_d = d + dist[k][last_idx]
				min = new_d if new_d < min
			end
			(hash[visited] ||= {})[last_idx] = min
			if min + dist[last_idx][0] <= t
				c = visited.to_s(2).count(?1)
				max_num = c if c > max_num
			end
		end
	end

	p max_num
end

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

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

Problem Statement

You are now participating in the Summer Training Camp for Programming Contests with your friend Jiro, who is an enthusiast of the ramen chain SIRO.
Since every SIRO restaurant has its own tasteful ramen, he wants to try them at as many different restaurants as possible in the night.
He doesn't have plenty of time tonight, however, because he has to get up early in the morning tomorrow to join a training session.
So he asked you to find the maximum number of different restaurants to which he would be able to go to eat ramen in the limited time.

There are $n$ railway stations in the city, which are numbered $1$ through $n$. The station $s$ is the nearest to the camp venue.
$m$ pairs of stations are directly connected by the railway: you can move between the stations $a_i$ and $b_i$ in $c_i$ minutes in the both directions.
Among the stations, there are $l$ stations where a SIRO restaurant is located nearby. There is at most one SIRO restaurant around each of the stations, and there are no restaurants near the station $s$.
It takes $e_i$ minutes for Jiro to eat ramen at the restaurant near the station $j_i$.

It takes only a negligibly short time to go back and forth between a station and its nearby SIRO restaurant.
You can also assume that Jiro doesn't have to wait for the ramen to be served in the restaurants.

Jiro is now at the station $s$ and have to come back to the station in $t$ minutes. How many different SIRO's can he taste?

Input

The input is a sequence of datasets. The number of the datasets does not exceed $100$. Each dataset is formatted as follows:

$n$ $m$ $l$ $s$ $t$
$a_1$ $b_1$ $c_1$
:
:
$a_m$ $b_m$ $c_m$
$j_1$ $e_1$
:
:
$j_l$ $e_l$

The first line of each dataset contains five integers:

$n$ for the number of stations,

$m$ for the number of directly connected pairs of stations,

$l$ for the number of SIRO restaurants,

$s$ for the starting-point station, and

$t$ for the time limit for Jiro.

Each of the following $m$ lines contains three integers:

$a_i$ and $b_i$ for the connected stations, and

$c_i$ for the time it takes to move between the two stations.

Each of the following $l$ lines contains two integers:

$j_i$ for the station where a SIRO restaurant is located, and

$e_i$ for the time it takes for Jiro to eat at the restaurant.

The end of the input is indicated by a line with five zeros, which is not included in the datasets.

The datasets satisfy the following constraints:

$2 \le n \le 300$

$1 \le m \le 5{,}000$

$1 \le l \le 16$

$1 \le s \le n$

$1 \le t \le 100{,}000$

$1 \le a_i, b_i \le n$

$1 \le c_i \le 1{,}000$

$1 \le j_i \le n$

$1 \le e_i \le 15$

$s \ne j_i$

$j_i$'s are distinct.

$a_i \ne b_i$

$(a_i, b_i) \ne (a_j, b_j)$ and $(a_i, b_i) \ne (b_j, a_j)$ for any $i \ne j$

Note that there may be some stations not reachable from the starting point $s$.

Output

For each data set, output the maximum number of different restaurants where Jiro can go within the time limit.

Sample Input

2 1 1 1 10
1 2 3
2 4
2 1 1 1 9
1 2 3
2 4
4 2 2 4 50
1 2 5
3 4 5
2 15
3 15
4 6 3 1 29
1 2 20
3 2 10
4 1 5
3 1 5
2 4 3
3 4 4
2 1
4 5
3 3
0 0 0 0 0

Output for the Sample Input

1
0
1
3

Submitted source-code file size, in bytes.

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

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


イクタ君は速いプログラムが大好きである。最近は、除算のプログラムを高速にしようとしている。しかしなかなか速くならないので、「常識的に考えて典型的」な入力に対してのみ高速にすればよいと考えた。イクタ君が解こうとしている問題は次のようなものである。

与えられた非負整数nに対し、10進法でp(n) − 1桁の正整数11...1をp(n)で割ったあまりを求めよ。ただしp(n)は22{ . . . 2}（2がn個）より大きい最小の素数を表すとする。p(0) = 2とする。

あなたの仕事は、イクタ君より速くプログラムを完成させることである。

Input

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

n

問題の入力の非負整数nがあたえられる。

Constraints

入力中の各変数は以下の制約を満たす。

0 ≤ n < 1000

Output

問題の解を1行に出力せよ。

Sample Input 1

0

Output for the Sample Input 1

1

n=0のとき、p(n) = 2 なので、1 mod 2 = 1 が解となる。

Sample Input 2

1

Output for the Sample Input 2

2

n=1のとき、p(n) = 3 なので、11 mod 3 = 2が解となる。

Sample Input 3

2

Output for the Sample Input 3

1


n=gets.to_i
c=gets.split.map &:to_i
a=[0]*n
gets.to_i.times{|i|
	t,x,d=gets.split.map &:to_i
	t=-1 if t==2
	x-=1
	a[x]+=t*d
	if a[x]<0||c[x]<a[x]
		p x+1
		exit
	end
}
p 0

A：沢山の種類の林檎 (Many Kinds of Apples)

Problem Statement

Apple Farmer Mon has two kinds of tasks: "harvest apples" and "ship apples".

There are N different species of apples, and N distinguishable boxes. Apples are labeled by the species, and boxes are also labeled, from 1 to N. The i-th species of apples are stored in the i-th box.

For each i, the i-th box can store at most c_i apples, and it is initially empty (no apple exists).

Mon receives Q instructions from his boss Kukui, and Mon completely follows in order. Each instruction is either of two types below.

"harvest apples": put d x-th apples into the x-th box.

"ship apples": take d x-th apples out from the x-th box.

However, not all instructions are possible to carry out. Now we call an instruction which meets either of following conditions "impossible instruction":

When Mon harvest apples, the amount of apples exceeds the capacity of that box.

When Mon tries to ship apples, there are not enough apples to ship.

Your task is to detect the instruction which is impossible to carry out.

Input

Input is given in the following format.

N
c_1 c_2 $\cdots$ c_N
Q
t_1 x_1 d_1
t_2 x_2 d_2
$\vdots$
t_Q x_Q d_Q

In line 1, you are given the integer N, which indicates the number of species of apples.

In line 2, given c_i (1 \leq i \leq N) separated by whitespaces. c_i indicates the capacity of the i-th box.

In line 3, given Q, which indicates the number of instructions.

Instructions are given successive Q lines. t_i x_i d_i means what kind of instruction, which apple Mon handles in this instruction, how many apples Mon handles, respectively. If t_i is equal to 1, it means Mon does the task of "harvest apples", else if t_i is equal to 2, it means Mon does the task of "ship apples".

Constraints

All input values are integers, and satisfy following constraints.

1 \leq N \leq 1,000

1 \leq c_i \leq 100,000 (1 \leq i \leq N)

1 \leq Q \leq 100,000

t_i \in \{1, 2\} (1 \leq i \leq Q)

1 \leq x_i \leq N (1 \leq i \leq Q)

1 \leq d_i \leq 100,000 (1 \leq i \leq Q)

Output

If there is "impossible instruction", output the index of the apples which have something to do with the first "impossible instruction".

Otherwise, output 0.

Sample Input 1

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

Sample Output 1

1

In this case, there are not enough apples to ship in the first box.

Sample Input 2

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

Sample Output 2

1

In this case, the amount of apples exceeds the capacity of the first box.

Sample Input 3

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

Sample Output 3

0

Sample Input 4

6
28 56 99 3 125 37
10
1 1 10
1 1 14
1 3 90
1 5 10
2 3 38
2 1 5
1 3 92
1 6 18
2 5 9
2 1 4

Sample Output 4

3


#encoding: utf-8

def input
  size = []
  n = gets.chomp.to_i
  (1..n).each do |i|
    sz = gets.chomp.split(/\s/).collect{ |x| x.to_i}
    size << { :row => sz[0], :col => sz[1]}
  end
  [n, size]
end

def solve(n, size)
  dp = { }
  0.upto(n - 1).each do |i|
    i.upto(n - 1).each do |j|
      dp[[i, j]] = 0x3fffffff
    end
  end

  0.upto(n - 1) { |i| dp[[i, i]] = 0}

  1.upto(n - 1).each do |k|
    0.upto(n - k - 1).each do |i|
      i.upto(i + k - 1).each do |j|
        sz = size[i][:row] * size[j][:col] * size[i + k][:col]
        dp[[i, i + k]] = [dp[[i, i + k]], dp[[i, j]] + dp[[j + 1, i + k]] + sz].min
      end
    end
  end
  dp
end

def main
  n, size = input
#  p size
  dp = solve(n, size)
  puts dp[[0, n - 1]]
end

main

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

Matrix-chain Multiplication

The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.

Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.

Input

In the first line, an integer $n$ is given. In the following $n$ lines, the dimension of matrix $M_i$ ($i = 1...n$) is given by two integers $r$ and $c$ which respectively represents the number of rows and columns of $M_i$.

Output

Print the minimum number of scalar multiplication in a line.

Constraints

$1 \leq n \leq 100$

$1 \leq r, c \leq 100$

Sample Input 1

6
30 35
35 15
15 5
5 10
10 20
20 25

Sample Output 1

15125


lines = $stdin.read
array = lines.split("\n")

Node = Struct.new(:u, :k, :v, :visited)

class Graph

  attr :nodes, :d, :f

  def initialize(n)
    @nodes = Array.new(n){ Node.new }
    @d = Array.new(n)
    @f = Array.new(n)
  end

  def set_graph_node(u, k, v)
    @nodes[u-1].u = u
    @nodes[u-1].k = k
    @nodes[u-1].v = v
  end

  def dfs(start = 0, count = 1)

    # puts "visit = #{@nodes[start].to_s}, count = #{count}"

    if @nodes[start].visited.nil?
      @nodes[start].visited = true
      @d[start] = count
      count = count + 1

      for i in @nodes[start].v
        count = dfs(i-1, count) unless @nodes[i-1].visited
      end
      # puts "visited = #{@nodes[start].to_s}, count = #{count}"
    end

    @f[start] = count
    count = count + 1
    count
  end
end

N     = array[0].to_i
graph = Graph.new(N)

for i in 1...array.length
  seps = array[i].split(" ")
  u = seps.drop(0).first.to_i
  k = seps.drop(1).first.to_i
  v = seps.drop(2).map(&:to_i)
  graph.set_graph_node(u, k, v)
end

graph.dfs()

# puts "d #{graph.d.to_s}"
# puts "f #{graph.f.to_s}"

1.upto(N).each do |n|
  puts "#{n} #{graph.d[n-1]} #{graph.f[n-1]}"
end

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

Depth First Search

Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.

This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.

DFS timestamps each vertex as follows:

$d[v]$ records when $v$ is first discovered.

$f[v]$ records when the search finishes examining $v$’s adjacency list.

Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:

$G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.

IDs in the adjacency list are arranged in ascending order.

The program should report the discover time and the finish time for each vertex.

When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.

The timestamp starts with 1.

Input

In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

Sample Input 1

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

Sample Output 1

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

Sample Input 2

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

Sample Output 2

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

This is example for Sample Input 2 (discover/finish)

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


# NOTE: 1-origin (not 0-origin)
$adj_lists = []

$cache= {}

# $queue = []

def find_min_dist(start_node, target_node)

  queue = []

  queue.push([start_node, 0])

  # min_dis = Float::INFINITY
  dis = 0
  while (n, d = queue.shift)
    if n == target_node
      return d
    else
    nodes = $adj_lists[n]
    nodes.each{|node|
      queue.push([node, dis])
    }
    dis += 1

    $cache[[start_node, target_node]] = dis

  end

  # $cache[[start_node, target_node]] = min_dis

  # return min_dis + 1

  # mins = nodes.map{|n|
  #
  # }
  # dis = mins.min + 1
  # $cache[[start_node, target_node]] = dis
  # return dis
  end

end

_ = gets

while line = gets
  i, _, *nodes= line.split(' ').map(&:to_i)
  $adj_lists[i] = nodes
end

# # NOTE: 1-origin
# distances = [nil] * $adj_lists.size
#
# distances[1] = 0
#
# # (1..$adj_lists.size).each{|i|
# #
# # }
#
# # p $adj_lists
#
#

# Node => min dist
node_to_min_dist_hash = {}

def find(start_node, target_node)
  open_list   = [[start_node, 0]]
  closed_list = []

  while open_list.size != 0
    node, dist = open_list.shift
    if node == target_node
      # puts("Found #{node}, #{target_node}: dist #{dist}")
      return dist
    end
    # puts(node)
    nodes = $adj_lists[node]
    nodes.each{|n|
      open_list.push([n, dist+1])
    }
    closed_list.push(node)
  end

  return -1

end

# Print
(1...$adj_lists.size).each{|target_node|
  min_dist = find(1, target_node)
  puts("#{target_node} #{min_dist}")
}

# p find_node(1, 2)
# p find_node(1, 3)
# p find_node(1, 4)
#
# # p distances

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

Breadth First Search

Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.

Input

In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.

Constraints

$1 \leq n \leq 100$

Output

For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1

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

Sample Output 1

1 0
2 1
3 2
4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


MAX_COST = Float::INFINITY

def calc_min_costs_from(v_start, costs)
  vert_struct = Struct.new :id, :cost_from_start do
    define_method :cost_to do |v_to|
      costs[id][v_to.id]
    end

    def connected_to?(v_to)
      0 <= cost_to(v_to)
    end

    def cost_from_start_through(other_v)
      other_v.cost_from_start + other_v.cost_to(self)
    end
  end

  n_vertexes = costs.size
  verts = n_vertexes.times.map do |id|
    vert_struct.new(id, MAX_COST)
  end

  verts[v_start].cost_from_start = 0
  visiting = {}
  visiting[v_start] = verts[v_start]

  while visiting.any?
    v_from = visiting.min_by { |_, v| v.cost_from_start }[1]
    visiting.delete v_from.id

    verts.each do |v_to|
      next unless v_from != v_to && v_from.connected_to?(v_to)
      through_cost = v_to.cost_from_start_through v_from
      if through_cost < v_to.cost_from_start
        v_to.cost_from_start = through_cost
        visiting[v_to.id] = v_to
      end
    end
  end

  verts.map { |v| v.cost_from_start }
end

n_vertexes = gets.to_i
costs      = Array.new(n_vertexes) { Array.new(n_vertexes, -1) }
n_vertexes.times do
  v_from, n_degrees, *inputs = gets.split.map &:to_i
  1.step(n_degrees * 2, 2) do |i|
    v_to, cost = inputs[i - 1], inputs[i]
    costs[v_from][v_to] = cost
  end
end

min_costs = calc_min_costs_from(0, costs)
puts min_costs.map.with_index{ |cost, v| "#{v} #{cost}" }

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

Single Source Shortest Path

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

$0 \leq c_i \leq 100,000$

$|E| \leq 10,000$

All vertices are reachable from vertex $0$

Sample Input 1

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

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


INFTY = 1<<21
WHITE = 0
GRAY  = 1
BLACK = 2

N = gets.to_i
@a = N.times.map{gets.split.map(&:to_i)}

@m = Array.new(N){Array.new(N){INFTY}}

def dijkstra
  d = Array.new(N){INFTY}
  color = Array.new(N){WHITE}

  d[0] = 0
  color[0] = GRAY

  loop do
    minv = INFTY
    u = -1

    (0...N).each do |i|
      if minv > d[i] && color[i] != BLACK
        u = i
        minv = d[i]
      end
    end

    break if u == -1
    color[u] = BLACK

    (0...N).each do |v|
      if color[v] != BLACK && @m[u][v] != INFTY
        if d[v] > d[u] + @m[u][v]
          d[v] = d[u] + @m[u][v]
          color[v] = GRAY
        end
      end
    end
  end

  (0...N).each do |i|
    puts "#{i} #{d[i] == INFTY ? -1 : d[i]}"
  end
end

(0...N).each do |i|
  u = @a[i][0]
  k = @a[i][1]

  (2...(k * 2 + 2)).each do |j|
    next if j.odd?
    v = @a[i][j]
    c = @a[i][j + 1]
    @m[u][v] = c
  end
end
dijkstra


def shortest_path
  cost = Array.new(@n-1, Float::INFINITY).unshift(0)
  node = Marshal.load(Marshal.dump(cost))

  @n.times do
    now = node.index(node.compact.min)
    @graph[now].each_with_index do |x, i|
      unless x == nil
        alt = cost[now] + x
        if cost[i] > alt
          cost[i] = alt
          node[i] = alt
        end
      end
    end
    node[now] = nil
  end

  return cost
end

@n = gets.to_i
@graph = Array.new(@n).map{Array.new(@n,nil)}

@n.times do |i|
  input = gets.split(" ").map{|x| x.to_i}
  u = input.shift
  k = input.shift
  k.times do
    @graph[u][input.shift] = input.shift
  end
end

shortest_path.each_with_index do |x, i|
  printf "%d %d\n",i ,x
end


B = 1000000007
DIV = 1<<64
def rolling_hash(s, n)
  hash = Array.new(n+1)
  hash[0] = 0
  n.times{ |i| hash[i+1] = (hash[i]*B + s[i].ord) % DIV }
  hash
end
s = gets.chomp
t = gets.chomp
sl = s.size
tl = t.size
p = Array.new(sl+1)
p[0] = 1
sl.times{ |i| p[i+1] = p[i]*B % DIV }
h1 = rolling_hash(s,sl)
h2 = rolling_hash(t,tl)
(0..(sl-tl)).each do |i|
  p i if (h1[i+tl] - h1[i]*p[tl]) % DIV == h2[tl]
end

String Search

Find places where a string P is found within a text T.
Print all indices of T where P found. The indices of T start with 0.

Input

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

Output

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

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output 3

The output should be empty.


t = gets.chomp
q = gets.to_i
p = []
min = 1.0 / 0.0
max = 0
q.times{|i|
  p[i] = gets.chomp
  min = p[i].size if p[i].size < min
  max = p[i].size if p[i].size > max
}

hash = {}
0.upto(t.size-min){|i|
  hash[t[i,min]] = [] unless hash[t[i,min]]
  hash[t[i,min]] << i
}

checked = {}
p.size.times{|i|
  unless checked[p[i]]
    unless hash[p[i][0,min]] then
      checked[p[i]] = 0
    else
      ans = 0
      hash[p[i][0,min]].each{|j|
        if t[j,p[i].size] == p[i] then
          ans = 1
          break
        end
      }
      checked[p[i]] = ans
    end
  end
  puts checked[p[i]]
}

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 = STDIN.gets.to_i
array = STDIN.gets.split.map(&:to_i)
for i in 1..(n-1) do
  v = array[i]
  j=i-1
  while (j>=0 && array[j] > v) do
    array[j+1] = array[j]
    j-=1
  end
  array[j+1] = v
  puts array.join(' ')
end

puts array.join(' ')

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 = gets.to_i
a = gets.split.map(&:to_i)
def insertionSort(a,n)
  for k in 0..n-2
    print "#{a[k]} "
  end
  puts a[n-1]
  for i in 1..n-1
    v = a[i]
    j = i-1
    while j >= 0 && a[j] > v
      a[j+1] = a[j]
      j -= 1
      a[j+1] = v
    end
    for k in 0..n-2
      print "#{a[k]} "
    end
    puts a[n-1]
  end
end
insertionSort(a,n)


x,y = gets.split.map(&:to_i)

def gcd(m, n)
  if n == 0
    m
  else
    gcd(n, m % n)
  end
end

puts x < y ? gcd(x, y) : gcd(y, x)

Greatest Common Divisor

Write a program which finds the greatest common divisor of two natural numbers a and b

Input

a and b are given in a line sparated by a single space.

Output

Output the greatest common divisor of a and b.

Constrants

1 ≤ a, b ≤ 109

Hint

You can use the following observation:

For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y)

Sample Input 1

54 20

Sample Output 1

2

Sample Input 2

147 105

Sample Output 2

21


x, y = gets.chomp.split.map(&:to_i)

if x > y
   rest = x % y
   y_common_divisors = Array.new
   for i in 1..y do
      y_common_divisors.push i if y % i == 0
   end
   x_y_common_divisors = Array.new
   for i in 1..rest do
      x_y_common_divisors.push i if rest % i == 0
   end

   common_divisors = y_common_divisors & x_y_common_divisors
   puts common_divisors[common_divisors.count - 1]
elsif x < y
   rest = y % x
   x_common_divisors = Array.new
   for i in 1..x do
      x_common_divisors.push i if x % i == 0
   end
   x_y_common_divisors = Array.new
   for i in 1..rest do
      x_y_common_divisors.push i if rest % i == 0
   end

   common_divisors = x_common_divisors & x_y_common_divisors
   puts common_divisors[common_divisors.count - 1]
elsif x = y
   puts x
end


require 'prime'

nums = []
count = 0

gets.to_i.times do
  nums << gets.to_i
end

nums.each do |num|
  count += 1 if Prime.prime?(num)
end

p count

Prime Numbers

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

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

Input

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

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

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

Sample Output 2

4


n = gets.to_i
max_diff = -1_001_001_001
minv = 1_001_001_001

n.times do |i|
  r = gets.to_i
  max_diff = [max_diff, r - minv].max unless i.zero?

  minv = [minv, r].min
end

p max_diff

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 = gets.chop.to_i
R = []

n.times { R << gets.to_i }

maxv = -2000000000
minv = R[0]

def maxof(x, y)
    return (x > y) ? x : y
end

def minof(x, y)
    return (x < y) ? x : y
end

(1...n).each do |i|
  maxv = maxof(maxv, R[i] - minv)
  minv = minof(minv, R[i])
end

puts maxv


N = gets.to_i
data = gets.split.map { |e| e.to_i }
swap_count = 0

for i in 0..N-1
  (N-1).downto(i+1) do |j|
    if data[j] < data[j-1]
      data[j],data[j-1] = data[j-1],data[j]
      swap_count += 1
    end
  end
end

puts data.join(" ")
p swap_count

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


N = gets.to_i
a = gets.split.map(&:to_i)

cnt = 0
N.times do |i|
    minJ = i
    for j in i..(N - 1) do
        minJ = j if a[j] < a[minJ]
    end
    if minJ != i then
        tmpV = a[i]
        a[i] = a[minJ]
        a[minJ] = tmpV
        cnt += 1
    end
end

puts a.join(' ')
puts cnt

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 calc(a)
  stack = []
  symbol = '+-*/'
  a.each do |e|
    if symbol.include?(e)
      a, b = stack.pop(2)
      aque =
      case e
      when '+' then a + b
      when '-' then a - b
      when '*' then a * b
      when '/' then a / b
      end
      stack << aque
    else
      stack << e.to_i
    end
  end
  stack[0]
end

p calc(gets.split)

Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free.

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100

1 ≤ the number of operators in the expression ≤ 99

-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1

1 2 +

Sample Output 1

3

Sample Input 2

1 2 + 3 4 - *

Sample Output 2

-3

Notes

Template in C


array = gets(chomp:true).split
stack = []

array.each do |elm|
  case elm
  when "+"
    n1 = stack.pop
    n2 = stack.pop
    stack.push(n2 + n1)
  when "-"
    n1 = stack.pop
    n2 = stack.pop
    stack.push(n2 - n1)
  when "*"
    n1 = stack.pop
    n2 = stack.pop
    stack.push(n2 * n1)
  else
    stack << elm.to_i
  end
end

puts stack


class Task
  def initialize(name, time)
    @name = name
    @time = time
  end
  attr_accessor :name, :time

  def process(quantum)
    if (@time > quantum) then
      @time -= quantum
      return quantum
    elsif
      a = @time
      @time = 0
      return a
    end
  end
end

n, q = gets.chomp.split(' ').map(&:to_i)
tasks = []
n.times do |i|
  array = gets.chomp.split(' ')
  tasks << Task.new(array[0], array[1].to_i)
end

proc_time_sum = 0
while (tasks.size > 0) do
  task = tasks.shift
  work_time = task.process(q)
  proc_time_sum += work_time

  if (task.time > 0) then
    tasks.push(task)
  else
    puts "#{task.name} #{proc_time_sum}"
  end
end

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


s1 = []
s2 = []

str = gets
i = 0
sum = 0
str.chars do |c|
	if c == "\\"
		s1.push(i)
	elsif c == "/" && s1.size > 0
		j = s1.pop
		sum += i - j
		a = i - j
		while s2.size > 0 && s2.last[:pos] > j
			st = s2.pop
			a += st[:area]
		end
		s2.push({:pos => j, :area => a})
	end
	i += 1
end

puts sum
printf("%d %s", s2.size, s2.map{|h|h[:area]}.join(" "))

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

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

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

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

Input

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

output

Report the areas of floods in the following format:

$A$

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

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

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

Constraints

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

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

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

Sample Output 2

35
5 4 2 1 19 9


n = gets.to_i
s = gets.split(" ").map &:to_i
q = gets
ta = gets.split(" ").map &:to_i

c = 0
ta.each { |t|
	s_start = 0
	s_end = n-1
	while true
		i = (s_start + s_end) / 2
		if t == s[i]
			c += 1
			break
		elsif t < s[i]
			s_end = i - 1
		elsif s[i] < t
			s_start = i + 1
		end
	end
}
puts c

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


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.


gets
l=gets.split.map{|c|[c.to_i]}
i=0
l.sort.map{|a|a[0]=i+=1}
b=[s=0]*r=l.size+1
l.reverse_each{|n,|i=n;(s+=b[i];i&=i-1)while i>0;(b[n]+=1;n+=n&-n)while n<r}
p s

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

The Number of Inversions

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

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

return cnt

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

Input

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

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


n = gets.to_i
arr = gets.split.map(&:to_i)
cnt = 0
for i in 0..n-1
  for j in i+1..n-1
    cnt += 1 if arr[i] > arr[j]
  end
end
puts cnt


gets
puts gets.split.sort_by(&:to_i)*" "

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

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

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


  def solve(n, cards)
    a = []
    b = []
    p cards
    for j in 0..(n-1)
      m = cards[j][0]
      i = cards[j][1].to_i
      a.push([m, i])
      b.push([m, i])
    end

    qsort(a, 0, n-1)

    stable = true
    (0..n-2).each do |i|
      if (a[i][1] == a[i+1][1])
        if b.index(a[i]) > b.index(a[i+1])
          stable = false
          break
        end
      end
    end

    if stable
      puts("Stable")
    else
      puts("Not stable")
    end

    a.each do |x|
      puts x.join(" ")
    end
  end

  def qsort(a, p, r)
    if p < r
      q = partion(a, p, r)
      qsort(a, p, q-1)
      qsort(a, q+1, r)
    end
  end

  def partion(a, p, r)
    x = a[r][1]
    i = p - 1
    (p...r).each do |j|
      if a[j][1] <= x
        i += 1
        a[i], a[j] = a[j], a[i]
      end
    end
    a[i+1], a[r] = a[r] , a[i+1]
    return i+1
  end

n = gets.chomp.to_i
cards = []
n.times do
  card = gets.chomp.split
  cards.push(card)
end
solve(n, cards)

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


c=[p]*gets.to_i
d=$<.map{|l|a,_,*b=l.split.map &:to_i;[a,b.map{|i|c[i]=i}]}.sort
(f=->n,e,a{t=d[n][1].map{|i|f[i,e+1,n]};d[n][1,0]=[a,e,a<0?:root:t==[]?:leaf:"internal node"]})[c.index(p),0,-1]
d.map{|i|puts"node %d: parent = %d, depth = %d, %s, %s"%i}

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

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

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


# 左子右兄弟表現(一番左の子と、自分の右隣の兄弟へのリンクを持つ)
class TreeNode
	attr_accessor :parent, :left_child, :right_sibling, :depth

	def type
		return "root" unless @parent
		return "leaf" unless @left_child
		"internal node"
	end

	# stack overflow
	# def self.set_depth(nodes, id, depth)
	# 	nodes[id].depth = depth
	# 	if nodes[id].right_sibling
	# 		set_depth(nodes, nodes[id].right_sibling, depth)
	# 	end
	# 	if nodes[id].left_child
	# 		set_depth(nodes, nodes[id].left_child, depth + 1)
	# 	end
	# end

	def self.depth(nodes, id)
		depth = 0
		while nodes[id].parent
			id = nodes[id].parent
			depth += 1
		end
		depth
	end

	def self.description(nodes, id)
		node = nodes[id]
		children_id_list = []

		child_id = node.left_child
		while child_id
			children_id_list << child_id
			child_id = nodes[child_id].right_sibling
		end

		desc  = "node #{id}: "
		desc += "parent = #{node.parent ? node.parent : -1}, "
		desc += "depth = #{TreeNode.depth(nodes, id)}, "
		desc += "#{node.type}, "
		desc += "[#{children_id_list.join(", ")}]"
	end
end

# 木全体を配列で管理する, indexがidと紐づく
n = STDIN.gets.to_i
nodes = []
n.times { nodes << TreeNode.new }

n.times.each do |i|
	id, degree, *children = STDIN.gets.split.map(&:to_i)

	prev = nil
	children[0...degree].each_index do |j|
		child = children[j]

		if j == 0
			nodes[id].left_child = child
		else
			nodes[prev].right_sibling = child
		end

		prev = child
		nodes[child].parent = id
	end
end

nodes.each_index { |id| puts TreeNode.description(nodes, id) }


class MyNode
  attr_accessor :parent, :left_child, :right_sibling, :depth

  def type
    if @parent == -1
      "root"
    elsif @left_child
      "internal node"
    else
      "leaf"
    end
  end

  def depth(nodes)
    if @parent == -1
      return 0
    else
      return nodes[@parent].depth(nodes) + 1
    end
  end

end

def set_depth(nodes, i, d)
  node = nodes[i]
  node.depth = d
  if node.left_child
    set_depth(nodes, node.left_child, d + 1)
  end
  if node.right_sibling
    set_depth(nodes, node.right_sibling, d)
  end
end

n = gets.to_i
nodes = []
n.times do
  nodes << MyNode.new
end

n.times do
  inputs = gets.split.map(&:to_i)
  node_id = inputs.shift
  node = nodes[node_id]
  d = inputs.shift
  prev_id = nil
  inputs.each_with_index do | c_id, i|
    nodes[c_id].parent = node_id
    if i.zero?
      node.left_child = c_id
    else
      nodes[prev_id].right_sibling = c_id
    end
    prev_id = c_id
  end
end

root_id = nil
nodes.each_with_index do |node, i|
  if node.parent.nil?
    node.parent = -1
    root_id = i
  end
end

# set_depth(nodes, root_id, 0)

nodes.each_with_index do |node, i|
  childlen_ids = []
  if node.left_child
    childlen_ids << node.left_child
    child_node = nodes[node.left_child]
    while child_node.right_sibling
      childlen_ids << child_node.right_sibling
      child_node = nodes[child_node.right_sibling]
    end
  end

  puts "node #{i}: parent = #{node.parent}, depth = #{node.depth(nodes)}, #{node.type}, [#{childlen_ids.join(', ')}]"
end


class BinTree
  attr_accessor :node
  def initialize(n)
    @node = Array.new(n){Node.new()}
  end
  def preorder(n=root())
    str = ""
    return str if n < 0
    #root
    str << sprintf(" %s", n)
    #left
    str << preorder(node[n].left)
    #right
    str << preorder(node[n].right)
    return str
  end
  def inorder(n=root())
    str = ""
    return str if n < 0
    #left
    str << inorder(node[n].left)
    #root
    str << sprintf(" %s", n)
    #right
    str << inorder(node[n].right)
    return str
  end
  def postorder(n=root())
    arr = []
    return [] if n < 0
    #left
    arr += postorder(node[n].left)
    #right
    arr += postorder(node[n].right)
    arr += [n]
  end
  def root
    #find root
    r = 0
    node.size.times {|i|
      if node[i].parent == -1 then
        r = i
        break
      end
    }
    return r
  end
  def add(i, l, r)
    node[i].left = l
    node[i].right = r
    node[l].parent = i unless l == -1
    node[r].parent = i unless r == -1
  end
  def order_to_tree(preorder, inorder)
    n = preorder.size
    i = preorder[0]
    idx_root = inorder.index(i)
    if idx_root == 0 then
      inorder_left = []
    else
      inorder_left = inorder[0..idx_root-1]
    end
    inorder_right = inorder[idx_root+1..n-1]
    idx = preorder.index(inorder_right[0])
    preorder_left = preorder[1..idx-1]
    preorder_right = preorder[idx..n-1]
#    p inorder_right.size, preorder_right.size

    if inorder_left.size == 1 then
      node[i].left = inorder_left[0]
      node[inorder_left[0]].parent = i
    end
    if inorder_right.size == 1 then
      node[i].right = inorder_right[0]
      node[inorder_right[0]].parent = i
    end
    if inorder_left.size > 1 then
      node[i].left = self.order_to_tree(preorder_left, inorder_left)
      node[node[i].left].parent = i
    end
    if inorder_right.size > 1 then
      node[i].right = self.order_to_tree(preorder_right, inorder_right)
      node[node[i].right].parent = i
    end
    return i
  end
end

class Node
  attr_accessor :parent, :left, :right
  def initialize
    @parent = -1
    @left = -1
    @right = -1
  end
end

n = gets.to_i
tree = BinTree.new(n)

preorder = gets.split.map(&:to_i).map{|i| i -= 1}
inorder = gets.split.map(&:to_i).map{|i| i -= 1}

tree.order_to_tree(preorder, inorder)

puts tree.postorder().map{|i| i += 1}.join(" ")

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

Reconstruction of a Tree

Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.

Input

In the first line, an integer $n$, which is the number of nodes in the binary tree, is given.

In the second line, the sequence of node IDs obtained by the preorder tree walk is given separated by space characters.

In the second line, the sequence of node IDs obtained by the inorder tree walk is given separated by space characters.

Every node has a unique ID from $1$ to $n$. Note that the root does not always correspond to $1$.

Output

Print the sequence of node IDs obtained by the postorder tree walk in a line. Put a single space character between adjacent IDs.

Constraints

$1 \leq n \leq 40$

Sample Input 1

5
1 2 3 4 5
3 2 4 1 5

Sample Output 1

3 4 2 5 1

Sample Input 2

4
1 2 3 4
1 2 3 4

Sample Output 2

4 3 2 1


x1, y1, x2, y2 = gets.split.map(&:to_i)
u = (x2 - x1) + (y2 - y1) * 1i
gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  v = x - x1 + (y - y1) * 1i
  d = (u.conj * v).imag
  case
  when d > 0
    puts 'COUNTER_CLOCKWISE'
  when d < 0
    puts 'CLOCKWISE'
  else
    d = (v / u).real
    case
    when d < 0
      puts 'ONLINE_BACK'
    when d < 1
      puts 'ON_SEGMENT'
    else
      puts 'ONLINE_FRONT'
    end
  end
end

Counter-Clockwise

For given three points p0, p1, p2, print

COUNTER_CLOCKWISE

if p0, p1, p2 make a counterclockwise turn (1),

CLOCKWISE

if p0, p1, p2 make a clockwise turn (2),

ONLINE_BACK

if p2 is on a line p2, p0, p1 in this order (3),

ONLINE_FRONT

if p2 is on a line p0, p1, p2 in this order (4),

ON_SEGMENT

if p2 is on a segment p0p1 (5).

Input

xp0 yp0 xp1 yp1
q
xp20 yp20
xp21 yp21
...
xp2q-1 yp2q-1

In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2.

Output

For each query, print the above mentioned status.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xi, yi ≤ 10000

p0 and p1 are not identical.

Sample Input 1

0 0 2 0
2
-1 1
-1 -1

Sample Output 1

COUNTER_CLOCKWISE
CLOCKWISE

Sample Input 2

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

Sample Output 2

ONLINE_BACK
ON_SEGMENT
ONLINE_FRONT


def make_2d_array(n, m, init)
  n.times.map{[init] * m}
end

def min(a, b)
  a < b ? a : b
end

n, _   = gets.split(' ').map(&:to_i)
# Available coins
coins = gets.split(' ').map(&:to_i)

# Initialize DP table
dp_table = make_2d_array(coins.size+1, n+1, 0) # (coins.size + 1).times{[nil] * (coins.size + 1)}
(1..n).each{|j|
  dp_table[0][j] = Float::INFINITY
}
dp_table[0][0] = 0

(1..coins.size).each{|i|
  (0..n).each{|j|
    coin = coins[i-1]
    if 0 <= j - coin
      dp_table[i][j] = min(dp_table[i-1][j], dp_table[i][j - coin] + 1)
    else
      dp_table[i][j] = dp_table[i-1][j]
    end
  }
}

puts(dp_table[-1][-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


n = gets.to_i
$c = Array.new(n)
n.times{ |i| $c[i] = gets.split.map(&:to_i)[1..-1] }
$depth = Array.new(n)
$max = (Math.log(n) / Math.log(2)).ceil
$dp = Array.new(n){ Array.new($max) }

def bfs
  arr = []
  arr << [0,-1,0]
  until arr.empty?
    a,pre,dep = arr.shift
    $depth[a] = dep
    $dp[a][0] = pre
    (1...$max).each do |i|
      if $dp[a][i-1] != -1 then $dp[a][i] = $dp[$dp[a][i-1]][i-1]
      else $dp[a][i] = -1
      end
    end
    $c[a].each do |i|
      next if i == pre
      arr << [i, a, dep+1]
    end
  end
end

def lca(a, b)
  a, b = b, a if $depth[a] > $depth[b]
  dh = $depth[b] - $depth[a]
  i = 0
  while (1<<i) <= dh
    b = $dp[b][i] if dh&(1<<i) == 1
    i += 1
  end
  return a if a == b
  ($max-1).downto(0) do |i|
    if $dp[a][i] != $dp[b][i]
      a = $dp[a][i]; b = $dp[b][i]
    end
  end
  $dp[a][0]
end

bfs
gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  p lca a, b
end

LCA: Lowest Common Ancestor

For a rooted tree, find the lowest common ancestor of two nodes u and v.

The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.

Input

n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.

In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.

Output

For each query, print the LCA of u and v in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

Sample Input 1

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

Sample Output 1

1
1
0
0


x1, y1, x2, y2 = gets.split.map(&:to_f)
puts Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)

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


#lines = <<'EOS'
#0 0 1 1
#EOS

lines = $stdin.read

array = lines.split("\n")

str = array[0]
x1  = str.split(" ")[0].to_f
y1  = str.split(" ")[1].to_f
x2  = str.split(" ")[2].to_f
y2  = str.split(" ")[3].to_f

diff = ((x1-x2)**2).abs + ((y1-y2)**2).abs
d    = Math.sqrt(diff)
puts "#{d}"


input = []
STDIN.gets.split(' ').each{|v| input.push(v.to_f) }

puts Math.sqrt((input[2] - input[0])*(input[2] - input[0]) + (input[3] - input[1])*(input[3] - input[1]))


class Dice
    def initialize(nums)
        @nums = [nil] + nums
    end
    def top
        @nums[1]
    end
    def rollx
        @nums[1], @nums[2], @nums[6], @nums[5] = @nums[5], @nums[1], @nums[2], @nums[6]
        self
    end
    def rolly
        @nums[1], @nums[3], @nums[6], @nums[4] = @nums[4], @nums[1], @nums[3], @nums[6]
        self
    end
    def rollz
        @nums[2], @nums[3], @nums[5], @nums[4] = @nums[4], @nums[2], @nums[3], @nums[5]
        self
    end
    def moveN
        rollx.rollx.rollx
    end
    def moveS
        rollx
    end
    def moveE
        rolly
    end
    def moveW
        rolly.rolly.rolly
    end
    def move(m)
        case m
        when 'N' then moveN
        when 'S' then moveS
        when 'E' then moveE
        when 'W' then moveW
        end
    end
end

nums = STDIN.gets.split.map(&:to_i)
moves = STDIN.gets.split('')

dice = Dice.new(nums)

moves.each do |m|
    dice.move(m)
end

puts dice.top

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

Dice I

Write a program to simulate rolling a dice, which can be constructed by the following net.

As shown in the figures, each face is identified by a different label from 1 to 6.

Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.

In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.

Output

Print the integer which appears on the top face after the simulation.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

$0 \leq $ the length of the command $\leq 100$

Sample Input 1

1 2 4 8 16 32
SE

Sample Output 1

8

You are given a dice where 1, 2, 4, 8, 16 are 32 are assigned to a face labeled by 1, 2, ..., 6 respectively. After you roll the dice to the direction S and then to the direction E, you can see 8 on the top face.

Sample Input 2

1 2 4 8 16 32
EESWN

Sample Output 2

32


class Dice

  def initialize (given_ary)
    @ary = given_ary
  end

  def roll (direction)
    case direction.downcase
    when "e"
      tmp = @ary[0]
      @ary[0] = @ary[3]
      @ary[3] = @ary[5]
      @ary[5] = @ary[2]
      @ary[2] = tmp
    when "w"
      tmp = @ary[0]
      @ary[0] = @ary[2]
      @ary[2] = @ary[5]
      @ary[5] = @ary[3]
      @ary[3] = tmp
    when "s"
      tmp = @ary[0]
      @ary[0] = @ary[4]
      @ary[4] = @ary[5]
      @ary[5] = @ary[1]
      @ary[1] = tmp
    when "n"
      tmp = @ary[0]
      @ary[0] = @ary[1]
      @ary[1] = @ary[5]
      @ary[5] = @ary[4]
      @ary[4] = tmp
    end
  end

  def top
    @ary[0]
  end

end

dice = Dice.new( gets.split.map(&:to_i) )
gets.split('').each do | which |
  dice.roll( which )
end
puts dice.top


class Dice
    attr_reader :top, :front, :right, :left, :back, :bottom

    def initialize(top, front, right, left, back, bottom)
        @top, @front, @right, @left, @back, @bottom \
            = top, front, right, left, back, bottom
    end

    def south
        @top, @front, @bottom, @back \
            = @back, @top, @front, @bottom
    end

    def north
        @top, @front, @bottom, @back \
            = @front, @bottom, @back, @top
    end

    def east
        @top, @right, @bottom, @left \
            = @left, @top, @right, @bottom
    end

    def west
        @top, @right, @bottom, @left \
            = @right, @bottom, @left, @top
    end

    def spin
        @front, @right, @back, @left \
            = @right, @back, @left, @front
    end

    def is_equal?(other)
        for i in 0...6
            (i % 2 == 1)? (self.north): (self.east)
            for j in 0...4
                self.spin
                if (self == other)
                    return true
                end
            end
        end

        return false
    end

    def ==(other)
        @top == other.top && @front == other.front \
            && @right == other.right && @left == other.left \
            && @back == other.back && @bottom == other.bottom
    end
end

dice01 = Dice.new(*(gets.chomp.split.map(&:to_i)))
dice02 = Dice.new(*(gets.chomp.split.map(&:to_i)))

puts ((dice01.is_equal?(dice02))? "Yes": "No")

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

Dice III

Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical.

Input

In the first line, six integers assigned to faces of a dice are given in ascending order of their corresponding labels.

In the second line, six integers assigned to faces of another dice are given in ascending order of their corresponding labels.

Output

Print "Yes" if two dices are identical, otherwise "No" in a line.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

Sample Input 1

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

Sample Output 1

Yes

Sample Input 2

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

Sample Output 2

No


def check(x, y)
  2.times do |z|
    4.times do
      return true if x == y
      a, b, c, d, e, f  = x
      x = z.zero? ? [e, a, c, d, f, b] : [d, b, a, f, e, c]
      c = x
      4.times do
        i, j, k, l, m, n = c
        c = [i, k, m, j, l, n]
        return true if c == y
      end
    end
  end
  false
end

ar = $<.read.split.map(&:split).drop(1)
ar.size.times do |x|
  (x+1).upto(ar.size-1) do |y|
    (puts 'No')^exit if check(ar[x], ar[y])
  end
end
puts 'Yes'

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

Dice IV

Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.

Input

In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III.

Output

Print "Yes" if given dices are all different, otherwise "No" in a line.

Constraints

$2 \leq n \leq 100$

$0 \leq $ the integer assigned to a face $ \leq 100$

Sample Input 1

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

Sample Output 1

No

Sample Input 2

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

Sample Output 2

Yes


def move(dice,dir)
  case dir
  when "N" then dice[0],dice[1],dice[5],dice[4] = dice[1],dice[5],dice[4],dice[0]
  when "S" then dice[0],dice[1],dice[5],dice[4] = dice[4],dice[0],dice[1],dice[5]
  when "E" then dice[0],dice[2],dice[5],dice[3] = dice[3],dice[0],dice[2],dice[5]
  when "W" then dice[0],dice[2],dice[5],dice[3] = dice[2],dice[5],dice[3],dice[0]
  end
end

def isSame(d1, d2)
yn = false
for i in 1..6
  d = Marshal.load(Marshal.dump(d2))
  case i
  when 2 then d = move(d,"S")
  when 3 then d = move(move(d,"W"),"S")
  when 4 then d = move(d,"N")
  when 5 then d = move(move(d,"E"),"S")
  when 6 then d = move(move(d,"S"),"S")
  end
  next if d[1] != d1[1]
  next if d[4] != d1[4]
  for j in 0..4
    d = move(d,"W")
    yn = (yn || d == d1)
 break if yn == true
  end
 break if yn == true
end
yn
end

n = gets.to_i
ds = Array.new(n){gets.split(" ").map{|i| i.to_i}}
yn = false

for i in 1..n-1
  for j in 0..i-1
    yn = isSame(ds[i],ds[j])
    break if yn == true
  end
  break if yn == true
end

puts(yn ? "Yes" : "No")


Dice = Struct.new(:top, :front, :right, :left, :back, :bottom) do
    def roll(x)
        case x
        when "E"
            k = self.top
            self.top = self.left
            self.left = self.bottom
            self.bottom = self.right
            self.right = k
        when "N"
            k = self.top
            self.top = self.front
            self.front = self.bottom
            self.bottom = self.back
            self.back = k
        when "S"
            k = self.top
            self.top = self.back
            self.back = self.bottom
            self.bottom = self.front
            self.front = k
        when "W"
            k = self.top
            self.top = self.right
            self.right = self.bottom
            self.bottom = self.left
            self.left =k
        end
    end

    def twist
        k = self.front
        self.front = self.right
        self.right = self.back
        self.back = self.left
        self.left = k
    end
end

dice_ary = []
dice_tmp = Dice.new

n = gets.to_i

n.times{|i|
    tmp = Dice.new
    tmp.top, tmp.front, tmp.right, tmp.left, tmp.back, tmp.bottom = gets.split
    dice_ary.push(tmp)
}

founded = false

ary = ["","N","W","E","S","NN"]

for i in 1..(dice_ary.length - 1)
    for c in ary
        dice_tmp = dice_ary[i].dup
        if c != "" then
            for x in c.split("")
                dice_tmp.roll(x)
            end
        end
        4.times{
            dice_tmp.twist
            if dice_ary[0] == dice_tmp then
                founded = true
                break
            end
        }
    end
end

if !founded then
    puts "Yes"
else
    puts "No"
end


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


while str = STDIN.gets
  puts str.to_i() ** 3
end


a, b = gets.split(" ")
puts "#{a.to_i * b.to_i} #{(a.to_i + b.to_i) * 2}"

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 = gets.split.map(&:to_i)
puts "#{a * b} #{a * 2 + b * 2}"


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


str = gets
num = str.split(" ")
a = num[0].to_i
b = num[1].to_i

if a > b then
  puts "a > b"
    elsif  a < b then
      puts "a < b"
	else
          puts "a == b"
end

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 = STDIN.gets.split.map(&:to_i)

if a == b then
  puts 'a == b'
elsif a < b then
  puts 'a < b'
else
  puts 'a > b'
end


Integer1,Integer2 = gets.split(" ").map(&:to_i)

if Integer2 > Integer1 then
	puts "a < b"
end
if Integer1 > Integer2 then
	puts "a > b"
end
if Integer1 == Integer2 then
	puts "a == b"
end


while i = STDIN.gets
  arr = i.split
  puts 'a==b' if arr[0]==arr[1]
  puts 'a<b' if arr[0]<arr[1]
  puts 'a>b' if arr[0]>arr[1]
end


a,b = gets.split.map(&:to_i)
if a > b then
    puts "a > b"
elsif a < b then
    puts "a < b"
else
    puts "a == b"
end


a, b = gets.split(' ').map(&:to_i)
condition = '<' if a < b
condition = '>' if a > b
condition = '==' if a == b

puts "a #{condition} b"


puts gets.split.map(&:to_i).each_cons(2).all?{|a, b| a < b} ? :Yes : :No

Range

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

Input

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

Output

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

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


a, b, c = gets.split(" ").map(&:to_i)

if a < b && b < c
  puts "Yes"
else
  puts "No"
end


a,b,c, = gets.split.map(&:to_i)
if a < b && b < c
  puts "Yes"
else
  puts "No"
end


nums = gets.split(" ").map(&:to_i)

nums.sort!

puts nums.join(' ')

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


a=gets.split.map(&:to_i)
puts a.sort.join(" ")


w,h,x,y,r=gets.chop.split.map(&:to_i)

x=x-r
y=y-r
w=w-r-r
h=h-r-r

if x>=0 && x<=w && y>=0 && y<=h
    print "Yes\n"
else
    print "No\n"
end

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


a = []
until a.last == 0 do
  a.push STDIN.gets.to_i
end
cnt = 0
a.each do |i|
  cnt += 1
  puts "Case #{cnt}: #{i}"
end

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


#!/usr/local/bin/ruby
i=0
while
   x=gets.to_i
   i+=1
   if x==0
      break
   end
   printf("Case %d:%d\n",i,x)
end


i =0
while true
x = STDIN.gets
i +=1
break if x.to_i == 0
 puts "Case#{i}:#{x}.to_s"
end


arr = Array.new
while str = STDIN.gets
    break if str.chomp == "0"
    arr.push(str.to_i)
end

i=0
until arr.length==i
        print "Case ",i+1, ":", arr[i],"\n"
        i=i+1
end


#! /usr/bin/ruby

i = 0
$stdin.each_line do |s|
	if s == "0\n"
		i = 0
		next
	end
	i += 1
	printf "Case %d: %s", i, s
end


count = 0
data = Array.new
arr = 0
while true
	data[arr] = gets
	break if data[arr] == nil
	data[arr].slice!("\n")
	count += 1
	puts "Case #{count}: " + data[arr]
	arr += 1
end


count = 0
while line = gets
n = line.chomp
break if n == 0
count += 1
puts "Case " + count.to_s + ": " + n
end


i = 1
a = gets.to_i
while a > 0
  puts "Case #{i}: #{a}\n}"
  i += 1
end


a = STDIN.gets.split.map do |i| i.to_i end
cnt = 0
(a[0]..a[1]).each do |i| cnt += 1 if a[2] % i == 0 end
puts cnt

How Many Divisors?

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

Input

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

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


a, b, c = gets.split.map(&:to_i)
d = 0
for num in a..b do
	if c % num == 0
		d += 1
	end
end
	puts d


tmp = gets.chomp.split.map(&:to_i)
a = tmp[0]
b = tmp[1]
answer = []
c = 10**10*a

answer.push(a/b)
answer.push(a%b)
answer.push(c/b/10**6.to_f.round(6))

puts answer.join(' ')

A/B Problem

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

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

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

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


a , b = gets.split.map {|i| i.to_i }
	d = a / b
	r = a % b
	f = a / b
puts "#{d} #{r} #{f.to_f}"


r = gets.to_f

area = r * r * 3.14159265359
cir = 2 * r * 3.14159265359

print area.round(6)
print " "
puts cir.round(6)

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


L = STDIN.read.split ?\n
L.each{|l|
  break if l.include? ??
  puts eval l
}

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


# -*- coding: utf-8 -*-
# case.rb

loop{ # 無限ループをするメソッド

  a, op, b = STDIN.gets.split(' ')
  a = a.to_i
  b = b.to_i

 case op
  when "+"
    puts a+b
  when "-"
    puts a-b
  when "*"
    puts a*b
  when "/"
    puts a/b
  else
    break
  end
}


a = 0
b = 0
c = 0
while b != "?" do
  a,b,c = gets.chomp.split
a = a.to_i
c = c.to_i
  if  b == "+"
    p a + c
  elsif b == "-"
    p a - c
  elsif b == "*"
    p a * c
  elsif b == "/"
    p a / c
  else
  end
end


while(1)
aa,op,bb=gets.chomp.split(" ").map(&:to_s);
a=aa.to_i
b=bb.to_i
if(op=="+")
r=a+b
elsif(op=="-")
r=a-b
elsif(op=="*")
r=a*b
elsif(op=="/")
r=a/b
else
 break
end
print"#{r}\n"
end


gets
line = gets.split.map(&:to_i).sort
sum = line.inject{|sum,i| sum + i}
print "#{line[0]} #{line[-1]} #{sum}"

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


h,w = gets.split.map {|n| n.to_i}
for i in 1..h
  for j in 1..w
    print "."
  end
  print "\n"
end

Print a Rectangle

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

Input

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

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

Output

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

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

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

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

##
##


while line = gets
  w, h = line.split.map(&:to_i)
  if w == 0 && h == 0 then break end
  h.times do
    w.times do
      print "#"
    end
    puts
  end
end


def draw
   mp=gets.split(' ').map(&:to_i)
   if mp[0]==0 && mp[1]==0 then return -1 end
   for y in 1..mp[0] do
      for x in 1..mp[1] do
         print "#"
      end
      print "\n"
   end
   print "\n"
   return 0
end

ret=draw
until ret==-1 do
    ret=draw
end


while (h, w = gets.split.map(&:to_i)) != [0, 0]
  h.times do |i|
    ptn = '#.'
    ptn = '.#' if i.odd?
    puts (ptn * (w / 2 + 1)).slice(0, w)
  end
  puts ''
end

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

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

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

#.#
.#.
#.#

#.
.#

#


n = gets.to_i
for num in 1..n do
    if num % 3 == 0 or num % 10 == 3
        print " ", num
    end
end

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.


l = gets.to_i;
a = gets.split.map(&:to_i).sort{|m, n| n <=> m}
ans = ""
for i in 0...l do
  ans << "#{a[i]} "
end
puts ans

Reversing Numbers

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

Input

The input is given in the following format:

n
a1 a2 . . . an

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

Output

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

Constraints

n ≤ 100

0 ≤ ai < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説


n = gets.to_i
a = gets.chomp.split(' ').map(&:to_i)
a.delete_if{|_a| _a > n}
b = a.reverse
b.each_with_index do |b, idx|
  printf idx != n - 1 ? "#{b}" : "#{b}"
end
printf "\n"


n = gets.to_i
x = gets()
y = x.split()
a = y.reverse

b = a.map{|w| w.to_i}

puts b.join(" ")


cards = []
suits = ['S', 'H', 'C', 'D']
suits.each do |s|
  (1..13).each do |i|
    cards << "#{s} #{i}"
  end
end
input_cards = []
n = gets.chomp.to_i
n.times do
  input_cards << gets.chomp
end
puts cards - input_cards

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

      解説


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


y,x=gets.split(' ').map(&:to_i)
a=[]; b=[]
y.times{|i| a << gets.split(' ').map(&:to_i)}
x.times{|i| b << gets.to_i}
a.each do |vs|
  puts vs.each_with_index.map{|v,i| v*b[i]}.inject(&:+)
end

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


#!/usr/bin/env ruby

temp = gets.split.map(&:to_i)
vectorA = Array.new(temp[0]*temp[1],0)
vectorB = Array.new(temp[1],0)
sum = 0
temp[0].times do |i|
    foo = gets.split.map(&:to_i)
    temp[1].times do |index|
        vectorA[i*temp[1] + index] = foo[index]
    end
end

temp[1].times do |index|
    vectorB[index] = gets.split.map(&:to_i)[0]
end

temp[0].times do |i|
    temp[1].times do |index|
        sum += vectorA[i*temp[1] + index] * vectorB[index]
    end
    puts sum
    sum = 0
end


while l=gets and l!="0 0\n"
  n,x=l.split(' ').map(&:to_i)
  p (1..n).to_a.combination(3).find_all{|v| v.inject(&:+)==x}.size
end

How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


class String
  def to_ia
    split(/\s+/).map { |s| s.to_i }
  end
end

def solve(n, x)
  memo = {}
  (1..n).each do |i|
    (1..n).each do |j|
      next if i == j
      v = i + j
      if memo[v].nil?
        memo[v] = [[i, j]]
      else
        res = true
        memo[v].each do |c|
          res = false if c.include? i
          res = false if c.include? j
        end
        memo[v] << [i, j] if res
      end
    end
  end
  ans = []
  memo.each do |sum, ary|
    v = x - sum
    next unless v > 0 and v <= n
    res = true
    ans.each do |a|
      res = false if a.include? v
    end
    if res
      ary.each do |c|
        ans << c + [v] unless c.include? v
      end
    end
  end
  ans.size
end

loop do
  ary = STDIN.gets.chomp.to_ia
  n = ary[0]
  x = ary[1]
  break if n == 0 and x == 0
  puts solve(n, x)
end


def print_table(table)
	r = table.length
	c = table[0].length
	for row_i in 0..r-1
		print "#{table[row_i][0]}"
		for col_i in 1..c
			print " #{table[row_i][col_i]}"
		end
		puts "" unless row_i == r-1
	end
end

inputs = gets.strip().split(" ").map{|i| i.to_i}
r, c = inputs[0], inputs[1]
table = Array.new(r+1){Array.new(c+1){0}}

for row_i in 0..r-1
	c_sum = 0
	rows = gets.strip().split(" ").map{|i| i.to_i}
	for col_i in 0..c-1
		table[row_i][col_i] = rows[col_i]
		c_sum += rows[col_i]
	end
	table[row_i][c] = c_sum
end
for col_i in 0..c
	for row_i in 0..r-1
		table[r][col_i] += table[row_i][col_i]
	end
end
print_table(table)

Spreadsheet

Your task is to perform a simple table calculation.

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

Input

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

Output

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

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

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


n, m, l = gets.chomp.split.map(&:to_i)

mat01 = Array.new(n) do
    Array.new(m)
end

mat02 = Array.new(m) do
    Array.new(l)
end

n.times do |i|
    mat01[i] = gets.chomp.split.map(&:to_i)
end

m.times do |i|
    mat02[i] = gets.chomp.split.map(&:to_i)
end

n.times do |i|
    l.times do |j|
        c = 0
        m.times do |k|
            c += mat01[i][k] * mat02[k][j]
        end
        print c.to_s + " "
    end
    puts ""
end

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

Matrix Multiplication

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

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

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

Input

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

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

Output

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

Constraints

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

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

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


n, m, l = gets.split.map(&:to_i)

vec_a = n.times.map { gets.split.map(&:to_i) }
vec_b = m.times.map { gets.split.map(&:to_i) }
vec_c = Array.new(n) { Array.new(l, 0) }

n.times do |i|
  l.times do |j|
    m.times do |k|
      vec_c[i][j] += vec_a[i][k] * vec_b[k][j]
    end
  end
end

vec_c.each do |v|
  puts v.join(' ')
end


Toggling Cases

Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string.

Input

A string is given in a line.

Output

Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical letters.

Constraints

The length of the input string < 1200

Sample Input

fAIR, LATER, OCCASIONALLY CLOUDY.

Sample Output

Fair, later, occasionally cloudy.


#!/usr/bin/env ruby

if __FILE__ == $0 then
	loop do
		s = gets.chomp
		if s == '0' then
			break
		end
		puts s.split('').map(&:to_i).sum
	end
end

Sum of Numbers

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

Input

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

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

Output

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

Sample Input

123
55
1000
0

Sample Output

6
10
1


s=$<.read
(?a..?z).map{|c|puts"#{c} : #{s.count c+c.upcase}"}

Counting Characters

Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters.

Input

A sentence in English is given in several lines.

Output

Prints the number of alphabetical letters in the following format:

a : The number of 'a'
b : The number of 'b'
c : The number of 'c'
.
.
z : The number of 'z'

Constraints

The number of characters in the sentence < 1200

Sample Input

This is a pen.

Sample Output

a : 1
b : 0
c : 0
d : 0
e : 1
f : 0
g : 0
h : 1
i : 2
j : 0
k : 0
l : 0
m : 0
n : 1
o : 0
p : 1
q : 0
r : 0
s : 2
t : 1
u : 0
v : 0
w : 0
x : 0
y : 0
z : 0


str = gets.chomp.upcase
('A'.ord..'Z'.ord).each { |c|
    puts "#{c.chr} : #{str.count(c.chr)}"
}


a=gets.chomp;b=a<<a
puts b.include?(gets.chomp) ?"Yes":"No"

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

Ring

Write a program which finds a pattern $p$ in a ring shaped text $s$.

Input

In the first line, the text $s$ is given.

In the second line, the pattern $p$ is given.

Output

If $p$ is in $s$, print Yes in a line, otherwise No.

Constraints

$1 \leq $ length of $p \leq $ length of $s \leq 100$

$s$ and $p$ consists of lower-case letters

Sample Input 1

vanceknowledgetoad
advance

Sample Output 1

Yes

Sample Input 2

vanceknowledgetoad
advanced

Sample Output 2

No


s = gets.chomp
p = gets.chomp
s << s
if s.match(p) then
  printf "Yes\n"
else
  printf "No\n"
end