### constant

MAX_H = 20

### main

loop do
  w, d = gets.split.map(&:to_i)
  break if (w | d) == 0

  hxs = gets.split.map(&:to_i)
  hys = gets.split.map(&:to_i)

  hxcs = (MAX_H + 1).times.map{0}
  hycs = (MAX_H + 1).times.map{0}

  hxs.each{|h| hxcs[h] += 1}
  hys.each{|h| hycs[h] += 1}

  count = 0
  for h in (1..MAX_H)
    count += ((hxcs[h] > hycs[h]) ? hxcs[h] : hycs[h]) * h
  end
  p count
end

Problem A: Cubist Artwork

International Center for Picassonian Cubism is a Spanish national museum of cubist artworks,
dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed
in front of the facade of the museum building. The artwork is a collection of cubes that are
piled up on the ground and is intended to amuse visitors, who will be curious how the shape of
the collection of cubes changes when it is seen from the front and the sides.

The artwork is a collection of cubes with edges of one foot long and is built on a flat ground
that is divided into a grid of one foot by one foot squares. Due to some technical reasons, cubes
of the artwork must be either put on the ground, fitting into a unit square in the grid, or put
on another cube in the way that the bottom face of the upper cube exactly meets the top face
of the lower cube. No other way of putting cubes is possible.

You are a member of the judging committee responsible for selecting one out of a plenty of
artwork proposals submitted to the competition. The decision is made primarily based on
artistic quality but the cost for installing the artwork is another important factor. Your task is
to investigate the installation cost for each proposal. The cost is proportional to the number of
cubes, so you have to figure out the minimum number of cubes needed for installation.

Each design proposal of an artwork consists of the front view and the side view (the view seen
from the right-hand side), as shown in Figure 1.

Figure 1: An example of an artwork proposal

The front view (resp., the side view) indicates the maximum heights of piles of cubes for each
column line (resp., row line) of the grid.

There are several ways to install this proposal of artwork, such as the following figures.

In these figures, the dotted lines on the ground indicate the grid lines. The left figure makes use
of 16 cubes, which is not optimal. That is, the artwork can be installed with a fewer number
of cubes. Actually, the right one is optimal and only uses 13 cubes. Note that, a single pile of
height three in the right figure plays the roles of two such piles in the left one.

Notice that swapping columns of cubes does not change the side view. Similarly, swapping
rows does not change the front view. Thus, such swaps do not change the costs of building the
artworks.

For example, consider the artwork proposal given in Figure 2.

Figure 2: Another example of artwork proposal

An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown
in the following figure, which can be obtained by exchanging the rightmost two columns of the
optimal installation of the artwork of Figure 1.

Input

The input is a sequence of datasets. The end of the input is indicated by a line containing two
zeros separated by a space. Each dataset is formatted as follows.

w d

h1 h2 ... hw

h'1 h'2 ... h'd

The integers w and d separated by a space are the numbers of columns and rows of the grid,
respectively. You may assume 1 ≤ w ≤ 10 and 1 ≤ d ≤ 10. The integers separated by a space
in the second and third lines specify the shape of the artwork. The integers hi (1 ≤ hi ≤ 20,
1 ≤ i ≤ w) in the second line give the front view, i.e., the maximum heights of cubes per each
column line, ordered from left to right (seen from the front). The integers hi (1 ≤ hi ≤ 20,
1 ≤ i ≤ d) in the third line give the side view, i.e., the maximum heights of cubes per each row
line, ordered from left to right (seen from the right-hand side).

Output

For each dataset, output a line containing the minimum number of cubes. The output should
not contain any other extra characters.

You can assume that, for each dataset, there is at least one way to install the artwork.

Sample Input

5 5
1 2 3 4 5
1 2 3 4 5
5 5
2 5 4 1 3
4 1 5 3 2
5 5
1 2 3 4 5
3 3 3 4 5
3 3
7 7 7
7 7 7
3 3
4 4 4
4 3 4
4 3
4 2 2 4
4 2 1
4 4
2 8 8 8
2 3 8 3
10 10
9 9 9 9 9 9 9 9 9 9
9 9 9 9 9 9 9 9 9 9
10 9
20 1 20 20 20 20 20 18 20 20
20 20 20 20 7 20 20 20 20
0 0

Output for the Sample Input

15
15
21
21
15
13
32
90
186


def sed(p,g,d)
    return nil if g.length > d.length
    return 0 if g == d
    min = Float::INFINITY
    p.each do |pt|
        next if !g.include?(pt[0])
        r = sed(p,g.gsub(pt[0],pt[1]),d)
        next if !r
        min = r + 1 if r + 1 < min
    end
    return nil if min == Float::INFINITY
    return min
end
loop do
    n = gets.to_i
    break if n == 0
    p = n.times.map{gets.split}
    g = gets.chomp
    d = gets.chomp
    ret = sed(p,g,d)
    puts ret ? ret : -1
end

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

Problem B: Repeated Substitution with Sed

Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every
occurrence of a string contained in the input string (actually each input line) with another
string β. More precisely, it proceeds as follows.

Within the input string, every non-overlapping (but possibly adjacent) occurrences of α are
marked. If there is more than one possibility for non-overlapping matching, the leftmost
one is chosen.

Each of the marked occurrences is substituted with β to obtain the output string; other
parts of the input string remain intact.

For example, when α is "aa" and β is "bca", an input string "aaxaaa" will produce "bcaxbcaa",
but not "aaxbcaa" nor "bcaxabca". Further application of the same substitution to the string
"bcaxbcaa" will result in "bcaxbcbca", but this is another substitution, which is counted as the
second one.

In this problem, a set of substitution pairs (αi, βi) (i = 1, 2, ... , n), an initial string γ, and a
final string δ are given, and you must investigate how to produce δ from γ with a minimum
number of substitutions. A single substitution (αi, βi) here means simultaneously substituting
all the non-overlapping occurrences of αi, in the sense described above, with βi.

You may use a specific substitution (αi, βi ) multiple times, including zero times.

Input

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

n

α1 β1

α2 β2

.

.

.

αn βn

γ

δ

n is a positive integer indicating the number of pairs. αi and βi are separated by a single space.
You may assume that 1 ≤ |αi| < |βi| ≤ 10 for any i (|s| means the length of the string s),

αi ≠ αj for any i ≠ j, n ≤ 10 and 1 ≤ |γ| < |δ| ≤ 10. All the strings consist solely of lowercase
letters. The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output the minimum number of substitutions to obtain δ from γ. If δ cannot
be produced from γ with the given set of substitutions, output -1.

Sample Input

2
a bb
b aa
a
bbbbbbbb
1
a aa
a
aaaaa
3
ab aab
abc aadc
ad dee
abc
deeeeeeeec
10
a abc
b bai
c acf
d bed
e abh
f fag
g abe
h bag
i aaj
j bbb
a
abacfaabe
0

Output for the Sample Input

3
-1
7
4

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.


class Array
	def accum
		ac = Array.new(size + 1)
		ac[0] = 0
		(1..size).each do |i|
			ac[i] = ac[i-1] + self[i-1]
		end
		ac
	end
end

loop do
	n, s, w, q = gets.split.map(&:to_i)
	break if n == 0

	g = s
	a = Array.new(n)
	(0..n-1).each do |i|
		a[i] = g / 7 % 10
		g = (g.even? ?  g / 2 : (g / 2) ^ w)
	end
	a.reverse!

	k = 0
	if q == 2 || q == 5
		t = 0
		a.each_with_index do |x, i|
			if x % q == 0
				k += n - i
				t += 1
				k -= t if x == 0
			end
		end
		puts k
		next
	end

	t = 1
	mod = a.map do |x|
		y = x * t % q
		t = t * 10 % q
		y
	end
	mod_accum = mod.accum.map {|x| x % q}

	count = Hash.new(0)
	(0..n).each do |i|
		x = mod_accum[i]
		k += count[x] if i > 0 && a[i-1] > 0
		count[x] += 1
	end
	p k
end

Problem F: Find the Multiples

You are given a sequence a0a1...aN-1 digits and a prime number Q. For each i ≤ j with ai ≠ 0, the subsequence aiai+1...aj can be read as a decimal representation of a positive integer. Subsequences with leading zeros are not considered. Your task is to count the number of pairs (i, j) such that the corresponding subsequence is a multiple of Q.

Input

The input consists of at most 50 datasets. Each dataset is represented by a line containing four integers N, S, W, and Q, separated by spaces, where 1 ≤ N ≤ 105, 1 ≤ S ≤ 109, 1 ≤ W ≤ 109, and Q is a prime number less than 108. The sequence a0...aN-1 of length N is generated by the following code, in which ai is written as a[i].

int g = S;
for(int i=0; i<N; i++) {
a[i] = (g/7) % 10;
if( g%2 == 0 ) { g = (g/2); }
else { g = (g/2) ^ W; }
}

Note: the operators /, %, and ^ are the integer division, the modulo, and the bitwise exclusiveor, respectively. The above code is meant to be a random number generator. The intended solution does not rely on the way how the sequence is generated.

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

Output

For each dataset, output the answer in a line. You may assume that the answer is less than 230.

Sample Input

3 32 64 7
4 35 89 5
5 555 442 3
5 777 465 11
100000 666 701622763 65537
0 0 0 0

Output for the Sample Input

2
4
6
3
68530

In the first dataset, the sequence is 421. We can find two multiples of Q = 7, namely, 42 and 21.

In the second dataset, the sequence is 5052, from which we can find 5, 50, 505, and 5 being the multiples of Q = 5. Notice that we don't count 0 or 05 since they are not a valid representation of positive integers. Also notice that we count 5 twice, because it occurs twice in different positions.

In the third and fourth datasets, the sequences are 95073 and 12221, respectively.


first = true
while true
  price = gets.to_i
  puts nil if !first
  first = false
  break if price == 0
  coin_numbers = gets.split.map(&:to_i)
  coin_values = [10, 50, 100, 500]
  coins_and_values = coin_numbers.zip(coin_values)
  total_price = coins_and_values.inject(0){ |sum, pair|
    sum += pair[0] * pair[1]
  }
  change = total_price - price
  change_coins = []
  coin_values.reverse.each do |value|
    coin = change / value
    change = change % value
    change_coins.insert(0, coin)
  end
  temp_pairs = coin_numbers.zip(change_coins)
  actual_coins = temp_pairs.map {|pair| pair[0] > pair[1] ? pair[0] - pair[1] : 0}
  coin_values.zip(actual_coins).each do |zip|
    puts "#{zip[0]} #{zip[1]}" if zip[1] > 0
  end
end

Problem B: Make Purse Light

