You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.

The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.

NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.

gets.to_i.times {
  n = gets.to_i
  xs = gets.split.map!(&:to_i).sort

  if n == 2
    puts xs.join(' ')
    next
  end

  best_d = nil
  best_i = nil
  (1...n).each { |i|
    d = (xs[i] - xs[i - 1]).abs
    if !best_d || d < best_d
      best_i = i
      best_d = d
    end
  }

  ys = xs[best_i..] + xs[...best_i]
  puts ys.join(' ')
}


Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.

The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly.  Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly.  All numbers on all lines are separated by single spaces.

On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.

f=->{gets.split.map &:to_i}
n,d=f[]
a,b=f[]
r=(1..n).map{|i|gets(" ").to_i*a+gets.to_i*b}.zip(1..n).sort_by(&:first).take_while{|i|0<=d-=i[0]}
puts r.size,r.map(&:last)*" "

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

w = [*$<].map{|i|t1,t2 = i.split.map(&:to_i); t1*a+t2*b}

x = w.zip(1..n).sort_by(&:first)

s = 0
r = x.take_while{ |i| d >= s += i.first }
puts r.size
puts r.map(&:last)*" "

n, d = gets.split.map(&:to_i)
a, b = gets.split.map(&:to_i)
xys = n.times.map{gets.split.map(&:to_i)}
array = xys.map.with_index{|(x, y), i| [i, x * a + y * b]}.sort_by(&:last)
taken = 0
array = array.take_while do |i, cost|
  flag = taken + cost <= d
  taken += cost
  flag
end
puts array.length
puts array.map(&:first).map{|i| i + 1}.join(" ")

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

w = [*$<].map{|i|t1,t2 = i.split.map(&:to_i); t1*a+t2*b}

x = w.zip(1..n).sort_by(&:first)

s = 0
r = x.take_while{ |i| d > s += i.first }
puts r.size
puts r.map(&:last)*" "

$n,$d = gets.split.map(&:to_i)
a,b = gets.split.map(&:to_i)

$w = [*$<].map{|i|t1,t2 = i.split.map(&:to_i); t1*a+t2*b}

def more i,s,n
    (i...$n).map{ |j|
        next [s,n] if s+$w[j] > $d
        more j+1,s+$w[j],n+[j]
    }.max_by{|i|[i[0],i[1].size]} || [s,n]
end

r = more 0,0,[]
puts r[1].size
puts r[1].map{ |i| i+1 }*" "

$n,$d = gets.split.map(&:to_i)
a,b = gets.split.map(&:to_i)

$w = [*$<].map{|i|t1,t2 = i.split.map(&:to_i); t1*a+t2*b}

def more i,s,n
    (i...$n).map{ |j|
        next [s,n] if s+$w[j] > $d
        more j+1,s+$w[j],n+[j]
    }.max_by(&:first) || [s,n]
end

r = more 0,0,[]
puts r[1].size
puts r[1].map{ |i| i+1 }*" "


The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.

aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are:  Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$  Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$  Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$  Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$

gets.to_i.times do
    res = 'a' * 200
    puts res
    gets.to_i
    gets.split.map(&:to_i).each do |pos|
        res[pos] = res[pos] == 'a' ? 'b' : 'a'
        puts res
    end
end

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  a = gets.chomp.split.map(&:to_i)

  s =  'a' * 100
  puts s
  a.each do |num|
    s = s[0, num] + ((s[num].ord + 1 - 97) % 26 + 97).chr * (100 - num)
    puts s
  end
end

def pin(a)
    a.each do |i|
        print((i%26+97).chr)
    end
    puts ""
end

# a = [1,2,3]
# pin(a)

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split.map(&:to_i)

    a = Array.new(51) {0}
    pin(a)
    arr.each do |x|
        for i in x...51
            a[i] += 1
        end
        pin(a)
    end
end

gets.to_i.times do
    res = 'a' * 200
    puts res
    gets.split.map(&:to_i).each do |pos|
        res[pos] = res[pos] == 'a' ? 'b' : 'a'
        puts res
    end
end

gets.to_i.times do
    res = "a" * 200
    puts res
    gets.to_i.times do
        pos = gets.to_i
        res[pos] = res[pos] == 'a' ? 'b' : 'a'
        puts res
    end
end

gets.to_i.times do
    res = 'a' * 200
    puts res
    gets.split.map(&:to_i).each do |pos|
        pos = gets.to_i
        res[pos] = res[pos] == 'a' ? 'b' : 'a'
        puts res
    end
end


A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is $$$6$$$ because all its substrings are palindromes, and the palindromic count of the string "abc" is $$$3$$$ because only its substrings of length $$$1$$$ are palindromes.You are given a string $$$s$$$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of string $$$s$$$. The second line contains string $$$s$$$ that consists of exactly $$$n$$$ lowercase characters of Latin alphabet.

Print string $$$t$$$, which consists of the same set of characters (and each characters appears exactly the same number of times) as string $$$s$$$. Moreover, $$$t$$$ should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them.

NoteIn the first example, string "ololo" has $$$9$$$ palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string "abccbaghghghgdfd" is $$$29$$$.

num_chars = gets.chomp.to_i
chars = gets.chomp

alphabets = "abcdefghijklmnopqrstuvwxyz"

char_counts = {};

alphabets.each_char {|c| char_counts[c] = 0;}

chars.each_char do |c|
  char_counts[c]  = char_counts[c] + 1;
end

output_string = "";

while (output_string.length != num_chars) do
  sorted_array = char_counts.sort_by {|k,v| v}.reverse

  letter_1 = sorted_array[0][0];
  letter_2 = sorted_array[1][0];
  count_1 = sorted_array[0][1];
  count_2 = sorted_array[1][1];

  output_string += letter_1 * count_1;
  char_counts[letter_1] = 0;

  # if (count_1 > 0)
  #   if (count_1 >= count_2 + 1)
  #     output_string += "#{letter_1}#{letter_2}" * count_2
  #     output_string += letter_1
  #     char_counts[letter_1] -= count_2 + 1
  #     char_counts[letter_2] = 0;
  #   elsif (count_1 == count_2)
  #     output_string += "#{letter_1}#{letter_2}" * count_2
  #     char_counts[letter_1] = 0;
  #     char_counts[letter_2] = 0;
  #   end
  # end
end

puts output_string

num_chars = gets.chomp.to_i
chars = gets.chomp

alphabets = "abcdefghijklmnopqrstuvwxyz"

char_counts = {};

alphabets.each_char {|c| char_counts[c] = 0;}

chars.each_char do |c|
  char_counts[c]  = char_counts[c] + 1;
end

output_string = "";

while (output_string.length != num_chars) do
  sorted_array = char_counts.sort_by {|k,v| v}.reverse

  letter_1 = sorted_array[0][0];
  letter_2 = sorted_array[1][0];
  count_1 = sorted_array[0][1];
  count_2 = sorted_array[1][1];

  if (count_1 > 0)
    if (count_1 >= count_2 + 1)
      output_string += "#{letter_1}#{letter_2}" * count_2
      output_string += letter_1
      char_counts[letter_1] -= count_2 + 1
      char_counts[letter_2] = 0;
    elsif (count_1 == count_2)
      output_string += "#{letter_1}#{letter_2}" * count_2
      char_counts[letter_1] = 0;
      char_counts[letter_2] = 0;
    end
  end
end

puts output_string


The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman

n = gets.to_i
r, w, m, c = [], [], [], []
n.times do
	a, b = gets.split
	case b
		when 'rat'
			r << a
		when 'child'
			w << a
		when 'woman'
			w << a
		when 'man'
			m << a
		when 'captain'
			c << a
	end
