Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?

The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees.

For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.

NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case — a square.

n = gets.chomp.to_i
res = []
(1..n).each {|k|
	a = gets.chomp.to_i
	a /= 180.0

	q = 2.0/(1.0-a)

	if (q-q.round).abs < 0.000001
		res.push "YES"
	else
		res.push "NO"
	end
}

res.each { |k|
 puts k
}

x =(1..179).to_a.select{|x| (360%(180-x)==0)}
n = gets.to_i
d = n.times.map{gets.to_i}
n.times{|y| (x.include?(d[y]))? (puts "YES") : (puts "NO")}

t = gets.to_i
ans = []
for i in 0...t
  ans[i] = 360 % (180 - gets.to_i) == 0 ? "YES" : "NO"
end
puts ans

t = gets.to_i

1.upto(t) { puts 360.modulo(180 - gets.to_i).zero? ? 'YES' : 'NO' }

#!/usr/bin/env ruby

n = gets.to_i
n.times do
	x = gets.to_i
	puts 360 % (180 - x) == 0 ? "YES" : "NO"
end

t = gets.chomp.to_i
t.times do
    a = gets.chomp.to_i

    rem = 360 % (180 - a)

    puts (rem == 0 ? "YES" : "NO")
end

n = gets.to_i

ok = []

180.times do |i|
	k = 360.0 / (180 - i)
	if k == k.to_i
		ok << i
	end
end

n.times do |i|
	a = gets.to_i

	if ok.include?(a)
		puts 'YES'
	else
		puts 'NO'
	end
end

t = gets.chomp.to_i
(1..t).each do |x|
	y = gets.chomp.to_i
	if y == 180 then puts "NO"
	else puts((360 % (180-y) == 0) ?"YES":"NO") end
end

#$stdin = File.open("1.txt")
T = gets.chomp.to_i
T.times do
	a = gets.chomp.to_f
	if (360/(180-a)) % 1 == 0
		puts "YES"
	else
		puts "NO"
	end
end

gets.to_i.times do
  puts 360 % (180 - gets.to_i) == 0 ? "YES" : "NO"
end

n = gets.to_i

ans = []
n.times do |i|
    ang = gets.to_f
    a = (360/(180-ang)).to_i == (360/(180-ang)) ? "YES" : "NO"
    ans << a
end

ans.each {|i| puts i}

# cook your code here

num = gets.to_i

for i in 1..num
    x = gets.to_i
    if 360%(180-x)==0
        puts "YES"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
for i in 1..n
  a = gets.chomp.to_i
  if 360 % (180-a) == 0
    puts "YES"
  else
    puts "NO"
  end
end

n=gets.to_i.times do
a=gets.to_i
if a>=60 and a<180 and 360%(180-a)==0
puts "YES"
else
puts "NO"
end
end

require 'set'
s = Set.new
a = Array.new
n = gets.to_i.times do
	a << gets.to_i
end
for i in 1..179 do
	s.add(i) if 360 % (180 - i) == 0
end
a.each{|el| s.include?(el) ? (puts "YES") : (puts "NO")}

n = gets.to_i
n.times do
  a = gets.to_i
  puts(if 360 % (180 - a) == 0 then "YES" else "NO" end)
end

num_tests = gets.to_i
for i in 0...num_tests
	angle = gets.to_i
	sides = 2.0/(1-(angle/180.0))
	if (sides - (sides+0.5).to_i).abs < 0.00000001
		puts "YES"
	else
		puts "NO"
	end
end

#!/usr/bin/ruby1.9

t = STDIN.readline.to_i
t.times do
	interior_angle = STDIN.readline.to_i
	if 360%(180-interior_angle) == 0
		puts "YES"
	else
		puts "NO"
	end
end

n = gets.to_i
n.times{
		a = gets.to_i
		x = 360.0 / ( 180.0 - a )
		if (x == x.floor) then
			puts "YES"
		else
			puts "NO"
		end
}

gets.to_i.times do
  x = gets.to_i
  puts 360 % (180 - x) == 0 ? "YES" : "NO"
end

n = gets.chomp.to_i

n.times do
  x = gets.chomp.to_i
  puts 360 % (180 - x) == 0 ? 'YES' : "NO"
end

n = gets.to_i
n.times do
    a = gets.to_i
    n = 360.0 / (180 - a)
    puts n.to_i == n ? "YES" : "NO"
end

def run
  ary = []
  cnt = 3
  begin
    ary << (180.0 * (cnt - 2)) / cnt
    cnt += 1
  end while ary.last < 179
  ary.uniq!

  n = ARGF.readline.chomp
  ARGF.readlines.map(&:to_i).each do |val|
    puts ary.include?(val) ? "YES" : "NO"
  end
end

run if $0 == __FILE__

arr = []
gets.to_i.times do
  arr << gets.to_i
end
arr.each { |x| puts 360 % (180 - x) == 0 ? "YES" : "NO" }

n=gets.to_i
s=(3..360).select{|e|
	(360%e==0)
}
s.map!{|e|
	180-360/e
}

n.times{
	m=gets.to_i
	if s.include?(m) then
		puts "YES"
	else
		puts "NO"
	end
}

n = gets.to_i
n.times do |i|
	x = gets.to_f
	x = (-2 * 180) / (x - 180)
	puts  x % 1 == 0 ? 'YES' : 'NO'
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

n.times do
  angle = gets.to_i
  n = 360.0 / (180.0 - angle)
  puts ((n.ceil == n.floor) ? :YES : :NO)
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

degrees = Set.new
index = 3
loop do
  angle = (index - 2) * 180.0 / index
  degrees << angle.to_i if angle.ceil == angle.floor
  index += 1

  break if index>2000
end

n.times do
  angle = gets.to_i
  puts ((degrees.include? angle) ? :YES : :NO)
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

degrees = Set.new
index = 3
loop do
  angle = (index - 2) * 180 / index
  degrees << angle
  index += 1

  break if index>1000
end

n.times do
  angle = gets.to_i
  puts ((degrees.include? angle) ? :YES : :NO)
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

degrees = Set.new
index = 3
loop do
  angle = (index - 2) * 180.0 / index
  degrees << angle.to_i if angle.ceil == angle.floor
  index += 1

  break if index>2000
end

puts degrees.inspect

n.times do
  angle = gets.to_i
  puts ((degrees.include? angle) ? :YES : :NO)
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

degrees = []
3.upto(12) do |index|
  degrees << (index - 2) * 180 / index
end

n.times do
  angle = gets.to_i
  puts ((degrees.include? angle) ? :YES : :NO)
end

gets.to_i.times{
	a=gets.to_i
	puts ((a>=60 && a<180) ? 'YES' : 'NO')
}

puts gets.to_i.times.map{gets.to_i}.map{|x| (x>=60&&360%x==0)? "YES" : "NO"}

puts gets.to_i.times.map{gets.to_i}.map{|x| (x>=60)? "YES" : "NO"}

#$stdin = File.open("1.txt")
T = gets.chomp.to_i

H = {}

3.upto(300) do |c|
	H[180*(c-2)/c] = 1
end
T.times do
	a = gets.chomp.to_i
	if H.has_key? (a)
		puts "YES"
	else
		puts "NO"
	end
end

n=gets.to_i.times do
a=gets.to_i
if a>=60 and a<180
puts "YES"
else
puts "NO"
end
end

possible_angles = [0,60,90,108,120,128,135,140,144,147,150,152,154,156,157,158,160]
tests = gets.to_i
for i in 0...tests
	test_case = gets.to_i
	if test_case > 160 and test_case <= 180
		puts "YES"
		next
	end
	while test_case > 180
		test_case -= 180
	end
	if possible_angles.include?(test_case)
		puts "YES"
	else
		puts "NO"
	end
end

num_tests = gets.to_i
for i in 0...num_tests
	angle = gets.to_i
	sides = 2.0/(1-(angle/180.0))
	if (sides - (sides+0.5).to_i) < 0.00000001
		puts "YES"
	else
		puts "NO"
	end
end

n = gets.to_i
n.times do
    a = gets.to_i
    n = 360 / (180 - a)
    puts n.to_i == n ? "YES" : "NO"
end
puts "over"

def run
  ary = []
  cnt = 3
  begin
    ary << (180 * (cnt - 2)) / cnt
    cnt += 1
  end while ary.last < 179
  ary.uniq!

  n = ARGF.readline
  ARGF.readlines.map(&:to_i).each do |val|
    puts ary.include?(val) ? "YES" : "NO"
  end
end

run if $0 == __FILE__

def run
  ary = []
  cnt = 3
  begin
    angle = (180 * (cnt - 2)) / cnt
    ary[cnt] = angle
    cnt += 1
  end while angle < 179

  n = ARGF.readline
  ARGF.readlines.map(&:to_i).each do |val|
    puts ary.include?(val) ? "YES" : "NO"
  end
end

run if $0 == __FILE__

n = gets.to_i
n.times do |i|
	x = gets.to_f
	x = (-2 * 180) / (x - 180)
	puts x
	puts  x % 1 == 0 ? 'YES' : 'NO'
end

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

degrees = []
3.upto(30) do |index|
  degrees << (index - 2) * 180 / index
end

n.times do
  angle = gets.to_i
  puts ((degrees.include? angle) ? :YES : :NO)
end


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $$$x \to (-x)$$$). What is the maximum number of different values in the array you can achieve?

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$).

For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.

NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything.

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each_slice(2) do |inp|
  inp.shift
  nums = inp[0].split(' ').map(&:to_i)

  found = {}
  nums.each do |n|
    if found[n]
      found[n * - 1] = true
    else
      found[n] = true
    end
  end

  pp found.keys.count
end


While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1, f2, ..., fn (1 ≤ fi ≤ n). The last line contains m integers, determining sequence b1, b2, ..., bm (1 ≤ bi ≤ n).

Print "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am. If there are multiple suitable sequences ai, print "Ambiguity". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".

NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi ≠ 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake.

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

gt = proc { gets.chomp.split.map(&:to_i) }

n, m = gt.call
f = gt.call
b = gt.call

fm = {}
n.times do |i|
    k = f[i]
    if fm.key? k
        fm[k] << [i]
    else
        fm[k] = [i]
    end
end

ans = ""
a = [0] * m
m.times do |i|
    k = b[i]
    if fm.key? k
        a[i] = fm[k][0].succ
        if fm[k].size > 1
            ans = "Ambiguity"
        end
    else
        puts 'Impossible'
        exit
    end
end

if ans.empty?
    puts 'Possible'
    puts a * " "
else
    puts ans
end

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

f_map = {}

f.each_index do |i|
  f_map[f[i]] ||= []
  f_map[f[i]] << i + 1
end

a = []
status = 'Possible'

b.each do |bi|
  f_map[bi] ||= []
  case f_map[bi].size
  when 0
    status = 'Impossible'
    break
  when 1
    a << f_map[bi][0]
  else
    if status == 'Possible'
      status = 'Ambiguity'
    end
  end
end

puts status
if status == 'Possible'
  puts a.join ' '
end

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

hs = Hash.new  { |hs, k| hs[k] = [] }

(1..n).map { |i| hs[fs[i - 1]] << i }

as = []
ans = 'Possible'
bs.each do |b|
  s = hs[b].size
  if s == 0
    ans = 'Impossible'
    break
  elsif 1 < s
    ans = 'Ambiguity'
  end
  as << hs[b][0]
end

puts ans
puts as.*' ' if ans == 'Possible'

require "set"
n, m = gets.split().map(&:to_i)
f = gets.split().map(&:to_i)
b = gets.split().map(&:to_i)
f = [0] + f
b = [0] + b
g = [0]*n
imf = Set.new()
d = Set.new()
x = 0
for i in 1..n
	if imf.include? f[i]
		d.add(f[i])
	else
		imf.add(f[i])
	end
	g[f[i]] = i