Mr. Bill は店で買い物をしている。 彼の財布にはいくらかの硬貨（10 円玉、50 円玉、100 円玉、500 円玉）が入っているが、彼は今この小銭をできるだけ消費しようとしている。 つまり、適切な枚数の硬貨によって品物の代金を払うことで、釣り銭を受け取った後における硬貨の合計枚数を最小にしようとしている。

幸いなことに、この店の店員はとても律儀かつ親切であるため、釣り銭は常に最適な方法で渡される。 したがって、例えば 1 枚の 500 円玉の代わりに 5 枚の 100 円玉が渡されるようなことはない。 また、例えば 10 円玉を 5 枚出して、50 円玉を釣り銭として受け取ることもできる。 ただし、出した硬貨と同じ種類の硬貨が釣り銭として戻ってくるような払いかたをしてはいけない。 例えば、10 円玉を支払いの際に出したにも関わらず、別の 10 円玉が釣り銭として戻されるようでは、完全に意味のないやりとりが発生してしまうからである。

ところが Mr. Bill は計算が苦手なため、実際に何枚の硬貨を使用すればよいかを彼自身で求めることができなかった。 そこで、彼はあなたに助けを求めてきた。 あなたの仕事は、彼の財布の中にある硬貨の枚数と支払い代金をもとに、使用すべき硬貨の種類と枚数を求めるプログラムを書くことである。なお、店員はお釣りに紙幣を使用することはない。

Input

入力にはいくつかのテストケースが含まれる。

それぞれのテストケースは 2 行から構成される。 1 行目には Mr. Bill の支払い金額を円単位で表した 1 つの整数が含まれている。 2 行目には 4 つの整数が含まれており、それらは順に財布の中にある 10 円玉、50 円玉、100 円玉、500 円玉の枚数をそれぞれ表す。

支払い金額は常に 10 円単位である。 すなわち、支払い金額の一円の位は常に 0 である。 また財布の中に、同じ種類の硬貨は最大で 20 枚までしかないと仮定してよい。 支払いが不可能なケースが入力中に与えられることはない。

入力の終了は単一の 0 を含む行によって表される。

Output

それぞれのテストケースについて、Mr. Bill が使用すべき硬貨の種類と枚数を出力せよ。

出力の各行には 2 つの整数 ci 、ki が含まれる。これは支払いの際に ci 円玉を ki 枚使用することを意味している。
複数種類の硬貨を使用する場合は、ci の小さいほうから順に、必要な行数だけ出力を行うこと。 下記の出力例を参考にせよ。

なお、出力には余計なスペースを含めてはならない。 連続するテストケースの間は空行で区切ること。

Sample Input

160
1 1 2 0
160
1 0 2 10
0

Output for the Sample Input

10 1
50 1
100 1

10 1
100 2


n = gets.to_i
while n != 0
	cnt = 0
	sum = 0
	sum_cnt = 0
	n.times do |i|
		j = 1 + i
		loop do
			sum += j
			sum_cnt += 1
			j += 1
			#puts sum
			if sum == n  && sum_cnt >= 2
				cnt += 1
				#print("sum = ",sum,"\n")
				break
			elsif sum > n
				break
			end
		end
		sum = 0
		sum_cnt = 0
	end
	puts cnt
	n = gets.to_i
end

Problem A: Sum of Consecutive Integers

あなたは数か月に渡る受験戦争を勝ち抜き，晴れてICPC大学に入学することができた．入学手続きの日，大学のキャンパス内では熱狂的なサークルの勧誘活動が行われており，あなたは大量のパンフレットを受け取って帰ってきた．部屋に戻ってきたあなたは受け取ったパンフレットの中から気になる一枚を見つけた．そのパンフレットは大学の広報部から渡されたものだった．

パンフレットには以下のような問題が記されていた．

和が N となるような，連続する2つ以上の正の整数の組み合わせは，何組存在するでしょうか？例えば， 9 は 2+3+4 と 4+5 の 2通りの組み合わせがあります．

この問題の答えが気になったあなたは，プログラムを書いてその答えを調べることにした．したがって，あなたの仕事は，入力として与えられる正の整数 N に対して，問題の答えを出力するプログラムを書くことである．

Input

入力はデータセットの並びである．各データセットはひとつの整数 N からなる一行である．ここで 1 ≤ N ≤ 1000 である．

入力の終りは，ひとつのゼロからなる一行で示される．

Output

出力は，入力の各データセットの表す正の整数に対する問題の答えを，入力データセットの順序通りに並べたものである．それ以外の文字が出力にあってはならない．

Sample Input

9
500
0

Output for the Sample Input

2
3


loop {
    n, q = gets.split.map(&:to_i)
    break if n + q == 0
    d = Hash.new
    n.times do
        s, a, b = gets.split
        a, b = [a, b].map(&:to_i)
        d[(b - a + 1)..b] = s
    end
    q.times do
        a = gets.to_i
        flag = false
        d.each do |r, s|
            if r.include?(a)
                puts [s, a - r.begin + 1].join(' ')
                flag = true
            end
        end
        puts "Unknown" if !flag
    end
}

Problem A: Era Name

As many of you know, we have two major calendar systems used in Japan today. One of them
is Gregorian calendar which is widely used across the world. It is also known as “Western
calendar” in Japan.

The other calendar system is era-based calendar, or so-called “Japanese calendar.” This system
comes from ancient Chinese systems. Recently in Japan it has been a common way to associate
dates with the Emperors. In the era-based system, we represent a year with an era name given
at the time a new Emperor assumes the throne. If the era name is “A”, the first regnal year
will be “A 1”, the second year will be “A 2”, and so forth.

Since we have two different calendar systems, it is often needed to convert the date in one
calendar system to the other. In this problem, you are asked to write a program that converts
western year to era-based year, given a database that contains association between several
western years and era-based years.

For the simplicity, you can assume the following:

A new era always begins on January 1st of the corresponding Gregorian year.

The first year of an era is described as 1.

There is no year in which more than one era switch takes place.

Please note that, however, the database you will see may be incomplete. In other words, some
era that existed in the history may be missing from your data. So you will also have to detect
the cases where you cannot determine exactly which era the given year belongs to.

Input

The input contains multiple test cases. Each test case has the following format:

N Q

EraName1 EraBasedYear1 WesternYear1

.

.

.

EraNameN EraBasedYearN WesternYearN

Query1
.

.

.

QueryQ

The first line of the input contains two positive integers N and Q (1 ≤ N ≤ 1000, 1 ≤ Q ≤ 1000).
N is the number of database entries, and Q is the number of queries.

Each of the following N lines has three components: era name, era-based year number and the
corresponding western year (1 ≤ EraBasedYeari ≤ WesternYeari ≤ 109 ). Each of era names
consist of at most 16 Roman alphabet characters. Then the last Q lines of the input specifies
queries (1 ≤ Queryi ≤ 109 ), each of which is a western year to compute era-based representation.

The end of input is indicated by a line containing two zeros. This line is not part of any dataset
and hence should not be processed.

You can assume that all the western year in the input is positive integers, and that there is no
two entries that share the same era name.

Output

For each query, output in a line the era name and the era-based year number corresponding to
the western year given, separated with a single whitespace. In case you cannot determine the
era, output “Unknown” without quotes.

Sample Input

4 3
meiji 10 1877
taisho 6 1917
showa 62 1987
heisei 22 2010
1868
1917
1988
1 1
universalcentury 123 2168
2010
0 0

Output for the Sample Input

meiji 1
taisho 6
Unknown
Unknown


def bitCount(i)
  res = 0

  while i > 0 do
    if i % 2 == 1
      res += 1
    end
    i /= 2
  end

  res
end

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

l = Array.new(n)
a = Array.new(n)
b = Array.new(n)

n.times do |i|
  l[i], a[i], b[i] = gets.chomp.split.map(&:to_f)
end

ans = 0.0

(1 << n).times do |i|
  if bitCount(i) != m
    next
  end

  sum = 0.0

  n.times do |j|
    if (i >> j) % 2 == 0
      next
    end
    n.times do |k|
      if  (i >> k) % 2 == 0 || j >= k
        next
      end
      sum += (l[j] - l[k]) ** 2
      sum += (a[j] - a[k]) ** 2
      sum += (b[j] - b[k]) ** 2
    end
  end

  if sum > ans
    ans = sum
  end
end

puts ans

Calender Colors

Taro is a member of a programming contest circle.
In this circle, the members manage their schedules in the system called Great Web Calender.

Taro has just added some of his friends to his calendar so that he can browse their schedule on his calendar.
Then he noticed that the system currently displays all the schedules in only one color, mixing the schedules for all his friends.
This is difficult to manage because it's hard to tell whose schedule each entry is.

But actually this calender system has the feature to change the color of schedule entries, based on the person who has the entries.
So Taro wants to use that feature to distinguish their plans by color.

Given the colors Taro can use and the number of members,
your task is to calculate the subset of colors to color all schedule entries.
The colors are given by "Lab color space".

In Lab color space,
the distance between two colors is defined by the square sum of the difference of each element.
Taro has to pick up the subset of colors that maximizes the sum of distances of all color pairs in the set.

Input

The input is like the following style.

N M

L_{0} a_{0} b_{0}

L_{1} a_{1} b_{1}

...

L_{N-1} a_{N-1} b_{N-1}

The first line contains two integers N and M (0 \leq M \leq N \leq 20), where N is the number of colors in the input, and M is the number of friends Taro wants to select the colors for.
Each of the following N lines contains three decimal integers L(0.0 \leq L \leq 100.0), a(-134.0 \leq a \leq 220.0) and b(-140.0 \leq b \leq 122.0) which represents a single color in Lab color space.

Output

Output the maximal of the total distance.
The output should not contain an error greater than 10^{-5}.

Sample Input 1

3 2
0 0 0
10 10 10
100 100 100

Output for the Sample Input 1

30000.00000000000000000000

Sample Input 2

5 3
12.0 15.0 9.0
10.0 -3.0 2.2
3.5 6.8 9.0
2.1 4.4 5.9
1.2 4.0 -5.4

Output for the Sample Input 2

1003.44000000000005456968

Sample Input 3

2 1
1.0 1.0 1.0
0.0 0.0 0.0

Output for the Sample Input 3

0.00000000000000000000


def compress(used_x)
	x_map = {}
	used_x.to_a.sort.each_with_index{|x, i| x_map[x] = i}
	x_map
end