end
puts (r + w + m + c) * "\n"

class Person
    attr_accessor :name, :priority, :number
    def initialize(name, type, number)
        @name = name
        @priority = case type
            when "rat" then 0
            when "child", "woman" then 1
            when "man" then 2
            when "captain" then 3
        end
        @number = number
    end
end

n = gets.to_i
h = []

n.times do |number|
    name = gets(" ")
    type = gets.chomp
    h.push(Person.new(name, type, number))
end

h.sort! do |a, b|
    if (a.priority == b.priority)
        a.number <=> b.number
    else
        a.priority <=> b.priority
    end
end

h.each { |e| puts e.name }

name=[]
type=[]
n=gets.to_i
for i in 0..n-1
        input=gets.split
        name.push(input[0])
        type.push(input[1])
end
for i in 0..n-1
        if type[i]=="rat" then
                puts name[i]
        end
end
for i in 0..n-1
        if type[i]=="child" || type[i]=="woman" then
                puts name[i]
        end
end
for i in 0..n-1
        if type[i]=="man" then
                puts name[i]
        end
end
for i in 0..n-1
        if type[i]=="captain" then
                puts name[i]
        end
end

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0
class Matrix;def inspect;empty? ? "Matrix.empty(#{row_size}, #{column_size})":"Matrix[\n#{@rows.map(&:inspect).join("\n")}\n]";end;end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;end
class String;def to_ia;split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

n=geti
s=[]
n.times{
    s<<gets.split(" ")
}
k=[["rat"],["woman","child"],["man"],["captain"]]
for i in 0...4
    for j in 0...n
        if k[i].include?(s[j][1])
            puts s[j][0]
        end
    end
end