end
for i in 1..m
	if not imf.include? b[i]
		puts "Impossible"
		x = 1
		break
	end
end
if x != 1
	y = 0
	for i in 1..m
		if d.include? b[i]
			puts "Ambiguity"
			y =1
			break
		end
	end
	if y != 1
		puts "Possible"
		for i in 1...m
			print(g[b[i]])
			print(" ")
		end
		puts g[b[m]]
	end
end

require 'scanf'

n, m = scanf("%d %d\n")
#f = Array.new(n)
f_inv = Array.new(n + 1)
#b = Array.new(m)

f = gets.split.map { |i| i.to_i  }
b = gets.split.map { |i| i.to_i  }
(0..n-1).each do |i|
  f_inv[f[i]] = i + 1
end
f_map = Array.new(n + 1, 0)
(0..n-1).each do |i|
  f_map[f[i]] += 1
end
a = false, im = false
ans = []
(0..m-1).each do |i|
  if f_map[b[i]] > 1
    a = true
  elsif f_map[b[i]] == 0
    im = true
    break
  else
    ans.push(f_inv[b[i]])
  end
end

if im == true
  puts "Impossible"
elsif a == true
  puts "Ambiguity"
else
  puts "Possible"
  (0..ans.size-1).each do |i|
    print ans[i], ' '
  end
  puts
end

class Solver
	def main
		n, m = gets.split.map { |x| x.to_i }
		f = gets.split.map { |x| x.to_i }
		b = gets.split.map { |x| x.to_i }
		h = Hash.new { |hash, key| hash[key] = Array.new }
		f.each.with_index do |x, id|
			h[x] << id
		end

		ambiguity = false
		impossible = false
		ans = []
		b.each do |x|
			if h[x].size == 0 then
				impossible = true
			elsif h[x].size > 1 then
				ambiguity = true
			else
				ans << h[x][0] + 1
			end
		end
		if impossible then
			puts "Impossible"
		elsif ambiguity then
			puts "Ambiguity"
		else
			puts "Possible"
			puts ans.join " "
		end
	end
end

Solver.new.main

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

hs = Hash.new  { |hs, k| hs[k] = [] }

(1..m).map { |i| hs[fs[i - 1]] << i }

as = []
ans = 'Possible'
bs.each do |b|
  s = hs[b].size
  if s == 0
    ans = 'Impossible'
    break
  elsif 1 < s
    ans = 'Ambiguity'
    break
  end
  as << hs[b][0]
end

puts ans
puts as.*' ' if ans == 'Possible'

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

hs = Hash.new()

(1..m).map { |i| hs[fs[i - 1]] = i }
fs.sort!
bs.sort!

if fs != bs
  puts 'Impossible'
else
  fs.uniq!
  if fs.size != m
    puts 'Ambiguity'
  else
    puts 'Possible'
    puts bs.map { |b| hs[b] }.*' '
  end
end

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

hs = Hash.new  { |hs, k| hs[k] = [] }

(1..n).map { |i| hs[fs[i - 1]] << i }

as = []
ans = 'Possible'
bs.each do |b|
  s = hs[b].size
  if s == 0
    ans = 'Impossible'
    break
  elsif 1 < s
    ans = 'Ambiguity'
    break
  end
  as << hs[b][0]
end

puts ans
puts as.*' ' if ans == 'Possible'


One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell:   if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $$$8$$$ neighboring cells).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.

Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.

NoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article.

n, $m = gets.split.map &:to_i

$prev = nil
$curr = gets
$ne = nil

def checkCurr()
	for j in 0..$m-1
    	if $curr[j] == "*"
    		next
    	end
    	bomb = 0
    	for k in [j-1, 0].max..[j+1, $m-1].min
    		bomb += ($prev[k] == "*" ? 1 : 0) if $prev != nil
    		bomb += ($curr[k] == "*" ? 1 : 0) if k != j
    		bomb += ($ne[k] == "*" ? 1 : 0) if $ne != nil
    	end

    	if bomb != $curr[j].to_i
    		return false
    	end
    end
end

res = 1

for i in 0..n-1

	if i < n-1
    	$ne = gets
    else
    	$ne = nil
    end

    if !checkCurr
    	res = 0
    	break
    end

    $prev = $curr
    $curr = $ne

end

if res == 1
	puts "YES"
else
	puts "NO"
end


Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.

Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.

NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.

n=gets.to_i
h=Hash.new 0
g=Hash.new 0
n.times{h[gets.chomp]+=1}
n.times{g[gets.chomp]+=1}
r=0
h.each{|k,v|r+=[0,g[k]-v].max;g.delete(k)}
g.each{|k,v|r+=v}
p r

N = gets.to_i
hash = Hash.new(0)
N.times do
    str = gets.chomp
    hash[str] += 1
end
ans = 0
N.times do
    str = gets.chomp
    if hash[str] > 0
        hash[str] -= 1
    else
        ans += 1
    end
end
puts ans

n = gets.to_i
a =[]
n.times {a << gets.chomp}
n.times do
  s = gets.chomp
  n.times do |i|
    if a[i]==s
      a.delete_at(i)
      break
    end
  end
end
puts a.length

n=gets.to_i
h=Hash.new 0
g=Hash.new 0
n.times{h[gets.to_i]+=1}
n.times{g[gets.to_i]+=1}
r=0
h.each{|k,v|r+=(v-g[k]).abs;g.delete(k)}
g.each{|k,v|r+=v}
p r

n=gets.to_i
h=Hash.new 0
g=Hash.new 0
n.times{h[gets.to_i]+=1}
n.times{g[gets.to_i]+=1}
r=0
h.each{|k,v|r+=(v-g[k]).abs;g.delete(k)}
r/=2
g.each{|k,v|r+=v}
p r

n=gets.to_i
h=Hash.new 0
g=Hash.new 0
n.times{h[gets.chomp]+=1}
n.times{g[gets.chomp]+=1}
r=0
h.each{|k,v|r+=[0,g[k]-v].max}
g.each{|k,v|r+=v}
p r

n=gets.to_i
h=Hash.new 0
g=Hash.new 0
n.times{h[gets.chomp]+=1}
n.times{g[gets.chomp]+=1}
r=0
h.each{|k,v|r+=(v-g[k]).abs;g.delete(k)}
g.each{|k,v|r+=v}
p r

n = gets.to_i
a1 = []
a2 = []
n.times { a1 << gets.chomp.chars}

n.times { a2 << gets.chomp.chars}

a1.sort!{|a,b| a.length <=> b.length}
a2.sort!{|a,b| a.length <=> b.length}
res = 0

n.times do |i|
  res += (a1[i] - a2[i]).length
end
puts res

n = gets.to_i
a =[]
a2=[]
n.times {a << gets.chomp}
n.times{a2 << gets.chomp}
puts (a2-a).length

n = gets.to_i
a1 = []
a2 = []
n.times { s = gets.chomp
valid = (s =~ /(\A(X{0,3})(S|L)$)|(\A(S|L|M)$)/) != nil
a1 << s.chars if valid
}

n.times { s = gets.chomp
valid = (s =~ /(\A(X{0,3})(S|L)$)|(\A(S|L|M)$)/) != nil
a2 << s.chars if valid}

a1.sort!{|a,b| a.length <=> b.length}
a2.sort!{|a,b| a.length <=> b.length}
res = 0
n.times do |i|
  res += (a1[i] - a2[i]).length
end
puts res


A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri).Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.

The first line contains integer number n (1 ≤ n ≤ 5·105) — number of orders. The following n lines contain integer values li and ri each (1 ≤ li ≤ ri ≤ 109).

Print the maximal number of orders that can be accepted.

#!/usr/bin/env ruby

num_orders = gets.to_i
orders = num_orders.times.map do gets.split(' ').map(&:to_i) end
orders = orders.sort_by do |order| order[1] end

total = 0
current_right = 0
orders.each do |left, right|
  if current_right < left
    current_right = right
    total += 1
  end
end

puts total

MAX = 10**9 + 1

n = 0
n = gets.chomp.to_i

numbers = Array.new
# input
for i in 0...n do
	t = gets.chomp.split " "
	numbers.push t.last.to_i * MAX + t.first.to_i
end

numbers.sort!

# calculating answer
ans = 1
last_fin = numbers[0] / MAX

for i in 1...n do
	if numbers[i] % MAX > last_fin
		ans = ans + 1
		last_fin = numbers[i] / MAX
	end

end

puts ans

class Solver
	def main
		n = gets.to_i
		orders = []
		n.times do
			orders << gets.split.map{ |x| x.to_i }
		end
		orders.sort! { |a, b| a[1] <=> b[1] }

		ans = 0
		last = 0
		orders.each do |order|
			if order[0] > last then
				last = order[1]
				ans += 1
			end
		end
		puts ans
	end
end

Solver.new.main

n = 0
l = Array.new
r = Array.new

n = gets.chomp.to_i
# input
for i in 0...n do
	t = gets.chomp.split " "
	l[i] = t.first.to_i
	r[i] = t.last.to_i
end

# insertion sorting
for i in 1...n do

	k = r[i]
	j = i

	while j > 0 and r[j] < r[j-1] do
		r[j] = r[j-1]
		j = j - 1
	end

	r[j] = k

	k = l[i]
	l[i] = l[j]
	l[j] = k
end

# calculating answer
ans = 1
r_last = r[0]

for i in 1...n do
	if l[i] > r_last
		ans = ans + 1
		r_last = r[i]
	end
end

puts ans

n = 0
l = Array.new
r = Array.new

n = gets.chomp.to_i

pointer = Hash.new
max_len = 1
# input
for i in 0...n do
	t = gets.chomp.split " "
	l[i] = t.first
	r[i] = t.last
	if r[i].length > max_len
		max_len = r[i].length
	end

	if pointer.keys.include? r[i]
		pointer[r[i]].push l[i]
	else
		pointer[r[i]] = Array.new
		pointer[r[i]].push l[i]
	end
end

pointer.each_key {|key| pointer[key].sort!}
r.sort!
# radix sorting

# calculating answer
ans = 1
r_last = r[0]

for i in 1...n do
	if pointer[r[i]].shift.to_i > r_last.to_i
		ans = ans + 1
		r_last = r[i]
	end
end

puts ans

n = 0
l = Array.new
r = Array.new

n = gets.chomp.to_i

strings = Array.new
max_len = 1
# input
for i in 0...n do
	t = gets.chomp.split " "
	strings.push t.last + " " + t.first
end

strings.sort!

# calculating answer
ans = 1
last_fin = (strings[0].split(" ")).first.to_i

for i in 1...n do
	t = strings[i].split(" ")
	if t.last.to_i > last_fin.to_i
		ans = ans + 1
		last_fin = strings[i].split(" ").first.to_i
	end

end

=begin
for i in 0...n
	print l[i], " ", r[i]
	puts
=end

puts ans

n = 0
n = gets.chomp.to_i

numbers = Array.new
# input
for i in 0...n do
	t = gets.chomp.split " "
	numbers.push t.last.to_i * 500001 + t.first.to_i
end

numbers.sort!

# calculating answer
ans = 1
last_fin = numbers[0] / 500001

for i in 1...n do
	if numbers[i] % 500001 > last_fin
		ans = ans + 1
		last_fin = numbers[i] / 500001
	end

end

puts ans


Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.  It is guaranteed that the given set of edges specifies a tree.

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test:  The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test:  The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