class Array
	def accum
		inject([0]){|a, x| a + [a[-1] + x]}
	end

	def accum!
		(1..size-1).each{|i|
			self[i] += self[i-1]
		}
		self.unshift(0)
	end

	def accum_2d
		ac = map{|r| r.accum}
		(1..size-1).each{|i|
			(1..ac[0].size-1).each{|j|
				ac[i][j] += ac[i-1][j]
			}
		}
		ac.unshift([0] * ac[0].size)
		ac
	end

	def accum_2d!
		each{|r| r.accum!}
		(1..size-1).each{|i|
			(1..self[0].size-1).each{|j|
				self[i][j] += self[i-1][j]
			}
		}
		unshift([0] * self[0].size)
	end

	def bsearch_first_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2
		if pred[self[c]]
			bsearch_first_index(l, c-1, &pred) || c
		else
			bsearch_first_index(c+1, r, &pred)
		end
	end

	def bsearch_first_item(l = 0, r = size - 1, &pred)
		i = bsearch_first_index(l, r, &pred)
		i ? self[i] : nil
	end

	def bsearch_last_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2
		if pred[self[c]]
			bsearch_last_index(c+1, r, &pred) || c
		else
			bsearch_last_index(l, c-1, &pred)
		end
	end

	def bsearch_last_item(l = 0, r = size - 1, &pred)
		i = bsearch_last_index(l, r, &pred)
		i ? self[i] : nil
	end
end

require 'set'

n, m = gets.split.map &:to_i
used_x = Set.new
used_y = Set.new

treasure = (1..n).map{
	x, y = gets.split.map &:to_i
	used_x << x
	used_y << y
	[x, y]
}

x_map = compress(used_x)
y_map = compress(used_y)
a = (0..x_map.size-1).map { [0] * y_map.size }
treasure.each{|x, y|
	a[x_map[x]][y_map[y]] += 1
}

a.accum_2d!

used_x = used_x.to_a.sort
used_y = used_y.to_a.sort

queries = (1..m).map {
	gets.split.map &:to_i
}

queries.each{|x1, y1, x2, y2|
	i1 = used_x.bsearch_first_index{|x| x1 <= x}
	if !i1
		puts 0
		break
	end
	j1 = used_y.bsearch_first_index{|y| y1 <= y}
	if !j1
		puts 0
		break
	end
	i2 = used_x.bsearch_last_index(i1, used_x.size-1){|x| x <= x2}
	if !i2
		puts 0
		break
	end
	j2 = used_y.bsearch_last_index(j1, used_y.size-1){|y| y <= y2}
	if !j2
		puts 0
		break
	end

	p a[i2+1][j2+1] - a[i2+1][j1] - a[i1][j2+1] + a[i1][j1]
}

宝探し

太郎君はある広場にお宝を探しにやってきました。この広場にはたくさんのお宝が埋められていますが、太郎君は最新の機械を持っているので、どこにお宝が埋まっているかをすべて知っています。広場はとても広いので太郎君は領域を決めてお宝を探すことにしましたが、お宝はたくさんあるためどのお宝がその領域の中にあるかすぐにわかりません。そこで太郎君はその領域の中にあるお宝の数を数えることにしました。

Input

n m
x1 y1
x2 y2
...
xn yn
x11 y11 x12 y12
x21 y21 x22 y22
...
xm1 ym1 xm2 ym2

nは広場に埋まっているお宝の数を表す

mは調べる領域の数を表す

2行目からn+1行目はそれぞれのお宝が埋まっている座標を表す

n+2行目からn+m+1行目はそれぞれの調べる領域を表す

x軸の正の方向が東、y軸の正の方向が北を表す

それぞれの領域は長方形であり、xi1とyi1は長方形の南西の頂点の座標、xi2とyi2は長方形の北東の頂点の座標を表す

Constraints

1 ≤ n ≤ 5000
1 ≤ m ≤ 5×105
|xi|, |yi| ≤ 109 (1 ≤ i ≤ n)
|xi1|, |yi1|, |xi2|, |yi2| ≤ 109 (1 ≤ i ≤ m)
xi1 ≤ xi2, yi1 ≤ yi2 (1 ≤ i ≤ m)

すべての入力は整数で与えられる

Output

C1
C2
...
Cm

それぞれの領域に含まれるお宝の数を各行に出力せよ

Sample Input 1

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

Output for the Sample Input 1

3

領域の境界線上にあるお宝も領域に含まれるものとみなす

Sample Input 2

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

Output for the Sample Input 2

2
1

領域は直線や点のようになる場合もある

Sample Input 3

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

Output for the Sample Input 3

2
2
0

同じ場所に複数のお宝が存在する場合もある

Sample Input 4

5 5
10 5
-3 -8
2 11
6 0
-1 3
-3 1 3 13
-1 -1 9 5
-3 -8 10 11
0 0 5 5
-10 -9 15 10

Output for the Sample Input 4

2
2
5
0
4


class String
	def suffix_array
		buckets = {}
		(0..size-1).each do |i|
			(buckets[self[i]] ||= []) << i
		end
		index_table = []
		r = 0
		rank = []
		buckets.keys.sort.each do |c|
			buckets[c].each do |i|
				rank[i] = r + buckets[c].size - 1
			end
			r += buckets[c].size
			index_table << buckets[c].pop until buckets[c].empty?
		end

		d = 1
		loop do
			i = 0
			loop do
				j = index_table[i]
				r = rank[j]
				if i == r
					i += 1
				else
					index_table.sa_sort!(i, r, rank, d)
					i = r + 1
				end
				break if i >= size
			end
			d <<= 1
			break if d >= self.size
		end

		index_table
	end
end

class Array
	def sa_sort!(l, r, rank, d)
		if r <= l
			if l == r
				rank[self[l]] = l
			end
			return
		end
		pivot_idx = self[rand(r-l+1) + l]
		pivot_rank = (rank[pivot_idx + d] || -1)

		lesser = l
		greater = r
		i = l
		loop do
			break if i > greater
			target_rank = (rank[self[i] + d] || -1)
			if target_rank < pivot_rank
				self[i], self[lesser] = self[lesser], self[i]
				lesser += 1
				i += 1
			elsif target_rank > pivot_rank
		 		self[i], self[greater] = self[greater], self[i]
		 		greater -= 1
			else
				i += 1
			end
		end

		raise if greater < 0
		sa_sort!(l, lesser-1, rank, d)
		(lesser..greater).each do |i|
			rank[self[i]] = greater
		end
		sa_sort!(greater+1, r, rank, d)
	end

	def bsearch_first_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2
		if pred[self[c]]
			bsearch_first_index(l, c-1, &pred) || c
		else
			bsearch_first_index(c+1, r, &pred)
		end
	end

	def bsearch_last_index(l = 0, r = size - 1, &pred)
		return nil if l > r
		c = (l + r) / 2
		if pred[self[c]]
			bsearch_last_index(c+1, r, &pred) || c
		else
			bsearch_last_index(l, c-1, &pred)
		end
	end
end

require 'set'
n, m = gets.split.map(&:to_i)
str = gets.chomp
sa = str.suffix_array

size_idx = {}
l = r = 0
m.times do
	query = gets.chomp.downcase[0..-2] + "=1"
	eval query
	(size_idx[r - l] ||= Set.new) << l
end

num = 0
size_idx.each do |size, indices|
	used = Set.new
	indices.each do |l|
		next if used.include?(l)
		num += 1
		substr = str[l..l+size]
		i = sa.bsearch_first_index {|k| substr <= str[k..k+size]}
		j = sa.bsearch_last_index {|k| str[k..k+size] <= substr}
		sa[i..j].each {|x| used << x}
	end
end

p num

Substring

長さnの文字列s=s1,s2,…,snおよびm個のクエリが与えられる。
各クエリqk (1 ≤ k ≤ m)は、"L++", "L--", "R++", "R--"の4種類のいずれかであり、
k番目のクエリqkに対してl[k]とr[k]を以下で定義する。

L++：l[k]=l[k-1]+1,r[k]=r[k-1]

L--：l[k]=l[k-1]-1,r[k]=r[k-1]

R++：l[k]=l[k-1],r[k]=r[k-1]+1

R--：l[k]=l[k-1],r[k]=r[k-1]-1

但し、l[0]=r[0]=1である。

この時、m個の部分文字列
sl[k], sl[k]+1, …, sr[k]-1, sr[k] (1 ≤ k ≤ m)
について、何種類の文字列が作られるかを答えよ。

Input

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

n m
s
q1
q2
…
qm

Constraints

文字列sは小文字アルファベットからなる

1 ≤ n ≤ 3×105

1 ≤ m ≤ 3×105

qk(1 ≤ k ≤ m)は、"L++"、"L--"、"R++"、"R--"のいずれか

1 ≤ l[k] ≤ r[k] ≤ n (1 ≤ k ≤ m)

Output

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

Sample Input 1

5 4
abcde
R++
R++
L++
L--

Output for the Sample Input 1

3

l[1]=1, r[1]=2であり、部分文字列は"ab"である

l[2]=1, r[2]=3であり、部分文字列は"abc"である

l[3]=2, r[3]=3であり、部分文字列は"bc"である

l[4]=1, r[4]=3であり、部分文字列は"abc"である

よって、生成される文字列は{"ab","abc","bc"}の3種類である。

Sample Input 2

4 6
abab
R++
L++
R++
L++
R++
L++

Output for the Sample Input 2

4

l[1]=1, r[1]=2であり、部分文字列は"ab"である

l[2]=2, r[2]=2であり、部分文字列は"b"である

l[3]=2, r[3]=3であり、部分文字列は"ba"である

l[4]=3, r[4]=3であり、部分文字列は"a"である

l[5]=3, r[5]=4であり、部分文字列は"ab"である

l[6]=4, r[6]=4であり、部分文字列は"b"である

よって、生成される文字列は{"a","ab","b","ba"}の4種類である。

Sample Input 3

10 13
aacacbabac
R++
R++
L++
R++
R++
L++
L++
R++
R++
L--
L--
R--
R--

Output for the Sample Input 3

11


#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
r=Float::INFINITY
(1..n).each{|i|
	if b%i==0
		(1..n).each{|j|
			r=[r,(a-b/i*j).abs].min
		}
	end
}
p r

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

B: イカったー / SNS

問題文

AOR イカちゃんは最近少し機嫌が悪い。
どうやら、”イカったー”のフォロー数とフォロワー数の比が気に入らないようだ
。現在、AOR イカちゃんのフォロー数は $A$ 人、フォロワー数は $B$ 人であり、比は $A:B$ である。

そこで、AOR イカちゃんはフォロー数とフォロワー数の比が気に入った整数比になるように、フォロー数を増減させることにした。
なお気に入った整数比とは、比に含まれるどちらの値も $1$ 以上 $N$ 以下の整数となるように表せる比である。

しかし、AOR イカちゃんはできるだけフォロー数を変更したくないので、変更前との差の絶対値をできるだけ小さくしたい。
AOR イカちゃんの機嫌を良くするために、少なくともフォロー数をいくつ変更する必要があるかを求めるプログラムを作成せよ。

入力

$A \ B \ N$

入力の制約