gets p
puts %w(rat child|woman man captain).map{|_|$_.scan /(.+) (?:#{_})/}

n = gets.to_i
a = Array.new(n)

a.each_index {|i| a[i] = gets.to_s.split(" ") }

rats       = []
womanchild = []
man        = []
captain    = []

for i in 0..(n-1)
  rats       << a[i][0] if a[i][1] == 'rat'
  womanchild << a[i][0] if(a[i][1] == 'woman') or (a[i][1] == 'child')
  man        << a[i][0] if a[i][1] == 'man'
  captain    << a[i][0] if a[i][1] == 'captain'
end

z = rats + womanchild + man + captain

z.each {|y| puts y}

priorities = [["rat"], ["woman", "child"], ["man"], ["captain"]]
n = gets.to_i
people = []
n.times { people << gets }

priorities.each do |statuses|
  people.each do |line|
    name, status = line.split
    puts name if statuses.include?(status)
  end
end

k = %w(rat child man captain)
gets
(a = readlines.map(&:chomp).map!(&:split).each { |x| x[1] = "child" if x[1] == "woman" }).sort_by {|x| [k.index(x[1]), a.index(x)] }.each { |x| puts x[0] }

k = %w(rat child man captain)
gets
a = readlines.map(&:chomp).map!(&:split).each { |x| x[1] = "child" if x[1] == "woman" }
a.sort_by! {|x| [k.index(x[1]), a.index(x)] }
a.each { |x| puts x[0] }

a=gets.chomp.to_i
a1=[]
a2=[]
a3=[]
a4=""
a.times do
temp=gets.chomp.split(" ")
if temp[1]=="woman" || temp[1]=="child"
a2 << temp[0]
elsif temp[1]=="rat"
a1 << temp[0]
elsif temp[1]=="man"
a3 << temp[0]
else
a4=temp[0]
end
end

puts a1
puts a2
puts a3
puts a4

s = gets(p)
puts %w(rat woman|child man captain).map { |x| s.scan(/(.+) (?:#{x})/) }

k=['rat','child','man','captain']
l=[[],[],[],[]]
1.upto(gets.to_i){m,n=gets.split;k.index(n)==nil ?o=1:o=k.index(n);l[o]<<m }
puts l

gets
data = ARGF.readlines

data.each do |l|
  a = l.split
  puts a[0] if a[1] == 'rat'
end

data.each do |l|
  a = l.split
  puts a[0] if a[1] == 'child' || a[1] == 'woman'
end

data.each do |l|
  a = l.split
  puts a[0] if a[1] == 'man'
end

data.each do |l|
  a = l.split
  puts a[0] if a[1] == 'captain'
end

members = {
    'rat' => [],
    'woman_and_child' => [],
    'man' => [],
    'captain' => [],
}

1.upto(gets.to_i) do
    (name, type) = gets.strip.split(/\s/)

    if ['rat', 'man', 'captain'].include?(type)
        members[type].push(name)
    else
        members['woman_and_child'].push(name)
    end
end

members['rat'].each do |name|
    puts name
end

members['woman_and_child'].each do |name|
    puts name
end

members['man'].each do |name|
    puts name
end

members['captain'].each do |name|
    puts name
end

members = []
for _ in 1..Integer(gets.chomp)
  members << gets.chomp.split
end
grouped = members.inject(Hash.new { |h, k| h[k] = (k == 'child') ? h['woman'] : [] }) { |h, m| h[m[1]] <<= m[0]; h }
%w(rat woman man captain).map.each { |c| puts grouped[c] }

members = []
for _ in 1..Integer(gets.chomp)
  members << gets.chomp.split
end
grouped = members.inject(Hash.new { |h, k| h[k] = (k == 'child') ? h['woman'] : [] }) { |h, m| h[m[1]] <<= m[0]; h }
puts grouped['rat']
puts grouped['woman']
puts grouped['man']
puts grouped['captain']

members = []
for _ in 1..Integer(gets.chomp)
  members << gets.chomp.split
end
grouped = members.inject(Hash.new { |h, k| h[k] = (k == 'child') ? h['woman'] : [] }) { |h, m| h[m[1]] <<= m[0]; h }
%w(rat woman man captain).each { |c| puts grouped[c] }

class Person
    attr_accessor :name, :priority, :number
    def initialize(name, type, number)
        @name = name
        @number = number
        case type
        when "rat"
            @priority = 0
        when "woman", "child"
            @priority = 1
        when "man"
            @priority = 2
        when "captain"
            @priority = 3
        end
    end
end

n = gets.to_i
h = []
n.times do |number|
    name = gets(" ")
    type = gets.chomp
    h.push(Person.new(name, type, number))
end

h.sort! do |a, b|
    if (a.priority == b.priority)
        a.number <=> b.number
    else
        a.priority <=> b.priority
    end
end

h.each{|person| puts person.name}

input = STDIN.read.split("\n").map {|i| i.split}; input.shift

rt, cw, mn, ca,= [], [], [], []

input.each do |i|
	case i.last
	when 'captain'
		ca.push i.first
	when 'man'
		mn.push i.first
	when 'woman'
		cw.push i.first
	when 'child'
		cw.push i.first
	when 'rat'
		rt.push i.first
	end
end

[rt, cw, mn, ca].each.each {|i| puts i}

input = STDIN.read.split("\n").map {|i| i.split}; input.shift

rt, cw, mn, ca,= [], [], [], []

input.each do |i|
	case i.last
	when 'captain'
		ca.push i.first
	when 'man'
		mn.push i.first
	when 'woman', 'child'
		cw.push i.first
	when 'rat'
		rt.push i.first
	end
end

[rt, cw, mn, ca].each.each {|i| puts i}

k = %w(rat child man captain)
gets
readlines.map(&:chomp).map(&:split).each { |x| x[1] = "child" if x[1] == "woman" }.sort_by {|x| k.index(x[1]) }.each do |x|
  puts x[0]
end

t = %w(rat woman|child man captain)
n, a = gets.to_i, []
n.times { a << gets.scan(/\w+/) }
a.sort_by { |x| t.index {|i| i =~ /([|]|^)#{x[1]}/} }.each { |x| puts x[0] }

t = %w(rat child man captain)
gets
a = gets(p).split.sort_by {|x| t.index(/ (\w+)$/)}
p a

class Person
    attr_accessor :name, :priority
    def initialize(name, type)
        @name = name
        case type
        when "rat"
            @priority = 0
        when "woman", "child"
            @priority = 1
        when "man"
            @priority = 2
        when "captain"
            @priority = 3
        end
    end
end

n = gets.to_i
h = []
n.times do
    name = gets(" ")
    type = gets.chomp
    h.push(Person.new(name, type))
end

h.sort! {|a, b| a.priority <=> b.priority}

h.each{|person| puts person.name}


Permutation $$$p$$$ is a sequence of integers $$$p=[p_1, p_2, \dots, p_n]$$$, consisting of $$$n$$$ distinct (unique) positive integers between $$$1$$$ and $$$n$$$, inclusive. For example, the following sequences are permutations: $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. The following sequences are not permutations: $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $$$p$$$ of length $$$n$$$. You don't know this permutation, you only know the array $$$q$$$ of prefix maximums of this permutation. Formally:  $$$q_1=p_1$$$,  $$$q_2=\max(p_1, p_2)$$$,  $$$q_3=\max(p_1, p_2,p_3)$$$,  ...  $$$q_n=\max(p_1, p_2,\dots,p_n)$$$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $$$q$$$ for this permutation is equal to the given array).

The first line contains integer number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ $$$(1 \le n \le 10^{5})$$$ — the number of elements in the secret code permutation $$$p$$$. The second line of a test case contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ $$$(1 \le q_i \le n)$$$ — elements of the array $$$q$$$ for secret permutation. It is guaranteed that $$$q_i \le q_{i+1}$$$ for all $$$i$$$ ($$$1 \le i < n$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, print:   If it's impossible to find such a permutation $$$p$$$, print "-1" (without quotes).  Otherwise, print $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). If there are multiple possible answers, you can print any of them.

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1227/B

n = gets.to_i

n.times do
 size = gets.to_i
 input = gets.split(' ').map(&:to_i)
 used = Array.new(size, false)

 maxi = 0
 min = 0
 output = []
 failed = false

 input.each_with_index do |num, i|
  if num < i + 1
   puts "-1"
   failed = true
   break
  end

  maxi = [maxi, num].max

  if !used[maxi-1]
   output << maxi
   used[maxi-1] = true
  else
   while used[min] == true do min += 1 end
   output << min += 1
  end
 end
 puts output.join(' ') unless failed
end

gets.to_i.times do
  n = gets.to_i
  q = gets.split.map &:to_i
  p = [q[0]]*n
  u = 1
  used = [false]*(n + 1)
  used[q[0]] = true
  (1...n).each do |i|
    if q[i] < i + 1
      p = [-1]
      break
    end
    if q[i] == q[i - 1]
      u += 1 while used[u]
      p[i] = u
      used[u] = true
      u += 1
    else
      p[i] = q[i]
      used[q[i]] = true
    end
  end
  puts p.join ' '
end

gets.to_i.times do
  n = gets.to_i
  q = gets.split.map &:to_i
  p = [q[0]]*n
  u = 1
  used = [false]*(n + 1)
  used[q[0]] = true
  (1...n).each do |i|
    if q[i] < i + 1
      p = [-1]
      break
    end
    if q[i] == q[i - 1]
      u += 1 while used[u]
      p[i] = u
      used[u] = true
      u += 1
    else
      p[i] = q[i]
    end
  end
  puts p.join ' '
end


One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $$$n$$$ machines, and the power of the $$$i$$$-th machine is $$$a_i$$$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $$$x$$$, then choose one machine and reduce the power of its machine by $$$x$$$ times, and at the same time increase the power of one another machine by $$$x$$$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $$$i$$$ and $$$j$$$, and one integer $$$x$$$ such that $$$x$$$ is a divisor of $$$a_i$$$, and change powers as following: $$$a_i = \frac{a_i}{x}$$$, $$$a_j = a_j \cdot x$$$Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — the number of machines. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the powers of the machines.

Print one integer — minimum total power.

NoteIn the first example, the farmer can reduce the power of the $$$4$$$-th machine by $$$2$$$ times, and increase the power of the $$$1$$$-st machine by $$$2$$$ times, then the powers will be: $$$[2, 2, 3, 2, 5]$$$.In the second example, the farmer can reduce the power of the $$$3$$$-rd machine by $$$2$$$ times, and increase the power of the $$$2$$$-nd machine by $$$2$$$ times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is.

require "prime"

class Integer
  def proper_divisors
    return [] if self == 1
    primes = prime_division.flat_map{|prime, freq| [prime] * freq}
    (1...primes.size).each_with_object([1]) do |n, res|
      primes.combination(n).map{ |combi| res << combi.inject(:*)}
    end.flatten.uniq
  end
end

n = gets.strip.to_i
a = gets.strip.split(' ').map(&:to_i).sort
n = a.size
min = a.min

res = []
a.uniq.each do |e|
  divs = e.proper_divisors
  next if divs.size.zero?
  divs.each { |d| res << [e, (e - (e / d)) - (min - (min * d)).abs] }
end

puts a.inject(:+) - (res.size.zero? ? 0 : res.map { |x| x[1] }.max)


Yaroslav likes algorithms. We'll describe one of his favorite algorithms.  The algorithm receives a string as the input. We denote this input string as a.  The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?".  At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates.  Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk >> wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates.  The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.

Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces. Your algorithm will be launched for each of these numbers. The answer will be considered correct if:      Each line will a correct algorithm command (see the description in the problem statement).  The number of commands should not exceed 50.  The algorithm will increase each of the given numbers by one.  To get a respond, the algorithm will perform no more than 200 iterations for each number.


Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up.

First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$.

Print the only integer — maximum possible total time when the lamp is lit.

NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$.

N, M = gets.split.map(&:to_i)
as = [0] + gets.split.map(&:to_i) + [M]

sum1 = Array.new(N+2, 0)
sum2 = Array.new(N+2, 0)

(1..(N+1)).each do |i|
    sum1[i] += sum1[i-1]
    sum2[i] += sum2[i-1]
    if i%2 == 0
        sum1[i] += as[i] - as[i-1]
    else
        sum2[i] += as[i] - as[i-1]
    end
end

ans = sum2[-1]
(1..N).each do |i|
    next if as[i+1] - as[i-1] == 2
    result = sum2[i] - 1 + sum1[N+1] - sum1[i]
    ans = result if ans < result
end
puts ans


Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7).

The first line contains an integer n (2  ≤ n ≤ 105) — the number of tree vertices.  The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.

Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7).


You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).

For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero:  choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$;  choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1260/B

n = gets.to_i

n.times do
 input = gets.split(' ').map(&:to_i)
 a = input.max
 b = input.min

 if b < a/2.0
  puts "NO"
 elsif (a % 3 + b % 3) % 3 == 0
  puts "YES"
 else
  puts "NO"
 end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b = inp
  if(a > 2*b or b > 2*a or (a+b)%3 != 0)
    puts "NO"
    next
  end
  sa = (a-b).abs
  min = [a,b].min
  max = [a,b].max
  a = min - sa
  b = max - sa*2
  if(a != b)
    min = [a,b].min
    max = [a,b].max
    a = min - 1
  end
  if(a%3 == 0)
    puts "YES"
  else
    puts "NO"
  end
end

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1260/B

n = gets.to_i

n.times do
 input = gets.split(' ').map(&:to_i)
 a = input.max
 b = input.min

 if b < a/2.0
  puts "NO"
  break
 end

 if (a % 3 + b % 3) % 3 == 0
  puts "YES"
 else
  puts "NO"
 end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b = inp
  if(a > 2*b or b > 2*a)
    puts "NO"
    exit
  end
  puts ((a+b)%3==0)? "YES" : "NO"
end


You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way.   Initially, you place block $$$1$$$ at $$$(0, 0)$$$.  For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently:   Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.

NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is:   place block $$$1$$$ at position $$$(0, 0)$$$;  place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$;  place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$;  place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$;  place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$;  place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$;  place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$.   The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$:  It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$.

def main
  t = inp.to_i
  t.times do |i|
    n = inp.to_i
    a = mapint(inarr)
    g = Array.new(n) { Array.new(0)}
    n.times do |i|
      g[a[i] - 1].push i
    end

    n.times do |i|
      if g[i].length == 0
        print 0
      else
        len1 = 1
        pre = g[i][0]

        fsk = -1
        1.upto(g[i].length - 1) do |j|
          if (g[i][j] - pre) & 1 == 1
            len1 += 1
            pre = g[i][j]
          else
            if fsk == -1
              fsk = j
            end
          end
        end

        len2 = 1
        if fsk != -1
          pre = g[i][fsk]
          (fsk + 1).upto(g[i].length - 1) do |j|
            if (g[i][j] - pre) & 1 == 1
              len2 += 1
              pre = g[i][j]
            end
          end
        end

        print max(len1, len2)
      end
      print " " if i + 1 != n
    end
    puts ""

  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

def max(a, b)
  (a > b)? a:b
end

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

main


You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.

Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains two even integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 50$$$) — the height and width of the binary matrix, respectively.

For each test case, print $$$n$$$ lines, each of which contains $$$m$$$ numbers, equal to $$$0$$$ or $$$1$$$ — any binary matrix which satisfies the constraints described in the statement. It can be proven that under the given constraints, an answer always exists.

NoteWhite means $$$0$$$, black means $$$1$$$. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case

step = ->xs {
  y = xs.map { |x| x + x.reverse }
  y + y.reverse
}

matrix = [[1, 0], [0, 1]]
5.times do
  matrix = step[matrix]
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  puts matrix.take(n).map { |row| row.take(m).join(" ") }.join("\n")
end

t = gets.to_i
t.times {
  r, c = gets.split.map &:to_i
  for p in (0...r/2)
    stuff = []
    stuff2 = []
    for q in (0...c/2)
      parity = (p + q) % 2
      stuff.push(parity)
      stuff.push((parity + 1) % 2)
      stuff2.push((parity + 1) % 2)
      stuff2.push(parity)
    end
    puts stuff.join(" ")
    puts stuff2.join(" ")
  end
}


After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.

The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000). The i-th of the next (m + 1) lines contains a single integer xi (1 ≤ xi ≤ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.

Print a single integer — the number of Fedor's potential friends.

def byte_count(num = 0)
  c = 0
  while true
    if (num - (num.div(2) * 2)) == 1
      c += 1
    end
    num = num.div(2)
    if num < 2
      c += 1
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

n, m, k = gets.chomp.split(' ').map {|x| x.to_i}
arr = []
(m).times do
  arr << gets.chomp.to_i
end
fedor = gets.chomp.to_i
total = 0
arr.each do |x|
  s = (fedor ^ x).to_s(2)
  count = 0;
  (0...s.length).each { |i| count += 1 if s[i]=='1' }
  total += 1 if count<=k
end
puts total

#!/usr/bin/ruby

n, m, k = STDIN.readline.split.map {|s| s.to_i }
players = []
m.times { players.push STDIN.readline.to_i }
fedor = STDIN.readline.to_i
count = 0
players.each do |player|
	bits = (player ^ fedor)
	diff = 0
	while bits != 0
		diff += (bits & 1)
		bits >>= 1
	end
	count += 1 if diff <= k
end
puts count

n,m,k=gets.chomp.split.map(&:to_i)
ar,ans=[],0
(m+1).times {ar<<gets.to_i}
for i in 0...m do
	a,b,c=ar[i],ar[m],0
	while a>0 || b>0
		c+=1 if a&1 != b&1
		a/=2
		b/=2
	end
	ans+=1 if c<=k
end
puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i
end

fedor = STDIN.gets.chomp.to_i

xs.each do |x|
  xor = x ^ fedor
  ans += 1 if xor.to_s(2).split(//).select{|e| e == "1"}.count <= k
end

puts ans

input = STDIN.read.split("\n")
n, m, k = *input[0].split(' ').map(&:to_i)
players = input[1..m].map(&:to_i)
fedya = input[m + 1].to_i

print players[0..m].count { |p| (p ^ fedya).to_s(2).chars.map(&:to_i).inject(:+) <= k }

n, m, k = gets.strip.split(" ").map(&:to_i)
armies = []
(m + 1).times do |i|
  armies[i] = gets.strip.to_i
end
# puts armies
number_of_friends = 0
m.times do |i|
  num = armies[i] ^ armies[m]
  # puts num.to_s(2)
  count = 0
  while num != 0 do
    count += 1 if num & 1 == 1
    num = num >> 1
    # puts num.to_s(2)
  end
  number_of_friends += 1 if count <= k
end
puts number_of_friends

#http://codeforces.com/contest/467/B

n,m, k = gets.split.map(&:to_i)
arr = []
m.times do
  arr += [gets.to_i]
end
fedor = gets.to_i
 ans =0
arr.each  do |val|
  bits= fedor ^ val             # to find  how much differences are there.....
  if bits.to_s(2).count('1') <= k  # counting 1 shows how much the two bits differ .....
    ans +=1
  end
end

p ans

n,m,k = gets.split
arr=[];
while a=gets do
	arr.push(a.to_i)
end
c=arr.pop
A=0
arr.each{|x| A=A+(((x^c).to_s(2).count('1') > k.to_i)?'0':'1').to_i}
puts A

n,m,k=gets.split.map{|e| e.to_i}
arr=[]
m.times{
	arr<<gets.to_i
}
r=gets.to_i
puts arr.count{|e|
	e1=e^r
	e1.to_s(2).scan("1").count<=k
}

n, m, k = gets.split.map(&:to_i)
a = m.times.map{ gets.to_i.to_s(2)}
f = gets.to_i.to_s(2)
r = 0
a.each do |s|
	c = 0
	1.upto([f.length,s.length].max) do |i|
		if s[-i] == '1' and f[-i] != s[-i]
			c += 1
		elsif f[-i] == '1' and s[-i] != f[-i]
			c += 1
		end
	end
	if c <= k
		r += 1
	end
end
puts r

s=gets.chomp.to_s
s=s.split(" ")
n=s[0].to_i
m=s[1].to_i
k=s[2].to_i
a = Array.new(m+1)
(m+1).times{ |iter|
	a[iter]=gets.chomp.to_i
}
i=0
count=0
while i<m
	hold=a[-1]^a[i]
	hold=hold.to_s(2)
	if hold.to_s.count("1")<=k
		count+=1
	end
	i+=1
end
puts (count)

n, m, @k = gets.chomp.split.map { |x| x.to_i }
a = m.times.collect { gets.to_i }
f = gets.to_i
def valid(i)
  i.to_s(2).scan(/1/).length <= @k
end
puts a.select { |x| valid x^f }.length

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i != me[v] }
  if f <= k
    c += 1
  end
end

puts c

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

arr = []

m += 1
m.times do
	n = gets.to_i
	arr << n
end
fedor = arr[-1]
count = 0
(0..m-2).each do |i|
	n = arr[i] ^ fedor
	set = 0
	while n >0
		n &= (n-1)
		set += 1
	end
	count += 1 if set <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i}
me = gets.to_i
ans = 0
a.each do |x|
  ans += 1 if (x ^ me).to_s(2).split("").count('1') <= k
end
puts ans

def nbits(n)
    nb = 0
    while n > 0
        nb += n%2
        n /= 2
    end
    nb
end

n, m, k = gets.split.map{|x| x.to_i}
x = []
(m + 1).times{x << gets.to_i}
f = 0
(0..m-1).each{|i| f += 1 if nbits(x[i]^x[m]) <= k}
puts f

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

a = 1.upto(m).map { gets.to_i }
x = gets.to_i

puts a.count { |y| (x ^ y).to_s(2).count('1') <= k }

n, m, k = gets.split.map(&:to_i)
a = (0..m).map { |_| gets.to_i }
puts a[0..-2].select { |x| (x ^ a[-1]).to_s(2).count('1') <= k }.size

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x).to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c <= k
end

puts count

class Players
  attr_reader :x
  def initialize(x)
    @x = x
  end

  def bitnum(i)
    n = 0
    while i > 0
      n += i % 2
      i >>= 1
    end
    return n
  end

  def friend?(k, other)
    return bitnum(@x ^ other.x) <= k
  end
end

n, m, k = gets.split.map(&:to_i)
list = []
m.times do
  list << Players.new(gets.to_i)
end
my = Players.new(gets.to_i)
fnum = 0
list.each do |e|
  if my.friend?(k, e)
    fnum += 1
  end
end
puts fnum

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    if "1" == (num - (num.div(2) * 2)).to_s
      c += 1
    end
    num = num.div(2)
    if num < 2
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    if "1" == (num - (num.div(2) * 2)).to_s + s
      c += 1
    end
    num = num.div(2)
    if num < 2
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    s = (num - (num.div(2) * 2)).to_s + s
    num = num.div(2)
    if num < 2
      s = num.to_s + s
      break
    end
  end

  for i in (0..s.length - 1)
    if s[i] = "1"
      c += 1
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

n,m,k=gets.chomp.split.map(&:to_i)
ar,ans=[],0
(m+1).times {ar<<gets.to_i}
for i in 0...m do
	a,b,c=ar[0],ar[m],0
	while a>0 || b>0
		c+=1 if a%2!=b%2
		a/=2
		b/=2
	end
	ans+=1 if c<=k
end
puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i.to_s(2).split(//).reverse
end

fedor = STDIN.gets.chomp.to_i.to_s(2).split(//).reverse

xs.each do |x|
  kake = fedor & x
  ans += 1 if kake.count <= k
end

puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i.to_s(2).split(//).reverse
end

fedor = STDIN.gets.chomp.to_i.to_s(2).split(//).reverse

xs.each do |x|
  c = [fedor.count, x.count].min
  diff = (fedor.count - x.count).abs
  c.times do |i|
    if fedor[i] != x[i]
      diff += 1
      break
    end
  end
  ans += 1 if diff <= k
end

puts ans

n,m,k = gets.split.map(&:to_i)
a = []
r = 0
(m + 1).times do |i|
	a[i] = gets.to_i
end
0.upto(m - 1) do |i|
	if [ a[m] , a[i] ].max - [ a[m] , a[i]].min <= k
		r += 1
	end
end
p r

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i == me[v] }
  c += 1 if f <= k
end

puts c

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
p me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i != me[v] }
  if f <= k
    c += 1
  end
end

puts c

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].min.times do |i|
    diff += 1 if x[i] != me[i]
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].max.times do |i|
    if (i >= [x.size, me.size].min && (x[i] == 1 || me[i] == 1)) || x[i] != me[i]
      diff += 1
    end
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].max.times do |i|
    diff += 1 if x[i] != me[i]
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].min.times do |i|
    diff += 1 if x[i] != me[i]
  end
  diff += (x.size - me.size).abs
  ans += 1 if diff <= k
