Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?

In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n,  - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.

Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.

NoteThe following image represents possible process of removing leaves from the tree:

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, false]]
while !_stack.empty?
  node, sum_cur, kill = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max

    kill_n = sum_cur_n > verts[node_nxt-1] || kill
    removed += 1 if kill_n
    _stack.push([node_nxt, sum_cur_n, kill_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, 0, false]]
while !_stack.empty?
  node, sum_max, sum_cur, kill = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max
    sum_max_n = [sum_cur_n, sum_max].max

    kill_n = sum_max_n > verts[node_nxt-1] || kill
    removed += 1 if kill_n
    _stack.push([node_nxt, sum_max_n, sum_cur_n, kill_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0, 0]]
while !_stack.empty?
  node, sum_max, sum_cur = _stack.pop
  (g[node] || []).each do |node_nxt, w|
    sum_cur_n = [sum_cur + w, 0].max
    sum_max_n = [sum_cur_n, sum_max].max
    if sum_max_n > verts[node_nxt-1]
      removed += 1
    end
    _stack.push([node_nxt, sum_max_n, sum_cur_n])
  end
end

puts removed

gets
verts = gets.split(' ').map(&:to_i)
g = {}
(2..verts.size).each { |i|
  parent, w = gets.split(' ').map(&:to_i)
  g[parent] ||= []
  g[parent].push([i, w])
}

removed = 0
_stack = [[1, 0]]
while !_stack.empty?
  node, w_acc = _stack.pop
  (g[node] || []).each do |node_nxt, w_nxt|
    w_acc_nxt = [w_acc + w_nxt, w_acc].max
    if w_acc_nxt > verts[node_nxt-1]
      removed += 1
    end
    _stack.push([node_nxt, w_acc_nxt])
  end
end

puts removed


It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.

The only line of the input contains two integers n (5 ≤ n < 109, n is prime) and r (1 ≤ r ≤ 109) — the number of the star corners and the radius of the circumcircle correspondingly.

Output one number — the star area. The relative error of your answer should not be greater than 10 - 7.


Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by $$$n$$$ characters '(' or ')' is simple if its length $$$n$$$ is even and positive, its first $$$\frac{n}{2}$$$ characters are '(', and its last $$$\frac{n}{2}$$$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The only line of input contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$) formed by characters '(' and ')', where $$$|s|$$$ is the length of $$$s$$$.

In the first line, print an integer $$$k$$$  — the minimum number of operations you have to apply. Then, print $$$2k$$$ lines describing the operations in the following format: For each operation, print a line containing an integer $$$m$$$  — the number of characters in the subsequence you will remove. Then, print a line containing $$$m$$$ integers $$$1 \le a_1 < a_2 < \dots < a_m$$$  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string. If there are multiple valid sequences of operations with the smallest $$$k$$$, you may print any of them.

NoteIn the first sample, the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '(((', and no more operations can be performed on it. Another valid answer is choosing indices $$$2$$$ and $$$3$$$, which results in the same final string.In the second sample, it is already impossible to perform any operations.

S = gets.chomp.chars
N = S.size

def f(n)
  return [] if n == 0

  left_pos = []
  left_cnt = 0

  0.upto(N - 1) do |i|
    s = S[i]

    if left_cnt < n && s == '('
      left_pos << i + 1
      left_cnt += 1
    end

    break if left_cnt == n
  end

  right_pos = []
  right_cnt = 0

  (N - 1).downto(0) do |i|
    s = S[i]

    if right_cnt < n && s == ')'
      right_pos.unshift(i + 1)
      right_cnt += 1
    end

    break if right_cnt == n
  end

  if left_cnt < n || right_cnt < n
    return false
  elsif left_pos[-1] > right_pos[0]
    return false
  else
    left_pos + right_pos
  end
end

ok = 0
ng = S.size

while (ok - ng).abs > 1
  n = (ok + ng) / 2

  if f(n)
    ok = n
  else
    ng = n
  end
end

if ok == 0
  puts 0
else
  res = f(ok)

  puts 1
  puts res.size
  puts res.join(' ')
end

def main
  s = gets.chomp.chars
  n = s.size
  # scan '(' from left and ')' from right
  left = 0
  right = n-1
  cnt = 0
  l_a = []
  r_a = []
  while (right > left)
    while left < n && s[left] != '('
      left += 1
    end
    # Here, s[left] == '(' or left == n
    while right >= 0 && s[right] != ')'
      right -= 1
    end
    # Here, s[right] == ')' or right == -1

    if (right <= left) # Meet
      break
    end

    cnt += 1
    l_a << left + 1 # 1-indexed
    r_a << right + 1 # 1-indexed
    left += 1
    right -= 1
  end
  # Here, right <= left. cnt contains the result
  if cnt > 0
    p 1
    p cnt * 2
    a = l_a + r_a
    a.sort!
    print a.join(" ") + "\n"
  else
    p 0
  end
end

main

s = gets.chomp
out = []
i = 0;
j = s.size - 1;
while j > i do
  if s[i] == '(' && s[j] == ')'
    out << [i, j]
    i += 1
    j -= 1
  elsif s[i] == '('
    j -= 1
  elsif s[j] == ')'
    i += 1
  else
    i += 1
    j -= 1
  end
end
if out.size.zero?
  puts 0
else
  puts 1
  out.flatten!.sort!
  puts out.size
  puts out.map{|x| x + 1}.join(' ')
end

def main
  s = gets.chomp.chars
  n = s.size
  # scan '(' from left and ')' from right
  left = 0
  right = n-1
  cnt = 0
  l_a = []
  r_a = []
  while (right > left)
    while left < n && s[left] != '('
      left += 1
    end
    # Here, s[left] == '(' or left == n
    while right >= 0 && s[right] != ')'
      right -= 1
    end
    # Here, s[right] == ')' or right == -1

    if (right <= left) # Meet
      break
    end

    cnt += 1
    l_a << left + 1 # 1-indexed
    r_a << right + 1 # 1-indexed
    left += 1
    right -= 1
  end
  # Here, right <= left. cnt contains the result
  if cnt > 0
    p 1
    p cnt * 2
    print (l_a + r_a).join(" ") + "\n"
  else
    p 0
  end
end

main


INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.

The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.

Output the initial array, which was used to produce text, one integer per line.

NoteLet's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.

def gao(_)
    ('%08b' % _).reverse.to_i(2)
end

s = gets.chomp
x = 0
s.each_byte do |b|
    y = (gao(x) - gao(b)) % 256
    p y
    x = gao((gao(x) - y) % 256)
end

s=gets.chomp
x=0
s.each_byte{|c|
	y=("%08b"%c).reverse.to_i(2);
	p x-y&255
	x=y
}

def to_bin n
        str=""

        while n!=0
                str+=(n%2).to_s
                n/=2
        end

        str+"0"*(8-str.length)
end

def to_ten bin
        pos=bin.length-1
        pow=0

        ans=0
        while pos>-1
                ans+=(bin[pos].to_i)*2**pow

                pow+=1
                pos-=1
        end

        ans
end

line=gets.strip

start=0
data=[]
line.split(//).each{|c|
        code=to_ten(to_bin(c.ord))

        data << (start-code)%256
        start=code
}

puts data

s = gets.bytes

def d(x)
  xs = x.to_s(2)
  xs.insert(0,'0') while xs.size < 8
  4.times { |i| xs[7-i], xs[i] = xs[i], xs[7-i] }
  xs.to_i(2)
end

s.size.pred.times do |i|
  x = i.zero? ? 0 : s[i-1]
  y = s[i]
  puts (d(x) - d(y)) % 256
end

s = gets.chomp
v = 0
s.each_byte do |c|
  x1 = ("%08b"%v).reverse.to_i(2)
  r = ("%08b"%c).reverse.to_i(2)
  x2 = (x1 - r + 256)%256

  p x2
  v = c
end

str=gets.chomp;
v=0;
str.each_byte do |c|
	p (v-("%08b"%c).reverse.to_i(2)+256)%256;
	v=("%08b"%c).reverse.to_i(2);
end

#!/usr/bin/ruby
while l = STDIN.gets
  prev = 0
  l.chomp.each_byte do |c|
    str = c.to_s(2)
    while str.size < 8
      str = "0" + str
    end
    str.reverse!
    v = (prev - str.to_i(2)) % 256
    prev = str.to_i(2)
    p v
  end
end

# def gray_code(n)
	# a = ['0', '1']
	# until a[0].length == n do
		# a = a.map{|i| '0' + i} + a.reverse.map{|i| i + '1'}
	# end
	# return a
# end

# puts gray_code(3)

# require 'set'
# visited = Set.new
# Dir.chdir ".."
# stack = Array.new
# stack.push("mine")
# until stack.length == 0 do
	# dir = false
	# Dir.chdir stack.pop

	# puts Dir.pwd
	# Dir["*"].each do |f|
		# print "File: ", f, "\n" if File.file?(f)
		# if (File.directory?(f) && visited.include?(Dir.pwd + "/" + f) == false) then
			# print "Directory: ", f, "\n"
			# stack.push(f) if File.directory?(f)
			# dir = true
			# break
		# end
	# end
	# if dir == false then
		# visited.add(Dir.pwd)
		# Dir.chdir ".."
	# end
	# puts Dir.pwd
# end
# puts "\nCompleted"

inp = STDIN.gets.chomp
start = 0
inp.each_byte do |ch|
	bin = ch.to_s(2).rjust(8, '0').reverse.to_i(2).to_s(10).to_i
	puts (start - bin) % 256
	start = bin
end

p = gets.chomp
ia = Array.new()
prev = 0
p.each_byte{|a|
  b = sprintf("%08b", a).reverse.to_i(2)
  c = (prev - b) % 256
  ia.push(c)
  prev = b
}
ia.each{|i|
  puts i
}

#!/usr/bin/ruby
#coding:utf-8

STR=gets.chomp
last=0
siz=STR.bytes.to_a.size
please=(siz+3)/4-2
STR.each_byte.with_index{|e,i|
	c = e
	c = (c & 0x55) << 1 | (c & 0xaa) >> 1
	c = (c & 0x33) << 2 | (c & 0xcc) >> 2
	c = (c & 0x0f) << 4 | (c & 0xf0) >> 4
	last2 = c
	c = (last-c)&0xff
	last = last2
	p c&0xff
}

__END__
[cesspool.c]
unsigned int lastout = 0;
c = lastout - a[i];
lastout = c;
c = (c & 0x0f) << 4 | (c & 0xf0) >> 4;
c = (c & 0x33) << 2 | (c & 0xcc) >> 2;
c = (c & 0x55) << 1 | (c & 0xaa) >> 1;
putchar(c);

#!/usr/bin/ruby

def readNextValues
  gets.split.map {|x| x.to_i}