$1 \le A, \ B \le 10^{12}$

$1 \leq N \leq 100 $

出力

気に入った整数比にできる、$A$ の変化量の絶対値の最小値を出力せよ。

サンプル

サンプル入力1

19 30 3

サンプル出力1

1

サンプル入力2

3 7 7

サンプル出力2

0

サンプル入力3

3 7 1

サンプル出力3

4

サンプル入力4

102 30 3

サンプル出力4

12

フォローを $12$ 人減らすことで $90:30 \ (=3:1)$ になり、比の大きい方の数字が $3$ 以下となります。

このとき、変化量は $12$ です。

サンプル入力5

3 4 2

サンプル出力5

1

一人フォローを外すと $2:4 \ (=1:2)$ に、フォローすると $4:4 \ (=1:1)$ になり、どちらも増減の絶対値は $1$ でそれが答えです。

サンプル入力6

1 100 2

サンプル出力6

49

最低でも $1$ 人はフォローしていなければいけない事に注意してください。


class FarmVillage
  def initialize(number_of_houses:, carrying_costs:, growing_costs:)
    @number_of_houses = number_of_houses
    @carrying_costs = carrying_costs.dup
    @growing_costs = growing_costs.dup
  end

  def calc_total_cost
    total_cost = 0

    @fields_productions = Array.new(@number_of_houses, 0)
    @left_moves = Array.new(@number_of_houses-1, 0)
    @right_moves = Array.new(@number_of_houses-1, 0)

    # order houses index by growing cost
    houses = (0...@number_of_houses).zip(@growing_costs).sort {|a, b| b[1] <=> a[1]}.map {|t| t[0]}

    houses.each do |house|
      local_cost = @growing_costs[house] if @fields_productions[house] < 2
      left_cost, left_crop_house = calc_left_crop_cost(consumer_house: house)
      right_cost, right_crop_house = calc_right_crop_cost(consumer_house: house)

      costs = []
      costs << local_cost unless local_cost.nil?
      costs << left_cost unless left_cost.nil?
      costs << right_cost unless right_cost.nil?

      if local_cost == costs.min
        @fields_productions[house] += 1
      elsif left_cost == costs.min
        @fields_productions[left_crop_house] += 1
        change_moves_to_left(from: house, to: left_crop_house)
      elsif right_cost == costs.min
        @fields_productions[right_crop_house] += 1
        change_moves_to_right(from: house, to: right_crop_house)
      end
    end

    sum_prices
  end

  private

  def change_moves_to_left(from:, to:)
    (to...from).each do |road|
      if @right_moves[road] > 0
        @right_moves[road] -= 1
      else
        @left_moves[road] += 1
      end
    end
  end

  def change_moves_to_right(from:, to:)
    (from...to).each do |road|
      if @left_moves[road] > 0
        @left_moves[road] -= 1
      else
        @right_moves[road] += 1
      end
    end
  end

  def sum_prices
    total_cost = 0
    (0...@number_of_houses).each do |house|
      total_cost += @growing_costs[house] * @fields_productions[house]
    end
    @carrying_costs.each_with_index do |cost, index|
      total_cost += @left_moves[index] * cost
      total_cost += @right_moves[index] * cost
    end
    total_cost
  end

  def calc_left_crop_cost(consumer_house:)
    lower_cost = nil
    crop_house = nil

    road_cost = 0
    finish_first_discount_road = false
    (0...consumer_house).each do |house|
      aux_house = consumer_house - 1 - house
      if @right_moves[aux_house] > 0
        road_cost -= @carrying_costs[aux_house]
      else
        road_cost += @carrying_costs[aux_house]
        finish_first_discount_road = true
      end
      next unless @fields_productions[aux_house] < 2

      house_cost = road_cost + @growing_costs[aux_house]
      if lower_cost.nil? || house_cost < lower_cost
        lower_cost = house_cost
        crop_house = aux_house
      elsif finish_first_discount_road
        break
      end
    end

    [lower_cost, crop_house]
  end

  def calc_right_crop_cost(consumer_house:)
    lower_cost = nil
    crop_house = nil

    road_cost = 0
    finish_first_discount_road = false
    ((consumer_house+1)...@number_of_houses).each do |house|
      if @left_moves[house-1] > 0
        road_cost -= @carrying_costs[house-1]
      else
        road_cost += @carrying_costs[house-1]
        finish_first_discount_road = true
      end
      next unless @fields_productions[house] < 2

      house_cost = road_cost + @growing_costs[house]
      if lower_cost.nil? || house_cost < lower_cost
        lower_cost = house_cost
        crop_house = house
      elsif finish_first_discount_road
        break
      end
    end

    [lower_cost, crop_house]
  end
end

number_of_houses = gets.to_i
carrying_costs = gets.split.map(&:to_i)
growing_costs = gets.split.map(&:to_i)

farm_village = FarmVillage.new(number_of_houses: number_of_houses,
                               carrying_costs: carrying_costs,
                               growing_costs: growing_costs)

puts farm_village.calc_total_cost

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], skipTags: ["script","noscript","style","textarea","code"], processEscapes: true }});

Farm Village

There is a village along a road. This village has $N$ houses numbered $1$ to $N$ in order along the road. Each house has a field that can make up to two units of the crop and needs just one unit of the crop. The total cost to distribute one unit of the crop to each house is the summation of carrying costs and growing costs.

The carrying cost: The cost to carry one unit of the crop between the $i$-th house and the ($i+1$)-th house is $d_i$. It takes the same cost in either direction to carry.

The growing cost: The cost to grow one unit of the crop in the $i$-th house's field is $g_i$.

Your task is to calculate the minimum total cost to supply one unit of the crop to each house.

Input

The input consists of a single test case formatted as follows.

$N$
$d_1$ ... $d_{N-1}$
$g_1$ ... $g_{N}$

The first line consists of an integer $N$ ($2 \leq 200,000$), which is the number of the houses. The second line consists of $N-1$ integers separated by spaces. The $i$-th integer $d_i$ ($1 \leq d_i \leq 10^9$, $1 \leq i \leq N-1$)represents the carrying cost between the $i$-th and the ($i+1$)-th houses. The third line consists of $N$ integers separated by spaces. The $i$-th integer $g_i$ ($1 \leq g_i \leq 10^9$, $1 \leq i \leq N$) represents the growing cost of the $i$-th house's field.

Output

Print the minimum cost to supply one unit of the crop to each house.

Sample Input 1

2
3
1 5

Output for Sample Input 1

5

Sample Input 2

3
100 100
1 2 3

Output for Sample Input 2

6

Sample Input 3

4
1 2 3
1 1 100 100

Output for Sample Input 3

12


G: 労働 (Working)

コウさんはこれから $N$ 日間、毎日同じ件数の仕事をすることにした。

$N$ 日間のうち $i$ 日目には仕事が $A_i$ 件追加される。

コウさんには今溜まっている仕事はなく、$N$ 日目までにすべての仕事が終わっている必要はない。

一日で最大何件の仕事ができるか。

ただしコウさんは優秀なので、仕事が存在する限り何件でも仕事をすることができる。

入力

1 行目には $N$が与えられる。

2 行目には $N$ 個の整数 $A_1, A_2, A_3, \dots, A_N$ が空白区切りで与えられる。

出力

一日にできる仕事の最大の件数を出力せよ。最後には改行を入れること。

制約

$N$ は $1$ 以上 $100$ 以下の整数

$A_1, A_2, A_3, \dots, A_N$ は $1$ 以上 $100$ 以下の整数

入力例1

5
4 2 5 3 1

出力例1

3

一日 $4$ 件以上仕事することにすると、2 日目に仕事が尽きてしまいます。

入力例2

5
9 9 1 9 9

出力例2

6


n = gets.to_i
if n.even?
    puts 1
elsif n.to_s(2).count(?0) == 0
    puts n + 1
else
    x0 = n - 1
    y0 = 2
    k = 0
    loop do
        x = x0
        until x & 1 == 1
            k += 1
            x >>= 1
        end
        y = y0
        until y & 1 == 1
            k -= 1
            y >>= 1
        end
        break if k > 0
        x0 -= 2
        y0 += 2
    end
    puts y0
end

Problem F: nCm

Problem

整数nが与えられた時、nCm(異なるn個のものからm個を選ぶ組み合わせの数)が偶数となるような最小のmを出力せよ。

Input

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

n

Constraints

入力は以下の条件を満たす。

1 ≤ n ≤ 1018

Output

nCmが偶数となるような最小のmを1行に出力する。

Sample Input 1

2

Sample Output 1

1

Sample Input 2

111

Sample Output 2

16

Sample Input 3

3

Sample Output 3

4


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

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

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


module Color
  WHITE = 0
  GRAY = 1
  BLACK = 2
end

def dijkstra(s)
  d = Array.new($n, Float::INFINITY)
  color = Array.new($n, Color::WHITE)

  d[s] = 0

  while true
    # puts d.join(' ')
    mincost = Float::INFINITY
    u = nil
    $n.times do |i|
      if color[i] != Color::BLACK && d[i] < mincost
        mincost = d[i]
        u = i
      end
    end

    if mincost == Float::INFINITY
      break
    end

    color[u] = Color::BLACK

    $n.times do |v|
      if color[v] != Color::BLACK && $m[u][v]
        if d[u] + $m[u][v] < d[v]
          d[v] = d[u] + $m[u][v]
          color[v] = Color::GRAY
        end
      end
    end
  end
  d
end

$n = gets.to_i
$m = Array.new($n) { Array.new($n) }
$n.times do |i|
  u, k, *arr = gets.split.map(&:to_i)
  arr.each_slice(2) do |v, c|
    $m[u][v] = c
  end
end
# puts "====="
# $m.each do |k|
#   puts k.join(' ')
# end
# puts "====="

d = dijkstra(0)
d.each_with_index do | v, i |
  puts "#{i} #{v}"
end

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.


# Algorithm from https://ja.wikipedia.org/wiki/%E3%83%80%E3%82%A4%E3%82%AF%E3%82%B9%E3%83%88%E3%83%A9%E6%B3%95?oldformat=true