end
puts ans

def nbits(n)
    nb = 0
    while n > 0
        nb += n%2
        n /= 2
    end
    nb
end

n, m, k = gets.split.map{|x| x.to_i}
x = []
(m + 1).times{x << gets.to_i}
f = 0
(0..m-1).each{|i| f += 1 if n - nbits(x[i]&x[m]) <= k}
puts f

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")
xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x)
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  break
  count += 1 if c < k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x)
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  break
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x).to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c < k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max

x = x.split("")
xs.map! do |r|
  r.split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x) & i
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
(m).times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end
x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")

xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")
xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count


Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":   cells are numbered starting from one;  cells are numbered from left to right by columns, and inside each column from top to bottom;  number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows":   cells are numbered starting from one;  cells are numbered from top to bottom by rows, and inside each row from left to right;  number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number $$$x$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.

For each test case, output the cell number in the numbering "by rows".

t = gets().to_i
while(t!=0)
  ar = gets.chomp.split().map { |e| e.to_i  }
  n = ar[0]
  m = ar[1]
  x = ar[2]
  x-=1
  col = (x/n).to_i
  row = x%n
  ans = row*m + col + 1
  puts "#{ans}\n"
  t-=1
end

def solve_case
  n, m, x = gets.chomp.split(' ').map(&:to_i)

  c = (x.to_f / n.to_f).ceil
  r = x - (n * (c - 1))

  row_x = c + (m * (r - 1))
  puts row_x