def getai; return gets.split.map{|e| e.to_i}; end
nm = getai
n = nm[0]; m = nm[1]
a = getai
adj = Array.new(n)
(n - 1).times do
    xy = getai
    x = xy[0] - 1
    y = xy[1] - 1
    nil == adj[x] ? adj[x] = [y] : adj[x] << y
    nil == adj[y] ? adj[y] = [x] : adj[y] << x
end
stack = [0]
used = Array.new(n, false)
last = Array.new(n, -1)
cats = Array.new(n)
cats[0] = a[0]
while (!stack.empty?)   # DFS
    v = stack.last
    used[v] = true
    l = last[v] + 1
    if l < adj[v].length && used[adj[v][l]]
        l += 1
    end
    if l < adj[v].length
        to = adj[v][l]
        cats[to] = cats[v] * a[to] + a[to]
        if cats[to] <= m
            stack << to
        end
    else
        stack.pop
    end
    last[v] = l
end
good_leaves = 0
for v in 0..n-1
    if adj[v].length == 1 && used[v] && v != 0
        good_leaves += 1
    end
end
puts good_leaves

def ri; gets.split.map(&:to_i); end
n, m = ri
cats = [nil] + ri
edges = Array.new(n + 1){Array.new}
(n - 1).times do
  u, v = ri
  edges[u] << v
  edges[v] << u
end

ans = 0
que = [[1, cats[1]]]
until que.empty?
  u, s = que.shift
  ans += 1 if edges[u].empty?
  edges[u].each do |v|
    edges[v].delete(u)
    ns = cats[v] == 1 ? s + 1 : 0
    que << [v, ns] if ns <= m
  end
end
puts ans

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
arr=[]
n.times{
	arr<<[]
}
(n-1).times{
	a,b=gets.split.map{|e| e.to_i-1}
	arr[a]<<b
	arr[b]<<a
}
stc=[[0,0,x[0]]]
ans=0
while !stc.empty?
	e=stc.last
	if (e[0]==0 || arr[e[0]].size>1) && arr[e[0]].size>e[1] then
		p1=arr[e[0]][e[1]]
		stc.last[1]+=1
		s1=stc.size
		if s1>1 && stc[s1-2][0]==p1 then
			next
		end
		add=x[p1]
		t1=0
		if add==1 then
			t1=e[2]+add
		end
		if t1<=m then
			stc<<[p1,0,t1]
		end
	else
		if e[0]==0 then
			break
		elsif arr[e[0]].size==1 then
			if e[2]<=m then
				ans+=1
			end
		end
		stc.pop
	end

end
puts ans

# coding: utf-8

require "set"

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
vertices = {}
(n-1).times {
    u, v = gets.split.map(&:to_i)

    vertices[v] ||= [] # initialize u with empty array
    vertices[u] ||= []
    vertices[u] << v
    vertices[v] << u
}

# Remember, rooted tree
#p vertices
TRAVERSE_UP = -99
stack = [1]
traverse = []
traverse_hashed = {} # do not delete, just mark with nil, put/delete with traverse stack control
cat_acc_stack = [0] # accumulator stack. push/pop with traverse stack control
reachables = []
while !stack.empty?
    i = stack.pop
    if i == TRAVERSE_UP
        traverse.pop
        cat_acc_stack.pop
        next
    end

    if cat_acc_stack.last + cats[i] > m
        # you can stop traversing from here. children can not be reached.
        # visiting node_i should stop
        next # back to stack again
    else
        #p vertices[i]
        #p traverse
        if vertices[i].length == 1 && vertices[i][0] == traverse.last
            reachables << i
        else
            # new traverse starts!
            if cats[i] == 0
                cat_acc_stack << 0
            else
                cat_acc_stack << cat_acc_stack.last + cats[i]
            end

            traverse.push(i)
            traverse_hashed[i] = 1
            stack.push(TRAVERSE_UP)
            for ni in vertices[i]
                if traverse_hashed[ni] == nil
                    stack.push(ni)
                end
            end
        end
    end
end

#p vertices
#p reachables
puts reachables.length # print reachables

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i)
edges = Array.new(n + 1){Array.new}
(n - 1).times do
  u, v = gets.split.map(&:to_i)
  edges[u] << v
  edges[v] << u
end

ans = 0
que = [[1, cats[1]]]
until que.empty?
  u, s = que.shift
  ans += 1 if edges[u].empty?
  edges[u].each do |v|
    edges[v].delete(u)
    ns = cats[v] == 1 ? s + 1 : 0
    que << [v, ns] if ns <= m
  end
end
puts ans

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i)
edges = Array.new(n + 1){Array.new}
(n - 1).times do
  u, v = gets.split.map(&:to_i)
  edges[u] << v
  edges[v] << u
end
con_cats = Array.new(n + 1)

que = [[1, 0]]
ans = 0
loop do
  ind, accum = que[0]
  break unless ind
  que.shift
  next if con_cats[ind]
  if cats[ind] == 1
    accum += 1
  else
    accum = 0
  end
  con_cats[ind] = accum
  if accum <= m
    ans += 1 if edges[ind].size == 1 && ind != 1
    que.push(*edges[ind].zip([accum] * edges[ind].size))
  end
end
puts ans

n, m = gets.split(' ').map(&:to_i)
cats = gets.split(' ').map(&:to_i)
cats.unshift 0

vert = Hash.new { |h, k| h[k] = [] }

1.upto(n - 1) do
  v1, v2 = gets.split(' ').map(&:to_i)
  vert[v1] << v2
  vert[v2] << v1
end

que = [prev: 0, curr: 1, cats: cats[1], failed: 1 > m]

result = 0

while !que.empty?
  curr = que.shift

  any = false

  vert[curr[:curr]].each do |v|
    next if curr[:prev] == v

    any = true

    que << {
      curr: v,
      cats: (curr[:cats] + cats[v]) * cats[v],
      prev: curr[:curr],
      failed: curr[:failed] || (curr[:cats] + cats[v]) * cats[v] > m
    }
  end

  result += 1 unless any || curr[:failed]
end

puts result

n=gets.split(' ').map(&:to_i)
m=n[1]
n=n[0]
a=gets.split(' ').map(&:to_i)
g=Array.new(n+1)
(1).upto(n) do |i|
  g[i]=[]
end
(1).upto(n-1) do
  x=gets.split(' ').map(&:to_i)
  g[x[0]].push(x[1])
  g[x[1]].push(x[0])
end
q=Queue.new
q.push([1,0])
ans=0
vis = Array.new(n+1,false)
while !(q.empty?)
  cur = q.pop
  node = cur[0]
  cats = cur[1]
  cats=0 if a[node-1]==0
  cats+=1 if a[node-1]==1
  next if cats==m+1
  ans+=1 if g[node].length==1 and node!=1
  g[node].each do |next_node|
    next if vis[next_node]
    vis[next_node]=true
    q.push([next_node,cats])
  end
end
puts ans

def get_i_arr
    return gets.chomp.split.map{|e| e.to_i}
end
nm = get_i_arr
n = nm[0]; m = nm[1]
a = get_i_arr
adj = Array.new(n)
(n - 1).times do
    xy = get_i_arr
    x = xy[0] - 1; y = xy[1] - 1
    if nil == adj[x]
        adj[x] = [y]
    else
        adj[x] << y
    end
    if nil == adj[y]
        adj[y] = [x]
    else
        adj[y] << x
    end
end
# DFS
stack = [0]
used = Array.new(n, false)
last = Array.new(n, -1)
cats = Array.new(n, 0)
cur_cats = cats[0] = a[0]
while (!stack.empty?)
    v = stack.last
    used[v] = true
    l = last[v] + 1
    if l < adj[v].length && used[adj[v][l]]
        l += 1
    end
    if l < adj[v].length
        to = adj[v][l]
        if 1 == a[to] && 0 == a[v]
            new_cur_cats = 1
        else
            new_cur_cats = cur_cats + a[to]
        end
        if new_cur_cats <= m
            stack << to
            cur_cats = new_cur_cats
            cats[to] = [cur_cats, cats[v]].max
        end
    else
        prev = stack.length > 1 ? stack[stack.length - 2] : -1
        if prev == -1
            cur_cats = 0
        else
            cur_cats = cats[prev]
        end
        stack.pop
    end
    last[v] = l
end
good_leaves = 0
for v in 0..n-1
    if adj[v].length == 1 && used[v] && v != 0
        good_leaves += 1
    end
end
puts good_leaves

def getai; return gets.split.map{|e| e.to_i}; end
nm = getai
n = nm[0]; m = nm[1]
a = getai
adj = Array.new(n)
(n - 1).times do
    xy = getai
    x = xy[0] - 1; y = xy[1] - 1
    if nil == adj[x] then adj[x] = [y]
    else                  adj[x] << y   end
    if nil == adj[y] then adj[y] = [x]
    else                  adj[y] << x   end
end
stack = [0]
used = Array.new(n, false)
last = Array.new(n, -1)
cats = Array.new(n, 0)
cur_cats = cats[0] = a[0]
while (!stack.empty?)   # DFS
    v = stack.last
    used[v] = true
    l = last[v] + 1
    if l < adj[v].length && used[adj[v][l]]
        l += 1
    end
    if l < adj[v].length
        to = adj[v][l]
        if 1 == a[v] && 0 == a[to]
            new_cats = 0
        else
            new_cats = cur_cats + a[to]
        end
        cats[to] = [new_cats, cats[v]].max
        if cats[to] <= m
            stack << to
            cur_cats = new_cats
        end
    else
        if stack.length > 1
            prev = stack[stack.length - 2]
            if 0 == a[v] && 1 == a[prev]
                cur_cats = cats[prev]
            else
                cur_cats -= a[v]
            end
        else
            cur_cats = 0
        end
        stack.pop
    end
    last[v] = l
end
good_leaves = 0
for v in 0..n-1
    if adj[v].length == 1 && used[v] && v != 0
        good_leaves += 1
    end
end
puts good_leaves

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
arr=[]
n.times{
	arr<<[]
}
(n-1).times{
	a,b=gets.split.map{|e| e.to_i-1}
	arr[a]<<b
	arr[b]<<a
}
stc=[[0,0,x[0]]]
ans=0
while !stc.empty?
	e=stc.last
	if arr[e[0]].size>1 && arr[e[0]].size>e[1] then
		p1=arr[e[0]][e[1]]
		stc.last[1]+=1
		s1=stc.size
		if s1>1 && stc[s1-2][0]==p1 then
			next
		end
		add=x[p1]
		t1=0
		if add==1 then
			t1=e[2]+add
		end
		if t1<=m then
			stc<<[p1,0,t1]
		end
	else
		if e[0]==0 then
			break
		elsif arr[e[0]].size==1 then
			if e[2]<=m then
				ans+=1
			end
		end
		stc.pop
	end

end
puts ans

n,m=gets.split.map{|e| e.to_i}
m-=1
x=gets.split.map{|e| e.to_i}
arr=[]
n.times{
	arr<<[]
}
(n-1).times{
	a,b=gets.split.map{|e| e.to_i-1}
	arr[a]<<b
	arr[b]<<a
}
stc=[[m,0,0]]

while !stc.empty?
	e=stc.last
	if arr[e[0]].size>e[1] then
		s1=stc.size
		p1=arr[e[0]][e[1]]
		stc.last[1]+=1
		if s1>1 && stc[s1-2][0]==p1 then
			next
		end
		stc<<[p1,0,0]
	else
		stc.pop
		if e[0]==m then
			puts e[2]+1
			break
		else
			if x[e[0]]==1 then
				stc.last[2]+=e[2]+1
			end
		end
	end