# NOTE: I would like to use pqueue as gem library
# (from: https://github.com/rubyworks/pqueue)
# Priority queue with array based heap.
#
# A priority queue is like a standard queue, except that each inserted
# elements is given a certain priority, based on the result of the
# comparison block given at instantiation time. Also, retrieving an element
# from the queue will always return the one with the highest priority
# (see #pop and #top).
#
# The default is to compare the elements in repect to their #<=> method.
# For example, Numeric elements with higher values will have higher
# priorities.
#
# Note that as of version 2.0 the internal queue is kept in the reverse order
# from how it was kept in previous version. If you had used #to_a in the
# past then be sure to adjust for the priorities to be ordered back-to-front
# instead of the oterh way around.
#
class PQueue

  #
  VERSION = "2.1.0"  #:erb: VERSION = "<%= version %>"

  #
  # Returns a new priority queue.
  #
  # If elements are given, build the priority queue with these initial
  # values. The elements object must respond to #to_a.
  #
  # If a block is given, it will be used to determine the priority between
  # the elements. The block must must take two arguments and return `1`, `0`,
  # or `-1` or `true`, `nil` or `false. It should return `0` or `nil` if the
  # two arguments are considered equal, return `1` or `true` if the first
  # argument is considered greater than the later, and `-1` or `false` if
  # the later is considred to be greater than the first.
  #
  # By default, the priority queue retrieves maximum elements first
  # using the #<=> method.
  #
  def initialize(elements=nil, &block) # :yields: a, b
    @que = []
    @cmp = block || lambda{ |a,b| a <=> b }
    replace(elements) if elements
  end

  protected

  #
  # The underlying heap.
  #
  attr_reader :que #:nodoc:

  public

  #
  # Priority comparison procedure.
  #
  attr_reader :cmp

  #
  # Returns the size of the queue.
  #
  def size
    @que.size
  end

  #
  # Alias of size.
  #
  alias length size

  #
  # Add an element in the priority queue.
  #
  def push(v)
    @que << v
    reheap(@que.size-1)
    self
  end

  #
  # Traditional alias for #push.
  #
  alias enq push

  #
  # Alias of #push.
  #
  alias :<< :push

  #
  # Get the element with the highest priority and remove it from
  # the queue.
  #
  # The highest priority is determined by the block given at instantiation
  # time.
  #
  # The deletion time is O(log n), with n is the size of the queue.
  #
  # Return nil if the queue is empty.
  #
  def pop
    return nil if empty?
    @que.pop
  end

  #
  # Traditional alias for #pop.
  #
  alias deq pop

  # Get the element with the lowest priority and remove it from
  # the queue.
  #
  # The lowest priority is determined by the block given at instantiation
  # time.
  #
  # The deletion time is O(log n), with n is the size of the queue.
  #
  # Return nil if the queue is empty.
  #
  def shift
    return nil if empty?
    @que.shift
  end

  #
  # Returns the element with the highest priority, but
  # does not remove it from the queue.
  #
  def top
    return nil if empty?
    return @que.last
  end

  #
  # Traditional alias for #top.
  #
  alias peek top

  #
  # Returns the element with the lowest priority, but
  # does not remove it from the queue.
  #
  def bottom
    return nil if empty?
    return @que.first
  end

  #
  # Add more than one element at the same time. See #push.
  #
  # The elements object must respond to #to_a, or be a PQueue itself.
  #
  def concat(elements)
    if empty?
      if elements.kind_of?(PQueue)
        initialize_copy(elements)
      else
        replace(elements)
      end
    else
      if elements.kind_of?(PQueue)
        @que.concat(elements.que)
        sort!
      else
        @que.concat(elements.to_a)
        sort!
      end
    end
    return self
  end

  #
  # Alias for #concat.
  #
  alias :merge! :concat

  #
  # Return top n-element as a sorted array.
  #
  def take(n=@size)
    a = []
    n.times{a.push(pop)}
    a
  end

  #
  # Returns true if there is no more elements left in the queue.
  #
  def empty?
    @que.empty?
  end

  #
  # Remove all elements from the priority queue.
  #
  def clear
    @que.clear
    self
  end

  #
  # Replace the content of the heap by the new elements.
  #
  # The elements object must respond to #to_a, or to be
  # a PQueue itself.
  #
  def replace(elements)
    if elements.kind_of?(PQueue)
      initialize_copy(elements)
    else
      @que.replace(elements.to_a)
      sort!
    end
    self
  end

  #
  # Return a sorted array, with highest priority first.
  #
  def to_a
    @que.dup
  end

  #
  # Return true if the given object is present in the queue.
  #
  def include?(element)
    @que.include?(element)
  end

  #
  # Push element onto queue while popping off and returning the next element.
  # This is qquivalent to successively calling #pop and #push(v).
  #
  def swap(v)
    r = pop
    push(v)
    r
  end

  #
  # Iterate over the ordered elements, destructively.
  #
  def each_pop #:yields: popped
    until empty?
      yield pop
    end
    nil
  end

  #
  # Pretty inspection string.
  #
  def inspect
    "<#{self.class}: size=#{size}, top=#{top || "nil"}>"
  end

  #
  # Return true if the queues contain equal elements.
  #
  def ==(other)
    size == other.size && to_a == other.to_a
  end

  private

  #
  #
  #
  def initialize_copy(other)
    @cmp  = other.cmp
    @que  = other.que.dup
    sort!
  end

  #
  # The element at index k will be repositioned to its proper place.
  #
  # This, of course, assumes the queue is already sorted.
  #
  def reheap(k)
    return self if size <= 1

    que = @que.dup

    v = que.delete_at(k)
    i = binary_index(que, v)

    que.insert(i, v)

    @que = que

    return self
  end

  #
  # Sort the queue in accorance to the given comparison procedure.
  #
  def sort!
    @que.sort! do |a,b|
      case @cmp.call(a,b)
      when  0, nil   then  0
      when  1, true  then  1
      when -1, false then -1
      else
        warn "bad comparison procedure in #{self.inspect}"
        0
      end
    end
    self
  end

  #
  # Alias of #sort!
  #
  alias heapify sort!

  #
  def binary_index(que, target)
    upper = que.size - 1
    lower = 0

    while(upper >= lower) do
      idx  = lower + (upper - lower) / 2
      comp = @cmp.call(target, que[idx])

      case comp
      when 0, nil
        return idx
      when 1, true
        lower = idx + 1
      when -1, false
        upper = idx - 1
      else
      end
    end
    lower
  end

end # class PQueue

# ======== BEGIN ========
require 'set'

N = gets.to_i

$graph       = Hash.new{|h,k| h[k] = Hash.new(Float::INFINITY)}
$q = PQueue.new([{id: 0, weight: 0}] + (1...N).each.map{|i| {id: i, weight: Float::INFINITY}}){|n1, n2|
  n1[:weight] < n2[:weight]
}

while (line = gets)
  node_id, _, *nodes = line.split(' ').map(&:to_i)
  nodes.each_slice(2){|id, weight|
    $graph[node_id][id] = weight
  }
end

$visited_nodes = []

$start_node_id = 0
# Min Distance '0' to `key`
$weights = Hash.new(Float::INFINITY)
$weights[$start_node_id] = 0
$decided_nodes = Set.new

$prev = {}

while !$q.empty?
  min_node = $q.pop
  u = min_node[:id]
  if $decided_nodes.include?(u)
    next
  end
  nodes = $graph[u]
  nodes.each{|v, weight|
    alt = $weights[u] + weight
    if $weights[v] > alt
      $weights[v] = alt
      $q.push({id: v, weight: alt})
      $prev[v] = u
    end
  }
  $decided_nodes.add(u)
end

# For path
# p $prev

$weights
  .sort_by{|k, v| k}
  .each{|node, weight|
    puts("#{node} #{weight}")
  }

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

Single Source Shortest Path II

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 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,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.


x, y = gets.chomp.split.map(&:to_i).sort
mod = y % x
ary = Array.new
if x == y
	puts x
else
	loop do
		if (y % x) % mod == 0
			if x % mod == 0
				puts mod
				break
			end
		else
			mod -= 1
		end
	end
end

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(/\s/).map{|x| x.to_i}
    puts x.gcd(y)


n=gets.to_i
n.times do
  max=gets.to_i
  plist=Array.new(max+1, 1)
  plist[0..1]=[nil,nil]
  (2..max**(1/2.0)).each do |i|
    if plist[i]
      (2..max/i).each do |j|
        plist[i*j]=nil
      end
    end
  end
  puts plist.compact.size
end

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
count = 0

n.times{|i|
    hit = false
    k = gets.to_i
    for j in 2..Math.sqrt(k)
        if k%j == 0
            hit = true
            break
        end

    end
    count += 1 if !hit
}

puts count


n = gets.chomp.to_i

nums = Array.new
n.times do |i|
   nums.push gets.chomp.to_i
end

nums = nums.reverse
max = -999999999
for j in 0..(n-2) do

   k = j + 1

   for m in k..(n-1) do

      diff = nums[j] - nums[m]
      if diff > max
         max = diff
      end

   end

end

puts max

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


max = -20000000000
ri = 0
count = 0;
STDIN.each_line {|line|
  if count == 0
    count = 1
    next
  end

  now_value = line.to_i
  if ri == 0
    ri = now_value
    next
  end

  if max < (now_value - ri)
    max = now_value - ri
  end

  if ri > now_value
    ri = now_value
  end
}

print max, "\n"


def bubbleSort(arr)
  i = arr.size - 1
  x = 0
  n = 0
  while i >= x
    j = arr.size - 1
    while j >= 1
      if arr[j] < arr[j - 1] then
        x = arr[j]
        arr[j] = arr[j - 1]
        arr[j - 1] = x
        n = n + 1
      end
      j = j - 1
    end
    x = x + 1
  end
  puts arr.join(' ')
  puts n
end

n = STDIN.gets.to_i
arr = STDIN.gets.split(' ').map{|x| x.to_i}
bubbleSort(arr)

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


a = gets.chomp.to_i
n = gets.chomp.split(" ").map(&:to_i)
flag = 1
count = 0
while flag == 1
  flag = 0
  (a-1).downto(1) do |j|
    if n[j] < n[j-1]
      n[j],n[j-1] = n[j-1],n[j]
      flag = 1
      count += 1
    end
  end
end
n[0,a-1].each do |d|
  print("#{d} ")
end
puts("#{n[a-1]}")
puts count


def bubble_sort(data, test_proc = proc { |a, b| (a <=> b) > 0 } )
  n = data.size
  0.upto(n - 2) { |i|
    (i + 1).upto(n - 1) { |j|
      if test_proc.call(data[i], data[j])
        tmp = data[j]
        data[j] = data[i]
        data[i] = tmp
      end
    }
  }
  data
end

def selection_sort(data, test_proc = proc { |a, b| (a <=> b) > 0 } )
  n = data.size
  0.upto(n - 2) { |i|
    swap_idx = i
    i.upto(n - 1) { |j|
      swap_idx = j if test_proc.call(data[swap_idx], data[j])
    }
    tmp = data[i]
    data[i] = data[swap_idx]
    data[swap_idx] = tmp
  }
  data
end

def stable_sort?(original, sorted)
  0.upto(sorted.size - 2) { |i|
    if sorted[i][1] == sorted[i + 1][1]
      is_not_stable = false
      original.each { |a|
        if a == sorted[i]
          break
        elsif a == sorted[i + 1]
          is_not_stable = true
          break
        end
      }
      if is_not_stable
        return false
      end
    end
  }
  true