end

t = gets.chomp.to_i
t.times do
  solve_case
end

def solution(n, m, x)
  x -= 1

  col = x / n
  row = x % n
  row * m + col + 1
end

test_cases = gets.to_i

test_cases.times do |test_case|
  arr = gets.split(' ').map(&:to_i)
  puts solution(arr[0], arr[1], arr[2])
end


You are given three integers $$$a$$$, $$$b$$$, and $$$c$$$. Determine if one of them is the sum of the other two.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 9261$$$) — the number of test cases. The description of each test case consists of three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$0 \leq a, b, c \leq 20$$$).

For each test case, output "YES" if one of the numbers is the sum of the other two, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, $$$1 + 3 = 4$$$.In the second test case, none of the numbers is the sum of the other two.In the third test case, $$$9 + 11 = 20$$$.

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i).sort
  puts array[0] + array[1] == array[2] ? 'YES' : 'NO'
end

t = gets.to_i

t.times do
  a, b, c = gets.split(' ').map(&:to_i)
  puts a + b == c || a + c == b || c + b == a ? 'YES' : 'NO'
end

t=gets.to_i
while t>=1
	a,b,c=gets.split.map(&:to_i)
	if a+b==c
		puts "YES"
	elsif b+c==a
		puts "YES"
	elsif a+c==b
		puts "YES"
	else
		puts "NO"
	end
	t=t-1
end

n=gets.to_i
n.times do
    a=gets.split.map(&:to_i)
    a.sort!
    if a.sum==a[-1]*2
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
  a=gets.split.map(&:to_i).sort
  puts a[0]+a[1]==a[2] ? 'YES' : 'NO'
end

    n = gets.to_i
    n.times do
      array = gets.split(' ').map(&:to_i)
      puts ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3 ? "YES" : "NO"
    end

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i)
  print ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3 ? "YES" : "NO"
end

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i)
  print ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3
end