end

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
arr=[]
n.times{
	arr<<[]
}
(n-1).times{
	a,b=gets.split.map{|e| e.to_i-1}
	arr[a]<<b
	arr[b]<<a
}
stc=[[0,0,0]]
ans=0
while !stc.empty?
	e=stc.last
	if arr[e[0]].size>1 && arr[e[0]].size>e[1] then
		p1=arr[e[0]][e[1]]
		stc.last[1]+=1
		s1=stc.size
		if s1>1 && stc[s1-2][0]==p1 then
			next
		end
		add=x[e[0]]
		add=0 if e[0]==0
		stc<<[p1,0,add+e[2]]
	else
		if e[0]==0 then
			break
		elsif arr[e[0]].size==1 then
			if e[2]<m then
				ans+=1
			end
		end
		stc.pop
	end

end
puts ans

# coding: utf-8

require "set"

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
vertices = {}
(n-1).times {
    u, v = gets.split.map(&:to_i)

    vertices[v] ||= [] # initialize u with empty array
    vertices[u] ||= []
    vertices[u] << v
    vertices[v] << u
}

# Remember, rooted tree
#p vertices
TRAVERSE_UP = -99
stack = [1]
traverse = []
reachables = []
while !stack.empty?
    i = stack.pop
    if i == TRAVERSE_UP
        traverse.pop
        next
    end

    #p vertices[i]
    #p traverse
    if vertices[i].length == 1 && vertices[i][0] == traverse.last
        traverse.push(i)

        cat_count = 0
        longest_cats = 0
        traverse.each { |j|
            if cats[j] == 0
                if longest_cats < cat_count
                    longest_cats = cat_count
                end
                cat_count = 0
            else
                cat_count += cats[j]
            end
        }
        if longest_cats < cat_count
            longest_cats = cat_count #last update.
        end

        p "longest_cats #{longest_cats} #{m}"
        p stack
        p traverse
        if longest_cats <= m
            reachables << i
        end

        traverse.pop
    else
        traverse.push(i)
        stack.push(TRAVERSE_UP)
        for ni in vertices[i]
            unless traverse.include?(ni)
                stack.push(ni)
            end
        end
    end
end

#p vertices
#p reachables
puts reachables.length # print reachables

# coding: utf-8

require "set"

# if __FILE__ == $0
# end
V = Struct.new("Vertex", :u, :v)

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
rvertices = {}
leaves = Set.new
(n-1).times {
    u, v = gets.split.map(&:to_i)

    # handle in reverse. 'v' first.
    leaves.add(v)
    leaves.delete(u) # if v' (past one) was not a leaf node, delete it

    rvertices[v] ||= []
    rvertices[v] << V.new(v, u)
}

# Remeber, rooted tree
#p rvertices
reachables = []
leaves.each { |i|
    j = i
    cats_on_way = 0
    max_consecutives = 0
    loop do
        # p "> #{j}"
        if cats[j] == 1
            cats_on_way += cats[j]
        else
            cats_on_way = 0 # reset, because not consecutive.
        end
        if cats_on_way > max_consecutives
            max_consecutives = cats_on_way # updates
        end
        break if j == 1
        # p "> #{j} -> #{rvertices[j][0].v}"
        j = rvertices[j][0].v
    end

    if max_consecutives <= m
        reachables << i
    end
}

# p reachables
puts reachables.length # print reachables

# coding: utf-8

require "set"

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
rvertices = {}
leaves = Set.new
(n-1).times {
    u, v = gets.split.map(&:to_i)
    leaves.add(v)
    leaves.delete(u)
    rvertices[u] ||= [] # initialize u with empty array
    rvertices[v] ||= []
    rvertices[v] << u

}

# Remember, rooted tree
#p rvertices
reachables = []

leaves.each { |i|
    if i == 1 # root node
        next
    end
    j = i
    cat_count = 0
    longest_cat_seq = 0
    loop do
        if cats[j] == 0
            if longest_cat_seq < cat_count
                longest_cat_seq = cat_count
                cat_count = 0
            end
        else
            cat_count += cats[j]
        end

        if rvertices[j].empty?
            if longest_cat_seq < cat_count
                longest_cat_seq = cat_count
            end
            break
        else
            j = rvertices[j][0]
        end
    end

    if longest_cat_seq <= m
        reachables << i
    end
}

p reachables
puts reachables.length # print reachables

# coding: utf-8

require "set"

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
vertices = {}
(n-1).times {
    u, v = gets.split.map(&:to_i)

    vertices[v] ||= [] # initialize u with empty array
    vertices[u] ||= []
    vertices[u] << v
    vertices[v] << u
}

# Remember, rooted tree
#p vertices
TRAVERSE_UP = -99
stack = [1]
traverse = []
reachables = []
while !stack.empty?
    i = stack.pop
    if i == TRAVERSE_UP
        traverse.pop
        next
    else
        traverse.push(i)
    end

    if vertices[i].length == 1
        if i == 1
            break
        end
        cat_count = 0
        longest_cats = 0
        traverse.each { |j|
            if cats[j] == 0
                if longest_cats < cat_count
                    longest_cats = cat_count
                end
                cat_count = 0
            else
                cat_count += cats[j]
            end
        }
        if longest_cats < cat_count
            longest_cats = cat_count #last update.
        end

        #p "longest_cats #{longest_cats} #{m}"
        #p stack
        #p traverse
        if longest_cats <= m
            reachables << i
        end

        traverse.pop
    else
        stack.push(TRAVERSE_UP)
        for ni in vertices[i]
            unless traverse.include?(ni)
                stack.push(ni)
            end
        end
    end
end

#p vertices
#p reachables
puts reachables.length # print reachables

# coding: utf-8

require "set"

# if __FILE__ == $0
# end

n, m = gets.split.map(&:to_i)
cats = [nil] + gets.split.map(&:to_i) # 1-based vertices
rvertices = {}
leaves = Set.new
(n-1).times {
    u, v = gets.split.map(&:to_i)
    leaves.add(v)
    leaves.delete(u)
    rvertices[u] ||= [] # initialize u with empty array
    rvertices[v] ||= []
    rvertices[v] << u

}

# Remember, rooted tree
#p rvertices
reachables = []

leaves.each { |i|
    if i == 1 # root node
        next
    end
    j = i
    cat_count = 0
    longest_cat_seq = 0
    loop do
        if cats[j] == 0
            if longest_cat_seq < cat_count
                longest_cat_seq = cat_count
                cat_count = 0
            end
        else
            cat_count += cats[j]
        end

        if rvertices[j].empty?
            if longest_cat_seq < cat_count
                longest_cat_seq = cat_count
            end
            break
        else
            j = rvertices[j][0]
        end
    end

    if longest_cat_seq <= m
        reachables << i
    end
}

# p reachables
puts reachables.length # print reachables

n, $m = gets.split.map(&:to_i)
$cats = [nil] + gets.split.map(&:to_i)
$edges = Array.new(n + 1){Array.new}
$edges[0] = [1]
(n - 1).times do
  u, v = gets.split.map(&:to_i)
  $edges[u] << v
end

$ans = 0
def dfs(lv, accum)
  return unless $edges[lv]
  if $cats[lv] == 1
    accum += 1
  elsif !$cats[lv].nil?
    accum = 0
    $ans += 1
  end
  $edges[lv].each{|v| dfs(v, accum)} if accum <= $m
end

dfs(0, 0)
puts $ans

n, $m = gets.split.map(&:to_i)
$cats = [nil] + gets.split.map(&:to_i)
$edges = Array.new(n + 1){Array.new}
(n - 1).times do
  u, v = gets.split.map(&:to_i)
  $edges[u] << v
  $edges[v] << u
end
$con_cats = Array.new(n + 1)

$ans = 0
def dfs(lv, accum)
  return if $con_cats[lv]
  if $edges[lv].size == 1
    $ans += 1 if accum + $cats[lv] <= $m
    return
  end
  if $cats[lv] == 1
    accum += 1
  else
    accum = 0
  end
  $con_cats[lv] = accum
  $edges[lv].each{|v| dfs(v, accum)} if accum <= $m
end

dfs(1, 0)
puts $ans

n, $m = gets.split.map(&:to_i)
$cats = [nil] + gets.split.map(&:to_i)
$edges = Array.new(n + 1){Array.new}
$edges[0] = [1]
(n - 1).times do
  u, v = gets.split.map(&:to_i).sort
  $edges[u] << v
end

$ans = 0
def dfs(lv, accum)
  if $edges[lv] == []
    $ans += 1 if accum + $cats[lv] <= $m
    return
  end
  if $cats[lv] == 1
    accum += 1
  else
    accum = 0
  end
  $edges[lv].each{|v| dfs(v, accum)} if accum <= $m
end

dfs(0, 0)
puts $ans

n, $m = gets.split.map(&:to_i)
$cats = [nil] + gets.split.map(&:to_i)
$edges = Array.new(n + 1){Array.new}
$edges[0] = [1]
(n - 1).times do
  u, v = gets.split.map(&:to_i)
  $edges[u] << v
end

$ans = 0
def dfs(lv, accum)
  if $edges[lv] == []
    $ans += 1 if accum + $cats[lv] <= $m
    return
  end
  if $cats[lv] == 1
    accum += 1
  else
    accum = 0
  end
  $edges[lv].each{|v| dfs(v, accum)} if accum <= $m
end

dfs(0, 0)
puts $ans

n, m = gets.split(' ').map(&:to_i)
cats = gets.split(' ').map(&:to_i)
cats.unshift 0

vert = Hash.new { [] }

1.upto(n - 1) do
  v1, v2 = gets.split(' ').map(&:to_i)
  vert[v1] = vert[v1] + [v2]
  vert[v2] = vert[v2] + [v1]
end

que = [v: [1], cats: 1, failed: false]

result = 0

while !que.empty?
  curr = que.shift
  vort = curr[:v].last

  any = false

  vert[vort].each do |v|
    next if curr[:v].include? v

    any = true

    que << {
      v: curr[:v] + [v],
      cats: (curr[:cats] + cats[v]) * cats[v],
      failed: curr[:failed] || (curr[:cats] + cats[v]) * cats[v] > m
    }
  end

  result += 1 unless any || curr[:failed]
end

puts result


Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Print m integers — the responses to Eugene's queries in the order they occur in the input.

_, a, *q = readlines.map{|i| i.split.map(&:to_i)}
n = 2 * [a.count(1), a.count(-1)].min
puts q.map{|i, j|
  j -= i
  j.odd? && j < n ? 1 : 0
}

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
aa,aaa=a.count(1),a.count(-1)
m.times do
	l,r=gets.chomp.split.map(&:to_i)
	x=a[l-1..r-1]
	len=x.length
	puts (len.even? && 2*aa>=len && 2*aaa>=len)? "1" : "0"
end

n, m = gets.split(' ').map { |i| i.to_i }
a = b = 0
gets.split(' ').map {|i|
    i = i.to_i
    a += 1 if i == 1
    b += 1 if i == -1
}
m.times do
    l, r = gets.split(' ').map { |i|  i.to_i}
    width = r - l + 1
    if width % 2 != 0 or (width / 2 > a or width / 2 > b)
        puts 0
    else
        puts 1
    end
end

n, m = gets.split(' ').map { |i| i.to_i }
a = b = 0
gets.split(' ').map {|i| i.to_i == 1 ? a += 1 : b += 1}
m.times do
    l, r = gets.split(' ').map { |i|  i.to_i}
    width = r - l + 1
    puts (width % 2 != 0 or (width / 2 > a or width / 2 > b)) ? 0 : 1
end

def run
  n, m = $stdin.gets.split.map(&:to_i)
  a = $stdin.gets.split.map(&:to_i)

  plus  = a.count {|x| x > 0 }
  minus = n - plus
  $stdin.readlines.each do |line|
    l, r = line.split.map(&:to_i)
    len = r - l + 1

    if len % 2 == 0 and plus*2 >= len and minus*2 >= len
      puts "1"
    else
      puts "0"
    end
  end