end

line = gets.chomp
prev_byte = 0

line.each_byte do |b|
  bin = sprintf("%08b", b)
  val = bin.reverse.to_i(2)

  bin2 = sprintf("%08b", prev_byte)
  step2 = bin2.reverse.to_i(2)

  n = (step2 - val) % 256
  puts n

  prev_byte = b
end

s = STDIN.gets.strip
s = s.bytes.to_a
s.collect!{|char| char.to_s(2)}
s.collect! do |str|
    str = Array.new(8-str.size, "0").join + str
end
result = 0
s.each do |str|
   temp = str.reverse.to_i(2)
   p (result - temp) % 256
   result = temp
end

s = gets.strip
a = 0
s.each_char do |c|
  b = c.bytes.to_a[0].to_s(2)
  b = "0" * (8-b.size) + b if b.size < 8
  n = 0
  p = 1
  b.each_char do |cc|
    n += p if cc == "1"
    p *= 2
  end
  p ((a - n) % 256)
  a = n
end

s=gets.chomp
pre=0
s.bytes.each{|b|post=("%08b"%b).reverse.to_i(2);puts (pre-post)%256;pre=post}

#!/usr/bin/ruby
# coding: utf-8

def revbin(c)
  c.ord.to_s(2).rjust(8, '0').reverse.to_i(2)
end
M = 256

s = $stdin.gets.chomp
s.chars.inject(0) do |acc, c|
  n = revbin c
  puts ((acc - n) % M)
  n
end

p = gets.chomp
prev = 0
p.each_byte{|l|
  cur = l.ord.to_s(2)
  cur = "0"*(8 - cur.length)+cur
  cur = cur.reverse.to_i(2)
  res = (prev - cur) % 256
  prev = cur
  puts res
}

a = []
n = gets.to_s.chomp
a = n.split("").map(&:to_s)
n = 0
j = 0
for i in a do
  n = i.ord.to_s(2).rjust(8,"0").reverse.to_i(2)
  puts (j-n) % 256
  j = n
end

#!/usr/bin/ruby
while l = STDIN.gets
  prev = 0
  l.each_byte do |c|
    str = c.to_s(2)
    while str.size < 8
      str = "0" + str
    end
    str.reverse!
    v = (prev - str.to_i(2)) % 256
    prev = str.to_i(2)
    p v
  end
end

#!/usr/bin/ruby
#coding:utf-8

STR=STDIN.read
last=0
siz=STR.bytes.to_a.size
please=(siz+3)/4-2
STR.each_byte.with_index{|e,i|
	c = e
	c = (c & 0x55) << 1 | (c & 0xaa) >> 1
	c = (c & 0x33) << 2 | (c & 0xcc) >> 2
	c = (c & 0x0f) << 4 | (c & 0xf0) >> 4
	last2 = c
	c = (last-c)&0xff
	last = last2
	p c&0xff
}

__END__
[cesspool.c]
unsigned int lastout = 0;
c = lastout - a[i];
lastout = c;
c = (c & 0x0f) << 4 | (c & 0xf0) >> 4;
c = (c & 0x33) << 2 | (c & 0xcc) >> 2;
c = (c & 0x55) << 1 | (c & 0xaa) >> 1;
putchar(c);

s = STDIN.gets
s = s.bytes.to_a
s.collect!{|char| char.to_s(2)}
s.collect! do |str|
    str = Array.new(8-str.size, "0").join + str
end
result = 0
s.each do |str|
   temp = str.reverse.to_i(2)
   p (result - temp) % 256
   result = temp
end

s = STDIN.gets
s = s.bytes.to_a
s.collect!{|char| char.to_s(2)}
s.collect! do |str|
    str = Array.new(8-str.size, "0").join + str
end
result = 0
s.push
s.each do |str|
   temp = str.reverse.to_i(2)
   p (result - temp) % 256
   result = temp
end


You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \in [1, n]$$$ let $$$c_i := d \cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$).

Print one integer — the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.

NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$.

n = gets.to_i

a = gets.split.map{ |x| x.to_i }
b = gets.split.map{ |x| x.to_i }

c = Hash.new(0)

d = Rational(5,6)
#puts 4

h = 0
k = 0

for i in 0...n
  if a[i]==0
    if b[i]==0
      k=k+1
    end
    next
  end
  d = Rational((-b[i]), a[i])
  #puts d
  c[d] = c[d] + 1
  #puts c[d]
end

f = c.values

f.each{ |a| h = (h>a)?h:a}

puts h+k

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

def gcd(a,b)
	return b if(a==0)
	return gcd(b%a,a)
end

=begin
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
=end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)

#c = d*a+b
#c needs to have 0s i.e. c = 0
# d*a = c-b = 0-b
# d = -b/a

hash=Hash.new(0)

zerocount=0
totcount=0

(0..n-1).each do |i|
	mya = a[i]
	myb = b[i]

	if(myb==0)
		if(mya==0)
			totcount+=1
		end
		zerocount+=1
		next
	end

	if(mya==0)
		next
	end

	mygcd = gcd(mya,myb)

	mya/=mygcd
	myb/=mygcd

	hash[[mya,myb]]+=1
end

if hash.empty?
	puts zerocount
else
	puts [hash.values.max+totcount,zerocount].max
end

n = gets.to_i

a = gets.split.map{ |x| x.to_i }
b = gets.split.map{ |x| x.to_i }

c = Hash.new(0)

d = Rational(5,6)
#puts 4

for i in 0...n
  if a[i]==0
    next
  end
  d = Rational((-b[i]), a[i])
  #puts d
  c[d] = c[d] + 1
  #puts c[d]
end

f = c.values

h = 0

f.each{ |a| h = (h>a)?h:a}

puts h

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

def gcd(a,b)
	return b if(a==0)
	return gcd(b%a,a)
end

=begin
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
=end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)

#c = d*a+b
#c needs to have 0s i.e. c = 0
# d*a = c-b = 0-b
# d = -b/a

hash=Hash.new(0)

totcount=0

(0..n-1).each do |i|
	mya = a[i]
	myb = b[i]

	if(myb==0)
		totcount+=1
		next
	end

	if(mya==0)
		next
	end

	mygcd = gcd(mya,myb)

	mya/=mygcd
	myb/=mygcd

	hash[[mya,myb]]+=1
end

if hash.empty?
	puts totcount
else
	puts hash.values.max+totcount
end


You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero):  swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \{1, 2, \dots, n - 1\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.

If it is impossible to obtain the string $$$t$$$ using moves, print "-1". Otherwise in the first line print one integer $$$k$$$ — the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the string $$$s$$$ changes as follows: "abcdef" $$$\rightarrow$$$ "abdcef" $$$\rightarrow$$$ "abdcfe" $$$\rightarrow$$$ "abdfce" $$$\rightarrow$$$ "abdfec".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves.

gets
s = gets.chomp.split('')
t = gets.chomp.split('')

container = {}
s.each do |item|
  if container.key?(item)
    container[item] += 1
  else
    container[item] = 1
  end
end

t.each do |item|
  container[item] -= 1 if container.key?(item)
end

if container.values.any? { |e| e != 0 }
  puts '-1'
else
  swaps = []
  t.each.with_index do |item, i|
    if item != s[i]
      j = s.rindex(item)
      k = j - 1
      while k != i - 1
        s[k], s[k + 1] = s[k + 1], s[k]
        swaps.push(k + 1)
        k -= 1
      end
    end
  end
  puts swaps.length
  puts swaps.join(' ') unless swaps.empty?
end

def solution
  n = read_int
  s = read_string
  t = read_string

  if s.chars.sort != t.chars.sort
    puts "-1"
    return
  end

  tpos = Hash.new { |h, k| h[k] = [] }
  t.chars.each.with_index{ |c,i| tpos[c] << i }

  ss = {}
  s.chars.each.with_index{ |c, i| ss[i] = c }

  moves = []

  n.times do |i|
    next if ss[i] == t[i]

    j = (i+1...s.size).find{|k| ss[k] == t[i]}

    [*(i+1)..j].reverse.each do |k|
      moves << k
      ss[k], ss[k-1] = ss[k-1], ss[k]
    end
  end

  puts moves.size
  puts moves.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N = gets.to_i
s = gets.chomp
t = gets.chomp
ans = []
N.times do |i|
    next if s[i] == t[i]
    j = ((i+1)...N).find{|k| s[k] == t[i]}
    if j
        (j-1).downto(i) do |k|
            ans.push(k+1)
            s[k, 2] = s[k, 2].reverse
        end
    else
        puts -1; exit
    end
end
puts ans.length
puts ans.join(' ') if ans.length > 0

n = gets.to_i
s = gets.strip
t = gets.strip

def swp(str, i)
  c=str[i]
  str[i]=str[i+1]
  str[i+1]=c
end

ans = []
(n-1).downto(0).each do |ti|
  next if s[ti]==t[ti]
  si=ti-1
  si-=1 while si>=0 && s[si]!=t[ti]
  if si==-1
    puts "-1"
    exit 0
  end
  si.upto(ti-1).each do |i|
    swp(s, i)
    ans << (i+1)
  end
end

puts ans.size
puts ans.join(" ")

gets
s = gets.chomp.split('')
t = gets.chomp.split('')

container = {}
s.each do |item|
  if container.key?(item)
    container[item] += 1
  else
    container[item] = 1
  end
end

t.each do |item|
  container[item] -= 1 if container.key?(item)
end

if container.values.any? { |e| e != 0 }
  puts '-1'
else
  swaps = []
  s.each.with_index do |item, i|
    if item != t[i]
      j = t.rindex(item)
      k = j - 1
      while k != i - 1
        t[k], t[k + 1] = t[k + 1], t[k]
        swaps.push(k)
        k -= 1
      end
    end
  end
  puts swaps.length
  puts swaps.join(' ') unless swaps.empty?
end

gets
s = gets.chomp.split('')
t = gets.chomp.split('')

container = {}
s.each do |item|
  if container.key?(item)
    container[item] += 1
  else
    container[item] = 1
  end
end

t.each do |item|
  container[item] -= 1 if container.key?(item)
end

if container.values.any? { |e| e != 0 }
  puts '-1'
else
  swaps = []
  s.each.with_index do |item, i|
    if item != t[i]
      j = t.rindex(item)
      k = j - 1
      while k != i - 1
        t[k], t[k + 1] = t[k + 1], t[k]
        swaps.push(k + 1)
        k -= 1
      end
    end
  end
  puts swaps.length
  puts swaps.join(' ') unless swaps.empty?
end

n = gets.to_i
s = gets.strip
t = gets.strip

def swp(str, i)
  c=str[i]
  str[i]=str[i+1]
  str[i+1]=c
end

ans = []
(n-1).downto(0).each do |ti|
  next if s[ti]==t[ti]
  si=ti-1
  si-=1 while si>=0 && s[si]!=t[ti]
  if si==-1
    puts "-1"
    exit 0
  end
  si.upto(ti-1).each do |i|
    swp(s, i)
    ans << i
  end
end

puts ans.size
puts ans.join(" ")


One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.

The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.

For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.

5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .

Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!

reF = Regexp.new( /lala\.$/ )
reR = Regexp.new( /^miao\./ )

gets.to_i.times do
	line = gets.chomp
	if ( reF =~ line && reR !~ line )
		puts "Freda's"
	elsif ( reR =~ line && reF !~ line )
		puts "Rainbow's"
	else
		puts "OMG>.< I don't know!"
	end
end

ans = []
gets.to_i.times do
  s = gets.to_s.chomp
  if s[0..4] == 'miao.' && s[-5..-1] != 'lala.' then
    ans << 'Rainbow\'s'
  elsif s[0..4] != 'miao.' && s[-5..-1] == 'lala.' then
    ans << 'Freda\'s'
    else
      ans << 'OMG>.< I don\'t know!'
  end
end
puts ans

n = gets.to_i
n.times do
    s = gets.gsub /\r\n|\r|\n/, ''
    is_f, is_r = false, false
    if s.length >= 5
        is_f = s[-5..-1] == 'lala.'
        is_r = s[0...5] == 'miao.'
    end
    if is_f and not is_r then
        puts "Freda's"
    elsif not is_f and is_r then
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..4] != 'miao.' && arStr[i][-5..-1] == 'lala.'
        puts "Freda's"
    elsif arStr[i][0..4] == 'miao.' && arStr[i][-5..-1] != 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