Alperen has two strings, $$$s$$$ and $$$t$$$ which are both initially equal to "a". He will perform $$$q$$$ operations of two types on the given strings:  $$$1 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$s$$$. In other words, $$$s := s + \underbrace{x + \dots + x}_{k \text{ times}}$$$.  $$$2 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$t$$$. In other words, $$$t := t + \underbrace{x + \dots + x}_{k \text{ times}}$$$. After each operation, determine if it is possible to rearrange the characters of $$$s$$$ and $$$t$$$ such that $$$s$$$ is lexicographically smaller$$$^{\dagger}$$$ than $$$t$$$.Note that the strings change after performing each operation and don't go back to their initial states.$$$^{\dagger}$$$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $$$p$$$ is lexicographically smaller than string $$$q$$$ if there exists a position $$$i$$$ such that $$$p_i < q_i$$$, and for all $$$j < i$$$, $$$p_j = q_j$$$. If no such $$$i$$$ exists, then $$$p$$$ is lexicographically smaller than $$$q$$$ if the length of $$$p$$$ is less than the length of $$$q$$$. For example, $$$\texttt{abdc} < \texttt{abe}$$$ and $$$\texttt{abc} < \texttt{abcd}$$$, where we write $$$p < q$$$ if $$$p$$$ is lexicographically smaller than $$$q$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$q$$$ $$$(1 \leq q \leq 10^5)$$$ — the number of operations Alperen will perform. Then $$$q$$$ lines follow, each containing two positive integers $$$d$$$ and $$$k$$$ ($$$1 \leq d \leq 2$$$; $$$1 \leq k \leq 10^5$$$) and a non-empty string $$$x$$$ consisting of lowercase English letters — the type of the operation, the number of times we will append string $$$x$$$ and the string we need to append respectively. It is guaranteed that the sum of $$$q$$$ over all test cases doesn't exceed $$$10^5$$$ and that the sum of lengths of all strings $$$x$$$ in the input doesn't exceed $$$5 \cdot 10^5$$$.

For each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that $$$s$$$ is lexicographically smaller than $$$t$$$ and "NO" otherwise.

3

5

2 1 aa

1 2 a

2 3 a

1 2 b

2 3 abca

2

1 5 mihai

2 2 buiucani

3

1 5 b

2 3 a

2 4 paiu

NoteIn the first test case, the strings are initially $$$s = $$$ "a" and $$$t = $$$ "a". After the first operation the string $$$t$$$ becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".After the second operation string $$$s$$$ becomes "aaa", and since $$$t$$$ is also equal to "aaa", we can't arrange $$$s$$$ in any way such that it is lexicographically smaller than $$$t$$$, so the answer is "NO".After the third operation string $$$t$$$ becomes "aaaaaa" and $$$s$$$ is already lexicographically smaller than it so the answer is "YES".After the fourth operation $$$s$$$ becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".After the fifth operation the string $$$t$$$ becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that $$$s$$$ is lexicographically smaller than $$$t$$$, so we should answer "YES".

gets.to_i.times do
  q=gets.to_i
  st=Array.new(2) {Hash.new(0)}
  len=Array.new(2,1)
  smin,tmax='a','a'
  2.times {|i| st[i]['a']=1}
  q.times do
    t,k,x=gets.split.map.with_index {|i,j| j==2 ? i.chomp : i.to_i}
    y=Hash.new(0)
    x.each_char {|i| y[i]+=1}
    y.each do |i,j|
      st[t-1][i]+=j*k
      smin=[smin,i].min if t==1
      tmax=[tmax,i].max if t==2
      len[t-1]+=j*k
    end
    if smin<tmax then
      puts 'YES'
    elsif smin>tmax then
      puts 'NO'
    elsif st[0][smin]<st[1][tmax] && len[0]==st[0][smin] then
      puts 'YES'
    elsif st[0][smin]==st[1][tmax] && len[0]==st[0][smin] && len[0]<len[1] then
      puts 'YES'
    else
      puts 'NO'
    end
  end
end


Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?