end

run if $0 == __FILE__

class A
  def initialize
    n, m = gets.chomp.split(' ').map(&:to_i)

    array = gets.chomp.split(' ').map(&:to_i)

    query = []

    m.times do
      query << gets.chomp.split(' ').map(&:to_i)
    end

    mc = array.count(-1)
    pc = array.count(1)

    query.each do |q|
      size = q[1] - q[0] + 1

      if(size.even? && size > 1 && size/2 <= mc && size/2 <= pc)
        puts 1
      else
        puts 0
      end
    end
  end
end

a = A.new

# def query(l,r)
#  ele = r - l + 1
#  return false if ele.odd?
#  val = ele / 2
#  return true if val <= @one_count && val <= @minus_count
#  return false
# end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ")
	l = l.to_i
	r = r.to_i
	ele = r - l + 1
	if ele.odd?
 		ans << "0"
 		next
 	end
 	val = ele / 2
 	if val <= @one_count && val <= @minus_count
 		ans << "1"
 		next
 	end
 	ans << "0"
end

ans.each do |a|
	puts a
end

#Good http://codeforces.com/contest/302/problem/A
# From TLE to 811 ms
# Appending to array and iterating and displaying result is way faster than puts result directly around 100 ms diff
# Removed the method calls
# removed boolean checks
# Removed the map and did to_i directly for l and r
# Directly appended string to answer - there will be a to_s call for puts that cost from 889 to 811 the fuck

# def query(l,r)
#  ele = r - l + 1
#  return false if ele.odd?
#  val = ele / 2
#  return true if val <= @one_count && val <= @minus_count
#  return false
# end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ")
	l = l.to_i
	r = r.to_i
	ele = r - l + 1
	if ele.odd?
 		puts "0"
 		next
 	end
 	val = ele / 2
 	if val <= @one_count && val <= @minus_count
 		puts "1"
 		next
 	end
 	puts "0"
end

# ans.each do |a|
# 	puts a
# end

#Good http://codeforces.com/contest/302/problem/A
# From TLE to 811 ms
# Removed the method calls
# removed boolean checks
# Removed the map and did to_i directly for l and r
# Directly appended string to answer - there will be a to_s call for puts that cost from 889 to 811 the fuck

# def query(l,r)
#  ele = r - l + 1
#  return false if ele.odd?
#  val = ele / 2
#  return true if val <= @one_count && val <= @minus_count
#  return false
# end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ").map(&:to_i)
	ele = r - l + 1
	if ele.odd?
 		ans << false
 		next
 	end
 	val = ele / 2
 	if val <= @one_count && val <= @minus_count
 		ans << true
 		next
 	end
 	ans << false
end

ans.each do |a|
	puts a ? 1 : 0
end

# def query(l,r)
#  ele = r - l + 1
#  return false if ele.odd?
#  val = ele / 2
#  return true if val <= @one_count && val <= @minus_count
#  return false
# end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ")
	l = l.to_i
	r = r.to_i
	ele = r - l + 1
	if ele.odd?
 		ans << 0
 		next
 	end
 	val = ele / 2
 	if val <= @one_count && val <= @minus_count
 		ans << 1
 		next
 	end
 	ans << 0
end

ans.each do |a|
	puts a
end

def query(l,r)
 ele = r - l + 1
 return false if ele.odd?
 val = ele / 2
 return true if val <= @one_count && val <= @minus_count
 return false
end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ").map(&:to_i)
	ans << (query(l,r) ? 1 : 0)
end
ans.each do |a|
	puts a
end

# def query(l,r)
#  ele = r - l + 1
#  return false if ele.odd?
#  val = ele / 2
#  return true if val <= @one_count && val <= @minus_count
#  return false
# end

n,m = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
@one_count = arr.count(1)
@minus_count = n - @one_count
ans = []
m.times do
	l,r = gets.split(" ")
	l = l.to_i
	r = r.to_i
	ele = r - l + 1
	if ele.odd?
 		ans << false
 		next
 	end
 	val = ele / 2
 	if val <= @one_count && val <= @minus_count
 		ans << true
 		next
 	end
 	ans << false
end

ans.each do |a|
	puts a ? 1 : 0
end

n, m = gets.split.collect{|i| i.to_i}
a = Array.new(3,0)
gets.split.each{|i| a[i.to_i+1]+=1}
(1..m).each do
    l, r = gets.split.collect{|i| i.to_i}
    if (r-l+1).odd?
        puts 0
    elsif a[0] < (r-l+1)/2 or a[2] < (r-l+1)/2
        puts 0
    else
        puts 1
    end
end

n,m = gets.strip.split(' ').map {|x| x.to_i}
a = gets.strip.split(' ')
h = {'1' => 0, '-1' => 0}
a.each do |e| h[e] += 1 end

m.times do
  l, r = gets.strip.split(' ').map {|x| x.to_i}
  if( (l+r)%2 == 0)
    puts 0
  else
    k = ((r-l).abs+1)/2
    puts( (h.values.min >= k) ? 1 : 0 )
  end
end

n_m = gets.split.map { |i| i.to_i }
n = n_m[0]
m = n_m[1]

a_count = b_count = 0

a = gets.split.map do |i|
  r = i.to_i
  if r == 1
    a_count += 1
  else
    b_count += 1
  end
  r
end

for i in 1..m
  from_to = gets.split.map { |i| i.to_i }
  from = from_to[0]
  to = from_to[1]
  len = to - from + 1

  if (len % 2 == 0) && a_count >= len / 2 && b_count >= len / 2
    puts 1
  else
    puts 0
  end
end

n, m = gets.chomp.split(' ').collect{|item| item.to_i}
a = gets.chomp.split(' ').collect{|item| item.to_i }
a1 = a.count{|item| item == -1}
a2 = a.length - a1
for i in 1..m
  l, r = gets.chomp.split(' ').collect{|item| item.to_i}
  numbers = r - l + 1
  if numbers % 2 == 0
    if a1 >= numbers / 2 and a2 >= numbers / 2
      puts 1
    else
      puts 0
    end
  else
    puts 0
  end
end

#!/usr/bin/env ruby

n, m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
a, b = x.count(-1), x.count(1)
m.times do
	l, r = gets.split.map(&:to_i)
	l = r - l + 1
	if l % 2 == 1
		puts 0
	else
		l = l / 2
		puts a >= l && b >= l ? 1 : 0
	end
end

n,m = gets.split.map{|x| x.to_i}
a = gets.split(' ').map{|x| x.to_i}
p = a.count{|x| x<0}
q = a.count{|x| x>0}
p += p;q += q;
# p p,q
m.times{
	(l,r) = gets.split.map{|x| x.to_i}
	l = r-l+1
	if (l&1)==1
		puts 0
	elsif l>p
		puts 0
	elsif l>q
		puts 0
	else
		puts 1
	end
}

puts readlines[2..-1].map{|i| i.split.map(&:to_i).inject(&:-) % 2}

_, a, *q = readlines.map{|i| i.split.map(&:to_i)}
n = 2 * [a.count(1), a.count(-1)].min
puts q.map{|i, j|
  j -= i
  j.even? && j <= n ? 1 : 0
}

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
aa,aaa=a.count(1),a.count(-1)
m.times do
	l,r=gets.chomp.split.map(&:to_i)
	x=a[l-1..r-1]
	len=x.length
	puts(len.even? && 2*aa>=len && 2*aaa>=x.length)? "1" : "0"
end

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
m.times do
	l,r=gets.chomp.split.map(&:to_i)
	x=a[l-1..r-1]
	puts (x.length.even? && 2*a.count(1)>=x.length && 2*a.count(1)>=x.length)? "1" : "0"
end

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
m.times do
	l,r=gets.chomp.split.map(&:to_i)
	x=a[l-1..r-1]
	puts (x.length.even? && 2*x.count(1)>=x.length && 2*x.count(1)>=x.length)? "1" : "0"
end

class A
  def initialize
    n, m = gets.chomp.split(' ').map(&:to_i)

    array = gets.chomp.split(' ').map(&:to_i)

    query = []

    m.times do
      query << gets.chomp.split(' ').map(&:to_i)
    end

    query.each do |q|
      if array[(q[0]-1)..(q[1]-1)].inject(:+) == 0
        puts 1
      else
        puts 0
      end
    end
  end
end

a = A.new

n,m = gets.strip.split(' ').map {|x| x.to_i}
a = gets.strip.split(' ')
h = Hash.new 0
a.each do |e|
  h[e] += 1
end
p h

(0...m).to_a.map do
  l, r = gets.strip.split(' ').map {|x| x.to_i}
  if( (l+r)%2 == 0)
    puts 0
  else
    k = ((r-l).abs+1)/2
    puts( (h.values.min >= k) ? 1 : 0 )
  end
end

n,m = gets.strip.split(' ').map {|x| x.to_i}
a = gets.strip.split(' ')
h = Hash.new 0
a.each do |e|
  h[e] += 1
end

(0...m).to_a.map do
  l, r = gets.strip.split(' ').map {|x| x.to_i}
  if( (l+r)%2 == 0)
    puts 0
  else
    k = ((r-l).abs+1)/2
    puts( (h.values.min >= k) ? 1 : 0 )
  end
end

n,m = gets.strip.split(' ').map {|x| x.to_i}
a = gets.strip.split(' ')
h = Hash.new 0
a.each do |e|
  h[e] += 1
end

(0...m).to_a.map do
  l, r = gets.strip.split(' ').map {|x| x.to_i}
  if( (l+r)%2 == 0)
    puts 0
  else
    k = (r-l+1)/2
    puts( (h.values.min >= k) ? 1 : 0 )
  end
end

n_m = gets.split.map { |i| i.to_i }
n = n_m[0]
m = n_m[1]

a = gets.split.map { |i| i.to_i }

for i in 1..m
  from_to = gets.split.map { |i| i.to_i }
  from = from_to[0]
  to = from_to[1]

  sum = 0
  for j in from..to
    sum += a[j-1]
  end
  if sum == 0
    puts 1
  else
    puts 0
  end
end

n, m = gets.chomp.split(' ').collect{|item| item.to_i}
a = gets.chomp.split(' ').collect{|item| item.to_i }
a1 = a.count{|item| item == -1}
a2 = a.length - a1
puts m
for i in 1..m
  l, r = gets.chomp.split(' ').collect{|item| item.to_i}
  numbers = r - l + 1
  if numbers % 2 == 0
    if a1 >= numbers / 2 and a2 >= numbers / 2
      puts 1
    else
      puts 0
    end
  else
    puts 0
  end
end

n, m = gets.chomp.split(' ').collect{|item| item.to_i}
a = gets.chomp.split(' ').collect{|item| item.to_i }
a1 = a.count{|item| item == -1}
a2 = a.length - a1
for i in 1..m
  l, r = gets.chomp.split(' ').collect{|item| item.to_i}
  numbers = r - l + 1
  if numbers % 2 == 0
    puts 1 if a1 >= numbers / 2 and a2 >= numbers / 2
  else
    puts 0
  end
end


Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:   A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.  Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.

The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).

Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.

7
win 10
win 5
win 3
sell 5
sell 3
win 10
sell 10

def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n = gets.to_i
n.times{$* << read}
ans = 0
$*.reject{|i| i >= 0}.sort.each do |x|
	next unless b = $*.index(x)
	next unless a = $*[0 .. b].rindex(-1 - x)
	next unless $*[a..b].all?	# WA5
	ans += 2 ** (-1 - x)
	$*[a..b] = [nil]
end
p ans