def myfun
n = gets.chomp.to_i
str = Array.new
for i in 1..n
  str[i] = gets.chomp
end

for i in 1..n
  if str[i].index('miao.') == 0 && str[i].rindex('lala.') != str[i].length - 5
    puts "Rainbow's"
  elsif str[i].index('miao.') != 0 && str[i].rindex('lala.') == str[i].length - 5
    puts "Freda's"
   else
     puts "OMG>.< I don't know!"
  end
end
return nil
end

puts myfun

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
n.times do
	sentence = STDIN.readline[0..-2]
	miao = (sentence[0..4] == 'miao.')
	lala = (sentence[-5..-1] == 'lala.')
	if miao and not lala
		puts "Rainbow's"
	elsif lala and not miao
		puts "Freda's"
	else
		puts "OMG>.< I don't know!"
	end
end

input = STDIN.read.split("\n")
input.shift
input.each do |line|
  r = line[0, 5] == 'miao.'
  f = line[-5..-1] == 'lala.'
  if not r ^ f
    puts 'OMG>.< I don\'t know!'
  elsif r
      puts 'Rainbow\'s'
  else
    puts 'Freda\'s'
  end
end

n = gets.chomp.to_i
(1..n).each do
    str = gets.chomp
    r = (str[(0..4)] == "miao.")
    f = (str[(-5..-1)] == "lala.")
    puts "OMG>.< I don't know!" if ((f && r) || (!f && !r))
    puts "Freda's" if f && !r
    puts "Rainbow's" if r && !f
end

class A
  def initialize
    n = gets.chomp.to_i

    freda = 0
    rain = 0

    answer = []

    n.times do
      text = gets.chomp

      if text =~ /lala\.$/ && (text =~ /^miao\./).nil?
        answer << "Freda's"
      elsif text =~ /^miao\./ && (text =~ /lala\.$/).nil?
        answer << "Rainbow's"
      else
        answer << "OMG>.< I don't know!"
      end
    end

    puts answer
  end
end

a = A.new

a=gets.chomp.to_i
a.times do
temp=gets.chomp
l=temp.length
if temp[0..4]=="miao." && temp[l-5..l-1]=="lala."
 puts "OMG>.< I don't know!"
elsif temp[0..4]=="miao."
 puts "Rainbow's"
elsif temp[l-5..l-1]=="lala."
 puts "Freda's"
else
puts  "OMG>.< I don't know!"
end
end

n  = gets.to_i
(1..n).each {
  s = gets.chomp
  f = s.end_with?("lala.")
  r = (s[0..4] == "miao.")
  if f ^ r
    if f
      puts "Freda's"
    else
      puts "Rainbow's"
    end
  else
    puts "OMG>.< I don't know!"
  end
}

gets.to_i.times do
	input = gets.chomp

	t = ( ( input =~(/.*lala\.$/)) )
	o = ( ( input =~(/^miao\..*/)) )

	if (o and t) or (!o and !t)
		puts "OMG>.< I don't know!"
	elsif o
		puts "Rainbow's"
	elsif t
		puts "Freda's"
	end
end

n = gets.to_i
(0...n).each do
    s = gets.chomp
    if s.size < 5
        puts "OMG>.< I don't know!"
    elsif s[0,5] == "miao." and s[s.size-5,5] != "lala."
        puts "Rainbow's"
    elsif s[0,5] != "miao." and s[s.size-5,5] == "lala."
        puts "Freda's"
    else
        puts "OMG>.< I don't know!"
    end
end

gets.to_i.times do
  s = gets
  lala = /.*lala\.$/.match s
  miao = /^miao\..*/.match s
  if( (lala && miao) || (!lala && !miao) )
    puts "OMG>.< I don't know!"
  elsif lala
    puts "Freda's"
  else
    puts "Rainbow's"
  end
end

omg = "OMG>.< I don't know!"
freda = "Freda's"
rainbow = "Rainbow's"
rainbow_begin = /^miao\./
freda_end = /lala\.$/

for _ in 1..gets.to_i
  s = gets.chomp
  if s[rainbow_begin]
    puts(s[freda_end] ? omg : rainbow)
  elsif s[freda_end]
    puts freda
  else
    puts omg
  end
end

n = gets.to_i
n.times do
	s = gets.chomp
	if s.length < 5
		puts "OMG>.< I don't know!"
	else
		R = s[0..4] == "miao."
		F = s[-5..-1] == "lala."
		if R == F
			puts "OMG>.< I don't know!"
		elsif R
			puts "Rainbow's"
		else
			puts "Freda's"
		end
	end
end

#!/usr/bin/ruby

n = gets.to_i

n.times do |i|
  line = gets.chomp
  a = line.match(/^miao\./)
  b = line.match(/lala\.$/)

  if (a and b) or (not a and not b)
    puts "OMG>.< I don't know!"
  elsif line.start_with?("miao.")
    puts "Rainbow's"
  elsif line.end_with?("lala.")
    puts "Freda's"
  end
end

lines = STDIN.read.split("\n")
n = lines[0].to_i

for i in 1..n
  line = lines[i]
  testA = line.rindex('lala.') == line.size - 5
  testB = line.index('miao.') == 0
  if testA && !testB
    puts "Freda's"
    next
  end
  if !testA && testB
    puts "Rainbow's"
    next
  end
  puts "OMG>.< I don't know!"
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] != 'miao.' && arStr[i][-5..-1] == 'lala.'
        puts "Freda's"
    elsif arStr[i][0..5] == 'miao.' && arStr[i][-5..-1] != 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] == 'miao.' && arStr[i][-6...-1] != 'lala.'
        puts "Rainbow's"
    elsif arStr[i][0..5] != 'miao.' && arStr[i][-6...-1] == 'lala.'
        puts "Freda's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] == 'miao.' && arStr[i][-6...-1] != 'lala.'
        puts "Freda's"
    elsif arStr[i][0..5] != 'miao.' && arStr[i][-5...-1] == 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] != 'miao.' && arStr[i][-6...-1] == 'lala.'
        puts "Freda's"
    elsif arStr[i][0..5] == 'miao.' && arStr[i][-6...-1] != 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] != 'miao.' && arStr[i][-6..-1] == 'lala.'
        puts "Freda's"
    elsif arStr[i][0..5] == 'miao.' && arStr[i][-6..-1] != 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

n = gets.chomp.to_i
arStr = Array.new(n).map do |str|
    str = gets.chomp
end
i = 0
while i != n
    if arStr[i][0..5] == 'miao.' && arStr[i][-5...-1] != 'lala.'
        puts "Freda's"
    elsif arStr[i][0..5] != 'miao.' && arStr[i][-5...-1] == 'lala.'
        puts "Rainbow's"
    else
        puts "OMG>.< I don't know!"
    end
    i += 1
end

def myfun
n = gets.chomp.to_i
str = Array.new
for i in 1..n
  str[i] = gets.chomp
  puts i
end

for i in 1..n
  if str[i].index('miao.') == 0 && str[i].rindex('lala.') != str[i].length - 5
    puts "Rainbow's"
  elsif str[i].index('miao.') != 0 && str[i].rindex('lala.') == str[i].length - 5
    puts "Freda's"
   else
     puts "OMG>.< I don't know!"
  end
end
return nil
end

puts myfun

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
n.times do
	sentence = STDIN.readline.strip
	miao = (sentence[0..4] == 'miao.')
	lala = (sentence[-5..-1] == 'lala.')
	if miao and not lala
		puts "Rainbow's"
	elsif lala and not miao
		puts "Freda's"
	else
		puts "OMG>.<I don't know!"
	end
end

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
n.times do
	sentence = STDIN.readline.strip
	miao = (sentence[0..4] == 'miao.')
	lala = (sentence[-5..-1] == 'lala.')
	if miao and not lala
		puts "Rainbow's"
	elsif lala and not miao
		puts "Freda's"
	else
		puts "OMG>.< I don't know!"
	end
end

n = gets.chomp.to_i
(1..n).each do
    str = gets.chomp
    r = (str[(0..4)] == "miao.")
    f = (str[(-5..-1)] == "lala.")
    puts "OMG>.< I don't know!" if ((f && r) || (!f && !r))
    puts "Freda's" if f
    puts "Rainbow's" if r
end

n = gets.chomp.to_i
(1..n).each do
    str = gets.chomp
    r = (str[(0..5)] == "miao.")
    f = (str[(-5..-1)] == "lala.")
    puts "OMG>.< I don't know!" if ((f && r) || (!f && !r))
    puts "Freda's" if f
    puts "Rainbow's" if r
end

n = gets.chomp.to_i
(1..n).each do
    str = gets.chomp
    r = (str[(-5..-1)] == "miao.")
    f = (str[(-5..-1)] == "lala.")
    puts "OMG>.< I don't know!" if ((f && r) || (!f && !r))
    puts "Freda's" if f
    puts "Rainbow's" if r
end