The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai ( - 105 ≤ xi ≤ 105, xi ≠ 0, 1 ≤ ai ≤ 105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.

Output the maximum number of apples Amr can collect.

NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x =  - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x =  - 2.In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.

def min(a,b)
	if a < b
		return a
	else
		return b
	end
end

def max(a,b)
	if a > b
		return a
	else
		return b
	end
end

n = gets.chomp.to_i

neg_arr = Array.new(100001){0}
pos_arr = Array.new(100001){0}

neg_size = 0
pos_size = 0

n.times do

x,a =  gets.chomp.split.map{|x| x.to_i}

if x < 0
	neg_arr[x*-1] = a
	neg_size+=1
else
	pos_arr[x] = a
	pos_size+=1
end

end
output = 0
if neg_size == pos_size
	(1..100000).each do |i|
	output+=neg_arr[i]
	output+=pos_arr[i]
	end
else

	min = min(neg_size,pos_size)
	max = max(neg_size,pos_size)

	if min == neg_size
		neg_arr.each do |v|
			output+=v
		end
		j = 0
		(1..100000).each do |i|
			if pos_arr[i]!=0
				output+=pos_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	else
		pos_arr.each do |v|
			output+=v
		end
		j = 0
		(1..100000).each do |i|
			if neg_arr[i]!=0
				output+=neg_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	end

end

puts output

#!/usr/bin/ruby
a,b=gets.to_i.times.map{
	gets.split.map(&:to_i)
}.partition{|e|
	e[0]>0
}.map{|e|
	e.sort_by{|f|f[0].abs}
}.sort_by(&:size)
p (a+b[0,a.size+1]).map(&:last).reduce(:+)

n = gets.to_i
pos = {}
neg = {}
n.times do
    arr = gets.split(' ')
    x = arr.first.to_i
    a = arr.last.to_i
    if x < 0
        neg[x.abs] = a
    else
        pos[x] = a
    end
end
t_size = [neg.size, pos.size].min
neg = neg.sort
pos = pos.sort
val = 0
t_size.times do |i|
    val+=neg[i].last
    val+=pos[i].last
end
if neg.size == pos.size
    puts val
else
    if neg.size < pos.size
        puts val+pos[t_size].last
    else
        puts val+neg[t_size].last
    end
end

n = gets.chomp.to_i

plus = []
minus = []
n.times do
  p,v = gets.split.map{ |x| x.to_i }
  minus << [-p,v] if p < 0
  plus << [p,v] if p > 0
end

plus.sort!
minus.sort!

sum = 0
if plus.size >= minus.size
  minus.size.times do |i|
    sum += plus[i][1];
    sum += minus[i][1];
  end
  if plus.size > minus.size
    sum += plus[minus.size][1];
  end
else
  plus.size.times do |i|
    sum += plus[i][1];
    sum += minus[i][1];
  end
  sum += minus[plus.size][1];
end
puts sum

n = gets.chomp.to_i
apples = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

a, b = apples.partition { |e| e.first < 0 }.sort_by(&:size).map do |e|
  e.sort_by! { |e| e.first.abs }
end

puts (a + b[0..a.size]).map(&:last).inject(0, :+)

n = gets.to_i;
arr = Array.new();
ans = 0;

n.times {|x| arr[x] = gets.split.map(&:to_i)};
arr.push([0, 0]);
arr.sort!;
pos = arr.index([0, 0]);

s, e = 0, n;
if (pos > n - pos)
  s = pos - (n - pos) - 1;
elsif (pos < n - pos)
  e = pos + pos + 1;
end
# puts s, e;
(s..e).each {|x| ans += arr[x][1]};
puts ans;

n = gets.to_i
t = (1..n).map{ gets.split.map(&:to_i) }
t.sort_by!{|x, a| x}
i = t.index{|x, a| x > 0}

if i == nil
    p t[-1][1]
elsif i == 0
    p t[0][1]
else
    l_num = i
    r_num = t.size - i
    l_taken = [l_num, r_num+1].min
    r_taken = [r_num, l_num+1].min
    p (t[i-l_taken..i-1] + t[i..i+r_taken-1]).map{|x,a| a}.inject(:+)
end

a=gets.chomp.to_i
negp=[]
posp=[]
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split
0.upto(1) {|i| temp[i]=temp[i].to_i}
if temp[0]<0
negp<<temp
else
posp<<temp
end
ans+=temp[1]
end
negp=negp.sort_by{|x,y|x}
negp.reverse!
posp=posp.sort_by{|x,y|x}

negp.each {|i| neg << i[1]}
posp.each {|i| pos << i[1]}
n=neg.length
p=pos.length

if n==p
puts "#{ans}"
elsif n<p
a=0
(n+1).upto(p-1){|i| a+=pos[i]}
ans=ans-a
puts "#{ans}"
else
a=0
(p+1).upto(n-1){|i| a+=neg[i]}
ans=ans-a
puts "#{ans}"
end

ls=[]
rs=[]
gets.to_i.times{
	x,y=gets.split.map{|e| e.to_i}
	if x<0 then
		ls<<[x,y]
	else
		rs<<[x,y]
	end
}
ls.sort!.reverse!
rs.sort!
ans=0
while ls.empty? ==false && rs.empty? ==false
	ans+=ls.shift[1]+rs.shift[1]
end
ans+=ls.shift[1] if ls.empty? ==false
ans+=rs.shift[1] if rs.empty? ==false
puts ans

l = []
r = []
n = gets.chomp.to_i
n.times do
	pair = gets.chomp.split(" ").map &(lambda { |x| x.to_i })
	r <<= [pair[0], pair[1]] if pair[0] > 0
	l <<= [pair[0], pair[1]] if pair[0] <= 0
end

r.sort!
l.sort! &(lambda { |a,b| b <=> a })

best = 0
for i in 0..1 do
	reachl = 0
	reachr = 0
	score = 0
	left = i == 0
	while (left && reachl != l.size) || (!left && reachr != r.size)
		if !left
			score += r[reachr][1]
			reachr += 1
			left = !left
		else
			score += l[reachl][1]
			reachl += 1
			left = !left
		end
	end
	best = [best, score].max
end
print best

d = gets.to_i.times.map{gets.split.map(&:to_i)}
m = d.select{|a,b| a < 0}.sort
p = d.select{|a,b| a > 0}.sort.reverse
sum = 0
while(m!=[] && p!=[])
    sum += m.pop[1]+p.pop[1]
end
if m!=[]
    sum+=m.pop[1]
end
if p!=[]
    sum+=p.pop[1]
end
p sum

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}.partition{|x| x[0] < 0}.map{|x| x.sort_by{|x| x[0].abs}}
m = [a[0].size, a[1].size].min
puts a[0][0..m].reduce(0){|s, x| s + x[1]} + a[1][0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg.sort.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos.sort[0..m].reduce(0){|s, x| s + x[1]}

def min(a,b)
	if a < b
		return a
	else
		return b
	end
end

def max(a,b)
	if a > b
		return a
	else
		return b
	end
end

n = gets.chomp.to_i

neg_arr = Array.new(100001){0}
pos_arr = Array.new(100001){0}

neg_size = 0
pos_size = 0

n.times do

x,a =  gets.chomp.split.map{|x| x.to_i}

if x < 0
	neg_arr[x*-1] = a
	neg_size+=1
else
	pos_arr[x] = a
	pos_size+=1
end

end
output = 0
if neg_size == pos_size
	(1..100).each do |i|
	output+=neg_arr[i]
	output+=pos_arr[i]
	end
else

	min = min(neg_size,pos_size)
	max = max(neg_size,pos_size)

	if min == neg_size
		neg_arr.each do |v|
			output+=v
		end
		j = 0
		(0..100).each do |i|
			if pos_arr[i]!=0
				output+=pos_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	else
		pos_arr.each do |v|
			output+=v
		end
		j = 0
		(0..100).each do |i|
			if neg_arr[i]!=0
				output+=neg_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	end

end

puts output

# http://codeforces.com/contest/558/problem/A

n = gets.chomp.to_i
apples = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

a, b = apples.partition { |a| a.first < 0 }.sort_by(&:size)
c = a + b[0..a.size]
puts c.map(&:last).inject(0, :+)

n = gets.chomp.to_i
hash = {}
n.times do
  idx, num = gets.chomp.split.map(&:to_i)
  hash[idx] = num
end

min, max = hash.keys.min, hash.keys.max
right, left = [], []
(min..max).each do |idx|
  next unless hash.key?(idx)
  idx < 0 ? left << hash[idx] : right << hash[idx]
end

scores = []
scores << right.inject(0, :+) + left.last unless left.empty?
scores << left.inject(0, :+) + right.first unless right.empty?
scores << right.first if left.empty?
scores << left.last if right.empty?
puts scores.max

a=gets.chomp.to_i
negp=[]
posp=[]
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split
0.upto(1) {|i| temp[i]=temp[i].to_i}
if temp[0]<0
negp<<temp
else
posp<<temp
end
ans+=temp[1]
end
negp.sort!
posp.sort!

negp.each {|i| neg << i[1]}
posp.each {|i| pos << i[1]}
n=neg.length
p=pos.length

if n==p
puts "#{ans}"
elsif n<p
a=0
(n+1).upto(p-1){|i| a+=pos[i]}
ans=ans-a
puts "#{ans}"
else
a=0
(p+1).upto(n-1){|i| a+=neg[i]}
ans=ans-a
puts "#{ans}"
end

a=gets.chomp.to_i
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split(" ")
if temp[0].to_i<0
neg << temp[1].to_i
elsif temp[0].to_i>0
pos << temp[1].to_i
else
ans+=temp[1].to_i
end
end
l=neg.length
b=pos.length
if l<b
0.upto(l-1) {|i| ans=ans+neg[i]}
0.upto(l) {|i| ans=ans+pos[i]}
puts "#{ans}"
elsif b<l
0.upto(b-1) {|i| ans=ans+pos[i]}
0.upto(b) {|i| ans=ans+neg[i]}
puts "#{ans}"
else
0.upto(b-1) {|i| ans=ans+pos[i]}
0.upto(b-1) {|i| ans=ans+neg[i]}

puts "#{ans}"

end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
p neg.sort.reverse , pos.sort
puts neg.sort.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos.sort[0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos[0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg[0..m].reduce(0){|a, b| a + b[1]} + pos[0..m].reduce(0){|a, b| a + b[1]}


In a far away galaxy there are n inhabited planets, numbered with numbers from 1 to n. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number 1 a hyperdrive was invented. As soon as this significant event took place, n - 1 spaceships were built on the planet number 1, and those ships were sent to other planets to inform about the revolutionary invention. Paradoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of s hyperyears in s years).When the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make n - 2 identical to it ships with a hyperdrive and send them to other n - 2 planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new n - 2 ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues.However the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy!Your task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet.

The first line contains a number n (3 ≤ n ≤ 5000) — the number of inhabited planets in the galaxy. The next n lines contain integer coordinates of the planets in format "xi yi zi" ( - 104 ≤ xi, yi, zi ≤ 104).

Print the single number — the solution to the task with an absolute or relative error not exceeding 10 - 6.

class Star
	def initialize(x, y, z)
		@x = x
		@y = y
		@z = z
	end
	def setzero(zs)
		@zero = distance(zs)
	end
	def distance(s)
		Math.sqrt((@x-s.x)*(@x-s.x)+(@y-s.y)*(@y-s.y)+(@z-s.z)*(@z-s.z))
	end
	attr_accessor :x, :y, :z, :zero
end

n = gets.chomp.to_i
stars = Array.new
for i in 0..n-1
	ar = gets.chomp.split(/ /).map!{|x| x.to_i}
	stars.push(Star.new(ar[0],ar[1],ar[2]))
	szero = stars[0] if i == 0
	stars[i].setzero(szero)
end

stars.sort!{|a,b| a.zero <=> b.zero}

ret = -1
for i in 2..n-1
	break if ret >= 0 && stars[i].zero > ret
	for j in 1..i-1
		wk = stars[i].zero + stars[j].zero
		break if ret >= 0 && wk > ret
		wk += stars[i].distance(stars[j])
		if ret < 0
			ret = wk
		else
			ret = [ret,wk].min
		end
	end
end

puts ret/2.0

class Star
	def initialize(x, y, z)
		@x = x
		@y = y
		@z = z
	end
	def setzero(zs)
		@zero = distance(zs)
	end
	def distance(s)
		Math.sqrt((@x-s.x)*(@x-s.x)+(@y-s.y)*(@y-s.y)+(@z-s.z)*(@z-s.z))
	end
	attr_accessor :x, :y, :z, :zero
end

n = gets.chomp.to_i
stars = Array.new
for i in 0..n-1
	ar = gets.chomp.split(/ /).map!{|x| x.to_i}
	stars.push(Star.new(ar[0],ar[1],ar[2]))
	szero = stars[0] if i == 0
	stars[i].setzero(szero)
end

stars.sort!{|a,b| a.zero <=> b.zero}

ret = -1
for i in 2..n-2
	break if ret >= 0 && stars[i].zero > ret
	for j in 1..i-1
		wk = stars[i].zero + stars[j].zero
		break if ret >= 0 && wk > ret
		wk += stars[i].distance(stars[j])
		if ret < 0
			ret = wk
		else
			ret = [ret,wk].min
		end
	end
end

puts ret/2.0


You are given a string $$$s$$$ of lowercase Latin letters. The following operation can be used:   select one character (from 'a' to 'z') that occurs at least once in the string. And replace all such characters in the string with the previous one in alphabetical order on the loop. For example, replace all 'c' with 'b' or replace all 'a' with 'z'. And you are given the integer $$$k$$$ — the maximum number of operations that can be performed. Find the minimum lexicographically possible string that can be obtained by performing no more than $$$k$$$ operations.The string $$$a=a_1a_2 \dots a_n$$$ is lexicographically smaller than the string $$$b = b_1b_2 \dots b_n$$$ if there exists an index $$$k$$$ ($$$1 \le k \le n$$$) such that $$$a_1=b_1$$$, $$$a_2=b_2$$$, ..., $$$a_{k-1}=b_{k-1}$$$, but $$$a_k < b_k$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. This is followed by descriptions of the test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^9$$$) — the size of the string $$$s$$$ and the maximum number of operations that can be performed on the string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.  It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output the lexicographically minimal string that can be obtained from the string $$$s$$$ by performing no more than $$$k$$$ operations.

4

3 2

cba

4 5

fgde

7 5

gndcafb

4 19

ekyv

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  s = gets.chomp.bytes.map { |c| c.ord - 97 }
  if max = s.take_while { |c| c <= k }.max
    0.upto(s.size - 1).each do |i|
      s[i] = 0 if s[i] <= max
    end
    k -= max
  end
  if i = s.find_index { |c| c > 0 }
    c = s[i]
    min = s[i] = s[i] - k
    (i + 1).upto(s.size - 1).each do |i|
      s[i] = min if s[i] <= c && s[i] >= min
    end
  end
  0.upto(s.size - 1).each do |i|
    s[i] += 97
  end
  puts s.pack("C*")
end


You are given two positive integers $$$n$$$ and $$$s$$$. Find the maximum possible median of an array of $$$n$$$ non-negative integers (not necessarily distinct), such that the sum of its elements is equal to $$$s$$$.A median of an array of integers of length $$$m$$$ is the number standing on the $$$\lceil {\frac{m}{2}} \rceil$$$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $$$1$$$. For example, a median of the array $$$[20,40,20,50,50,30]$$$ is the $$$\lceil \frac{m}{2} \rceil$$$-th element of $$$[20,20,30,40,50,50]$$$, so it is $$$30$$$. There exist other definitions of the median, but in this problem we use the described definition.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with two integers $$$n$$$ and $$$s$$$ ($$$1 \le n, s \le 10^9$$$) — the length of the array and the required sum of the elements.

For each test case print a single integer — the maximum possible median.

NotePossible arrays for the first three test cases (in each array the median is underlined):  In the first test case $$$[\underline{5}]$$$  In the second test case $$$[\underline{2}, 3]$$$  In the third test case $$$[1, \underline{2}, 2]$$$

t = gets.to_i
t.times do

n, s = gets.split.map!(&:to_i)

nh = n / 2
x = s / (nh + 1)

puts x

end


Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.

For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.

NoteLet's consider the test cases of the example:  $$$n=8$$$, $$$k=3$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$;  during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$.   $$$n=6$$$, $$$k=6$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$.   $$$n=7$$$, $$$k=1$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$;  during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$;  during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$;  during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.

def solve()
  n, k = ints
  m = 1
  t = 0
  # until >= k
  while m <= k
    m *= 2
    t += 1
  end
  t += (n - m + k - 1) / k
  t
end

def main
  t = int
  t.times do
    puts solve
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def rep(n, &b); Array.new(n, &b) end
def yes; puts YESNO[1] end
def no; puts YESNO[0] end
def yesno t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * mod_inv(y, mod) % mod end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main


Вася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.

В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей. Во второй строке следует последовательность из 2n целых положительных чисел a1, a2, ..., a2n (1 ≤ ai ≤ 100 000) — длины частей ножек стола в произвольном порядке.

Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.

#!/usr/bin/env ruby

n = gets.to_i
nums = gets.split(' ').map { |item| item.to_i }
avg = nums.inject(:+)/n
for i in 0..2*n-2
  if !nums[i].nil? then
    for j in 1..2*n-1
      if i != j and !nums[i].nil? and !nums[j].nil? and nums[i] + nums[j] == avg then puts nums[i].to_s+" "+nums[j].to_s; nums[i] = nil; nums[j] = nil end
    end
  end
end

#!/usr/bin/env ruby

n = gets.to_i
nums = gets.split(' ').map { |item| item.to_i }
avg = nums.inject(:+)/n
for i in 0..2*n-2
  for j in 1..2*n-1
    if !nums[i].nil? and !nums[j].nil? and nums[i] + nums[j] == avg then puts nums[i].to_s+" "+nums[j].to_s; nums[i] = nil; nums[j] = nil end
  end
end

#!/usr/bin/env ruby

n = gets.to_i
nums = gets.split(' ').map { |item| item.to_i }
avg = nums.inject(:+)/n
for i in 0..2*n-2
  for j in 0..2*n-1
    if !nums[i].nil? and !nums[j].nil? and nums[i] + nums[j] == avg then puts nums[i].to_s+" "+nums[j].to_s; nums[i] = nil; nums[j] = nil end
  end
end


The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:  employee ::= name. | name:employee1,employee2, ... ,employeek.  name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.

The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.

Print a single number — the number of uncomfortable situations in the company.

def gao()
	s = $a.slice!(/\w*/)
	$c += $*.count(s)
	$* << s
	if $a.slice!(0) == ':'
		gao()
		gao() while $a.slice!(0) == ','
	end
	$*.pop
end

$a, $c = gets, 0
gao()
p $c