n = gets.to_i
x = Array.new(n, -1)
dp = Array.new(n, 0)
(0 .. n - 1).each do |i|
	a, b = gets.split
	b = b.to_i
	dp[i] = dp[i - 1] if i > 0
	if a == 'win' then
		x[i] = b
	else
		(0 .. i - 1).each do |j|
			dp[i] = [dp[i], dp[j] + (1 << b)].max if x[j] == b
		end
	end
end
p dp[-1]

__END__
def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i >= 0}.sort.each do |x|
	next unless t = a.index(x)
	next unless f = a[0 .. t].rindex(-1 - x)
	s += 1 << -1 - x
	a.slice!(f .. t)
end
p s

WA5: test data error?

dp = [0];
for i in 1..2001
	dp[i] = -1
end

n = gets.to_i

for i in 1..n
	t, x = gets.split(' ')
	x = x.to_i + 1
	if t == 'sell' && dp[x] >= 0
		dp[0] = [dp[0], dp[x] + 2**(x-1)].max
	else
		dp[x] = dp[0]
	end
end

puts dp[0]

dp = [0]
for i in 1..2001
    dp[i] = -1
end
n = STDIN.gets.to_i

for i in 1..n
    data = STDIN.gets.split(' ')
    s = data[0]
    t = data[1].to_i + 1
    if s == "sell"
        if dp[t] >= 0 && dp[t] + 2 ** (t-1) > dp[0]
            dp[0] = dp[t] + 2 ** (t-1)
        end
    else
        dp[t] = dp[0]
    end
end

puts dp[0]

def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 10000000000000000000, []
n.times{a << read}
a.reject{|i| i >= 0}.sort.each do |x|
	next unless t = a.index(x)
	next unless f = a[0 .. t].rindex(-1 - x)
	s += 1 << -1 - x
	a.slice!(f .. t)
end
p s - 10000000000000000000

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
g = a.reject{|i| i >= 0}.sort
g.each do |x|
    next if (t = a.index(x)).nil?
    next if (f = a[0 .. t].rindex(-1 - x)).nil?
    s += 1 << -1 - x
    a.slice!(f .. t)
end
p s

def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n = gets.to_i
n.times{$* << read}
ans = 0
$*.reject{|i| i >= 0}.sort.each do |x|
	next unless b = $*.index(x)
	next unless a = $*[0 .. b].rindex(-1 - x)
	ans += 2 ** (-1 - x)
	$*.slice!(a, b - a)
end
p ans

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
t = a.reject{|i| i >= 0}.sort
t.each do |x|
    next if (t = a.index(x)).nil?
    next if (f = a[0 .. t].rindex(-1 - x)).nil?
    s += 1 << -1 - x
    a.slice!(f .. t)
end
p s

def read
    a, b = gets.split
    a == 'win' ? -1 - b.to_i : b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i < 0}.sort.reverse.each do |x|
    next unless t = a.rindex(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << x
    a.slice!(f .. t)
end
p s

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i >= 0}.sort.each do |x|
    next unless t = a.index(x)
    raise Exception.new() if a.index(x) != a.rindex(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << -1 - x
    a.slice!(f .. t)
end
p s

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i >= 0}.sort.each do |x|
    next if (t = a.index(x)).nil?
    next if (f = a[0 .. t].rindex(-1 - x)).nil?
    s += 1 << -1 - x
    a.slice!(f .. t)
end
p s

def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n = gets.to_i
a = []
n.times{a << read}
s = 0
a.reject{|i| i >= 0}.sort.each do |x|
	next unless t = a.index(x)
	next unless f = a[0 .. t].rindex(-1 - x)
	s += 2 ** (-1 - x)
	a.slice!(f .. t)
end
puts s

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
raise Exception.new() if a.reject{|i| i >= 0}.sort.uniq!
a.reject{|i| i >= 0}.sort.each do |x|
    next unless t = a.index(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << -1 - x
    a.slice!(f .. t)
end
p s

def read
    a, b = gets.split
    a == 'win' ? -1 - b.to_i : b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i < 0}.sort.each do |x|
    next unless t = a.index(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << x
    a.slice!(f .. t)
end
p s

def read
    a, b = gets.split
    a == 'win' ? -1 - b.to_i : b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i < 0}.sort.reverse.each do |x|
    next unless t = a.index(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << x
    a.slice!(f .. t)
end
p s

def read
	a, b = gets.split
	a == 'win' ? b.to_i : -1 - b.to_i
end

n = gets.to_i
n.times{$* << read}
ans = 0
$*.reject{|i| i >= 0}.sort.each do |x|
	next unless b = $*.index(x)
	next unless a = $*[0 .. b].rindex(-1 - x)
	ans += 2 ** (-1 - x)
	$*.slice!(a .. b)
end
p ans

def read
    a, b = gets.split
    a == 'win' ? b.to_i : -1 - b.to_i
end

n, s, a = gets.to_i, 0, []
n.times{a << read}
a.reject{|i| i >= 0}.sort.each do |x|
    next unless t = a.index(x)
    next unless f = a[0 .. t].rindex(-1 - x)
    s += 1 << -1 - x
    a[f .. t] = nil
end
p s


ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.

The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... < tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.

Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.

NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.

a,b=gets.split.map &:to_i
k=1
m=gets.split
a.times{|x|
m[a-x-1].to_i-m[a-x-2].to_i>b ? break : k+=1}
$><<[k,a].min

n, c = gets.split.map &:to_i
a = gets.split.map &:to_i
ans = 1
(1...n).each do |i|
    if a[i] - a[i - 1] > c
        ans = 1
    else
        ans += 1
    end
end
puts ans

#!/usr/bin/ruby
n,c,*a=$<.read.split.map(&:to_i)
r=1
a.each_cons(2){|x,y|
	if y-x>c
		r=1
	else
		r+=1
	end
}
p r

n,c = gets.split.map(&:to_i)
mas = gets.split.map(&:to_i)

ans = 1
for i in 1...mas.size() do
    if(mas[i]-mas[i-1] <= c)
        ans+=1;
    else
        ans = 1;
    end
end

puts ans;

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

last = a.first
count = 0
a.each do |d|
  if last - d <= c
    count += 1
    last = d
  else
    break
  end
end
puts count

c = gets.chop.split(' ').map{ |x| x.to_i }[1]

t = gets.chop.split(' ').map{ |x| x.to_i }

count = 1

i = t.size - 1

while i != 0
    break if t[i] - c > t[i - 1]
    count += 1
    i -= 1;
end

print count

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

times = gets.split.map{|x| x.to_i}

words = 0
prevtime = 0
for sec in times
  if (sec - prevtime) > c
    words = 1
  else
    words += 1
  end
  prevtime = sec
end

puts words

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                args = line.split(" ")
                @n = Integer(args[0])
                @c = Integer(args[1])
            when 1
                @arr = line.split(" ")
                @arr = @arr.map{ |i| i = Integer(i) }
                @arr.reverse!
                puts getScreen()
                #@arr.sort!
            when 2

            else

            end
        end
    end

    def getScreen()
        rtn = 1
        @arr.each_with_index do |e,i|
            if i + 1 < @n
                if e - @arr[i+1] > @c
                    rtn = i + 1
                    break
                end
                if i + 1 == @n - 1
                    rtn = @n
                end
            end
        end
        return rtn
    end
end

main = Program.new(ARGF)

n, c = gets.split.map(&:to_i)
ts = gets.split.map(&:to_i)

ans = 1
(n-1).downto(1) do |i|
  b = ts[i]
  a = ts[i-1]
  if b - a <= c
    ans += 1
  else
    break
  end
end
puts ans

n, c = gets.strip.split.map(&:to_i)
t = gets.strip.split.map(&:to_i)
a = t[0]
words = 1
(1...n).each do |i|
    b = t[i]
    if b - a <= c
        words += 1
    else
        words = 1
    end
    a = b
end
puts words

n,c=gets.split.map{|e| e.to_i}
x=gets.split.reverse.map{|e| e.to_i}
ans=1
while x.size>1
	if x[0]-x[1]>c then
		break
	end
	ans+=1
	x.shift
end
puts ans

n,c = gets.split.map(&:to_i)
t = gets.split.map(&:to_i)
r = 1
(n - 1).downto(1) do |i|
	if t[i] - t[i - 1] <= c
		r += 1
	else
		break
	end
end
p r

total, dist = gets.split(' ').map(&:to_i)
ats = gets.split(' ').map(&:to_i)

next_at = ats.last
count = 0
ats.reverse_each do |at|
  if next_at - at <= dist
    count += 1
  else
    break
  end
  next_at = at
end

puts count

n, c=gets.split.map &:to_i
t=gets.split.map &:to_i

res=0
x=t[0]
t.each {|i|
    if i-x<=c
        res+=1
    else
        res=1
    end
    x=i
}
p res

n,c,a=gets.split.map(&:to_i)<<1
gets.split.map(&:to_i).each_cons(2){|x,y|a=(y-x>c)?1:a+1}
p a

n,c=gets.split.map(&:to_i)
cnt=1
gets.split.map(&:to_i).each_cons(2) do|x,y|
    cnt+=1
    cnt=1 if y-x>c
end
p cnt

# coding: utf-8

# if __FILE__ == $0
# end

n, c = gets.split.map(&:to_i)
words = 0
last_words_spent = 0
gets.split.each { |i|
    i = i.to_i
    if (i - last_words_spent) > c
        words = 1
    else
        words += 1
    end
    last_words_spent = i
}

puts words

# be name khoda ...
def read_ints; STDIN.gets.split.map(&:to_i); end
n, c = read_ints
a = read_ints
res = 1
i = 0
(n-1).times do
  if(a[i]+c < a[i+1])
    res = 1
  else
    res +=1
  end
  i+=1
end
puts res

input_values = gets.chomp
in_val = input_values.split(' ').map(&:to_i)
total_input = in_val[0]
cons_value = in_val[1]
string_input = gets.chomp
array = string_input.split(' ').map(&:to_i)
i = 1
count = 1
while i < total_input do
	if array[i]-array[i-1] <= cons_value
		count += 1
	else
	  count = 1
	end
	i += 1
end
puts count

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

k = 0
p = 0
a.each do |x|
  k += 1
  k = 1 if x-p>c
  p = x
end

puts k

n, c = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 1
n.times do |i|
  if a[i] - a[i - 1] > c || i == 0
    ans = 1
  else
    ans += 1
  end
end
puts ans

n, c = gets.split.map(&:to_i)
t = gets.split.map(&:to_i)
ans = 1
1.upto(n - 1){|i|
    if t[i] - t[i - 1] > c
        ans = 1
    else
        ans += 1
    end
    }
p ans

n, c = gets.split.map{|x| x.to_i}
puts(gets.split.map{|x| x.to_i}.inject([0, 0]){|s, x| [x - s[1] <= c ? s[0] + 1 : 1, x]}[0])

typeNum, delay = gets.chomp.split(' ').map(&:to_i)
inputs = gets.chomp.split(' ').map(&:to_i)

char = 1

for i in (1...(inputs.length))
	diff = inputs[i] - inputs[i - 1]
	char = 1 if diff > delay
	char += 1 if diff <= delay
end

puts char

a,b=gets.split.map &:to_i
k=1
m=gets.split
a.times{|x|
m[a-x-1].to_i-m[a-x-2].to_i<=b ? k+=1 : break}
$><<k

n,c = gets.split.map(&:to_i)
mas = gets.split.map(&:to_i)

ans = 1
for i in 1...mas.size() do
    if(mas[i]-mas[i-1] <= c)
        ans+=1;
    else
        ans = 0;
    end
end

puts ans;

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

a.map!.with_index do |_, i|
  diff = a[i + 1].nil? ? -10000000000 : a[i] - a[i + 1]
  diff <= c ? 1 : 0
end
puts a.chunk { |x| x == 1 }.to_a.first.last.length + 1

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

a.map!.with_index do |_, i|
  diff = a[i + 1].nil? ? -10000000000 : a[i] - a[i + 1]
  diff <= c ? 1 : 0
end
if n == 1
  puts 1
else
  puts a.chunk { |x| x == 1 }.to_a.first.last.length + 1
end

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

times = gets.split.map{|x| x.to_i}

words = 0
prevtime = 0
for sec in times
  if (sec - prevtime) >= c
    words = 2
  else
    words += 1
  end
  prevtime = sec
end

puts words

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                args = line.split(" ")
                @n = Integer(args[0])
                @c = Integer(args[1])
            when 1
                @arr = line.split(" ")
                @arr = @arr.map{ |i| i = Integer(i) }
                @arr.reverse!
                puts getScreen()
                #@arr.sort!
            when 2

            else

            end
        end
    end

    def getScreen()
        rtn = 1
        @arr.each_with_index do |e,i|
            if i + 1 < @n
                if e - @arr[i+1] > @c
                    rtn = i + 1
                    break
                end
            end
        end
        return rtn
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                args = line.split(" ")
                @n = Integer(args[0])
                @c = Integer(args[1])
            when 1
                @arr = line.split(" ")
                @arr = @arr.map{ |i| i = Integer(i) }
                @arr.reverse!
                puts getScreen()
                #@arr.sort!
            when 2

            else

            end
        end
    end

    def getScreen()
        rtn = 1
        @arr.each_with_index do |e,i|
            if i + 1 < @n
                if e - @arr[i+1] > @c
                    rtn = i + 1
                    break
                end
                if i == @n - 1
                    rtn = @n
                end
            end
        end
        return rtn
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                args = line.split(" ")
                @n = Integer(args[0])
                @c = Integer(args[1])
            when 1
                @arr = line.split(" ")
                @arr = @arr.map{ |i| i = Integer(i) }
                @arr.reverse!
                puts getScreen()
                #@arr.sort!
            when 2

            else

            end
        end
    end

    def getScreen()
        rtn = 0
        @arr.each_with_index do |e,i|
            if i + 1 < @n
                if e - @arr[i+1] > @c
                    rtn = i + 1
                    break
                end
            end
        end
        return rtn
    end
end

main = Program.new(ARGF)

total, dist = gets.split(' ').map(&:to_i)
ats = gets.split(' ').map(&:to_i)

next_at = ats.last
count = 0
ats.reverse_each do |at|
  if next_at - at <= dist
    count += 1
  end
  next_at = at
end

puts count

input_values = gets.chomp
in_val = input_values.split(' ').map(&:to_i)
total_input = in_val[0]
cons_value = in_val[1]
string_input = gets.chomp
array = string_input.split(' ').map(&:to_i)
i = 1
count = 0
while i < total_input do
	if array[i]-array[i-1] <= cons_value
		count += 1
	else
	  count = 1
	end
	i += 1
end
puts count

n, c = gets.split.map(&:to_i)
t = gets.split.map(&:to_i)
ans = 0
tmp = 1
1.upto(n - 1){|i|
    if t[i] - t[i - 1] > c
        ans = [ans, tmp].max
        tmp = 1
    else
        tmp += 1
    end
    }
ans = [ans, tmp].max
p ans


You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n \le 10^5, 1 \le m \le 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case print the answer to the problem.

NoteIn the first test case we can divide the elements as follows:  $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$.  $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$.  $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element.

t = gets.chomp.to_i
for test in (1..t)
  n, m = gets.chomp.split(' ').map { |x| x.to_i }
  a = gets.chomp.split(' ').map { |x| x.to_i }
  r = Array.new(m).fill(0)
  for i in (0..n-1)
    r[a[i] % m] += 1
  end
  ans = 0
  for i in (1..m/2)
    if r[i] == r[m - i]
      if r[i] > 0
        ans += 1
      end
    elsif r[i] == 0 && r[m - i] != 0
      ans += r[m - i]
    elsif r[i] != 0 && r[m - i] == 0
      ans += r[i]
    else
      ans += 1 + [0, (r[i] - r[m - i]).abs - 1].max
    end
  end
  if r[0] != 0
    ans += 1
  end
  puts ans
end

require 'set'

def fn(aa, d)
  out = []
     ret = 0
  for e in aa
    n = e % d
    if (n != 0)
      out << n
    else
     ret = 1
    end
  end
  r = out.tally

  for k,v in r
    if k + k == d
      ret += 1
      next
    end
    if v == 0; next; end

    j = d - k
    r[k] = 0
    vj = r[j]
    if vj
      r[j] = 0
      if vj >= v+1
        ret += 1
        ret += vj - (v+1)
       # printf("j:%d k:%d > ret:%d\n",k,j,ret)
      elsif vj == v
        ret += 1
       # printf("k:%d j:%d == ret:%d\n",k,j,ret)
      else
        ret += 1
        ret += v - (vj+1)
       # printf("k:%d j:%d < ret:%d\n",k,j,ret)
      end
    else
      ret += v
       # printf("j:%d ret:%d\n",k,ret);
    end

  end
  puts ret
end

tt = gets.to_i
tt.times {
  (_, d)= gets.chomp!.split(' ').map &:to_i
  aa = gets.chomp!.split(' ').map &:to_i
  fn(aa,d)
}

gets.to_i.times {
  n, m = gets.split(' ').map(&:to_i)
  xs = gets.split(' ').map(&:to_i)

  groups = Array.new(m) { [] }
  xs.each do |el|
    groups[el % m].push(el)
  end

  res = 0
  if groups[0].size > 0
    res += 1
  end
  if m % 2 == 0 && groups[m / 2].size > 0
    res += 1
  end
  (1..((m - 1) / 2)).each do |rem|
    min = [groups[rem].size, groups[m - rem].size].min
    max = [groups[rem].size, groups[m - rem].size].max
    if min == 0
      res += max
    elsif min == max
      res += 1
    else
      res += (max - min)
    end
  end
  puts res
}

t = gets.chomp.to_i
for test in (1..t)
  n, m = gets.chomp.split(' ').map { |x| x.to_i }
  a = gets.chomp.split(' ').map { |x| x.to_i }
  r = Array.new(m).fill(0)
  for i in (0..n-1)
    r[a[i] % m] += 1
  end
  z = 0
  for i in (1..(m-1)/2)
    y = [r[i], r[m - i]].min * 2 + 1
    z += 1 + [0, r[i] + r[m - i] - y].max
  end
  if r[0] != 0
    z += 1
  end
  if m % 2 == 0 && r[m / 2] != 0
    z += 1
  end
  puts z
end


You are given two arrays $$$a$$$ and $$$b$$$ both consisting of $$$n$$$ positive (greater than zero) integers. You are also given an integer $$$k$$$.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) and swap $$$a_i$$$ and $$$b_j$$$ (i.e. $$$a_i$$$ becomes $$$b_j$$$ and vice versa). Note that $$$i$$$ and $$$j$$$ can be equal or different (in particular, swap $$$a_2$$$ with $$$b_2$$$ or swap $$$a_3$$$ and $$$b_9$$$ both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ such moves (swaps).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30; 0 \le k \le n$$$) — the number of elements in $$$a$$$ and $$$b$$$ and the maximum number of moves you can do. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 30$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 30$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.