class A
  def initialize
    n = gets.chomp.to_i

    freda = 0
    rain = 0

    answer = []

    n.times do
      text = gets.chomp

      if text =~ /lala\.$/ && (text =~ /miao\./).nil?
        answer << "Freda's"
      elsif text =~ /^miao\./ && (text =~ /lala\./).nil?
        answer << "Rainbow's"
      else
        answer << "OMG>.< I don't know!"
      end
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n = gets.chomp.to_i

    freda = 0
    rain = 0

    answer = []

    n.times do
      text = gets.chomp

      if text =~ /lala\./ && (text =~ /miao\./).nil?
        answer << "Freda's"
      elsif text =~ /miao\./ && (text =~ /lala\./).nil?
        answer << "Rainbow's"
      else
        answer << "OMG>.< I don't know!"
      end
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n = gets.chomp.to_i

    freda = 0
    rain = 0

    answer = []

    n.times do
      text = gets.chomp

      if text =~ /lala\./
        answer << "Freda's"
      elsif text =~ /mial\./
        answer << "Rainbow's"
      else
        answer << "OMG>.< I don't know!"
      end
    end

    puts answer
  end
end

a = A.new


Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

x1, y1 = gets.split.map(&:to_i)
x2, y2 = gets.split.map(&:to_i)
n = gets.to_i
r = 0
n.times do
  a, b, c = gets.split.map(&:to_i)
  r += 1 if (a * x1 + b * y1 + c) * (a * x2 + b * y2 + c) < 0
end
puts r

def getints
  gets.split.map &:to_i
end
x1,y1 = getints
x2,y2 = getints
n, = getints
s = 0
n.times do
  a,b,c = getints
  s += 1 if (a*x1+b*y1+c) * (a*x2+b*y2+c) < 0
end
puts s

x1, y1 = STDIN.readline.split.map {|s| s.to_i }
x2, y2 = STDIN.readline.split.map {|s| s.to_i }
if x2 < x1
  x1, x2 = x2, x1
  y1, y2 = y2, y1
end
n = STDIN.readline.to_i
count = 0

n.times do
  a, b, c = STDIN.readline.split.map {|s| s.to_i }
  if b == 0
    if (a*x1 < -c and -c < a*x2) or (a*x2 < -c and -c < a*x1)
      count += 1
    end
  else
    y3 = -a*x1 - c
    y4 = -a*x2 - c
    if (y3 < b*y1 and b*y2 < y4) or (b*y1 < y3 and y4 < b*y2)
      count += 1
    end
  end
end

puts count

x1, y1 = gets.split.collect{|i| i.to_i}
x2, y2 = gets.split.collect{|i| i.to_i}
n = gets.to_i
ans = 0
for i in 0...n
    a, b, c = gets.split.collect{|i| i.to_i}
    ans += 1 if (a*x1+b*y1+c)*(a*x2+b*y2+c) < 0
end
puts ans

x1, y1 = STDIN.readline.split.map {|s| s.to_i }
x2, y2 = STDIN.readline.split.map {|s| s.to_i }

n = STDIN.readline.to_i
count = 0

n.times do
  a, b, c = STDIN.readline.split.map {|s| s.to_i }
  if ((a*x1 + b*y1 + c) * (a*x2 + b*y2 + c) < 0)
      count += 1
  end
end

puts count

def getints
  gets.split.map &:to_i
end
x1,y1 = getints
x2,y2 = getints
n, = getints
s = 0
n.times do
  a,b,c = getints
  s += 1 if (a*x1+b*y1-c) * (a*x2+b*y2-c) < 0
end
puts s

x1, y1 = STDIN.readline.split.map {|s| s.to_i }
x2, y2 = STDIN.readline.split.map {|s| s.to_i }
if x2 < x1
  x1, x2 = x2, x1
  y1, y2 = y2, y1
end
n = STDIN.readline.to_i
count = 0

n.times do
  a, b, c = STDIN.readline.split.map {|s| s.to_i }
  if b == 0
    if a*x1 < -c and -c < a*x2
      count += 1
    end
  else
    y3 = -a*x1 - c
    y4 = -a*x2 - c
    if (y3 < b*y1 and b*y2 < y4) or (b*y1 < y3 and y4 < b*y2)
      count += 1
    end
  end
end

puts count


Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.

The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp.

If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO".

def solve(t0, t1)
  y0 = yield(t0)
  y1 = yield(t1)

  return nil if y1 > 1e-8
  return t0 if y0 == 0
  return t1 if y1 == 0

  99.times do
    t2 = (t0 + t1) / 2
    y2 = yield(t2)

    if y2 > 0
      t0 = t2
      y0 = y2
    elsif y2 < 0
      t1 = t2
      y1 = y2
    else
      return t2
    end
  end

  (t0 + t1) / 2
end

def dist(a, b)
  (0..2).inject(0){|s, i| s + (a[i] - b[i]) ** 2} ** 0.5
end

n = gets.to_i
a = (0..n).map{ gets.split.map(&:to_f) }
vp, vs = gets.split.map(&:to_f)
xp, yp, zp = pos = gets.split.map(&:to_f)

t = 0.0
n.times do |i|
  x0, y0, z0 = a[i]
  x1, y1, z1 = a[i+1]

  du = dist(a[i], a[i+1]) / vs
  vx = (x1 - x0) / du
  vy = (y1 - y0) / du
  vz = (z1 - z0) / du

  r = solve(0, du) { |dt|
    dist([x0 + dt * vx, y0 + dt * vy, z0 + dt * vz], [xp, yp, zp]) - vp * (t + dt)
  }

  if r
    puts "YES"
    puts t + r
    puts [x0 + r * vx, y0 + r * vy, z0 + r * vz] * " "
    exit
  end

  t += du
end
puts "NO"

EPS = 1e-8

def find_zero(t0, t1, depth=0, &block)
  y0 = yield(t0)
  y1 = yield(t1)

  return nil if y1 > EPS
  return t0 if y0 == 0
  return t1 if y1 == 0

  100.times do
    t2 = (t0+t1)/2
    y2 = yield(t2)
    return t2 if y2 == 0

    if y2 > 0
      t0 = t2
      y0 = y2
    else
      t1 = t2
      y1 = y2
    end
  end

  (t0+t1)/2
end