end

data = $stdin.read.lines[1].split(' ').each { |n| n.instance_eval { def <=>(other); self[1].to_i <=> other[1].to_i; end } }
[bubble_sort(data.clone), selection_sort(data.clone)].each { |sorted|
  puts sorted.join(' ')
  puts stable_sort?(data, sorted) ? 'Stable' : 'Not stable'
}

Stable Sort

Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1.

Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubble Sort algorithms and the Selection Sort algorithm respectively. These algorithms should be based on the following pseudocode:

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

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

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

For each algorithm, 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 line. Each card is represented by two characters. Two consecutive cards are separated by a space character.

Output

In the first line, print the arranged cards provided by the Bubble Sort algorithm. Two consecutive cards should be separated by a space character.

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

In the third line, print the arranged cards provided by the Selection Sort algorithm. Two consecutive cards should be separated by a space character.

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

Constraints

1 ≤ N ≤ 36

Sample Input 1

5
H4 C9 S4 D2 C3

Sample Output 1

D2 C3 H4 S4 C9
Stable
D2 C3 S4 H4 C9
Not stable

Sample Input 2

2
S1 H1

Sample Output 2

S1 H1
Stable
S1 H1
Stable


s = gets.split
stack = []
s.each do |a|
  if a =~ /[\+\-\*]/
    o1 = stack.pop
    o2 = stack.pop
    stack << eval("#{o2}#{a}#{o1}")
  else
    stack << a
  end
end

p stack[-1]

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