For each test case, print the answer — the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ swaps.

NoteIn the first test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_2 = 4$$$, so $$$a=[4, 2]$$$ and $$$b=[3, 1]$$$.In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_1 = 10$$$, $$$a_3 = 3$$$ and $$$b_3 = 10$$$ and $$$a_2 = 2$$$ and $$$b_4 = 10$$$, so $$$a=[10, 10, 10, 4, 5]$$$ and $$$b=[1, 9, 3, 2, 9]$$$.In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays $$$a$$$ and $$$b$$$, so $$$a=[4, 4, 5, 4]$$$ and $$$b=[1, 2, 2, 1]$$$.

gets.to_i.times do
	n, k = gets.split.map(&:to_i)
	a = gets.split.map(&:to_i).sort
	b = gets.split.map(&:to_i).sort.reverse
	puts (0...k).sum { |i| [a[i], b[i]].max } + (k...n).sum { |i| a[i] }
end

t = gets.to_i
t.times do
	n,k = gets.split.map(&:to_i)
	a = gets.split.map(&:to_i)
	b = gets.split.map(&:to_i)
	sum = a.sum
	a.sort!
	b.sort!.reverse!
	for i in 0...k
		sum += b[i] - a[i] if b[i] > a[i]
	end
	puts sum
end

t = gets.chomp.to_i
t.times do |testcase|
  (n,k) = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  b = gets.split.map(&:to_i)
  a = a.sort;a = a.reverse;b = b.sort
  #print a ; print "\n"
  a_ptr = -1 ; b_ptr = -1
  while k>0
    if b[b_ptr] >= a[a_ptr]
      a[a_ptr] = b[b_ptr]
      a_ptr-=1 ; b_ptr-=1
    end
    k-=1
  end
  res = 0
  a.each do |num|
    res += num
  end
  puts res
end

1.upto(gets.to_i) do
  n, k = gets.split(' ').map(&:to_i)

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

  result = a.inject(&:+)

  a[0, k].zip(b[0, k]).each do |x|
    break if x.first >= x.last

    result += x.last - x.first
  end

  puts result
end


You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().

The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.

Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".

p = readline.chomp.rjust(10**6, "0")
#puts p
q = readline.chomp.rjust(10**6, "0")
#puts q
if p == q
  puts("=")
elsif p < q
  puts("<")
else
  puts(">")
end

a = gets.to_i
b = gets.to_i
if a < b
 puts "<"
elsif a > b
 puts ">"
else
 puts "="
end

a=gets.to_i
b=gets.to_i
if a<b
  puts "<"
elsif a>b
 puts ">"
else
 puts "="
end

num1, num2 = STDIN.read.split("\n").map { |s| s.sub /^0+/,'' }
res = case (num1.size <=> num2.size)
	when 1
		'>'
	when -1
		'<'
	else
		case num1 <=> num2
		when 1
			'>'
		when -1
			'<'
		else
			'='
		end
end

puts res

a = gets.chomp.rjust(10**6, "0")
b = gets.chomp.rjust(10**6, "0")

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

a = gets.strip
b = gets.strip

if a.size > b.size
   b = ("0" * (a.size - b.size)).concat(b)
elsif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

0.upto(a.size-1) do |shift|
  if a[shift] > b[shift]
    puts(">")
    exit
  end
  if a[shift] < b[shift]
    puts("<")
    exit
  end
end

puts "="

a=gets.to_i
b=gets.to_i
if a<b
 puts"<"
elsif a>b
 puts">"
else
 puts"="
end

a = gets.chomp
b = gets.chomp
a = a[1..-1] while a[0] == '0'
b = b[1..-1] while b[0] == '0'
puts ">" if a.length > b.length
puts "<" if a.length < b.length
exit unless a.length == b.length

(0..a.length - 1).each do |i|
  puts "<" if a[i] < b[i]
  puts ">" if a[i] > b[i]
  exit unless a[i] == b[i]
end
puts "="

a = gets.chomp
b = gets.chomp
while a[0] == '0'
  a = a[1..-1]
end
while b[0] == '0'
  b = b[1..-1]
end
if a.length > b.length
  puts ">"
  exit
end
if a.length < b.length
  puts "<"
  exit
end

(0..a.length - 1).each do |i|
  if a[i] < b[i]
    puts "<"
    exit
  end
  if a[i] > b[i]
    puts ">"
    exit
  end
end
puts "="

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

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

a=gets.to_i
b=gets.to_i
p "=" if a==b
p "<" if a<b
p ">" if a>b

a = gets
b = gets