def distance(a, b)
  ((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)**0.5
end

n = gets.to_i
a = []
(n+1).times{ a << gets.split.map(&:to_f)}
vp, vs = gets.split.map(&:to_f)
xp, yp, zp = pos = gets.split.map(&:to_f)

t = 0.0
n.times do |i|
  x0, y0, z0 = a[i]
  x1, y1, z1 = a[i+1]

  du = distance(a[i], a[i+1])/vs
  vx = (x1-x0)/du
  vy = (y1-y0)/du
  vz = (z1-z0)/du

  tm = find_zero(0, du) do |dt|
    distance([x0+dt*vx, y0+dt*vy, z0+dt*vz], [xp, yp, zp]) - vp*(t + dt)
  end

  if tm
    puts "YES"
    puts t+tm
    puts [x0+tm*vx, y0+tm*vy, z0+tm*vz]*" "
    exit
  end

  t += du
end
puts "NO"

def distance_lp(alpha, beta, pos)
  return distance(alpha, pos) if alpha == beta

  s1 = alpha.zip(beta,pos).inject(0.0){|r,(a,b,po)| r+(a+b-po)*(b-a)}
  s2 = alpha.zip(beta,pos).inject(0.0){|r,(a,b,po)| r+(b-a)*(b-a)}

  s = s1/s2
  if s < 0
    s = 0
  elsif s > 1
    s = 1
  end

  alpha.zip(beta,pos).inject(0.0){|r,(a,b,po)| r + (s*a + (1-s)*b - po)**2} **0.5
end

def find_zero(t0, t1)
  y0 = yield(t0)
  return t0 if y0 == 0
  y1 = yield(t1)
  return t1 if y1 == 0

  t2 = (t0+t1)/2
  y2 = yield(t2)
  return t2 if y2 == 0
  return nil if y2 > 0 && y1 > 0 && y0 > 0
  return nil if y2 > y1 && y2 > y0

  while t1-t0 > 1e6
    t3 = (t0+t2)/2
    y3 = yield(t3)
    return t3 if y3 == 0
  end
end

def find_zero_s(t0, t1, depth=0, &block)
  y0 = yield(t0)
  y1 = yield(t1)

  20.times do
    t2 = (t0+t1)/2
    y2 = yield(t2)

    if y2 > 0
      t0 = t2
      y0 = y2
    else
      t1 = t2
      y1 = y2
    end

    #break if (y0 - y1).abs < 1e7
  end

  (t0+t1)/2
end

EPS = 1e-8
DZ = 128
def find_zero(t0, t1, depth=0, &block)
  return t0 if yield(t0) <= EPS
  return t1 if yield(t1) <= EPS

  return (t0+t1)/2 if depth == 2
  return find_zero_s(t0, t1, &block) if depth >= 1

  yz = nil
  0.upto(DZ) do |d|
    dt = (t1-t0)/DZ.to_f
    y = yield(t0 + d*dt)
    return (t0 + d*dt) if y == 0
    if y < 0
      return find_zero_s(t0+(d-1)*dt, t0+d*dt, &block)
    elsif y <= EPS
      return find_zero(t0+(d-1)*dt, t0+d*dt, depth+1, &block)
    end
  end
  return nil
end

def distance(a, b)
  ((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)**0.5
end

n = gets.to_i
a = []
(n+1).times{ a << gets.split.map(&:to_f)}
vp, vs = gets.split.map(&:to_f)
xp, yp, zp = pos = gets.split.map(&:to_f)

t = 0.0
n.times do |i|
  x0, y0, z0 = a[i]
  x1, y1, z1 = a[i+1]

  du = distance(a[i], a[i+1])/vs
  vx = (x1-x0)/du
  vy = (y1-y0)/du
  vz = (z1-z0)/du

  if distance_lp(a[i], a[i+1], pos) - (t+du)*vp < 1e5

    tm = find_zero(0, du) do |dt|
      distance([x0+dt*vx, y0+dt*vy, z0+dt*vz], [xp, yp, zp]) - vp*(t + dt)
    end

    if tm
      puts "YES"
      puts t+tm
      puts [x0+tm*vx, y0+tm*vy, z0+tm*vz]*" "
      exit
    end
  end

  t += du
end
puts "NO"

def find_zero(t0, t1)
  y0 = yield(t0)
  return t0 if y0 == 0
  y1 = yield(t1)
  return t1 if y1 == 0

  t2 = (t0+t1)/2
  y2 = yield(t2)
  return t2 if y2 == 0
  return nil if y2 > 0 && y1 > 0 && y0 > 0
  return nil if y2 > y1 && y2 > y0

  while t1-t0 > 1e6
    t3 = (t0+t2)/2
    y3 = yield(t3)
    return t3 if y3 == 0
  end
end

def find_zero_s(t0, t1, depth=0, &block)
  y0 = yield(t0)
  y1 = yield(t1)

  20.times do
    t2 = (t0+t1)/2
    y2 = yield(t2)

    if y2 > 0
      t0 = t2
      y0 = y2
    else
      t1 = t2
      y1 = y2
    end
  end

  (t0+t1)/2
end

DZ = 100
def find_zero(t0, t1, depth=0, &block)
  return (t0+t1)/2 if depth == 2

  yz = nil
  0.upto(DZ) do |d|
    dt = (t1-t0)/DZ.to_f
    y = yield(t0 + d*dt)
    return (t0 + d*dt) if y == 0
    if y < 0
      return find_zero_s(t0+(d-1)*dt, t0+d*dt, &block)
    elsif y <= 1e-8
      return find_zero(t0+(d-1)*dt, t0+d*dt, depth+1, &block)
    end
  end
  return nil
end

def distance(a, b)
  ((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)**0.5
end

n = gets.to_i
a = []
(n+1).times{ a << gets.split.map(&:to_f)}
vp, vs = gets.split.map(&:to_f)
xp, yp, zp = gets.split.map(&:to_f)

t = 0.0
n.times do |i|
  x0, y0, z0 = a[i]
  x1, y1, z1 = a[i+1]

  du = distance(a[i], a[i+1])/vs
  vx = (x1-x0)/du
  vy = (y1-y0)/du
  vz = (z1-z0)/du

  tm = find_zero(0, du) do |dt|
    distance([x0+dt*vx, y0+dt*vy, z0+dt*vz], [xp, yp, zp]) - vp*(t + dt)
  end

  if tm
    puts "YES"
    puts t+tm
    puts [x0+tm*vx, y0+tm*vy, z0+tm*vz]*" "
    exit
  end

  t += du
end
puts "NO"


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).

For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.

NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.

test_cases = gets.chomp.to_i

test_cases.times do |tc|
  n, k = gets.chomp.split(" ").map(&:to_i)

  counter = 0

  while n != 0
    if n % k == 0
      n = n / k
      counter += 1
    else
      rem = n % k
      counter += rem
      n -= rem
    end
  end

  puts(counter)
end

gets.to_i.times do
    ans = 0
    n,k = gets.split.map(&:to_i)
    while n != 0
        if n%k == 0
            ans += 1
            n /= k
        else
            ans += n%k
            n -= n%k
        end
    end
    puts ans
end

n = gets.chomp.to_i

tests = []

n.times do
  tests.push(gets.split(' ').map {|e| e.to_i})
end

tests.each do |test|
  remainder = 0
  current_num = test[0]
  operations = 0
  while current_num >= test[1] do
    remainder += current_num % test[1]
    current_num = current_num / test[1]
    operations += 1
  end

  operations += remainder + current_num

  puts operations
end


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of polygons in the market.  Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  if n % 4 == 0
    puts 'YES'
  else
    puts 'NO'
  end
end

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    # kakudo = 360  * 10000000000000000000/ t
    # # puts kakudo
    # ama = 360  * 10000000000000000000 % t
    # # puts "YY"
    # # puts ama
    # if ama != 0
    #     puts "NO"
    #     next
    # end
    # hantei = 90  * 10000000000000000000 / kakudo
    # amari = 90  * 10000000000000000000 % kakudo
    # if amari != 0
    #     puts "NO"
    #     next
    # end
    # saigo = (hantei * kakudo) % 10000000000000000000
    hantei = t % 4

    if hantei == 0
        puts "YES"
    else
        puts "NO"
    end
end

t = gets.chomp.to_i
t.times do
	n = gets.chomp.to_i
	puts n % 4 == 0 ? "YES" : "NO"
end

gets.to_i.times { puts gets.to_i.modulo(4).zero? ? "YES" : "NO" }

n = gets.chomp.to_i
n.times {
  arrNum = gets.chomp.to_i
  if arrNum%4 != 0
    puts 'NO'
  else
    puts 'YES'
  end
}

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    kakudo = 360  * 10000000000000000000/ t.to_f
    # puts kakudo
    ama = 360  * 10000000000000000000 % t
    # puts "YY"
    # puts ama
    if ama != 0
        puts "NO"
        next
    end
    hantei = 90  * 10000000000000000000 / kakudo
    amari = 90  * 10000000000000000000 % kakudo
    if amari != 0
        puts "NO"
        next
    end
    if hantei * kakudo / 10000000000000000000 == 90
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    # kakudo = 360  * 10000000000000000000/ t
    # # puts kakudo
    # ama = 360  * 10000000000000000000 % t
    # # puts "YY"
    # # puts ama
    # if ama != 0
    #     puts "NO"
    #     next
    # end
    # hantei = 90  * 10000000000000000000 / kakudo
    # amari = 90  * 10000000000000000000 % kakudo
    # if amari != 0
    #     puts "NO"
    #     next
    # end
    # saigo = (hantei * kakudo) % 10000000000000000000
    hantei = n % 4

    if hantei == 0
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    kakudo = 360  * 10000000000000000000/ t
    # puts kakudo
    ama = 360  * 10000000000000000000 % t
    # puts "YY"
    # puts ama
    if ama != 0
        puts "NO"
        next
    end
    hantei = 90  * 10000000000000000000 / kakudo
    amari = 90  * 10000000000000000000 % kakudo
    if amari != 0
        puts "NO"
        next
    end
    if hantei * kakudo / 10000000000000000000 == 90
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do |i|
    t = gets.chomp.to_i
    kakudo = 360  * 10000000000000000000/ t.to_f
    # puts kakudo
    ama = 360  * 10000000000000000000 % t
    # puts "YY"
    # puts ama
    if ama != 0
        puts "NO"
        next
    end
    hantei = 90  * 10000000000000000000 / kakudo
    amari = 90  * 10000000000000000000 % kakudo
    if amari != 0
        puts "NO"
        next
    end
    if hantei * kakudo / 10000000000000000000 == 90
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do |i|
    t = gets.chomp.to_i
    kakudo = 360  * 1000000000/ t
    hantei = 90  * 1000000000 / kakudo
    if hantei * kakudo / 1000000000 == 90
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    kakudo = 360  * 10000000000000000000/ t
    # puts kakudo
    ama = 360  * 10000000000000000000 % t
    # puts "YY"
    # puts ama
    if ama != 0
        puts "NO"
        next
    end
    hantei = 90  * 10000000000000000000 / kakudo
    amari = 90  * 10000000000000000000 % kakudo
    if amari != 0
        puts "NO"
        next
    end
    saigo = (hantei * kakudo) % 10000000000000000000
    if hantei * kakudo / 10000000000000000000 == 90 && saigo == 0
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times {
  arrNum = gets.chomp.to_i
  if arrNum%2 != 0
    puts 'NO'
  else
    puts 'YES'
  end
}


You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of elements in array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of array a.

Print the number of local extrema in the given array.

n,*a=$<.read.split.map &:to_i
p a.each_cons(3).count{|x,y,z|(x>y&&z>y)||(x<y&&z<y)}

n = gets.to_i
a = gets.split ' '
a = a.collect {|i| i.to_i}
total = 0
for i in 1...n-1
	if a[i] < a[i - 1] && a[i] < a[i + 1]
		total += 1
	elsif a[i] > a[i + 1] && a[i] > a[i - 1]
		total += 1
	end
end
puts total

gets
x1=gets.split.map{|e| e.to_i}
x2=x1.clone
x2.shift
x3=x2.clone
x3.shift
x1=x1.zip(x2,x3)
x1.pop
x1.pop
puts x1.count{|e|
	(e[0]<e[1] && e[1]>e[2]) || (e[0]>e[1] && e[1]<e[2])
}

def extremum(a, b, c)
  a = a.to_i
  b = b.to_i
  c = c.to_i
  if a < b && b > c
    return true
  elsif a > b && b < c
    return true
  else
    return false
  end
end

ans = 0
n = gets.to_i
a = gets.split
for i in (1...n-1) do
  if extremum(a[i - 1], a[i], a[i + 1])
    ans = ans + 1
  end
end
p ans

n = Integer(gets.chomp)

a = gets.chomp
        .split
        .map{ |i| Integer(i) }

print (1...n-1).inject(0){ |res, i|
  ((a[i] > a[i-1] and a[i] > a[i+1]) or (a[i-1] > a[i] and a[i+1] > a[i])) ? res + 1 : res}

n=gets.to_i
a=gets.split ' '
a=a.collect{|i| i.to_i}
sum=0
for i in 1..n-2
if a[i]<a[i-1] && a[i]<a[i+1] || a[i]>a[i-1] && a[i]>a[i+1]
    sum+=1
end
end
print sum

n= gets.to_i
a = gets.split(" ").map(&:to_i)
count = 0
for i in 1..n-2
	if (a[i]>a[i-1] && a[i]>a[i+1]) || (a[i]<a[i-1] && a[i]<a[i+1])
    	count  +=  1
    end
end
print(count)

n,*a=gets.split.map &:to_i
p a.each_cons(3).count{|x,y,z|!( (x>y&&z>y)||(x<y&&z<y) )}

n,*a=gets.split.map &:to_i
p a.each_cons(3).count{|x,y,z|(x>y&&z>y)||(x<y&&z<y)}

gets
x1=gets.split.map{|e| e.to_i}
x2=x1.clone
x2.shift
x3=x2.clone
x3.shift
x1=x1.zip(x2,x3)
x1.pop
x1.pop
ans=x1.index{|e|
	e[0]<e[1] && e[1]>e[2]
}
if ans
	puts ans+2
else
	puts 0
end

n=gets.to_i
a=gets.split ' '
a=a.collect{|i| i.to_i}
sum=0
for i in 1..n-2
if a[i]<a[i-1] and a[i]<a[i+1] or a[i]>a[i-1] and a[i]>a[i+1]
    sum+=1
end
end
print sum

n=gets.to_i
a=gets.split ' '
a=a.collect{|i| i.to_i}
sum=0
for i in 2..n-2
if a[i]<a[i-1] and a[i]<a[i+1] or a[i]>a[i-1] and a[i]>a[i+1]
    sum+=1
end
end
print sum


A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.The store will work seven days a week, but not around the clock. Every day at least k people must work in the store.Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly n consecutive days, then rest for exactly m days, then work for n more days and rest for m more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day x, then he should work on days [x, x + 1, ..., x + n - 1], [x + m + n, x + m + n + 1, ..., x + m + 2n - 1], and so on. Day x can be chosen arbitrarily by Vitaly.There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least k working employees, and one of the working employees should have the key to the store.Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.

The first line contains three integers n, m and k (1 ≤ m ≤ n ≤ 1000, n ≠ 1, 1 ≤ k ≤ 1000).

In the first line print a single integer z — the minimum required number of employees. In the second line print z positive integers, separated by spaces: the i-th integer ai (1 ≤ ai ≤ 104) should represent the number of the day, on which Vitaly should hire the i-th employee. If there are multiple answers, print any of them.

n,m,k=gets.split.map &:to_i;z=[1]*k+[n]+[n+1]*(k-1);if m>n-(k>1?1:2) then z<<2*n-1 end;p z.size;puts z.join' '


Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.

Print a single integer – the answer to the problem.

NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.

require 'pp'

n,k = STDIN.gets.chomp.split(/ /).map(&:to_i)
h = {}
ans = 0

STDIN.gets.chomp.split(//).each do |c|
  h[c] ||= 0
  h[c] += 1
end

vs = h.values.sort.reverse
vs.each do |v|
  if v <= k
    ans += v*v
    k -= v
  else
    ans += k*k
    k = 0
  end
end

puts ans

n, k = gets.split.map(&:to_i)
s = gets.chomp.chars
c = s.uniq.map{|x| s.count(x)}.sort.reverse
ans = 0
c.each do |x|
  t = [x, k].min
  ans += t * t
  k -= t
end
p ans

n, k = gets.split.map { |x| x.to_i }

cards = Hash.new(0)

gets.split(//).each { |card| cards[card] += 1 }

cards = cards.to_a.sort { |c1, c2| c2[1] <=> c1[1] }

ans = 0
i = 0

while k > 0
    x = cards[i][1]

    if x > k
        ans += k ** 2
        k = 0
    elsif x <= k
        ans += x ** 2
        k -= x
    end

    i += 1
end

puts ans

n,k=gets.split(/ /).map(&:to_i)
h=Hash.new
gets.split(//).each do |i|
  h[i]?h[i]+=1:h[i]=1
end
ans=0
h.values.sort.reverse.each do |i|
  if i<=k
    ans+=i**2
    k-=i
  else
    ans+=k*k
    k=0
  end
end
puts ans

nAndk = gets.chomp.split(' ').map { |x| x.to_i }
n = nAndk[0]
k = nAndk[1]
bins = {}
cards = gets.chomp.split('')

for card in cards
  if bins[card].nil?
    bins[card] = 0
  end
  bins[card] += 1
end
work = bins.sort_by {|_key, value| value}
score = 0
while k > 0
  count = work.last[1]
  if count < k
    k -= count
    score += bins[work.last[0]] ** 2
    work.pop
  else
    score += k*k
    k = 0
  end
end
p score

n,k = gets.split(/\s+/).map(&:to_i)
h = Hash.new { |h, k| h[k] = 0 }
gets.strip.split(//).inject(h) {|h,s| h[s] += 1; h}

result = 0

h.values.sort.reverse.each do |v|
  if v < k
    k -= v
    result += v**2
  else
    result += k**2
    break
  end
end

p result

n, k = gets.split.map(&:to_i)
s = gets.chomp.chars
c = s.uniq.map{|x| s.count(x)}.sort.reverse
ans = 0
t = 0
c.each do |i|
  t = [i, k].min
  ans += t * t
  break if t == k
  k -= t
end
p ans

n,k=gets.split.map(&:to_i)
str=gets.to_s.chomp
arr=str.split(//)
# hsh=arr.inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
#     |k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r }

hsh = Hash.new(0)
arr.each { | v | hsh.store(v, hsh[v]+1) }

sum=0
kol=0
while (kol<k) do
    maxval=hsh.values.max
    kol+=maxval
    if (kol<=k)
        sum+=maxval**2
    else
        sum+=(maxval-(kol-k))**2
    end
    key=hsh.select{|k,v| v==maxval}.keys
    hsh.delete key[0]
end

puts sum

line = gets
i, ka = line.split.map(&:to_i)
line = gets
char_count = {}
line.each_char do |char|
	next if char == "\n"
	char_count[char] ||= 0
	char_count[char] += 1
end
char_ar = []
char_count.each do |k, v|
	char_ar << [k, v]
end
char_ar.sort! do |a, b|
	a[1] <=> b[1]
end.reverse!
output = 0

char_ar.each do |a|
	b = if ka >= a[1]
		a[1]
	else
	    ka
	end
	ka -= b
	output += (b ** 2)
	break if ka < 1
end
puts output
# a => 1, b => 5

n, k = gets.split.map(&:to_i)
tab = gets.strip.split(//)
amount = {}
#p tab
tab.each do |i|
    if amount[i] == nil
        amount[i] = 1
    else
        amount[i] += 1
    end
end
#amount = tab.inject(0){|x, y| p y}
#amount = tab.inject({}){|x, y| if x[y] == nil; x[y] = 1 else x[y] += 1 end}

amount = amount.to_a.map(&:reverse).sort.reverse
result = 0
i = 0

while i < amount.size && k > 0
    result += [amount[i][0], k].min**2
    k -= [amount[i][0], k].min
    i += 1
end

puts result

n, k = gets.split.map(&:to_i)
s = gets.chomp.chars
c = s.uniq.map{|x| s.count(x)}.sort.reverse
ans = 0
t = 0
accum = 0
c.each do |i|
  t = [i, k].min
  accum += t
  ans += t * t
  break if accum == k
  k -= t
end
p ans

line = gets
i, ka = line.split.map(&:to_i)
line = gets
char_count = {}
line.each_char do |char|
	char_count[char] ||= 0
	char_count[char] += 1
end
char_ar = []
char_count.each do |k, v|
	char_ar << [k, v]
end
char_ar.sort! do |a, b|
	a[1] <=> b[1]
end

output = 0

char_ar.each do |a|
	break if ka < 1
	b = if a[1] > ka
		ka
	else
		ka - a[1]
	end
	puts b
	ka -= b
	output += b ** 2
end
puts output
# a => 1, b => 5

line = gets
i, ka = line.split.map(&:to_i)
line = gets
char_count = {}
line.each_char do |char|
	char_count[char] ||= 0
	char_count[char] += 1
end
char_ar = []
char_count.each do |k, v|
	char_ar << [k, v]
end
char_ar.sort! do |a, b|
	a[1] <=> b[1]
end

output = 0

char_ar.each do |a|
	break if ka < 1
	b = if a[1] > ka
		ka
	else
		ka - a[1]
	end
	ka -= b
	output += b ** 2
end
puts output
# a => 1, b => 5

n, k = gets.split.map(&:to_i)
tab = gets.strip.split(//)
amount = {}
#p tab
tab.each do |i|
    if amount[i] == nil
        amount[i] = 1
    else
        amount[i] += 1
    end
end
#amount = tab.inject(0){|x, y| p y}
#amount = tab.inject({}){|x, y| if x[y] == nil; x[y] = 1 else x[y] += 1 end}

amount = amount.to_a.map(&:reverse).sort.reverse
result = 0
i = 0

while i < amount.size && k > 0
    result += [amount[i][0], k].min**2
    k -= [amount[i][0], k].min
end

puts result


Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.  A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.

The first line contains an integer n (2 ≤ n ≤ 105) — the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≤ ci, si ≤ 109) — the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.

Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them.  Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

def gao(a, b, dump = nil)
    a, b = b, a if a.size < b.size
    if dump
        c = []
        a.size.times do |i|
            c << a[i][1]
            break if i == b.size
            c << b[i][1]
        end
        c
    else
        a[[a.size, b.size + 1].min - 1][0] + b[-1][0]
    end
end

n = gets.to_i
h = Hash.new{[]}
n.times do |i|
    c, s = gets.split.map(&:to_i)
    h[c] <<= [s, i + 1]
end
h.each do |c, s|
    s.sort!
    s.reverse!
    1.upto(s.size - 1) do |i|
        s[i][0] += s[i - 1][0]
    end
end

a = []
h.sort{|x, y| [x[1].size, x[1][-1]] <=> [y[1].size, y[1][-1]]}.each {|c, s|
    a << s if a.size < 2 || a[-2].size < s.size
}

ans = [-1]
a.each do |x|
    a.each do |y|
        break if x.equal?(y)
        tmp = gao(x, y)
        ans = [tmp, x, y] if tmp > ans[0]
    end
end
p ans[0]
ans = gao(ans[1], ans[2], true)
p ans.size
puts ans * ' '


Consider a conveyor belt represented using a grid consisting of $$$n$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row from the top and the $$$j$$$-th column from the left is labelled $$$(i,j)$$$. Every cell, except $$$(n,m)$$$, has a direction R (Right) or D (Down) assigned to it. If the cell $$$(i,j)$$$ is assigned direction R, any luggage kept on that will move to the cell $$$(i,j+1)$$$. Similarly, if the cell $$$(i,j)$$$ is assigned direction D, any luggage kept on that will move to the cell $$$(i+1,j)$$$. If at any moment, the luggage moves out of the grid, it is considered to be lost. There is a counter at the cell $$$(n,m)$$$ from where all luggage is picked. A conveyor belt is called functional if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $$$(i,j)$$$, any luggage placed in this cell should eventually end up in the cell $$$(n,m)$$$. This may not hold initially; you are, however, allowed to change the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.Please note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines each contain $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line, $$$a_{i,j}$$$ is the initial direction of the cell $$$(i, j)$$$. Please note that $$$a_{n,m}=$$$ C.

For each case, output in a new line the minimum number of cells that you have to change to make the conveyor belt functional.

4
3 3
RRD
DDR
RRC
1 4
DDDC
6 9
RDDDDDRRR
RRDDRRDDD
RRDRDRRDR
DDDDRDDRR
DRRDRDDDR
DDRDRRDDC
1 1
C

NoteIn the first case, just changing the direction of $$$(2,3)$$$ to D is enough.You can verify that the resulting belt is functional. For example, if we place any luggage at $$$(2,2)$$$, it first moves to $$$(3,2)$$$ and then to $$$(3,3)$$$. In the second case, we have no option but to change the first $$$3$$$ cells from D to R making the grid equal to RRRC.

# t = gets.chomp.to_i
# t.times do
# n, m = gets.chomp.split(" ").map(&:to_i)
#     yy = []
#     xx = []
#     arr = []
#     count = 0
#     n.times do |i|
#     r = gets.chomp.split("")
#         arr << r
#         if n == 1
#             puts "YY"
#             yy << "C"
#             xx << r
#             break
#         elsif m == 1 && i != n-1
#             yy << r
#         elsif m == 1 && i == n-1
#             yy << "C"
#             break
#         end
#         if i != n-1 && n != 1 && m != 1
#             yy << r[-1]
#         elsif i == n-1 && n != 1 && m != 1
#             xx << r
#             yy << r[-1]
#         end
#     end
#     p xx
#     p yy
#     me_x = 0
#     me_y = 0
#     if xx[0].include?("R")
#         ar =  xx[0].count("D")
#         count += ar
#     else
#         me_x += 1
#     end
#     if yy.include?("D")
#         ar = yy.count("R")
#         count += ar
#     else
#         me_y += 1
#     end
#     if me_x >= 1
#         count += m-1
#     elsif me_y >= 1
#         count += n-1
#     end
#     puts count
    # x = 0
    # y = 0
    # ans = 0
    # if  n != 1 && m != 1
    #     until arr[y][x] == "C"
    #         if arr[y][x] == "R"
    #             x += 1
    #         elsif arr[y][x] == "D"
    #             y += 1
    #         end
    #         if x == m - 1
    #             ans = n - y - 1
    #             (y..n-1).each do |k|
    #                 if yy[0][k] == "D"
    #                     ans -= 1
    #                 end
    #             end
    #             break
    #         end
    #         if y == n - 1
    #             ans = m - x - 1
    #             (x..m-1).each do |k|
    #                 if xx[0][k] == "R"
    #                     ans -= 1
    #                 end
    #             end
    #             break
    #         end
    #     end
    # elsif n == 1 || m == 1
    #     if n == 1
    #         if xx.include?("R")
    #             ans = m - 1 - xx.count("R")
    #         else
    #             ans = m - 1
    #         end
    #     elsif m == 1
    #         if yy.include?("D")
    #             ans = n - 1 - yy.count("D")
    #         else
    #             ans = n -1
    #         end
    #     end
    # end
t = gets.chomp.to_i
t.times do |i|
    n, m = gets.chomp.split(" ").map(&:to_i)
    count = 0
    if n == 1
        ar = gets.chomp.split("")
        arr = ar
        yy = ["C"]
        xx = ar
        count = xx.count("D")
    elsif n >= 2
        arr = []
        yy = []
        xx = []
        if m >= 2
            n.times do |i|
            ar = gets.chomp.split("")
            arr << ar
            yy << ar[-1]
                if i == n - 1
                    xx = ar
                end
            end
        elsif m == 1
            xx = ["C"]
            n.times do |i|
                ar = gets.chomp
                arr << ar
                yy << ar
            end
        end
        count += xx.count("D")
        count += yy.count("R")

    end
    puts count
end

t = gets.to_i
ans = []
t.times do
  h,w = gets.chomp.split(" ").map(&:to_i)
  a = h.times.map{gets.chomp}
  cnt = 0
  (h-1).times do |i|
    cnt += 1 if a[i][-1] == "R"
  end
  (w-1).times do |i|
    cnt += 1 if a[-1][i] == "D"
  end
  ans << cnt
end
ans.each do |x|
  puts x
end


You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.

The first line contains single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the maximum length of an increasing subarray of the given array.

n = gets.chomp.to_i
a = gets.split.map(&:to_i)
ans=1
z = 1
(n-1).times do |i|
    if a[i]<a[i+1]
        z+=1
    else
        ans = [ans, z].max
        z=1
    end
end
ans = [ans, z].max
p ans

#!/usr/bin/ruby
gets
r=c=1
a=gets.split.map(&:to_i).each_cons(2){|x,y|
	if x<y
		c+=1
		r=[r,c].max
	else
		c=1
	end
}
p r

n = gets.to_i

mas = gets.split.map(&:to_i)

ans = 1
temp = 1

for i in 1...n do
  if mas[i] > mas[i-1] then
    temp+=1
  else
    ans = temp if temp > ans
    temp = 1
  end
end

ans = temp if temp > ans

puts ans

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

max = 1
arr = [a.first]
(1...n).each do |idx|
  if arr.last < a[idx]
    arr << a[idx]
  else
    arr = [a[idx]]
  end
  max = [max, arr.length].max
end
puts max

n = gets.to_i
as = gets.split.map(&:to_i)

ans = 1
cnt = 1
now = as[0]

(1..n-1).each do |i|
  if now < as[i]
    cnt += 1
  else
    cnt = 1
  end
  now = as[i]
  ans = [ans, cnt].max
end

puts ans

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
prev = a[0]
count = ans = i = 1
while i < n
    if prev < a[i]
        count += 1
    else
        count = 1
    end
    ans = [ans, count].max
    prev = a[i]
    i += 1
end
puts ans

n=gets.to_i
x=gets.split.map{|e| e.to_i}
c=0
ans=1
x.inject(0){|l,e|
	if l<e then
		c+=1

		ans=[ans,c].max
	else
		c=1
	end
	e
}
puts ans

n=gets.to_i
a=gets.split.map &:to_i
dp=[1]*n
for i in 1...n
    dp[i]=dp[i-1]+1 if a[i]>a[i-1]
end
puts dp.max

gets
dp=[1]
a=gets.split.map(&:to_i)
(1..a.size-1).each {|i| dp << ((a[i]>a[i-1])? dp.last+1: 1)}
puts dp.max

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
l = 0
consecutive = 0
longest_consecutive = 0
gets.split.each { |i|
    i = i.to_i
    if l < i
        consecutive += 1
    else
        consecutive = 1 # new first one
    end

    if longest_consecutive < consecutive
        longest_consecutive = consecutive
    end

    l = i
}

puts longest_consecutive

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

count = 1
array = []
array << count
for i in (1..n-1)
	if a[i] > a[i-1]
		count += 1
		array << count
	else
		count = 1
	end
end

print array.max

def solution(arr)
  counter = 1
  max = 0
  for i in 1...arr.size do
    if arr[i] > arr[i-1]
      counter += 1
    else
      max = [max, counter].max
      counter = 1
    end
  end
  max = [max, counter].max
end

_ = gets
puts solution(gets.split.map(&:to_i))

n = gets.chomp.to_i
#a = Array.new
#n.times { puts gets }
longest = 0
current = 0
before = -1
a = STDIN.gets.split(" ").to_a
a.each do |b|
  b = b.to_i
  if b > before
    current += 1
    longest = current if current > longest
  else
    current = 1
  end
  before = b
end
puts longest

def read_line
  gets.chomp.split.map &:to_i
end

n = read_line
a = read_line
k = 0
x = 0
m = 0
a.each do |y|
  if x<y
    k += 1
  else
    k = 1
  end
  m = k if k>m
  x = y
end

puts m

gets
a = gets.split.map{|x| x.to_i}
t, l = 1, 1
(1..a.size-1).each do |i|
    l = 0 if a[i] <= a[i - 1]
    l += 1
    t = [t, l].max
end
puts t

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

result = a.each_with_object({ prev: a.first, max: 1, s: 1 }) do |elm, obj|
  if elm > obj[:prev]
    obj.merge!({ max: [obj[:s]+1, obj[:max]].max, s: obj[:s]+1 })
  else
    obj.merge!({ max: obj[:max], s: 1 })
  end
  obj[:prev] = elm
end

puts result[:max]

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

max = 0
arr = [a.first]
(1...n).each do |idx|
  if arr.last < a[idx]
    arr << a[idx]
  else
    arr = [a[idx]]
  end
  max = [max, arr.length].max
end
puts max

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

count = 1
array = []
for i in (1..n-1)
	if a[i] > a[i-1]
		count += 1
		array << count
	else
		count = 1
	end
end

print array.max

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

count = 1
array = []
for i in (1..n-1)
	if a[i] > a[i-1]
		count += 1
		array << count
	else
		count = 1
		array << count
	end
end

print array.max


You are given an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. After you watched the amazing film "Everything Everywhere All At Once", you came up with the following operation.In one operation, you choose $$$n-1$$$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $$$[1, 2, 3, 1]$$$ we can get the array $$$[2, 2, 2, 1]$$$, if we choose the first three elements, or we can get the array $$$[\frac{4}{3}, \frac{4}{3}, 3, \frac{4}{3}]$$$, if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$)  — the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$).

For each test case, if it is possible to make all elements equal after some number of operations, output $$$\texttt{YES}$$$. Otherwise, output $$$\texttt{NO}$$$. You can output $$$\texttt{YES}$$$ and $$$\texttt{NO}$$$ in any case (for example, strings $$$\texttt{yEs}$$$, $$$\texttt{yes}$$$, $$$\texttt{Yes}$$$ will be recognized as a positive response).

NoteIn the first test case, all elements are already equal.In the second test case, you can choose all elements except the third, their average is $$$\frac{1 + 2 + 4 + 5}{4} = 3$$$, so the array will become $$$[3, 3, 3, 3, 3]$$$.It's possible to show that it's impossible to make all elements equal in the third and fourth test cases.

gets.to_i.times do
n=gets.to_i
a=gets.split(' ').map(&:to_i)
sum=a.reduce(:+)
answer = ! a.select{|v| v % (n - 1) == sum % (n-1) && v == (sum - v) / (n - 1)}.empty?
puts answer ? 'YES' : 'NO'
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.chomp!.split.map! &:to_i
  s = a.sum
  if s % a.size == 0 && a.include?(s / a.size)
    puts 'YES'
  else
    puts 'NO'
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = a.reduce(:+)
  ans = "NO"
  0.upto(n-1) do |i|
    if (s == n*a[i]) then
      ans = "YES"
    end
  end
  puts ans
end

gets.to_i.times do
n=gets.to_i
a=gets.split(' ').map(&:to_i)
sum=a.reduce(:+)
answer = ! a.select{|v| v % n == sum % n && v == (sum - v) / (n - 1)}.empty?
puts answer ? 'YES' : 'NO'
end

gets.to_i.times do
n=gets.to_i
a=gets.split(' ').map(&:to_i)
sum=a.reduce(:+)
answer = ! a.select{|v| v % n == sum % n && v == (sum - v) / n}.empty?
puts answer ? 'YES' : 'NO'
end


Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.

The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 ( = 220) bytes. Newlines are included in this size. In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one. It is guaranteed that the input contains at least one character other than a newline. It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.

Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline. Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.

#   include <cstdio>

using namespace std;

int main     (   ){
puts("Hello # World"); #
#
}

#   include <cstdio>
usingnamespacestd;intmain(){puts("Hello#World");#
#
}

NoteIn the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other.

lines = STDIN.readlines
result = []

lines.each_with_index do |line, i|
  if line.strip[0] == '#'
    if result.length != 0 and result[-1][-1] != "\n"
      result.push("\n")
    end
    result.push(line)
  else
    result.push(line.gsub(/\s/, ''))
  end
end

if result[-1][-1] != "\n"
  result.push("\n")
end
puts result.join

lines = STDIN.readlines
result = []
is_amplifying = []

lines.each do |line|
  if line.strip[0] == '#'
    result.push(line)
    is_amplifying.push(true)
  else
    result.push(line.gsub(/\s/, ''))
    is_amplifying.push(false)
  end
end

(1..lines.length-1).each do |i|
  if is_amplifying[i] and !is_amplifying[i-1]
    result[i-1] += "\n"
  end
end

if result[-1][-1] != "\n"
  result.push("\n")
end
puts(result.join)

lines = STDIN.readlines
result = []
is_amplifying = []

lines.each do |line|
  if line.strip[0] == '#'
    result.push(line)
    is_amplifying.push(true)
  else
    result.push(line.gsub(/\s/, ''))
    is_amplifying.push(false)
  end
end

(1..lines.length-1).each do |i|
  if is_amplifying[i] and !is_amplifying[i-1]
    result[i-1] += "\n"
  end
end

if result[-1][-1] != "\n"
  result.push("\n")
end
print(result.join)

#!/usr/bin/ruby

buf = []
$stdin.readlines.each do |line|
  line.chomp!
  if line =~ /^ *#/
    if not buf.empty?
      puts buf.join('')
      buf = []
    end
    puts line
  else
    buf << line.gsub(/ /, '')
  end
end
if not buf.empty?
  puts buf.join('')
end

tmp = []

readlines.each do |line|
  if line =~ /^ *#/
    if not tmp.empty?
      puts tmp.join
      tmp = []
    end
    puts line
  else
    tmp << line.delete(' ').chomp
  end
end

puts tmp.join if not tmp.empty?

tmp = []

while line = gets
  if line.lstrip[0] == '#'
    if not tmp.empty?
      puts tmp.join
      tmp = []
    end
    puts line
  else
    tmp << line.delete(' ').chomp
  end
end

puts tmp.join if not tmp.empty?

tmp = []

readlines.each do |line|
  if line.lstrip[0] == '#'
    if not tmp.empty?
      puts tmp.join
      tmp = []
    end
    puts line
  else
    tmp << line.delete(' ').chomp
  end
end

puts tmp.join if not tmp.empty?

last = nil
f = true

while s = gets
	t = s.strip.gsub(' ','')
	if t[0] == '#'
		if last != nil
			puts last
			last = nil
		end
		puts s
	else
		last ||= ""
		last << t
	end
	f = false
end
if last != nil
	puts last
end

lines = STDIN.readlines
result = []
is_amplifying = []

lines.each do |line|
  if line.strip[0] == '#'
    result.push(line)
    is_amplifying.push(true)
  else
    result.push(line.gsub(/\s/, ''))
    is_amplifying.push(false)
  end
end

(1..lines.length-1).each do |i|
  if is_amplifying[i] and !is_amplifying[i-1]
    result[i-1] += "\n"
  end
end

print(result.join)

lines = STDIN.readlines
result = []

lines.each_with_index do |line, i|
  if line.strip[0] == '#'
    if result.length != 0 and result[-1][-1] != "\n"
      result.push("\n")
    end
    result.push(line)
  else
    result.push(line.gsub(/\s/, ''))
  end
end

puts result.join

lines = STDIN.readlines
result = []

lines.each_with_index do |line, i|
  if line.strip[0] == '#'
    if result.length > 0
      if result[-1].length == 0 or result[-1][-1] != "\n"
        result.push("\n")
      end
    end
    result.push(line)
  else
    result.push(line.gsub(/\s/, ''))
  end
end

puts result.join

lines = STDIN.readlines
result = []
is_amplifying = []

lines.each do |line|
  if line.strip[0] == '#'
    result.push(line)
    is_amplifying.push(true)
  else
    result.push(line.gsub(/\s/, ''))
    is_amplifying.push(false)
  end
end

(1..lines.length-1).each do |i|
  if is_amplifying[i] and !is_amplifying[i-1]
    result[i-1] += "\n"
  end
end

puts result.join

tmp = ''
last_line_was_text = false

while line = gets
  if line.lstrip[0] == '#'
    tmp += "\n" if last_line_was_text
    tmp += line
  else
    tmp += line.delete(' ').chomp
    last_line_was_text = true
  end
end

puts tmp.chomp

tmp = ''
last_line_was_text = false

while line = gets
  if line.lstrip[0] == '#'
    tmp += "\n" if last_line_was_text
    tmp += line
    last_line_was_text = false
  else
    tmp += line.delete(' ').chomp
    last_line_was_text = true
  end
end

puts tmp.chomp

#$/ = nil
tmp = ''
last_line_was_text = false

while line = gets
  if line.lstrip[0] == '#'
    tmp += "\n" if last_line_was_text
    tmp += line
    last_line_was_text = false
  else
    tmp += line.delete(' ').chomp
    last_line_was_text = true
  end
end

print tmp.chomp

last = ""
f = true

while s = gets
	t = s.strip.gsub(' ','')
	if t[0] == '#'
		if not f
			puts last
			last = ""
		end
		puts s
	else
		last << t
	end
	f = false
end
puts last

imp = false
f = true
while s = gets
	t = s.strip
	if t[0] == '#'
		if not imp and not f
			puts
		end
		print s
		imp = true
	else
		t = t.gsub(' ','')
		print t
		imp = false
	end
	f = false
end

imp = false
f = true
while s = gets
	t = s.strip
	if t[0] == '#'
		if not imp and not f
			puts
		end
		puts s
		imp = true
	else
		t = t.gsub(' ','')
		print t
		imp = false
	end
	f = false
end
puts


Карта звёздного неба представляет собой прямоугольное поле, состоящее из n строк по m символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда). Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.

В первой строке входных данных записаны два числа n и m (1 ≤ n, m ≤ 1000) — количество строк и столбцов на карте звездного неба. В следующих n строках задано по m символов. Каждый символ — это либо «.» (пустой участок неба), либо «*» (звезда). Гарантируется, что на небе есть хотя бы одна звезда.

Выведите одно число — минимально возможную сторону квадрата, которым можно накрыть все звезды.

ПримечаниеОдин из возможных ответов на первый тестовый пример:  Один из возможных ответов на второй тестовый пример (обратите внимание, что покрывающий квадрат выходит за пределы карты звездного неба):  Ответ на третий тестовый пример:

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
arr = [[]]
for i in 0..n-1
  arr[i] = gets.chomp.chars
end
coord = Struct.new(:x, :y)
tl = coord.new(nil, nil)
tr = coord.new(nil, nil)
bl = coord.new(nil, nil)
br = coord.new(nil, nil)
for y in 0..n-1
  if arr[y].include? '*' then
    # Left
    if tl.y == nil then tl.y = y; tl.x = arr[y].index('*')
    elsif tl.x > arr[y].index('*') then tl.x = arr[y].index('*') end

    if bl.x == nil or bl.x > arr[y].index('*') then bl.x = arr[y].index('*') end
    bl.y = y

    # Right
    if tr.y == nil then tr.y = y; tr.x = arr[y].rindex('*');
    elsif tr.x < arr[y].rindex('*') then tr.x = arr[y].rindex('*') end

    if br.x == nil or br.x < arr[y].rindex('*') then br.x = arr[y].rindex('*') end
    br.y = y
  end
end

puts [bl.y - tl.y, br.x - bl.x].max + 1
#printf "TopLeft: %d %d\n", tl.x + 1, tl.y + 1
#printf "TopRight: %d %d\n", tr.x + 1, tr.y + 1
#printf "BottomLeft: %d %d\n", bl.x + 1, bl.y + 1
#printf "BottomRight: %d %d\n", br.x + 1, br.y + 1


Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon $$$P$$$ which is defined by coordinates of its vertices. Define $$$P(x,y)$$$ as a polygon obtained by translating $$$P$$$ by vector $$$\overrightarrow {(x,y)}$$$. The picture below depicts an example of the translation:Define $$$T$$$ as a set of points which is the union of all $$$P(x,y)$$$ such that the origin $$$(0,0)$$$ lies in $$$P(x,y)$$$ (both strictly inside and on the boundary). There is also an equivalent definition: a point $$$(x,y)$$$ lies in $$$T$$$ only if there are two points $$$A,B$$$ in $$$P$$$ such that $$$\overrightarrow {AB} = \overrightarrow {(x,y)}$$$. One can prove $$$T$$$ is a polygon too. For example, if $$$P$$$ is a regular triangle then $$$T$$$ is a regular hexagon. At the picture below $$$P$$$ is drawn in black and some $$$P(x,y)$$$ which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if $$$P$$$ and $$$T$$$ are similar. Your task is to check whether the polygons $$$P$$$ and $$$T$$$ are similar.

The first line of input will contain a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$) — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i, y_i$$$ ($$$|x_i|, |y_i| \le 10^9$$$), denoting the coordinates of the $$$i$$$-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.

Output "YES" in a separate line, if $$$P$$$ and $$$T$$$ are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).

NoteThe following image shows the first sample: both $$$P$$$ and $$$T$$$ are squares. The second sample was shown in the statements.

n = gets.chomp.to_i
arr = (1..n).map {|_| gets.chomp.split(' ').map(&:to_i)}
diff = arr.each_with_index.map do |_, i|
  val = [
    arr[i][0]-arr[i-1][0],
    arr[i][1]-arr[i-1][1]
  ]
  if val[0] < 0 || (val[0] == 0 && val[1] < 0)
    val[0] *= -1
    val[1] *= -1
  end
  val
end
puts (n%2 == 0 && diff.uniq.length == n/2 ? "YES" : "NO")


The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital — number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.

The first input line contains two integers n and m (2 ≤ n ≤ 100, ) — the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 ≤ vi, ui ≤ n, vi ≠ ui) — the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.  It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.

Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.

NoteIn the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make .In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal .

#!/usr/bin/ruby

require 'pp'

inf = 1001001001

while line = gets
	n, m = line.split.map(&:to_i)
	d = Array.new(n)
	n.times do |u|
		d[u] = Array.new(n, inf)
		d[u][u] = 0
	end
	m.times do
		u, v = gets.split.map{|x| x.to_i - 1}
		d[u][v] = d[v][u] = 1
	end
	n.times do |w|
		n.times do |u|
			n.times do |v|
				if  d[u][v] > d[u][w] + d[w][v]
					d[u][v] = d[u][w] + d[w][v]
				end
			end
		end
	end
	e = Array.new(n)
	n.times do |u|
		e[u] = Array.new(n, 0.0)
	end
	n.times do |u|
		n.times do |v|
			if d[u][v] <= 1
				e[u][v] = 1.0
			end
		end
	end
	2.upto(n) do |dist|
		n.times do |u|
			n.times do |v|
				if d[u][v] == dist
					n.times do |w|
						if d[u][w] == 1 && d[u][v] == 1 + d[w][v]
							e[u][v] += e[u][w] * e[w][v]
						end
					end
				end
			end
		end
	end
	# pp e
	ans = 1.0
	n.times do |w|
		if w != 0 && w != n - 1 && d[0][n - 1] == d[0][w] + d[w][n - 1]
			tmp = 2.0 * e[0][w] * e[w][n - 1] / e[0][n - 1]
			# p w
			# p tmp
			if  ans < tmp
				ans = tmp
			end
		end
	end
	p ans
end