def main(input = $stdin)
  str = input.gets.chomp.split(//)
  stack = Array.new
  lake_size = Array.new(1, 0)
  height = 0
  str.each{|char|
    case char
    when '\\'
      height += 1
      stack.push char
    when '/'
      if height != 0
        width = 1
        while case temp = stack.pop
              when '\\'
                stack.push width + 1
                lake_size.push(lake_size.pop + width)
                lake_size.push 0
                false
              when Integer
                width += temp
                lake_size.push(lake_size.pop + lake_size.pop)
              else
                width += 1
              end
        end
        height -= 1
      end
    else
      stack.push char
    end
  }
  puts lake_size.reduce(&:+)
  lake_size.pop
  puts lake_size.size.to_s + " " + lake_size.join(" ")
end
main

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

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

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

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

Input

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

output

Report the areas of floods in the following format:

$A$

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

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

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

Constraints

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

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

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

Sample Output 2

35
5 4 2 1 19 9


s1 = []
s2 = []

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


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

sum = 0

for i in 0..(q-1)
  left = 0
  right = n-1
  key = t[i]
  while left < right
    mid = (right+left)/2
    if key == s[mid]
      sum += 1
      break
    elsif key < s[mid]
      right = mid
    else
      left = mid+1
    end
  end
end
puts sum

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


require 'benchmark'

n = gets.to_i
S = gets.split.map(&:to_i)
q = gets.to_i
T = gets.split.map(&:to_i)

Benchmark.measure do
  cnt = 0
  S.sort!
  T.each do |x|
    l = 0
    r = n
    while l < r
      m = (l + r) / 2
      if S[m] == x
        cnt += 1
        break
      elsif x < S[m]
        r = m
      else
        l = m + 1
      end
    end
  end
  puts cnt
end


n=gets.to_i
s=gets.split.map(&:to_i)
q=gets.to_i
t=gets.split.map(&:to_i).sort
c=0
q.times{|i|
	l=0
	r=n
	while l<r
		m=(l+r)/2
		if t[i]==s[m]
			c+=1
			break
		elsif t[i]<s[m]
			r=m
		else
			l=m+1
		end
	end
}
p c


gets
a=gets.split(' ').map(&:to_i)
def merge(a, left, mid, right,count)
  n1 = mid-left
  n2 = right-mid
  l = (0..n1).to_a
  r = (0..n2).to_a
  for i in 0..n1-1
    l[i] = a[i+left]
  end
  for i in 0..n2-1
    r[i] = a[mid+i]
  end
  i = j = 0
  l[n1] = r[n2] = Float::INFINITY
  for k in left..right-1
    count += 1
    if l[i] <= r[j]
      a[k] = l[i]
      i += 1
    else
      a[k] = r[j]
      j += 1
    end
  end
  count
end

def merge_sort(a, left, right, count)
  if left+1 < right
    mid = (left+right) / 2
    count = merge_sort(a,left,mid,count)
    count = merge_sort(a,mid,right,count)
    count = merge(a,left,mid,right,count)
  end
  count
end

# p a
count = 0
ans=""
for i in 0..a.size-1
  ans += "#{a[i]}"
  ans += " " if i != a.size-1
end
puts ans
puts merge_sort(a,0,a.size,count)

Merge Sort

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

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

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

Input

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

Output

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

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


n = gets.to_i
node = Array.new(n)
parent = Array.new(n,-1)
sibling = Array.new(n,-1)
degree = Array.new(n,0)
depth = Array.new(n)
height = Array.new(n)

n.times do
  l = gets.split.map(&:to_i)
  node[l[0]] =  l[1,2]
end
n.times do |i|
  a, b = node[i]
  parent[a] = i if a != -1
  parent[b] = i if b != -1
  sibling[a] = b if a != -1 && b != -1
  sibling[b] = a if a != -1 && b != -1
  degree[i] = 2 - [a,b].count(-1)
end
depth[p = parent.index(-1)] = 0
cnt = 0
while depth.any?{|v| v.nil?}
  n.times do |i|
    if depth[i] == cnt
      a, b = node[i]
      depth[a] = cnt + 1 if a != -1
      depth[b] = cnt + 1 if b != -1
    end
  end
  cnt += 1
end
n.times{ |i| height[i] = 0 if degree[i] == 0 }
cnt = 0
while true
  f = false
  n.times do |i|
    if height[i] == cnt
      next if parent[i] == -1
      height[parent[i]] = cnt + 1
      f = true
    end
  end
  break unless f
  cnt += 1
end
type = Array.new(n)
n.times{|i| type[i] = parent[i] == -1 ? "root" : node[i].count(-1) == 2 ? "leaf" : "internal node"}
n.times{|i| puts "node #{i}: parent = #{parent[i]}, sibling = #{sibling[i]}, degree = #{degree[i]}, depth = #{depth[i]}, height = #{height[i]}, #{type[i]}"}

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

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

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 is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.

Output

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

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

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

deg, dep and h are the number of children, depth and height of the node respectively.

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.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 25

Sample Input 1

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

Sample Output 1

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

Reference

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


$arr=Array.new()
class BinaryTree
  attr_accessor :id,:parent,:sibling,:degree,:depth,:height,:type,:children
  def initialize(id,children,degree)
    @id=id
    @parent=-1
    @sibling=-1
    @degree=degree
    @height=0
    @children=children
    @type=(children==[-1,-1] ? 'leaf' :'internal node')
  end
  def print
    puts "node #{id}: parent = #{parent}, sibling = #{sibling},degree = #{degree}, depth = #{depth}, height = #{height}, #{type}"
  end
  def setDepth
    children.each do |c|
      unless parent == -1
        $arr[c].depth=depth+1
        $arr[c].depth
      end
    end
  end
  def setHeight
    unless parent==-1
      $arr[parent].height=height+1 if $arr[parent].height<height+1
      $arr[parent].setHeight
    end
  end
end
n=gets.to_i
n.times do
  id,*children=gets.split.map(&:to_i)
  degree=2
  children.each do |e|
    degree-=1 if e==-1
  end
  $arr << BinaryTree.new(id,children,degree)
end
$arr.sort_by! do |e| e.id end
$arr.each do |ele|
  ele.children.each do |e|
    unless e==-1
      $arr[e].parent=ele.id
      $arr[e].sibling=(e==ele.children[0] ? ele.children[1] : ele.children[0])
    end
  end
end
$arr.each do |e|
  if e.parent==-1
    e.type='root'
    e.depth=0
    e.setDepth
  end
  e.setHeight if e.type=='leaf'
end
$arr.each do |e|
  e.print
end


class Tree
	attr_accessor :parent, :root, :dep, :key, :left,:right, :sib

	def initialize(key)
		@parent = -1
		@left = -1
		@right = -1
		@dep = -1
		@key = key
		@sib = -1
	end

	def depth(answer,tree)
		if @left!=-1
			@left.depth(answer + 1,tree)
		end

		if @right != -1
			@right.depth(answer + 1,tree)
		end
		@dep = answer
	end

	def height(h)
		n1 = h
		n2 = h

		if @left!=-1
			n1 = left.height(h + 1)
		end

		if @right!=-1
			n2 = right.height(h + 1)
		end

		return n1 > n2 ? n1:n2
	end

	def showparent
		if @parent == -1
			return -1
		else
			return @parent.key
		end
	end

	def showsib
		if @sib == -1
			return -1
		else
			return @sib.key
		end
	end

	def degree
		answer = 0
		if @left != -1
			answer+=1
		end
		if @right != -1
			answer+=1
		end
		answer
	end
end

n = gets.to_i

tree = Hash.new
check = Array.new(n){true}
n.times do |i|
	tree[i] = Tree.new(i)
end

n.times do
	data = gets.split.map(&:to_i)
	num = data[0]
	tree[num].left = tree[data[1]] || -1
	tree[num].right = tree[data[2]] || -1
	if tree[data[1]]
		tree[data[1]].parent = tree[num]
		tree[data[1]].sib = tree[data[2]] || -1
		check[data[1]] = false
	end
	if tree[data[2]]
		tree[data[2]].parent = tree[num]
		tree[data[2]].sib = tree[data[1]] || -1
		check[data[2]] = false
	end
end
r = check.index(true)
tree[r].depth(0,tree)

n.times do |i|
	obj = tree[i]
	type = nil
	if obj.parent == -1
		type = "root"
	elsif obj.left == -1 && obj.right == -1
		type = "leaf"
	else
		type = "internal node"
	end

	puts "node #{i}: parent = #{obj.showparent}, sibling = #{obj.showsib}, degree = #{obj.degree}, depth = #{obj.dep}, height = #{obj.height(0)}, #{type}"

end


n=*0...gets.to_i
g=$<.map{|l|l.split.map &:to_i}.sort
r=n.-g.map{|v|v[1,2]}.reduce:+
x,y,*z=[],[]
w=->f,i{i<0&&next
x<<i
f[f,g[i][1]]
y<<i
f[f,g[i][2]]
z<<i}
w[w,r[0]]
s=" "
puts :Preorder,s+x*s,:Inorder,s+y*s,:Postorder,s+z*s

Tree Walk

Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either

contains no nodes, or

is composed of three disjoint sets of nodes:

- a root node.

- a binary tree called its left subtree.

- a binary tree called its right subtree.

Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:

Print the root, the left subtree and right subtree (preorder).

Print the left subtree, the root and right subtree (inorder).

Print the left subtree, right subtree and the root (postorder).

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

Input

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

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

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1

Output

In the 1st line, print "Preorder", and in the 2nd line print a list of node IDs obtained by the preorder tree walk.

In the 3rd line, print "Inorder", and in the 4th line print a list of node IDs obtained by the inorder tree walk.

In the 5th line, print "Postorder", and in the 6th line print a list of node IDs obtained by the postorder tree walk.

Print a space character before each node ID.

Constraints

1 ≤ n ≤ 25

Sample Input 1

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

Sample Output 1

Preorder
0 1 2 3 4 5 6 7 8
Inorder
2 1 3 0 6 5 7 4 8
Postorder
2 3 1 6 7 5 8 4 0

Reference

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


m = gets.chomp.to_i
commands = []
m.times do
    cmd, v = gets.chomp.split(' ')
    v = v.to_i unless v.nil?
    commands.push([cmd, v])
end

def insert(tree, z)
    y = nil
    x = tree[:root]
    # p x, y, z
    until x.nil? do
        y = x
        # puts "x[:key] = #{x[:key]}"
        # puts "z[:key] = #{z[:key]}"
        if z[:key] < x[:key] then
            x = tree[x[:l]]
        else
            x = tree[x[:r]]
        end
    end
    z[:p] = y[:key] unless y.nil?
    if y.nil? then
        tree[:root] = z
        tree[z[:key]] = z
    elsif z[:key] < y[:key]
        y[:l] = z[:key]
        tree[z[:key]] = z
    else
        y[:r] = z[:key]
        tree[z[:key]] = z
    end
end

def preParse(tree, key)
    return if key == nil
    print " #{key}"
    preParse(tree, tree[key][:l])
    preParse(tree, tree[key][:r])
end

def inParse(tree, key)
    return if key == nil
    inParse(tree, tree[key][:l])
    print " #{key}"
    inParse(tree, tree[key][:r])
end

tree = { root: nil }
commands.each do |cmd|
    if cmd[0] == "insert" then
        node = { key: cmd[1], p: nil, l: nil, r: nil }
        insert(tree, node)
    else
        # p tree
        inParse(tree, tree[:root][:key])
        puts "\n"
        preParse(tree, tree[:root][:key])
        puts "\n"
    end
end

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

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

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


class PriorityQueue
  #?????????
  def initialize
    @queue = Array.new
  end

  #???????????????????´??????????
  def top
    @queue[0]
  end

  #???????????????????´??????????????????????????´??????????
  def pop
    top = @queue[0]
    n = @queue.size - 1

  end

  #?????§?????´??°
  def max_heap_fy(i)
    l = 2 * i
    r = 2 * i + 1
    if l<= @queue.size && @queue[l] > @queue[i] then largest = l
    else largest = i end
    largest = r if r <= @queue.size && @queue[r] > @queue[largest]
    if largest != i then
      @queue[i],@queue[largest] = @queue[largest],@queue[i]
      max_heap_fy(largest)
    end
  end
end

def max_heap_fy(i)
  l = 2 * i
  r = 2 * i + 1
  if l<= @h && @que[l] > @que[i] then largest = l
  else largest = i end
  largest = r if r <= @h && @que[r] > @que[largest]
  if largest != i then
    @que[i],@que[largest] = @que[largest],@que[i]
    max_heap_fy(largest)
  end
end

@h = gets.to_i
@que = gets.split.map(&:to_i)
@que.insert(0,-114514)
(@h / 2).downto(1)do |i|
  max_heap_fy(i)
end
puts " #{@que[1..@que.size - 1].join(" ")}"

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

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

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


def extract(i)
  l = 2*i -1
  r = 2*i
  i -= 1

  if A[l] == nil
    return
  elsif A[r] == nil
    A[i], A[l] = A[l], A[i]
  elsif A[l] >= A[r] && A[l] > A[i]
    A[i], A[l] = A[l], A[i]
    extract(l+1)
  elsif A[l] < A[r] && A[r] > A[i]
    A[i], A[r] = A[r], A[i]
    extract(r+1)
  end
end

def insert(i)
  if i == 1
    return
  end

  parent = i/2 -1
  i -= 1

  if A[i] > A[parent]
    A[i], A[parent] = A[parent], A[i]
    insert(parent+1)
  end
end

A = Array.new

until (str=gets.chomp) == "end"
  if str == "extract"
    puts A.shift
    # A.shift
    A.unshift(A.pop)
    extract(1)
  else  # insert
    str = str.split(" ")
    A << str[1].to_i
    insert(A.length)
  end
  # p A
end

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

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


class PriorityQueue
  def initialize
    @n = 0
    @heap = []
  end

  def maxHeapify x
    l = 2*x
    r = 2*x+1
    if l <= @n && @heap[l] > @heap[x]
      largest = l
    else
      largest = x
    end
    if r <= @n && @heap[r] > @heap[largest]
      largest = r
    end
    if largest != x
      @heap[x], @heap[largest] = @heap[largest], @heap[x]
      maxHeapify(largest)
    end
  end

  def extract
    key = @heap[1]
    @heap[1] = @heap[@n]
    @n -= 1
    maxHeapify(1)
    key
  end

  def insert key
    @n += 1
    @heap[@n] = key
    i = @n
    while i > 1 && @heap[i/2] < @heap[i]
      @heap[i], @heap[i/2] = @heap[i/2], @heap[i]
      i /= 2
    end
  end
end

pq = PriorityQueue.new
while l = gets
  break if l.chomp == "end"
  if l.chomp == "extract" then puts pq.extract
  else pq.insert(l.split[1].to_i)
  end
end


require 'matrix'
q = gets.to_i
q.times do
  x0, y0, x1, y1, x2, y2, x3, y3 = gets.split.map &:to_i
  s1 = Vector[ x1 - x0, y1 - y0, 0 ]
  s2 = Vector[ x3 - x2, y3 - y2, 0 ]
  if s1.inner_product(s1) == 0
    puts 1
  elsif s1.cross_product(s2).norm == 0
    puts 2
  else
    puts 0
  end
end

Parallel/Orthogonal

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

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

Input

The entire input looks like:

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

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

xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3

Output

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

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

Sample Input 1

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

Sample Output 1

2
1
0


@data = '50
5
60,10
100,20
120,30
210,45
10,4
20
8
10,7
4,2
5,9
1,4
7,9
3,7
6,4
3,5
0
'.split("\n")

# @data = readlines

P_CROSS = 0.6
P_MUTATION = 0.01

Item = Struct.new(:value, :weight)

Problem = []

def init(count = 0)
  if @data[0] != '0'
    Problem << {Max_weight: @data[0].to_i, N: @data[1].to_i, Items: Array.new(@data[1].to_i)}
    @data[1].to_i.times do |i|
      Problem[count][:Items][i] = Item.new(*@data[i+2].split(',').map(&:to_i))
    end
#    p Problem[count]
    @data = @data[(@data[1].to_i+2)...@data.length]
    init(count+1)
  end
end

def aoj
  n,w = gets().chomp.split(' ').map(&:to_i)
  @data = []
  @data << w
  @data << n
  n.times do |i|
    @data << gets().chomp.split(' ').join(',')
  end

  Problem << {Max_weight: @data[0], N: @data[1], Items: Array.new(@data[1])}
  @data[1].times do |i|
    Problem[0][:Items][i] = Item.new(*@data[i+2].split(',').map(&:to_i))
  end
end

class GA

  # 0: ??\???????????? 1: ??\?????????
  GENE = Struct.new(:score, :chromosome)

  def initialize(population, items, max)
    @generation = 1
    @population = population # ????????°
    @items = items
    @max = max # ??????????????????????????§??????
    @size = items.length # ????????????
    @genes = Array.new(@population) { GENE.new(0, Array.new(@items.length)) }
    start_time = Time.now
#    p @items

#    srand(start_time.sec)

    @genes.each do |gene|
      gene.chromosome.map! { |locas| locas = rand(2) }
#      puts gene
    end

    evaluate(@genes)

    sort_genes
#   puts @genes

  end

  def evaluate(genes)
    genes.each do |gene|
      value_sum = 0
      weight_sum = 0
      gene.chromosome.each_with_index do |locas, index|
        if locas == 1
          value_sum += @items[index].value
          weight_sum += @items[index].weight
        end
      end
      if weight_sum <= @max && weight_sum != 0
        gene.score = value_sum
      else
        gene.score = 1
      end
    end
#   puts genes
  end

  def sort_genes
    @genes.sort_by! { |gene| -gene.score }
  end

  def start
    prev = 0
    end_count = 0
    loop do
      yield(@generation, @genes[0, @population], @genes[0], avg)
      selection
      mutation

      evaluate(@genes)
      sort_genes
#      puts @genes

      if prev == @genes[0].score && prev != 1
        break if end_count > 100
        end_count += 1
      else
        end_count = 0
      end
      prev = @genes[0].score
      @generation += 1
    end

    value_sum = 0
    weight_sum = 0
    @genes[0].chromosome.each_with_index do |locas, index|
        if locas == 1
          value_sum += @items[index].value
          weight_sum += @items[index].weight
        end
    end
#    puts "value_sum : " + value_sum.to_s
    puts value_sum.to_s
#    puts "weight_sum : " + weight_sum.to_s

    yield(@generation, @genes[0,@population], @genes[0], avg)
  end

  def selection
    # ??¨???????????????
    # ??¨??????????????????????????????????????????
    # http://mikilab.doshisha.ac.jp/dia/research/person/jiro/reports/GAparams/GAparams03.html
    # ??????????????????????????????????????¶?????°?????????"??????????????????
    # ?¬?????????£??§?????????????????????????????°???????????????

    # ??¨????????????????????????????????????????????? ???
    #    @genes.first.chromosome = @parents.first.chromosome

    #    @parents = Marshal.load(Marshal.dump(@genes))
    @parents = Array.new(@population)
    @elite = Marshal.load(Marshal.dump(@genes.first))
    @parents[0] = @elite

#    p @genes

    linear_scaling

    # ????????¬????????????
    #    1.upto((@size)/2) do |i|
    # ??????????????????????????????????????¬?????????????????????
#    p sum
#    p @genes
    1.upto(@population-1) do |i|
      @parents[i] = Marshal.load(Marshal.dump(@genes[roulette(rand(sum))]))
#      crossover(roulette,roulette,@size-(i*2-1),@size-(i*2))
    end

    @genes = []

    # ????????????????????????????????????,?¬?????????£????????????????????? ? ???????????????????????????????????§?????¶ => N ~ 2N ???????
    #    count = 0
    @population.times do |i|
      @population.times do |j|
        if rand < P_CROSS
          crossover(i, j) #, count, count+1)
#          count += 2
#          break if count > @population
          break
        else
          @genes << @parents[i]
          break
        end
      end
    end

  end

  # ?????¢?????±???????????°
  # ????????? fi ??? f'i ??????????????????
  # a = 1 , b = (fN - f1*N) / N -1  =>  f'i = a * fi + b
  def linear_scaling
    f_avg = avg
    f_max = @genes[0].score
    f_min = @genes[-1].score
#    p f_avg, f_min

    return if f_avg == f_min

    a = 0
    b = 0
    c = 2.0
    n = @parents.length

#    p f_min >= (c * f_avg - f_max)/(c - 1.0)

    if f_min >= (c * f_avg - f_max)/(c - 1.0)
      a = (c - 1.0) * f_avg / (f_max - f_avg)
      b = f_avg * (f_max - c*f_avg)/(f_max - f_avg)
    else
      a = f_avg / (f_avg - f_min)
      b = -f_min * f_avg / (f_avg - f_min)
    end
    @genes.each { |gene| gene.score = a * gene.score + b }
  end

  def roulette(prob)
#    puts "sum : %d" % sum
    @genes.each_with_index do |gene, index|
      prob -= gene.score
      return index if prob < 0
    end
  end

  # 2?????????
  def crossover(p1, p2) #, c1, c2)
#    p p1, p2
    parent1 = Marshal.load(Marshal.dump(@parents[p1]))
    parent2 = Marshal.load(Marshal.dump(@parents[p2]))

    start_id = rand(@size)
    cross_length = rand(@size - start_id)

    parent1.chromosome[start_id, cross_length], parent2.chromosome[start_id, cross_length] = parent2.chromosome[start_id, cross_length], parent1.chromosome[start_id, cross_length]
    @genes << parent1
    @genes << parent2
#@genes[c1].chromosome = parent1
#@genes[c2].chromosome = parent2
#    evaluate(@genes[-1])
#    evaluate(@genes[-2])
  end

  def mutation
    @genes.each_with_index do |gene, index|
      if rand < P_MUTATION
        i = rand(@size)
        gene.chromosome[i] = (gene.chromosome[i] - 1).abs
      end
    end
  end

  def sum
#    p @genes
#    p @genes.map{|item| item[:score]}
     @genes.map { |item| item[:score] }.inject(:+)
  end

  def avg
    sum / @genes.length
    #sum = @genes.select{|item| item[:score]>1}
    #sum.map{|item| item[:score]}.inject(:+)/sum.length
    #    p sum.inject{|arr,item| arr + item[:score]}#/sum.length
  end

end

if __FILE__ == $0
  aoj
#  init
#  p Problem
#  p Problem[0][:Items][0].weight

  population = 100

  Problem.each do |problem|
    ga = GA.new(population, problem[:Items], problem[:Max_weight])
    ga.start do |generation, genes, max_score, average|
#      puts 'generation : ' + generation.to_s
#      puts 'elite : ' + genes[0].to_s
#      genes.each do |item|
#        p item
#      end
#      break if gets =~ /x/
    end

  end

end

0-1 Knapsack Problem

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 1000

1 ≤ wi ≤ 1000

1 ≤ W ≤ 10000

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9


class Point
  attr_reader :id, :x, :y
  def initialize(id, x, y)
    @id = id
    @x = x
    @y = y
  end
end

class Node
  attr_reader :point, :left, :right
  def initialize(point, left, right)
    @point = point
    @left = left
    @right = right
  end
end

class XYRange
  attr_reader :sx, :tx, :sy, :ty
  def initialize(sx, tx, sy, ty)
    @sx, @tx, @sy, @ty = sx, tx, sy, ty
  end

  def member?(point)
    sx <= point.x && point.x <= tx &&
      sy <= point.y && point.y <= ty
  end
end

class TDTree
  def initialize
    @points = []
    @nodes = []
  end

  def add_point(point)
    @points << point
  end

  def build(left = 0, right = @points.length, depth = 0)
    return if left >= right
    middle = (left + right) / 2

    method = depth.even? ? :x : :y
    @points[left...right] = @points[left...right].sort_by(&method)

    Node.new(
      @points[middle],
      build(left, middle, depth + 1),
      build(middle + 1, right, depth + 1)
    ).tap { |n| @nodes << n }
  end

  def search(range, node = root, depth = 0, results = [])
    point = node.point
    if range.member?(point)
      results << point
    end

    if depth.even?
      if node.left && range.sx <= point.x
        search(range, node.left, depth + 1, results)
      end
      if node.right && point.x <= range.tx
        search(range, node.right, depth + 1, results)
      end
    else
      if node.left && range.sy <= point.y
        search(range, node.left, depth + 1, results)
      end
      if node.right && point.y <= range.ty
        search(range, node.right, depth + 1, results)
      end
    end

    results.tap { |r| r.sort_by!(&:id) if depth == 0 }
  end

  def root
    @nodes.last
  end
end

tree = TDTree.new

n = gets.to_i
n.times do |i|
  tree.add_point(Point.new(i, *gets.split.map(&:to_i)))
end
tree.build

q = gets.to_i
q.times do
  range = XYRange.new(*gets.split.map(&:to_i))
  tree.search(range).each { |point| puts point.id }
  puts
end

Range Search (kD Tree)

The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.

For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.

Input

n
x0 y0
x1 y1
:
xn-1 yn-1
q
sx0 tx0 sy0 ty0
sx1 tx1 sy1 ty1
:
sxq-1 txq-1 syq-1 tyq-1

The first integer n is the number of points. In the following n lines, the coordinate of the i-th point is given by two integers xi and yi.

The next integer q is the number of queries. In the following q lines, each query is given by four integers,
sxi,
txi,
syi,
tyi.

Output

For each query, report IDs of points such that
sxi ≤ x ≤ txi and
syi ≤ y ≤ tyi.
The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query.

Constraints

0 ≤ n ≤ 500,000

0 ≤ q ≤ 20,000

-1,000,000,000 ≤ x, y, sx, tx, sy, ty ≤ 1,000,000,000

sx ≤ tx

sy ≤ ty

For each query, the number of points which are within the range is less than or equal to 100.

Sample Input 1

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

Sample Output 1

0
1
2
4

2
3
5


a, b, c, d = gets.split.map(&:to_f)
puts '%.4f' % Math.sqrt((c - a)**2 + (d - b)**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


input = STDIN.gets.split(' ')
a = input[0].to_f
b = input[1].to_f
c = input[2].to_f * (Math::PI / 180.0)

s = 0.5 * a * b * Math.sin(c)
l = a + b + Math.sqrt(a*a + b*b - 2 * a * b * Math.cos(c))
h = b * Math.sin(c)

puts s
puts l
puts h

Triangle

For given two sides of a triangle a and b and the angle C between them, calculate the following properties:

S: Area of the triangle

L: The length of the circumference of the triangle

h: The height of the triangle with side a as a bottom edge

Input

The length of a, the length of b and the angle C are given in integers.

Output

Print S, L and h in a line respectively. The output should not contain an absolute error greater than 10-4.

Sample Input

4 3 90

Sample Output

6.00000000
12.00000000
3.00000000


# encoding: utf-8

def main
  while n = gets.chomp.to_i and n != 0
    nums = gets.chomp.split(/\s/).collect { |x| x.to_f}
    avg = nums.inject(0) { |s, e| s + e} / nums.size
    ans = 0.0
    nums.each do |num|
      ans += (num - avg) ** 2
    end
    puts ("%.6f" %  Math.sqrt((ans / nums.size)))
  end
end

main

Standard Deviation

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

The variance α2 is defined by

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

where m is an average of si.

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

Input

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

n
s1 s2 ... sn

The input ends with single zero for n.

Output

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

Constraints

n ≤ 1000

0 ≤ si ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000


n = gets.to_i
x = gets.split(" ").map(&:to_f)
y = gets.split(" ").map(&:to_f)

for i in 0..n-1
  x[i] = (x[i] - y[i]).abs
end

puts x.reduce(:+)
puts (x.map {|q| q*q}.reduce(:+))**0.5
puts (x.map {|q| q*q*q}.reduce(:+))**(1.0/3)
puts x.max

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

Distance II

Your task is to calculate the distance between two $n$ dimensional vectors $x = \{x_1, x_2, ..., x_n\}$ and $y = \{y_1, y_2, ..., y_n\}$.

The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.

\[
D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)^{\frac{1}{p}}
\]

It can be the Manhattan distance

\[
D_{xy} = |x_1 - y_1| + |x_2 - y_2| + ... + |x_n - y_n|
\]

where $p = 1 $.

It can be the Euclidean distance

\[
D_{xy} = \sqrt{(|x_1 - y_1|)^{2} + (|x_2 - y_2|)^{2} + ... + (|x_n - y_n|)^{2}}
\]

where $p = 2 $.

Also, it can be the Chebyshev distance

\[
D_{xy} = max_{i=1}^n (|x_i - y_i|)
\]

where $p = \infty$

Write a program which reads two $n$ dimensional vectors $x$ and $y$, and calculates Minkowski's distance where $p = 1, 2, 3, \infty$ respectively.

Input

In the first line, an integer $n$ is given. In the second and third line, $x = \{x_1, x_2, ... x_n\}$ and $y = \{y_1, y_2, ... y_n\}$ are given respectively. The elements in $x$ and $y$ are given in integers.

Output

Print the distance where $p = 1, 2, 3$ and $\infty$ in a line respectively.
The output should not contain an absolute error greater than 10-5.

Constraints

$1 \leq n \leq 100$

$0 \leq x_i, y_i \leq 1000$

Sample Input

3
1 2 3
2 0 4

Sample Output

4.000000
2.449490
2.154435
2.000000


dice0 = STDIN.gets.chomp().split(" ")
dice1 = STDIN.gets.chomp().split(" ")

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

def getDrection(ran)
  case ran
  when 0
    return "S"
  when 1
    return "N"
  when 2
    return "E"
  when 3
    return "W"
  end
end

while true
  direction = getDrection(rand(4))
  dice0 = move(direction, dice0)
  # p "dice0 = #{dice0}"
  # p "dice1 = #{dice1}"
  # p "dice0.length = #{dice0.length}"
  count = 0
  for i in 0..dice0.length - 1 do
    # p "dice0[i] = #{dice0[i]}"
    # p "dice1[i] = #{dice1[i]}"
    if dice0[i] == dice1[i] then count +=1 end
    # p "count = #{count}"
  end
  if count == 4 then
    puts "No"
    break
  elsif count == 6 then
    puts "Yes"
    break
  end
end

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