if a.size > b.size
   b = ("0" * (a.size - b.size)).concat(b)
elseif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

0.upto(a.size-1) do |shift|
  if a[-1-shift] > b[-1-shift]
    puts(">")
    exit
  end
  if a[-1-shift] < b[-1-shift]
    puts("<")
    exit
  end
end

puts "="

a = gets
b = gets

if a.size > b.size
  b = ("0" * (a.size - b.size)).concat(b)
elseif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

0.upto(a.size-1) do |shift|
  puts ">" and exit if a[-1-shift] > b[-1-shift]
  puts "<" and exit if a[-1-shift] > b[-1-shift]
end

puts "="

a = gets.strip
b = gets.strip

if a.size > b.size
   b = ("0" * (a.size - b.size)).concat(b)
elsif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

0.upto(a.size-1) do |shift|
  if a[-1-shift] > b[-1-shift]
    puts(">")
    exit
  end
  if a[-1-shift] < b[-1-shift]
    puts("<")
    exit
  end
end

puts "="

a = gets.strip
b = gets.strip

if a.size > b.size
   b = ("0" * (a.size - b.size)).concat(b)
elsif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

puts a
puts b
0.upto(a.size-1) do |shift|
  if a[shift] > b[shift]
    puts(">")
    exit
  end
  if a[shift] < b[shift]
    puts("<")
    exit
  end
end

puts "="

a = gets
b = gets

if a.size > b.size
  b = ("0" * (a.size - b.size)).concat(b)
elseif b.size > a.size
   a = ("0" * (b.size - a.size)).concat(a)
end

0.upto(a.size-1) do |shift|
  puts ">" && exit if a[-1-shift] > b[-1-shift]
  puts "<" && exit if a[-1-shift] < b[-1-shift]
end

puts "="

a = gets.chomp
b = gets.chomp
while a[0] == '0'
  a = a[1..-1]
end
while b[0] == '0'
  b = b[1..-1]
end
if a.length > b.length
  puts ">"
  exit
end
if a.length < b.length
  puts "<"
  exit
end

a.length.downto 1 do |i|
  if a[i - 1] < b[i - 1]
    puts "<"
    exit
  end
  if a[i - 1] > b[i - 1]
    puts ">"
    exit
  end
end
puts "="

a = gets.chomp
b = gets.chomp
a = a[1..-1] while a[0] == '0'
b = b[1..-1] while b[0] == '0'
p a
p b
puts ">" if a.length > b.length
puts "<" if a.length < b.length
exit unless a.length == b.length

(0..a.length - 1).each do |i|
  puts "<" if a[i] < b[i]
  puts ">" if a[i] > b[i]
  exit unless a[i] == b[i]
end
puts "="

a = gets.chomp
b = gets.chomp
a = a[1...-1] while a[0] == '0'
b = b[1..-1] while b[0] == '0'
puts ">" if a.length > b.length
puts "<" if a.length < b.length
exit unless a.length == b.length

(0..a.length - 1).each do |i|
  puts "<" if a[i] < b[i]
  puts ">" if a[i] > b[i]
  exit unless a[i] == b[i]
end
puts "="


It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.

The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.

Print a single number without leading zeroes — the product of the number of tanks presented by each country.

NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful.

n = gets.to_i
as = gets.chomp.split

p = 1
z = 0
as.each do |a|
  if a == '0'
    p = 0
    z = 0
    break
  elsif a != '1' + '0' * (a.size - 1)
    p = a
  else
    z += a.size - 1
  end
end

puts p.to_s + '0' * z

def isb(s)
    ones = 0
    zero = 0
    n = false
    for i in 0...s.length do
        ones += 1 if s[i] == '1'
        zero += 1 if s[i] == '0'
        n = true if s[i] != '1' && s[i] != '0'
    end
    return ones == 1 && n == false
end
def czero(s)
    zero = 0
    for i in 0...s.length do
        zero += 1 if s[i] == '0'
    end
    return zero
end
n = gets.to_i
p = gets.strip.split(" ")
ans = ""
ze = 0
cb = false
contzero = false
for str in p do
    contzero = true if str == "0"
   if isb(str)
       ze += czero(str)
   else
       cb = true
       ans << str
   end
end
if contzero
    puts ("0")
else
    ans << "1" if cb == false
    for i in 0...ze do
        ans << "0"
    end
    puts ans
end

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

pow = 0
notbeautiful = "1"
tanks.each do |t|
  n1 = t.count("1")
  n0 = t.count("0")
  nrem = t.length - n1 - n0
  if t.length == 1 && n0 == 1 then
    puts 0
    exit
  elsif n1 != 1 or nrem != 0 then
    notbeautiful = t
  else
    pow += t.length - 1
  end
end
puts notbeautiful + "0" * pow

n = Integer( gets.chomp )
input = gets.chomp
num = input.split(" ")

n -= 1
aux = "-1"
cont = 0
flag = false

while n>=0
	one = zero = 0
	i = 0

	while i<num[n].length

		if num[n][i]=='1'
			one += 1
		elsif num[n][i]=='0'
			zero += 1
		end

		i += 1

	end

	if(one==1 && zero+one==i)
		cont += num[n].length - 1
	else
		aux = num[n]
	end

	if i==1 && zero==i
		flag = true
	end

	n -= 1
end

if flag
	puts "0"
else
	if(aux=="-1")
		aux = "1"
	end

	print aux

	while cont>0
		print "0"
		cont -= 1
	end

	print "\n"
end

def isb(s)
    ones = 0
    zero = 0
    n = false
    for i in 0...s.length do
        ones += 1 if s[i] == '1'
        zero += 1 if s[i] == '0'
        n = true if s[i] != '1' && s[i] != '0'
    end
    return ones == 1 && n == false
end
def czero(s)
    zero = 0
    for i in 0...s.length do
        zero += 1 if s[i] == '0'
    end
    return zero
end
n = gets.to_i
p = gets.strip.split(" ")
ans = ""
ze = 0
for str in p do
   if isb(str)
       ze += czero(str)
   else
       ans << str
   end
end
for i in 0...ze do
    ans << "0"
end
puts ans

def isb(s)
    ones = 0
    zero = 0
    n = false
    for i in 0...s.length do
        ones += 1 if s[i] == '1'
        zero += 1 if s[i] == '0'
        n = true if s[i] != '1' && s[i] != '0'
    end
    return ones == 1 && n == false
end
def czero(s)
    zero = 0
    for i in 0...s.length do
        zero += 1 if s[i] == '0'
    end
    return zero
end
n = gets.to_i
p = gets.strip.split(" ")
ans = ""
ze = 0
contzero = false
for str in p do
    contzero = true if str == "0"
   if isb(str)
       ze += czero(str)
   else
       ans << str
   end
end
if contzero
    puts ("0")
else
    for i in 0...ze do
        ans << "0"
    end
    puts ans
end

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

pow = 0
notbeautiful = "1"
tanks.each do |t|
  n1 = t.count("1")
  n0 = t.count("0")
  nrem = t.length - n1 - n0
  if n1 == 0 && n0 == 1 then
    puts 0
    exit
  elsif n1 != 1 or nrem != 0 then
    notbeautiful = t
  else
    pow += t.length - 1
  end
end
puts notbeautiful + "0" * pow

n = Integer( gets.chomp )
input = gets.chomp
num = input.split(" ")

n -= 1
aux = "0"
cont = 0
flag = false

while n>=0
	one = zero = 0
	i = 0

	while i<num[n].length
		if num[n][i]=='1'
			one += 1
		elsif num[n][i]=='0'
			zero += 1
		end
		i += 1
	end

	if(one==1 && zero+one==i)
		cont += num[n].length - 1
	else
		aux = num[n]
	end

	if i==1 && zero==i
		flag = true
	end

	n -= 1
end

if flag
	puts "0"
else
	print aux
	while cont>0
		print "0"
		cont -= 1
	end
	print "\n"
end


You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with $$$a$$$ cans in a pack with a discount and some customer wants to buy $$$x$$$ cans of cat food. Then he follows a greedy strategy:   he buys $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ packs with a discount;  then he wants to buy the remaining $$$(x \bmod a)$$$ cans one by one. $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ is $$$x$$$ divided by $$$a$$$ rounded down, $$$x \bmod a$$$ is the remainer of $$$x$$$ divided by $$$a$$$.But customers are greedy in general, so if the customer wants to buy $$$(x \bmod a)$$$ cans one by one and it happens that $$$(x \bmod a) \ge \frac{a}{2}$$$ he decides to buy the whole pack of $$$a$$$ cans (instead of buying $$$(x \bmod a)$$$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.You know that each of the customers that come to your shop can buy any number of cans from $$$l$$$ to $$$r$$$ inclusive. Can you choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the range of the number of cans customers can buy.

For each test case, print YES if you can choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially. Otherwise, print NO. You can print each character in any case.

NoteIn the first test case, you can take, for example, $$$a = 5$$$ as the size of the pack. Then if a customer wants to buy $$$3$$$ cans, he'll buy $$$5$$$ instead ($$$3 \bmod 5 = 3$$$, $$$\frac{5}{2} = 2.5$$$). The one who wants $$$4$$$ cans will also buy $$$5$$$ cans.In the second test case, there is no way to choose $$$a$$$.In the third test case, you can take, for example, $$$a = 80$$$.

T = gets.to_i

T.times do
  l, r = gets.split.map(&:to_i)

  if r < 2 * l
    puts 'YES'
  else
    puts 'NO'
  end
end

t = gets.chomp.to_i
t.times do
    l, r = gets.chomp.split(" ").map(&:to_i)
    kizyun = r
    if l <= kizyun / 2
        puts "NO"
    else
        puts "YES"
    end
end

gets.to_i.times do
  l, r = gets.split.map &:to_i
  puts 2 * l > r ? "YES" : "NO"
end

gets.to_i.times do
  l, r = gets.split.map(&:to_i)
  a = r + 1
  puts(if l * 2 >= a then "YES" else "NO" end)
end

t = gets.chomp.to_i
t.times do
    l, r = gets.chomp.split(" ").map(&:to_i)
    kizyun = r + 1
    if l <= kizyun / 2
        puts "NO"
    else
        puts "YES"
    end
end


DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:  where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  ;  edge  if and only if , and edge ;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.

The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.

Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.

NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.

n, m = gets.split(' ').map(&:to_i)
node = gets.split(' ').map(&:to_i)
max = 0.0
m.times do
  a, b, c = gets.split(' ').map(&:to_i)
  v = (node[a-1]+node[b-1]+0.0)/(c+0.0)
  max = v if max < v
end
puts max

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

values = gets.split(' ').map { |s| s.to_f }
best = 0.0
m.times do
  edge = gets.split(' ')
  a = edge[0].to_i
  b = edge[1].to_i
  edge_val = edge[2].to_f
  best = [best, (values[a - 1] + values[b - 1]) / edge_val].max
end

puts best

n,m=gets.split.map(&:to_i)
x=[0]+gets.split.map(&:to_f)
r=0.0
m.times do
  a,b,c=gets.split.map(&:to_i)
  y=(x[a]+x[b])/c
  r=y if r<y
end
p r

result = 0.0

n, m = gets.split.map(&:to_i)
v = [0] + gets.split.map(&:to_i)

m.times do
  a, b, c = gets.split.map(&:to_i)
  if result < (v[a] + v[b]).to_f / c
    result = (v[a] + v[b]).to_f / c
  end
end

puts result

n, m = gets.split.map { |i| i.to_i }
answer = 0.0
weight = gets.split.map{ |i| i.to_i }
m.times do
	x, y, w = gets.split.map{ |i| i.to_i }
	answer = [answer, (weight[x-1] + weight[y-1]) / w.to_f].max
end
puts answer