Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where  is equal to 1 if some ai = 1, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.

The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).

In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.

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

b = []
a = Array.new(m) {Array.new(n)}
correct_b = Array.new(m) {Array.new(n, 0)}

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

b.each_with_index do |arr, i|
  arr.each_with_index do |el, j|
    if el == 0
      m.times {|line| a[line][j] = 0}
      n.times {|col| a[i][col] = 0}
    end
  end
end

is_correct = true

m.times do |i|
  n.times do |j|
    unless a[i][j]
      a[i][j] = 1

      m.times {|line| correct_b[line][j] = 1 }
      n.times {|col| correct_b[i][col] = 1  }
    end
  end
end

m.times do |i|
  break unless is_correct
  n.times do |j|
    if b[i][j] != correct_b[i][j]
      is_correct = false
      break
    end
  end
end

if is_correct
  puts 'YES'
  a.each {|k| puts k.join(' ')}
else
  puts 'NO'
end

# puts
# correct_b.each {|k| puts k.join(' ')}

row_num, col_num = STDIN.readline.split.map {|s| s.to_i }
b = []
row_num.times do
	b.push(STDIN.readline.split.map {|s| s.to_i })
end

or_row = row_num.times.map { 1 }
or_col = col_num.times.map { 1 }

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 0
			or_row[r] = 0
			or_col[c] = 0
		end
	end
end

if or_row.inject(:+) == 0
	col_num.times {|c| or_col[c] = 0 }
end
if or_col.inject(:+) == 0
	row_num.times {|r| or_row[r] = 0 }
end

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 1
			if or_row[r] == 0 and or_col[c] == 0
				puts 'NO'
				exit
			end
		end
	end
end

a = row_num.times.map { col_num.times.map { 1 } }
or_row.each_with_index do |x, r|
	col_num.times { |c| a[r][c] = 0 } if x == 0
end
or_col.each_with_index do |x, c|
	row_num.times { |r| a[r][c] = 0 } if x == 0
end

puts 'YES'
row_num.times {|r| puts a[r].join ' ' }

row_num, col_num = STDIN.readline.split.map {|s| s.to_i }
b = []
row_num.times do
	b.push(STDIN.readline.split.map {|s| s.to_i })
end

or_row = row_num.times.map { 1 }
or_col = col_num.times.map { 1 }

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		or_row[r] = or_col[c] = 0 if x == 0
	end
end

if or_row.inject(:+) == 0
	col_num.times {|c| or_col[c] = 0 }
end
if or_col.inject(:+) == 0
	row_num.times {|r| or_row[r] = 0 }
end

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 1 and or_row[r] == 0 and or_col[c] == 0
			puts 'NO'
			exit
		end
	end
end

a = row_num.times.map { col_num.times.map { 1 } }
or_row.each_with_index do |x, r|
	col_num.times { |c| a[r][c] = 0 } if x == 0
end
or_col.each_with_index do |x, c|
	row_num.times { |r| a[r][c] = 0 } if x == 0
end

puts 'YES'
row_num.times {|r| puts a[r].join ' ' }

r,c=gets.chomp.split.map(&:to_i)
a,b,fr,fc,dr,dc=Array.new(r,0),Array.new(c,0),0,0,0,0
r.times do |i|
	x=gets.chomp.split.map(&:to_i)
	x.each_index do |j|
		if x[j]==1
			a[i]+=1
			b[j]+=1
		end
	end
end
=begin
print a
puts
print b
puts
=end
r.times { |i| (a[i]==c) ? fr+=1 : dr+=a[i] }
c.times { |i| (b[i]==r) ? fc+=1 : dc+=b[i] }
#puts "#{dr} #{dc} #{fr} #{fc} #{r} #{c}"
if (dr!=(r-fr)*fc)||(dc!=(c-fc)*fr)||(fr==0&&fc!=0)||(fr!=0&&fc==0)
	puts "NO"
else
	puts "YES"
	r.times do |i|
		c.times do |j|
			print (a[i]==c && b[j]==r) ? "1 " : "0 "
		end
		puts
	end
end

M, N = gets.split.map(&:to_i)
val = []
M.times{|m|
    val[m] = gets.split.map(&:to_i).map{|i| i==1}
}

Mallone = []
M.times{|m|
    Mallone[m] = true
    N.times{|n|
        Mallone[m] &= (val[m][n])
       # puts "Mallone[#{m}]=#{Mallone[m]}"
    }
}

Nallone = []
N.times{|n|
    Nallone[n] = true
    M.times{|m|
        Nallone[n] &= (val[m][n])
       # puts "Nallone[#{n}]=#{Nallone[n]}"
    }
}

result = []
M.times{|m|
    result[m] = []
    N.times{|n|
        result[m][n] = false
    }
}

M.times{|m|
    if Mallone[m]
        flag = false
        N.times{|n|
            if Nallone[n]
                flag = true
                result[m][n] = true
            end
        }
        if !flag
            puts "NO"
            exit 0
        end
    else
        N.times{|n|
            if val[m][n]
                if ! Nallone[n]
                    puts "NO"
                    exit 0
                end
            end
        }
    end
}

N.times{|n|
    if Nallone[n]
        flag = false
        M.times{|m|
            if Mallone[m]
                flag = true
                result[m][n] = true
            end
        }
        if !flag
            puts "NO"
            exit 0
        end
    else
        M.times{|m|
            if val[m][n]
                if ! Mallone[m]
                    puts "NO"
                    exit 0
                end
            end
        }
    end
}
puts "YES"
M.times{|m|
    puts result[m].map{|b| (b&&1||0)}.join(" ")
}

def make_zero(i,j,n,m)
	@arr[i] = Array.new(m,0)
	(0..(n-1)).each do |row|
		@arr[row][j] = 0
	end
end

def calc(i,j,n,m)
	row_or = @arr[i].inject(0,&:|)
	col_or = 0
	(0..(n-1)).each do |row|
		col_or |= @arr[row][j]
	end
	row_or | col_or
end

n,m = gets.split(" ").map(&:to_i)
b_arr = []
@arr = []
n.times do
	b_arr << gets.split(" ").map(&:to_i)
	@arr << Array.new(m,1)
end

n.times do |i|
	m.times do |j|
		make_zero(i,j,n,m) if b_arr[i][j] ==0
	end
end

@new_arr = []
n.times do |i|
	@new_arr << []
	m.times do |j|
		@new_arr[i][j] = calc(i,j,n,m)
	end
end
# puts "#{@arr}"
# puts "barr #{b_arr}"
# puts "new #{@new_arr}"
if b_arr == @new_arr
	puts "YES"
	@arr.each do |a|
		puts a.join(" ")
	end
else
	puts "NO"
end

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

n, m = read_line
a, b = [], []

n.times {
  a << Array.new(m,1)
  b << read_line
}

n.times { |i|
  a[i] = Array.new(m, 0) if b[i].include? 0
}

m.times { |j|
  a.each { |x| x[j] = 0 } if (0...n).map { |i| b[i][j] }.include? 0
}

c = Array.new(n)
n.times { |i|
  c[i] = Array.new(m)
  m.times { |j|
    c[i][j] = (a[i] + (0...n).map { |k| a[k][j] }).inject { |x, y| x|y }
  }
}

if c == b
	puts 'YES'
	a.each { |x|
		puts x*' '
	}
else
	puts 'NO'
end

# 486B

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

m, n = read_line
a, b = [], []
m.times {
  a << Array.new(n, 1)
  b << read_line
}

m.times { |i|
  a[i] = Array.new(n, 0) if b[i].include? 0
}

n.times { |j|
  a.each { |x| x[j] = 0 } if (0...m).map { |i| b[i][j] }.include? 0
}

c = Array.new(m)
m.times { |i|
  c[i] = Array.new(n)
  n.times { |j|
    c[i][j] = (a[i] + (0...m).map { |k| a[k][j] }).inject { |x, y| x | y }
  }
}

if c == b
  puts 'YES'
  a.each { |x|
    puts x * ' '
  }
else
  puts 'NO'
end

row_num, col_num = STDIN.readline.split.map {|s| s.to_i }
b = []
row_num.times do
	b.push(STDIN.readline.split.map {|s| s.to_i })
end

or_row = row_num.times.map { 1 }
or_col = col_num.times.map { 1 }

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 0
			or_row[r] = 0
			or_col[c] = 0
		end
	end
end

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 1
			if or_row[r] == 0 and or_col[c] == 0
				puts 'NO'
				exit
			end
		end
	end
end

if row_num >= col_num and or_row.inject(:+) == 0
	col_num.times {|c| or_col[c] = 0 }
end
if col_num >= row_num and or_col.inject(:+) == 0
	row_num.times {|r| or_row[r] = 0 }
end

a = row_num.times.map { col_num.times.map { 1 } }
or_row.each_with_index do |x, r|
	col_num.times { |c| a[r][c] = 0 } if x == 0
end
or_col.each_with_index do |x, c|
	row_num.times { |r| a[r][c] = 0 } if x == 0
end

puts 'YES'
row_num.times {|r| puts a[r].join ' ' }

row_num, col_num = STDIN.readline.split.map {|s| s.to_i }
b = []
row_num.times do
	b.push(STDIN.readline.split.map {|s| s.to_i })
end

or_row = row_num.times.map { 1 }
or_col = col_num.times.map { 1 }

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 0
			or_row[r] = 0
			or_col[c] = 0
		end
	end
end

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 1
			if or_row[r] == 0 and or_col[c] == 0
				puts 'NO'
				exit
			end
		end
	end
end

a = row_num.times.map { col_num.times.map { 1 } }
or_row.each_with_index do |x, r|
	col_num.times { |c| a[r][c] = 0 } if x == 0
end
or_col.each_with_index do |x, c|
	row_num.times { |r| a[r][c] = 0 } if x == 0
end

puts 'YES'
row_num.times {|r| puts a[r].join ' ' }

row_num, col_num = STDIN.readline.split.map {|s| s.to_i }
b = []
row_num.times do
	b.push(STDIN.readline.split.map {|s| s.to_i })
end

or_row = row_num.times.map { 1 }
or_col = col_num.times.map { 1 }

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 0
			or_row[r] = 0
			or_col[c] = 0
		end
	end
end

if row_num >= col_num and or_row.inject(:+) == 0
	col_num.times {|c| or_col[c] = 0 }
end
if col_num >= row_num and or_col.inject(:+) == 0
	row_num.times {|r| or_row[r] = 0 }
end

b.each_with_index do |row, r|
	row.each_with_index do |x, c|
		if x == 1
			if or_row[r] == 0 and or_col[c] == 0
				puts 'NO'
				exit
			end
		end
	end
end

a = row_num.times.map { col_num.times.map { 1 } }
or_row.each_with_index do |x, r|
	col_num.times { |c| a[r][c] = 0 } if x == 0
end
or_col.each_with_index do |x, c|
	row_num.times { |r| a[r][c] = 0 } if x == 0
end

puts 'YES'
row_num.times {|r| puts a[r].join ' ' }


While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

#!/usr/bin/ruby
a,b=$<.map &:chomp
p a==b ? -1 : [a.size,b.size].max

a = gets.chomp
b = gets.chomp
if a == b
  puts -1
else
  puts [a, b].map(&:length).max
end

a = gets.chomp()
b = gets.chomp()

if a == b
  puts "-1"
elsif a.size > b.size
  puts a.size
else
  puts b.size
end

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end
def p(*arg); puts "DEBUG: " + arg.to_s if TEST_MODE; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

# actual codes here

def solve(input, output)
  a, b = input[0], input[1]
  if a == b
    output << "-1"
  elsif a.length == b.length
    output << a.length
  else
    output << [a.length, b.length].max.to_s
  end
end

tests do
  # test cases
  t(["abcd", "defgh"], "5")
  t(["a", "a"], "-1")
  t(["abc", "b"], "3")
  t(["abcde", "acde"], "5")
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE

a = gets.strip
b = gets.strip
if a == b
    puts "-1"
else
    puts [a.length, b.length].max
end

def f(a,b)
	p1=0
	p2=0
	while p1<b.size && p2<a.size
		if a[p2]==b[p1] then
			p1+=1
		end
		p2+=1
	end
	return p1
end
a=gets.chomp
b=gets.chomp
b1=f(a,b)
a1=f(b,a)

if b1==b.size && a1==a.size then
	puts -1
else
	puts [a.size,b.size].max
end

a=gets.chomp
b=gets.chomp
n=a.size
m=b.size

if a==b
    puts -1
else
    puts [n, m].max
end

first = gets.chop
second = gets.chop
last_name = "asdsad"

if first == second
        print "-1"
    else
        print [first.length, second.length].max
    end

while !STDIN.eof? && (string1 = STDIN.readline.strip) && (string2 = STDIN.readline.strip)
  if string1 == string2
    puts "-1"
  else
    puts [string1.length, string2.length].max
  end
end

# coding: utf-8

# if __FILE__ == $0
# end

s1 = gets.chomp
s2 = gets.chomp

if s1 == s2
    puts -1
else
    puts [s1.length, s2.length].max
end

module Memoizer
  def memoize(methodname)
    raise ArgumentError, "statefull method [#{methodname}]should not be memoized" if methodname.match(/\!\z/)
    unbound_method = instance_method(methodname)
    raise ArgumentError, "method [#{methodname}] with argument cannot be memoized" if unbound_method.arity > 0
    memoized_object_name = "@_memoized_#{methodname}"
    define_method(methodname) do
      if(instance_variable_get(memoized_object_name).nil?)
        instance_variable_set(memoized_object_name, unbound_method.bind(self).call)
      end
      instance_variable_get(memoized_object_name)
    end
  end
end

class Problem
  attr_reader(:a, :b)
  def initialize(a, b)
    @a = a
    @b = b
  end

  def ans
    return -1 if a == b
    return [a.length, b.length].max
  end

  def print!
    puts(ans)
  end
end

a = gets.strip
b = gets.strip
Problem.new(a, b).print!

a = gets.chomp
b = gets.chomp

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

if a == b
	puts -1
else
	puts max(a.size, b.size)
end

#!/usr/bin/ruby

a = gets.chomp
b = gets.chomp

if a.size > b.size then
	puts a.size
elsif a.size < b.size then
	puts b.size
elsif a == b then
	puts -1
else
	puts a.size
end

#!/usr/bin/env ruby

a = gets.strip
b = gets.strip

a_size = a.size
b_size = b.size

cmp = a_size <=> b_size
if cmp == 1
  puts a_size
elsif cmp == -1
  puts b_size
elsif a == b
  puts -1
else
  puts a_size
end

exit 0

x = gets.chomp
y = gets.chomp
res = x != y ? (x.size < y.size ? y.size : x.size) : -1
puts res

a = gets.chop
b = gets.chop
if a == b
  puts -1
else
  puts [a.size, b.size].max
end

a = gets.strip
b = gets.strip
n = [a.length, b.length].max
ans = count = 0
n.times do |i|
    if a[i] != b[i]
        count += 1
    else
        count = 0
    end
    ans = [ans, count].max
end
ans = -1 if ans == 0
puts ans

a=gets.chomp
b=gets.chomp

p1=0
p2=0

while p1<b.size && p2<a.size
	if a[p2]==b[p1] then
		p1+=1
	end
	p2+=1
end
if p1==b.size then
	puts -1
else
	puts b.size
end

x = gets.chomp
y = gets.chomp
res = x != y ? (x.size < y.size ? y : x) : -1
puts res


In the pet store on sale there are:  $$$a$$$ packs of dog food;  $$$b$$$ packs of cat food;  $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \le a,b,c,x,y \le 10^8$$$).

For each test case in a separate line, output:   YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats;  NO else.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

t=gets.chomp.to_i
t.times do
    s= gets.chomp.split
    a=s[0].to_i
    b=s[1].to_i
    c=s[2].to_i
    x=s[3].to_i
    y=s[4].to_i
    ax = (a-x)
    by = (b-y)
    if(a>=x)
        summaA = 0
    else
        summaA=a-x
    end
    if(b>=y)
        summaB=0
    else
        summaB=b-y
    end
    summa = summaA+summaB+c
    if(summa>=0)
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
  a, b, c, x, y = gets.split.map(&:to_i)
  x = [x - a, 0].max
  y = [y - b, 0].max
  puts x + y <= c ? "YES" : "NO"
end


Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation:   Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \leq k \leq n$$$ and any sequence of $$$k$$$ indices $$$1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$$$ such that $$$s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$$$.  Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\ldots$$$ and swap $$$s_{i_{\lfloor k/2 \rfloor}}$$$ with $$$s_{i_{\lceil k/2 \rceil + 1}}$$$ (Here $$$\lfloor x \rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\lceil x \rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 1000)$$$  — the length of the binary string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ containing only $$$0$$$s and $$$1$$$s. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the following:   The minimum number of operations $$$m$$$ in the first line ($$$0 \le m \le n$$$).  Each of the following $$$m$$$ lines should be of the form: $$$k$$$ $$$i_1$$$ $$$i_2$$$ ... $$$i_{k}$$$, where $$$k$$$ is the length and $$$i_1 \lt i_2 \lt ... \lt i_{k}$$$ are the indices of the chosen subsequence. For them the conditions from the statement must hold.

NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation:   $$$k = 4:$$$ choose the indices $$$\{1, 3, 4, 5\}$$$$$$\underline{1}$$$ $$$0$$$ $$$\underline{1}$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$ $$$\underline{1}$$$ In the third test case, we can perform the following operation:  $$$k = 3:$$$ choose the indices $$$\{3, 5, 6\}$$$$$$0$$$ $$$0$$$ $$$\underline{1}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$0$$$ $$$0$$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$

def swap(a)
  str = a.join
  i, j = -1, a.size
  rec = []

  while true
    i = str.index("1", i + 1) || a.size
    j = str.rindex("0", j - 1) || -1
    break if i >= j

    rec << i << j
    a[i], a[j] = a[j], a[i]
  end

  rec.sort!
end

gets.to_i.times do

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

ans = []
until (rec = swap(a)).empty?
  ans << rec
end

puts ans.size
ans.each do |a|
  a.map!(&:succ)
  a.unshift(a.size)
  puts a * " "
end

end


A string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the English alphabet, is given.You must choose some number $$$k$$$ between $$$0$$$ and $$$n$$$. Then, you select $$$k$$$ characters of $$$s$$$ and permute them however you want. In this process, the positions of the other $$$n-k$$$ characters remain unchanged. You have to perform this operation exactly once.For example, if $$$s=\texttt{"andrea"}$$$, you can choose the $$$k=4$$$ characters $$$\texttt{"a_d_ea"}$$$ and permute them into $$$\texttt{"d_e_aa"}$$$ so that after the operation the string becomes $$$\texttt{"dneraa"}$$$.Determine the minimum $$$k$$$ so that it is possible to sort $$$s$$$ alphabetically (that is, after the operation its characters appear in alphabetical order).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 40$$$) — the length of the string. The second line of each test case contains the string $$$s$$$. It is guaranteed that $$$s$$$ contains only lowercase letters of the English alphabet.

For each test case, output the minimum $$$k$$$ that allows you to obtain a string sorted alphabetically, through the operation described above.

NoteIn the first test case, we can choose the $$$k=2$$$ characters $$$\texttt{"_ol"}$$$ and rearrange them as $$$\texttt{"_lo"}$$$ (so the resulting string is $$$\texttt{"llo"}$$$). It is not possible to sort the string choosing strictly less than $$$2$$$ characters.In the second test case, one possible way to sort $$$s$$$ is to consider the $$$k=6$$$ characters $$$\texttt{"_o__force_"}$$$ and rearrange them as $$$\texttt{"_c__efoor_"}$$$ (so the resulting string is $$$\texttt{"ccdeefoors"}$$$). One can show that it is not possible to sort the string choosing strictly less than $$$6$$$ characters.In the third test case, string $$$s$$$ is already sorted (so we can choose $$$k=0$$$ characters).In the fourth test case, we can choose all $$$k=4$$$ characters $$$\texttt{"dcba"}$$$ and reverse the whole string (so the resulting string is $$$\texttt{"abcd"}$$$).

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def main
  t = gi
  t.times do
    n = gi
    s = gs.split('')
    sd = s.sort
    d = 0
    for i in (0..n - 1) do
      d += 1 unless s[i] == sd[i]
    end
    puts d
  end
end

main


Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all nodes for which $$$v$$$ is the parent. A vertex is a leaf if it has no children.The rooted tree Serval owns has $$$n$$$ nodes, node $$$1$$$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $$$\max$$$ or $$$\min$$$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are $$$k$$$ leaves in the tree. Serval wants to put integers $$$1, 2, \ldots, k$$$ to the $$$k$$$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?

The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 3\cdot 10^5$$$), the size of the tree. The second line contains $$$n$$$ integers, the $$$i$$$-th of them represents the operation in the node $$$i$$$. $$$0$$$ represents $$$\min$$$ and $$$1$$$ represents $$$\max$$$. If the node is a leaf, there is still a number of $$$0$$$ or $$$1$$$, but you can ignore it. The third line contains $$$n-1$$$ integers $$$f_2, f_3, \ldots, f_n$$$ ($$$1 \leq f_i \leq i-1$$$), where $$$f_i$$$ represents the parent of the node $$$i$$$.

Output one integer — the maximum possible number in the root of the tree.

NotePictures below explain the examples. The numbers written in the middle of the nodes are their indices, and the numbers written on the top are the numbers written in the nodes.In the first example, no matter how you arrange the numbers, the answer is $$$1$$$.  In the second example, no matter how you arrange the numbers, the answer is $$$4$$$.  In the third example, one of the best solution to achieve $$$4$$$ is to arrange $$$4$$$ and $$$5$$$ to nodes $$$4$$$ and $$$5$$$.  In the fourth example, the best solution is to arrange $$$5$$$ to node $$$5$$$.

n = gets.to_i
op = [-1] + gets.split.map(&:to_i)
f = [-1,-1] + gets.split.map(&:to_i)

g = Array.new(n+1){[]}
2.upto(n) do |i|
  g[f[i]] << i
end

rank = [[1]]
flg = true
while flg
  tmp = []
  rank[-1].each do |k|
    g[k].each do |v|
      tmp << v
    end
  end
  if tmp.empty?
    flg = false
  else
    rank << tmp
  end
end

ans = []*(n+1) #rank of node-i value in leafs which are descendat of node-1
leaf = 0
rank.length.times do |i|
  rank[-i-1].each do |v|
    if g[v].empty?
      ans[v] = 1
      leaf += 1
    else
      if op[v] == 0
        ans[v] = 0
        g[v].each do |k|
          ans[v] += ans[k]
        end
      else
        min = 10**6
        g[v].each do |k|
          min = ans[k] if ans[k] < min
        end
        ans[v] = min
      end
    end
  end
end

p leaf + 1 - ans[1]

n = gets.to_i
op = [-1] + gets.split.map(&:to_i)
f = [-1,-1] + gets.split.map(&:to_i)

g = Array.new(n+1){[]}
2.upto(n) do |i|
  g[f[i]] << i
end
#p g

rank = [[1]]
flg = true
while flg
  tmp = []
  rank[-1].each do |k|
    g[k].each do |v|
      tmp << v
    end
  end
  if tmp.empty?
    flg = false
  else
    rank << tmp
  end
end
#p rank

cnt = [0]*(n+1)
ans = []*(n+1)
leaf = 0
rank.length.times do |i|
  rank[-i-1].each do |v|
    if g[v].empty?
      ans[v] = -1
      cnt[f[v]] += 1
      leaf += 1
    else
      if op[v] == 0
        ans[v] = -cnt[v]
      else
        max = -10**6
        g[v].each do |k|
          max = ans[k] if ans[k] > max
        end
        ans[v] = max
      end
      cnt[f[v]] += cnt[v]+1
    end
  end
end
#p ans

p ans[1] + leaf + 1


There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.

The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.

Print two integer numbers — the minimal distance and the quantity of pairs with this distance.

NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.

n = gets.chomp.to_i
cities = gets.chomp.split().map { |e| e.to_i }
distances = []
cities.sort!
for i in 0 ... (n - 1)
  distances << (cities[i] - cities[i + 1]).abs
end
minDis = distances.min
repeat = distances.count(minDis)
print "#{minDis} #{repeat}\n"

#!/usr/bin/ruby
n,*a=$<.read.split.map(&:to_i)
b=a.sort.each_cons(2).map{|x,y|y-x}
m=b.min
puts '%d %d'%[m,b.count(m)]

n=gets.to_i
a=gets.split.map{ |x| x.to_i }
a.sort!
min_distance=2*10**9+1
min_count=0
for i in 1...a.length
	if a[i]-a[i-1] < min_distance
		min_distance=a[i]-a[i-1]
		min_count=1
	elsif a[i]-a[i-1] == min_distance
		min_count+=1
	end
end
puts "#{min_distance} #{min_count}"

n = gets.strip.to_i
data = gets.split.map(&:to_i).sort

dis = (0..n-2).map { |i| data[i+1] - data[i] }
ans = dis.min
print "#{ans} #{dis.select { |v| v == ans }.length}\n"

n=gets.to_i
aa=gets.split.map(&:to_i).sort
aa=aa[1, n-1].zip(aa).map { |a, b| a-b }
m=aa.min
print m, ' ', aa.count(m)

gets
pos = gets.split.map{|x| x.to_i}.sort

for idx in (0...pos.length-1) do
  pos[idx] = pos[idx+1]-pos[idx]
end

pos.pop

m = pos.min
puts "#{m} #{pos.count(m)}"

n=3
aa=gets.split.map(&:to_i).sort
aa=aa[1, n-1].zip(aa).map { |a, b| a-b }
m=aa.min
print m, ' ', aa.count(m)


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

def koukan()
    return -1 if $sum < $aa[0]
    5.downto(1) { |i|
        return i-1 if $aa[i-1] <= $sum
    }
end

$n = gets.chomp.to_i
$sa = gets.chomp.split(/ /).map!{|x| x.to_i}
$aa = gets.chomp.split(/ /).map!{|x| x.to_i}
$sum = 0
$suma = Array.new(5).map!{|x| x = 0}
for i in 0..$n-1
    $sum += $sa[i]
    while (true)
        if $sum > $aa[4]
            wka = $sum.divmod($aa[4])
            $suma[4] += wka[0]
            $sum -= $aa[4] * wka[0]
        end
        ret = koukan()
        break if ret < 0
        $suma[ret] += 1
        $sum -= $aa[ret]
    end
end
puts $suma.join(" ")
puts $sum

gets
b=gets.split
z=gets.split.map &:to_i
s=0
r=z.map{0}
b.map{|c|s+=c.to_i
while(t=z.select{|i|i<=s})[0]
r[z.index m=t.max]+=s/m
s%=m
end}
puts r*" ",s

gets
bats = gets.split
prizes = gets.split.map &:to_i
score = 0
res = prizes.map{0}
for bat in bats
    score += bat.to_i
    loop do
        can = prizes.select{ |e| e <= score }
        break if can.empty?
        x = can.max
        res[prizes.index x] += score / x
        score %= x
    end
end

puts res.join " "
puts score

gets
bats = gets.split
prizes = gets.split.map.with_index{|e,i|[e.to_i,i]}
score = 0
res = prizes.map{0}
for bat in bats
    score += bat.to_i
    loop do
        can = prizes.select{ |e,i| e <= score }
        break if can.empty?
        x = can.max_by(&:first)
        res[x.last] += score / x.first
        score %= x.first
    end
end

puts res.join " "
puts score

n = gets.to_i
p = gets.split.map(&:to_i)
st = gets.split.map(&:to_i)
res = Array.new(5,0)

r = p.inject(0) { |acc, x|  t = acc + x; (0..4).reverse_each { |j| res[j] += t / st[j]; t %= st[j] }; t }
puts res*' '
puts r

n = gets.to_i
p = gets.split.map{|e| e.to_i }
cost = gets.split.map{|e| e.to_i }
count = Array.new(5){0}
remain = 0
cost.reverse!
p.each do |i|
    remain += i
    5.times do |j|
        if remain >= cost[j]
            tmp = (remain / cost[j]).truncate
            remain -= cost[j] * tmp
            count[4-j] += tmp
        end
    end
end
puts "#{count[0]} #{count[1]} #{count[2]} #{count[3]} #{count[4]}"
puts remain

n = gets.to_i
a = gets.split.map { |s| s.to_i }
b = gets.split.map { |s| s.to_i }
s, r, i = 0, b.map {0}
n.times { |i|
   s = s + a[i] if i < n
   loop {
      c = b.select { |p| s >= p }
      break if c.empty?
      m = c.max
      r[b.index(m)] += (s / m)
      s = s - ((s / m) * m)
   }
   i = i + 1
}
puts r.join(" ")
puts s

n = gets.to_i
a = gets.split.map { |s| s.to_i }
b = gets.split.map { |s| s.to_i }
s, r, i = 0, b.map {0}
n.times { |i|
   s = s + a[i] if i < n
   loop {
      m, o = 0, -1
      5.times { |j|
         if s >= b[j]
            m = b[j]
            o = j
         end
      }
      break if o == -1
      r[o] = r[o] + (s / m)
      s = s - ((s / m) * m)
   }
   i = i + 1
}
puts r.join(" ")
puts s

#!/usr/bin/ruby
n = gets.chomp.to_i
p = gets.chomp.split(' ').map{|x| x.to_i}
a,b,c,d,e = gets.chomp.split(' ').map{|x| x.to_i}
na = 0
nb = 0
nc = 0
nd = 0
ne = 0
curr = 0
for i in 0..p.size-1
	curr += p[i]
	while curr >= a
		if curr >= e
			ne += curr/e
			curr=curr%e
		elsif curr >= d
			nd +=curr/d
			curr =curr%d
		elsif curr >= c
			nc += curr/c
			curr = curr%c
		elsif curr >= b
			nb += curr/b
			curr =curr%b
		elsif curr >= a
			na +=curr/a
			curr =curr%a
		end
	end
end
print "#{na} #{nb} #{nc} #{nd} #{ne}\n"
puts curr

require "scanf"
n = gets.to_i
list = []
gets.split(" ").each {
    |i| list.push(i.to_i)
}
cost = scanf("%d%d%d%d%d")
cnt = [0,0,0,0,0]
tot = 0
list.each { |i|
    tot += i
    5.times { |j|
        cnt[4 - j] += tot / cost[4 - j]
        tot %= cost[4 - j]
    }
}
cnt.each{ |i| print i, " "}
print "\n", tot

n = gets.to_i
p = gets.split.collect{|i| i.to_i}
c = gets.split.collect{|i| i.to_i}
ans = Array.new(5,0)
points = 0
p.each do |pp|
    points += pp
    4.downto(0).each do |i|
        ans[i] += points/c[i]
        points = points%c[i]
    end
end
puts ans.join(" ")
puts points

n,=gets.split.map{|e| e.to_i}
a=gets.split.map{|e| e.to_i}
b=gets.split.map{|e| e.to_i}
c=Array.new(5,0)
i=0
k=0
while i<n do
  k+=a[i]
  4.downto(0) {|j|
    c[j]+=k/b[j]
    k=k%b[j]
  }
  i+=1
end
for i in 0..4 do
  print c[i],' '
end
puts "\n", k

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

gets
p = read_next_line
a = read_next_line

t = Array.new(5, 0)
s = 0
p.each { |x|
  s += x
  4.downto(0).each { |i|
    t[i] += s / a[i]
    s %= a[i]
  }
}

puts t * ' '
puts s

#!/usr/bin/ruby

while line = gets
	n = line.to_i
	ps = gets.split.map(&:to_i)
	as = gets.split.map(&:to_i)
	ans = Array.new(as.length, 0)
	now = 0
	ps.each do |p|
		now += p
		(as.length - 1).downto(0) do |i|
			tmp = now / as[i]
			ans[i] += tmp
			now -= tmp * as[i]
		end
	end
	as.length.times do |i|
		if i > 0
			print " "
		end
		print ans[i]
	end
	puts
	puts now
end

gets
bats = gets.split.map &:to_i
prizes = gets.split.map &:to_i
score = 0
res = prizes.map{0}
for bat in bats
    score += bat

    can = prizes.select{ |prize| prize <= score }
    break if can.empty?
    res[prizes.index(can.max)] += score / can.max
    score %= can.max

end
puts res.join " "
puts score

#!/usr/bin/ruby
n = gets.chomp.to_i
p = gets.chomp.split(' ').map{|x| x.to_i}
a,b,c,d,e = gets.chomp.split(' ').map{|x| x.to_i}
na = 0
nb = 0
nc = 0
nd = 0
ne = 0
curr = 0
for i in 0..p.size-1
	curr += p[i]
	while curr >= a
		if curr >= e
			curr-=e
			ne += 1
		elsif curr >= d
			curr -= d
			nd +=1
		elsif curr >= c
			curr -= c
			nc += 1
		elsif curr >= b
			curr -= b
			nb += 1
		elsif curr >= a
			curr -=a
			na +=1
		end
	end
end
print "#{na} #{nb} #{nc} #{nd} #{ne}\n"

require "scanf"
n = gets.to_i
list = []
gets.split(" ").each {
    |i| list.push(i.to_i)
}
cost = scanf("%d%d%d%d%d")
cnt = [0,0,0,0,0]
tot = 0
list.each { |i|
    tot += i
    5.times { |j|
        p j
        while tot >= cost[4 - j]
            cnt[4 - j] += 1
            tot -= cost[4 - j]
        end
    }
}
cnt.each{ |i|
    print i , " "}
print "\n",tot

n,=gets.split.map{|e| e.to_i}
a=gets.split.map{|e| e.to_i}
b=gets.split.map{|e| e.to_i}
c=Array.new(5,0)
i=0
k=0
while i<n do
  k+=a[i]
  puts k
  for j in 0..4 do
    if b[j]>k then break end
  end
  j-=1
  if j>=0 then c[j]+=1; k-=b[j] end
  i+=1
end
for i in 0..4 do
  print c[i],' '
end
puts "\n", k

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

gets
p = read_next_line
a = read_next_line

t = Array.new(5, 0)
s = 0
p.each { |x|
  s += x
  t[4] += s / a[4]
  s %= a[4]
  3.downto(0).each { |i|
    if a[i] <= s
      s -= a[i]
      t[i] += 1
    end
  }
}

puts t * ' '
puts s


NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:  It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.

The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \leq n \leq 100$$$, $$$1 \leq r \leq 100$$$) — the number of the outer circles and the radius of the inner circle respectively.

Output a single number $$$R$$$ — the radius of the outer circle required for building the required picture.  Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$$$.

# Input
n, r = gets.split(" ").map { |e| e.to_f }

# Processing
alpha = 2 * Math::PI / n
v = Math.sin(alpha / 2)
result = r * v / (1 - v)

# Output
puts result

n, r = gets.split.map(&:to_f)
l = 0.0
rt = 10e5
eps = 10e-8
while (rt - l > eps)
  m = (rt - l) / 2 + l # радиус r
  rr = m + r
  d = Math.acos((rr ** 2 + rr ** 2 - (m * 2) ** 2)/(2 * rr * rr))
  if (d / Math::PI * 180 > (360.0 / n))
    rt = m
  else
    l = m
  end
end
puts rt

n,r = gets.split.map(&:to_f)
s = Math.sin(Math::PI/n)
puts r*s/(1-s)


We all know the problem about the number of ways one can tile a 2 × n field by 1 × 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes.You are given a 4 × n rectangular field, that is the field that contains four lines and n columns. You have to find for it any tiling by 1 × 2 dominoes such that each of the n - 1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2 × 1 as well as 1 × 2 dominoes.Write a program that finds an arbitrary sought tiling.

The input contains one positive integer n (1 ≤ n ≤ 100) — the number of the field's columns.

If there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing n characters each — that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling.

N = gets.to_i

#01234567
#aaffaaff
#bbggbbgg
#cddhhcchh
#ceeiiddii

str = []
str[0] = "aaff" * 25
str[1] = "bbgg" * 25
str[2] = "cdd" + "hhcc" * 25
str[3] = "cee" + "iidd" * 25

if N == 1
  print "a\na\nb\nb\n"
elsif N == 2
  puts "aa"
  puts "bb"
  puts "cd"
  puts "cd"
else
#  p str
  if (N % 2 == 1)
    str[1][N - 1] = str[0][N - 1]
  else
    str[3][N - 1] = str[2][N - 1]
  end
  4.times do |i|
    puts str[i][0..(N - 1)]
  end
end

n = gets.to_i

def dig2str(dig)
    p = 'a'
    (dig%26).times { p = p.succ }
    p
end

def solve(n)
    return ['a', 'a', 'b', 'b'] if n == 1
    return ['aa', 'bb', 'cc', 'dd'] if n == 2
    a = Array.new(4) { Array.new(n) }
    dig = 0
    0.step(n-2, 2) do |i|
        a[0][i] = a[0][i+1] = dig2str(dig)
        dig += 1
        a[1][i] = a[1][i+1] = dig2str(dig)
        dig += 1
    end
    dig = 10
    1.step(n-2, 2) do |i|
        a[2][i] = a[2][i+1] = dig2str(dig)
        dig += 1
        a[3][i] = a[3][i+1] = dig2str(dig)
        dig += 1
    end
    if n%2==0
        a[2][-1] = a[3][-1] = dig2str(dig)
    else
        a[0][-1] = a[1][-1] = dig2str(dig)
    end
    a[2][0] = a[3][0] = dig2str(9)
    return a.map(&:join)
end

puts solve(n)

def build_line(s1, s2, len)
  (1..len).map { |i| i.odd? ? s1 : s2 }.join ''
end

def build_odd(n)
  line1 = build_line('aa', 'bb', (n - 1) / 2)
  line2 = build_line('cc', 'dd', (n - 1) / 2)
  puts line1 + 'x'
  puts line2 + 'x'
  puts 'y' + line1
  puts 'y' + line2
end

def build_even(n)
  line1 = build_line('aa', 'bb', n / 2)
  puts line1
  puts 'x' + build_line('cc', 'dd', n / 2 - 1) + 'y'
  puts 'x' + build_line('ee', 'ff', n / 2 - 1) + 'y'
  puts line1
end

n = gets.to_i
if n.odd?
  build_odd(n)
else
  build_even(n)
end

N = gets.to_i

#01234567
#aaffaaff
#bbggbbgg
#cddhhcchh
#ceeiiddii

str = []
str[0] = "aaff" * 25
str[1] = "bbgg" * 25
str[2] = "cdd" + "hhcc" * 25
str[3] = "cee" + "iidd" * 25

if N == 1
  print "a\na\nb\nb\n"
elsif N == 2
  puts "aa"
  puts "bb"
  puts "cd"
  puts "cd"
else
  p str
  if (N % 2 == 1)
    str[1][N - 1] = str[0][N - 1]
  else
    str[3][N - 1] = str[2][N - 1]
  end
  4.times do |i|
    puts str[i][0..(N - 1)]
  end
end


The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.

On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.

NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

s=(gets.to_i+1)/2
a=gets(p).scan /(\S+) (.+)/
x=a.flatten.sort.each_slice([a.size/2,1].max).map(&:first).select{|i|a.count{|j,k|j==i||k==i}>=s}
p x[0]?[s-x.map{|i|a.map(&:first).count i}.max,0].max: -1

s2 = (gets.to_i+1)/2
a = gets(p).scan(/(\S+) (\S+)/)
af,al = a.transpose

as = a.flatten.sort.each_slice([a.size/2,1].max).map(&:first)
x = as.select{ |i|
    a.count{ |j,k| j == i || k == i } >= s2
}

p x.empty? ? -1 : [(
    a1 = af.group_by{|i|i}
    s2 - x.map{ |i| a1[i] ? a1[i].size : 0 }.max
    #s2 - x.map{ |i| af.count i }.max
), 0].max

s2 = (gets.to_i+1)/2
a = gets(p).scan(/(\S+) (\S+)/)
af,al = a.transpose

as = a.flatten.sort.each_slice([a.size/2,1].max).map(&:first)
x = as.select{ |i|
    a.count{ |j,k| j == i || k == i } >= s2
}

p x.empty? ? -1 : [(
    a1 = af.group_by{|i|i}
    #s2 - x.map{ |i| a1[i] ? a1[i].size : 0 }.max
    s2 - x.map{ |i| af.count i }.max
), 0].max

n = gets.to_i
o = (n - 1) / 2 + 1
@m = 1 << 30
h, k = {}, {}
def f(a, b, p, q)
   a.each_pair { |y, v|
      if b.has_key?(y) and v + b[y] >= p
         @m = q == 0 ? [@m, p - v].min : [@m, p - b[y]].min
      elsif v >= p
         @m = [@m, q].min
      end
   }
end
n.times { |x|
   a, b = gets.split.map { |i| i.to_i }
   h[a] = h.has_key?(a) ? h[a] + 1 : 1
   k[b] = k.has_key?(b) ? k[b] + 1 : 1 if a != b
}
f(h, k, o, 0)
f(k, h, o, o)
puts @m == 1 << 30 ? -1 : [0, @m].max

n = gets.to_i
o = (n - 1) / 2 + 1
b = []
h, k = {}, {}
n.times { |x|
   b << gets.split.map { |i| i.to_i }
   h[b[x][0]] = h.has_key?(b[x][0]) ? h[b[x][0]] + 1 : 1
   k[b[x][1]] = k.has_key?(b[x][1]) ? k[b[x][1]] + 1 : 1 if b[x][1] != b[x][0]
}
m = 1 << 30
h.each_pair { |y, v|
   if k.has_key?(y) and v + k[y] >= o
      m = [m, o - v].min
   elsif v >= o
      puts 0
      exit
   end
}
k.each_pair { |y, v|
   if h.has_key?(y) and v + h[y] >= o
      m = [m, o - h[y]].min
   elsif v >=o
      puts o
      exit
   end
}
puts m == 1 << 30 ? -1 : [0, m].max

s2 = (gets.to_i+1)/2
a = gets(p).scan(/(\S+) (\S+)/)
af,al = a.transpose

as = a.flatten.sort
x = [as[0],as[as.size/2]].select{ |i|
    a.count{ |j,k| j == i || k == i } >= s2
}

p x.empty? ? -1 : [(
    a1 = af.group_by{|i|i}
    s2 - x.map{ |i| a1[i] ? a1[i].size : 0 }.max
    #s2 - x.map{ |i| af.count i }.max
), 0].max

n = gets.to_i
o = (n - 1) / 2 + 1
b = []
h, k = {}, {}
n.times { |x|
   b << gets.split.map { |i| i.to_i }
   h[b[x][0]] = h.has_key?(b[x][0]) ? h[b[x][0]] + 1 : 1
   k[b[x][1]] = k.has_key?(b[x][1]) ? k[b[x][1]] + 1 : 1
}
m = 1 << 30
h.each_pair { |y, v|
   if k.has_key?(y) and v + k[y] >= o
      m = [m, o - v].min
   elsif v >= o
      puts 0
      exit
   end
}
k.each_pair { |y, v|
   if h.has_key?(y) and v + h[y] >= o
      m = [m, o - h[y]].min
   elsif v >=o
      puts o
      exit
   end
}
puts [0, m].max

n = gets.to_i
o = (n - 1) / 2 + 1
b = []
h, k = {}, {}
n.times { |x|
   b << gets.split.map { |i| i.to_i }
   h[b[x][0]] = h.has_key?(b[x][0]) ? h[b[x][0]] + 1 : 1
   k[b[x][1]] = k.has_key?(b[x][1]) ? k[b[x][1]] + 1 : 1
}
m = 1 << 30
h.each_pair { |y, v|
   if k.has_key?(y) and v + k[y] >= o
      m = [m, o - v].min
   elsif v >= 0
      puts 0
      exit
   end
}
k.each_pair { |y, v|
   if h.has_key?(y) and v + h[y] >= o
      m = [m, o - h[y]].min
   elsif v >=o
      puts 0
      exit
   end
}
puts [0, m].max

n = gets.to_i
o = (n - 1) / 2 + 1
@m = 1 << 30
h, k = {}, {}
def f(a, b, p, q)
   a.each_pair { |y, v|
      if b.has_key?(y) and v + b[y] >= p
         @m = [@m, p - v].min
      elsif v >= p
         @m = [@m, q].min
      end
   }
end
n.times { |x|
   a, b = gets.split.map { |i| i.to_i }
   h[a] = h.has_key?(a) ? h[a] + 1 : 1
   k[b] = k.has_key?(b) ? k[b] + 1 : 1 if a != b
}
f(h, k, o, 0)
f(h, k, o, o)
puts @m == 1 << 30 ? -1 : [0, @m].max

n = gets.to_i
o = (n - 1) / 2 + 1
@m = 1 << 30
h, k = {}, {}
def f(a, b, p, q)
   a.each_pair { |y, v|
      if b.has_key?(y) and v + b[y] >= p
         @m = [@m, p - v].min
      elsif v >= p
         @m = [@m, q].min
      end
   }
end
n.times { |x|
   a, b = gets.split.map { |i| i.to_i }
   h[a] = h.has_key?(a) ? h[a] + 1 : 1
   k[b] = k.has_key?(b) ? k[b] + 1 : 1 if a != b
}
f(h, k, o, 0)
f(k, h, o, o)
puts @m == 1 << 30 ? -1 : [0, @m].max

n = gets.to_i
o = (n - 1) / 2 + 1
b = []
h, k = {}, {}
n.times { |x|
   b << gets.split.map { |i| i.to_i }
   h[b[x][0]] = h.has_key?(b[x][0]) ? h[b[x][0]] + 1 : 1
   k[b[x][1]] = k.has_key?(b[x][1]) ? k[b[x][1]] + 1 : 1
}
m = 1 << 30
h.each_pair { |y, v|
   if k.has_key?(y) and v + k[y] >= o
      m = [m, o - v].min
   elsif v >= o
      puts 0
      exit
   end
}
k.each_pair { |y, v|
   if h.has_key?(y) and v + h[y] >= o
      m = [m, o - h[y]].min
   elsif v >=o
      puts o
      exit
   end
}
puts m == 1 << 30 ? -1 : [0, m].max


Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse.The warehouse has one set of shelving. It has n shelves, each of which is divided into m sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught.After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you.The process of counting contains two types of query messages:   «+1 x y id» (where x, y are integers, 1 ≤ x ≤ n, 1 ≤ y ≤ m, and id is a string of lower case Latin letters — from 1 to 10 characters long). That query means that the warehouse got a box identified as id, which should be put in the section y on the shelf x. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query.  «-1 id» (where id is a string of lower case Latin letters — from 1 to 10 characters long). That query means that a box identified as id is removed from the warehouse. You have to answer this query (see output format).

The first input line contains integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ 2000) — the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following k lines the queries are given in the order of appearance in the format described above.

For each query of the «-1 id» type output two numbers in a separate line — index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output «-1 -1» without quotes.

2 2 9
+1 1 1 cola
+1 1 1 fanta
+1 1 1 sevenup
+1 1 1 whitekey
-1 cola
-1 fanta
-1 sevenup
-1 whitekey
-1 cola

2 2 8
+1 1 1 cola
-1 cola
+1 1 1 fanta
-1 fanta
+1 1 1 sevenup
-1 sevenup
+1 1 1 whitekey
-1 whitekey

f = open("input.txt", "r")
fw = open("output.txt", "w")
n,m,k = f.gets.chomp.split(/ /).map!{|x|x.to_i}
sh = Array.new(n)
sh.map!{|x| Array.new(m) }
h = Hash.new
for i in 0..k-1
	ar = f.gets.chomp.split(/ /)
	if ar[0] == "+1"
		x = ar[1].to_i-1
		y = ar[2].to_i-1
		while true
			if sh[x][y] == nil
				h[ar[3]] = (x+1).to_s +  " " + (y+1).to_s
				sh[x][y] = ar[3]
				break
			end
			y += 1
			if y == m
				x += 1
				y = 0
			end
			if x == n
				break
			end
		end
	else
		if h.has_key?( ar[1] )
			fw.puts h[ar[1]]
			x,y = h[ar[1]].split(/ /).map!{|x|x.to_i-1}
			sh[x][y] = nil
			h.delete(ar[1])
		else
			fw.puts "-1 -1"
		end
	end
end
f.close
fw.close

I = open('input.txt')
O = open('output.txt','w')
n, m, k = I.gets.split.map &:to_i
t = [nil] * (n *= m)
k.times do
	a, b, c, d = I.gets.split
	if /-1/ then
		c = t.index b
		if c then
			t[c] = nil
			O.puts "#{c / m + 1} #{c % m + 1}"
		else
			O.puts '-1 -1'
		end
	else
		b = (b.to_i - 1) * m + (c.to_i - 1)
		b += 1 while b < n && t[b]
		t[b] = d if b < n
	end
end

I = open('input.txt')
O = open('output.txt','w')
n, m, k = I.gets.split.map &:to_i
t = Array.new(n *= m)
k.times do
	a, b, c, d = I.gets.split
	if /-1/ then
		c = t.index b
		if c then
			t[c] = nil
			O.puts "#{c / m + 1} #{c % m + 1}"
		else
			O.puts '-1 -1'
		end
	else
		b = (b.to_i - 1) * m + (c.to_i - 1)
		c = 0
		b, c = b + 1, c + 1 while t[b % n] && c < n
		t[b % n] = d unless t[b % n]
	end
end


You are given a non-decreasing array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Also you are given a positive integer $$$k$$$.You want to find $$$m$$$ non-decreasing arrays of non-negative integers $$$b_1, b_2, \ldots, b_m$$$, such that:  The size of $$$b_i$$$ is equal to $$$n$$$ for all $$$1 \leq i \leq m$$$.  For all $$$1 \leq j \leq n$$$, $$$a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$$$. In the other word, array $$$a$$$ is the sum of arrays $$$b_i$$$.  The number of different elements in the array $$$b_i$$$ is at most $$$k$$$ for all $$$1 \leq i \leq m$$$. Find the minimum possible value of $$$m$$$, or report that there is no possible $$$m$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n \leq 100$$$, $$$1 \leq k \leq n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$$$, $$$a_n > 0$$$).

For each test case print a single integer: the minimum possible value of $$$m$$$. If there is no such $$$m$$$, print $$$-1$$$.

NoteIn the first test case, there is no possible $$$m$$$, because all elements of all arrays should be equal to $$$0$$$. But in this case, it is impossible to get $$$a_4 = 1$$$ as the sum of zeros.In the second test case, we can take $$$b_1 = [3, 3, 3]$$$. $$$1$$$ is the smallest possible value of $$$m$$$.In the third test case, we can take $$$b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$$$ and $$$b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$$$. It's easy to see, that $$$a_i = b_{1, i} + b_{2, i}$$$ for all $$$i$$$ and the number of different elements in $$$b_1$$$ and in $$$b_2$$$ is equal to $$$3$$$ (so it is at most $$$3$$$). It can be proven that $$$2$$$ is the smallest possible value of $$$m$$$.

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)
  us = nums.uniq.size

  if k == 1
    if us == 1
      puts 1
    else
      puts -1
    end

    next
  end

  if us <= k
    puts 1
    next
  end

  puts Rational(us - 1, k - 1).ceil
end

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)
  us = nums.uniq.size

  if k == 1
    if us == 1
      puts 1
    else
      puts -1
    end

    next
  end

  c = nums.each_cons(2).map { |a, b| b - a }
  c.delete(0)

  puts Rational(c.size, k - 1).ceil
end

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)
  us = nums.uniq.size

  if k == 1
    if us == 1
      puts 1
    else
      puts -1
    end

    next
  end

  puts Rational(us - 1, k - 1).ceil
end

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)

  if k == 1
    if nums.uniq.size == 1
      puts 1
    else
      puts -1
    end

    next
  end

  base = [0]

  nums.each do |n|
    base.each do |b|
      if n ^ b < n
        n ^= b
      end
    end

    if n != 0
      base << n
    end
  end

  puts Rational(base.size, k).ceil
end

T = gets.to_i

T.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)
  us = nums.uniq.size

  if k == 1
    if us == 1
      puts 1
    else
      puts -1
    end

    next
  end

  if us <= k
    puts 1

    next
  end

  base = [0]

  nums.each do |n|
    base.each do |b|
      if n ^ b < n
        n ^= b
      end
    end

    if n != 0
      base << n
    end
  end

  puts Rational(base.size, k).ceil
end


Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th year — an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.

The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers ai ( - 100 ≤ ai ≤ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces.

Output k — the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map!{|x|x.to_i}

years = Array.new
seq = 1
for i in 0..n-1
	if a[i] == seq
		years.push((2001+i).to_s)
		seq += 1
	end
end

if years.length == 0
	puts "0"
else
	puts years.length.to_s
	puts years.join(' ')
end

gets
a, b = gets.split.map(&:to_i), [2000]
while a.any? && p = a.index(b.size) do
	b << b[-1] + p + 1
	a = a[p + 1 .. -1]
end
b[0] = b.size - 1
puts b * ' '

n = gets.to_i

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

ans ||= []

pre = 0
a.each_index do |x|
  if a[x] == pre + 1
    ans << x + 2001
    pre = a[x]
  end
end

puts ans.size
puts ans * " " if ans.any?


A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di < di + 1.

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.

n, m = gets.strip.split(" ").map(&:to_i)
record = Array.new
m.times do |i|
  d, h = gets.strip.split(" ").map(&:to_i)
  record.push [d, h]
end
possible = true
maxh = 0
(m-1).times do |i|
  dd = record[i+1][0] - record[i][0]
  dh = record[i+1][1] - record[i][1]
  if dh.abs > dd
    possible = false
  end
  hh = (dd - dh.abs) / 2
  maxh = [maxh, record[i+1][1] + hh, record[i][1] + hh].max
end

c1 = record[0][0] + record[0][1] - 1
c2 = (n - record[-1][0]) + record[-1][1]
maxh = [c1, c2, maxh].max

if possible
  puts maxh
else
  puts "IMPOSSIBLE"
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * m
    h = [0] * m

    m.times do |i|
        d[i], h[i] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = h[0]
    1.upto(m-1) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    r = [r, h[-1] + (n - d[-1])].max
    r = [r, h[0] + (d[0] - 1)].max
    puts r
end

if __FILE__ == $0 then
    main()
end

n, m = gets.split.collect{|i| i.to_i}
pre = gets.split.collect{|i| i.to_i}
ans = pre[1]+pre[0]-1
(1...m).each do
    tmp = gets.split.collect{|i| i.to_i}
    t = tmp[0]-pre[0]
    v1, v2 = [pre[1], tmp[1]].minmax
    x = (1.0*t+v2-v1)/2
    if x < 0 or x > t
        puts "IMPOSSIBLE"
        exit
    end
    x = x.round
    ans = [ans,v1+x-1,v2+t-x].max
    pre = tmp
end
ans = [ans,pre[1]+n-pre[0]].max
puts ans

n, m = gets.split.map {|i| i.to_i}
b1, a1 = gets.split.map {|i| i.to_i}
maxx = a1 + b1 - 1
for i in 0...m - 1
  b, a = gets.split.map {|i| i.to_i}
  maxx = [maxx, (b - b1 + a1 + a) / 2].max
  if (a1 - a).abs > (b1 - b).abs
    print 'IMPOSSIBLE'
    exit(0)
  end
  a1, b1 = a, b
end
print [maxx, a1 + n - b1].max
# a - a1 + a - a2 <= b2 - b1
# a + a <= b2 - b1 + a1 + a2
# a <= (b2 - b1)

n, m = gets.strip.split(" ").map(&:to_i)
record = Array.new
m.times do |i|
  d, h = gets.strip.split(" ").map(&:to_i)
  record.push [d, h]
end
possible = true
maxh = 0
(m-1).times do |i|
  dd = record[i+1][0] - record[i][0]
  dh = record[i+1][1] - record[i][1]
  if dh.abs > dd
    possible = false
  end
  hh = (dd - dh.abs) / 2
  maxh = [maxh, record[i+1][1] + hh, record[i][1] + hh].max
end

c1 = record[0][0] + record[0][1]
c2 = (n - record[-1][0]) + record[-1][1]
maxh = [c1, c2, maxh].max

if possible
  puts maxh
else
  puts "IMPOSSIBLE"
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * m
    h = [0] * m

    m.times do |i|
        d[i], h[i] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = h[0]
    1.upto(m-1) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    puts r
end

if __FILE__ == $0 then
    main()
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * m
    h = [0] * m

    m.times do |i|
        d[i], h[i] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = h[0] + d[0]
    1.upto(m-1) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    puts r
end

if __FILE__ == $0 then
    main()
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * (m + 1)
    h = [0] * (m + 1)

    m.times do |i|
        d[i+1], h[i+1] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = 0
    1.upto(m) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    puts r
end

if __FILE__ == $0 then
    main()
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * m
    h = [0] * m

    m.times do |i|
        d[i], h[i] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = 0
    1.upto(m-1) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    puts r
end

if __FILE__ == $0 then
    main()
end

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

# c.rb

def main()
    n, m = gets.chomp.split(" ").map{|s| next s.to_i }
    d = [0] * m
    h = [0] * m

    m.times do |i|
        d[i], h[i] = gets.chomp.split(" ").map{|s| next s.to_i }
    end

    r = h[0]
    1.upto(m-1) do |i|
        dd = d[i] - d[i-1]
        dh = h[i] - h[i-1]
        if dd.abs < dh.abs then
            puts("IMPOSSIBLE")
            return
        else
            r = [r, h[i]].max
            r = [r, [h[i], h[i-1]].min + (dd.abs + dh.abs) / 2 ].max
        end
    end
    r = [r, h[-1] + (n - d[-1])].max
    puts r
end

if __FILE__ == $0 then
    main()
end

n, m = gets.split.collect{|i| i.to_i}
pre = gets.split.collect{|i| i.to_i}
ans = pre[1]+pre[0]-1
(1...m).each do
    tmp = gets.split.collect{|i| i.to_i}
    t = tmp[0]-pre[0]
    v1, v2 = [pre[1], tmp[1]].minmax
    x = (1.0*t+v2-v1)/2
    if x < 0 or x > t
        puts "IMPOSSIBLE"
        exit
    end
    if x%1 >= 0.5
        x = x.ceil
    else
        x = x.floor
    end
    ans = [ans,v1+x-1,tmp[1]].max
    pre = tmp
end
ans = pre[1]+n-pre[0] if ans < pre[1]+n-pre[0]
puts ans

n, m = gets.split.collect{|i| i.to_i}
pre = gets.split.collect{|i| i.to_i}
ans = pre[1]+pre[0]-1
(1...m).each do
    tmp = gets.split.collect{|i| i.to_i}
    t = tmp[0]-pre[0]
    v1, v2 = [pre[1], tmp[1]].minmax
    x = (1.0*t+v2-v1)/2
    if x < 0 or x > t
        puts "IMPOSSIBLE"
        exit
    end
    if x%1 >= 0.5
        x = x.ceil
    else
        x = x.floor
    end
    ans = [v1+x-1,tmp[1]].max
    pre = tmp
end
ans = pre[1]+n-pre[0] if ans < pre[1]+n-pre[0]
puts ans

n, m = gets.split.collect{|i| i.to_i}
pre = gets.split.collect{|i| i.to_i}
ans = pre[1]+pre[0]-1
(1...m).each do
    tmp = gets.split.collect{|i| i.to_i}
    t = tmp[0]-pre[0]-1
    v1, v2 = [pre[1], tmp[1]].minmax
    x = (1.0*t+v2-v1)/2
    if x < 0 or x > t
        puts "IMPOSSIBLE"
        exit
    end
    if x%1 >= 0.5
        x = x.ceil
    else
        x = x.floor
    end
    ans = v1+x if ans < v1+x
    pre = tmp
end
ans = pre[1]+n-pre[0] if ans < pre[1]+n-pre[0]
puts ans

n, m = gets.split.collect{|i| i.to_i}
pre = gets.split.collect{|i| i.to_i}
ans = pre[1]+pre[0]-1
(1...m).each do
    tmp = gets.split.collect{|i| i.to_i}
    t = tmp[0]-pre[0]
    v1, v2 = [pre[1], tmp[1]].minmax
    x = (1.0*t+v2-v1)/2
    if x < 0 or x > t
        puts "IMPOSSIBLE"
        exit
    end
    if x%1 >= 0.5
        x = x.ceil
    else
        x = x.floor
    end
    ans = v1+x-1 if ans < v1+x-1
    pre = tmp
end
ans = pre[1]+n-pre[0] if ans < pre[1]+n-pre[0]
puts ans


Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.

t = gets.to_i
for j in 1..t do
	n, k = gets.split.map(&:to_i)
	tmp = 1; res = 0
	for i in 0..31 do
		if (k&(1<<i)) != 0
			res = (res + tmp) % 1000000007
		end
		tmp = (tmp * n) % 1000000007
	end
	puts res
end

t = gets
t = t.to_i
for j in 1..t do
	n, k = gets.split.map(&:to_i)
	tmp = 1; res = 0
	for i in 0..31 do
		if (k&(1<<i)) != 0
			res = (res + tmp) % 1000000007
		end
		tmp = (tmp * n) % 1000000007
	end
	puts res
end

t = gets
t = t.to_i
for j in 1..t do
	n = gets; k = gets
	n = n.to_i; k = k.to_i
	tmp = 1; res = 0
	for i in 0..31 do
		if (k&(1<<i)) != 0
			res = (res + tmp) % 1000000007
		end
		tmp = (tmp * n) % 1000000007
	end
	puts res
end


Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses.You own a small bus service business and you have just received an order to replace $$$n$$$ tires. You know that the bus fleet owns two types of buses: with two axles (these buses have $$$4$$$ wheels) and with three axles (these buses have $$$6$$$ wheels).You don't know how many buses of which type the AvtoBus bus fleet owns, so you wonder how many buses the fleet might have. You have to determine the minimum and the maximum number of buses that can be in the fleet if you know that the total number of wheels for all buses is $$$n$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. The following lines contain description of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$) — the total number of wheels for all buses.

For each test case print the answer in a single line using the following format. Print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x \le y$$$) — the minimum and the maximum possible number of buses that can be in the bus fleet. If there is no suitable number of buses for the given $$$n$$$, print the number $$$-1$$$ as the answer.

NoteIn the first test case the total number of wheels is $$$4$$$. It means that there is the only one bus with two axles in the bus fleet.In the second test case it's easy to show that there is no suitable number of buses with $$$7$$$ wheels in total.In the third test case the total number of wheels is $$$24$$$. The following options are possible:  Four buses with three axles.  Three buses with two axles and two buses with three axles.  Six buses with two axles. So the minimum number of buses is $$$4$$$ and the maximum number of buses is $$$6$$$.

t=gets
n = t.to_i
n.times do
    t2=gets
    x=t2.to_i
    if x%4==1 || x%4==3 || x==2
        puts -1
    elsif x % 6==0
        print x/6, ' ', x/4, "\n"
    else
        print x/6+1, ' ', x/4, "\n"
    end
end

gets.to_i.times do
  n = gets.to_i
  if (n % 2 == 1) or (n<3)
    puts -1
  else
    mn = n / 6
    if n % 6 != 0 then
      mn += 1
    end
    mx = n / 4
    puts "#{mn} #{mx}"
  end
end


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

class Manuscrito
	def initialize(count, string)
		@count = count
		@string = string
	end

	def decipher
		string = @string.dup
		words = string.split
		words.map! do |word|
			word.split('').sort.join.squeeze
		end
		puts objects = words.uniq.size
	end

end

n = gets
string = gets

manuscrito = Manuscrito.new(n, string)
manuscrito.decipher

gets;
ar = gets.split
res = 0;
ar.map!{|s| s.chars.uniq.sort.join()}
p ar.uniq.size

n = gets
str = gets
str = str.split(" ")
mas = Array.new(n.to_i)
str.size.times do |i|
	mas[i] = str[i].split("").uniq.sort.join
end
puts mas.uniq.size

n = gets.to_i
puts gets.chomp.split.map{|s| s.split('').sort.uniq.join}.sort.uniq.size

gets
puts gets.split.map{|s| s.chars.uniq.sort.join}.uniq.size

class Manuscrito
	def initialize(count, string)
		@count = count
		@string = string
	end

	def decipher
		string = @string.dup
		words = string.split
		roots = find_roots(words)
		words = delete_same(words, roots)
		objects = roots.size + words.size
		puts objects
	end

	private

	def find_roots(words)
		roots = Array.new
		words.each do |word|
			sorted_word = word.split('').sort.join.squeeze
			if sorted_word.size == word.size
				if !(roots.include? sorted_word)
					roots << sorted_word
				end
			end
		end
		roots
	end

	def delete_same(words, roots)
		same = Array.new
		words.each do |word|
			roots.each do |root|
				if word.split('').sort.join.squeeze == root
					same << word
				end
			end
		end
		words = words - same
		words
	end
end

n = gets
string = gets

manuscrito = Manuscrito.new(n, string)
manuscrito.decipher


Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.  The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously.

a,b=gets.split.map(&:to_f)
p gets.to_i.times.map{
x,y,z=gets.split.map(&:to_f)
	Math.hypot(a-x,b-y)/z
}.min

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

ans = []
n.times do
   x,y,v = gets.split.map(&:to_f)
   ans << Math.sqrt(((x-a)*(x-a)).abs + ((y-b)*(y-b)).abs) / v
end

puts ans.min

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

arr = []
n.times do
  x2, y2, v = gets.chomp.split.map(&:to_f)
  arr << Math.sqrt(((x2 - x)**2).abs + ((y2 - y)**2).abs) / v
end
puts arr.min

class Point

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

  def distance(p1)
    Math.sqrt((@x-p1.x)**2 + (@y-p1.y)**2)
  end
end

class Car

  def initialize(point_car, point_res, speed)
    @point_car = point_car
    @point_res = point_res
    @speed = speed
  end

  def res()
    @point_car.distance(@point_res)/@speed
  end
end

a, b = gets.split.map{|x| x.to_f}
user_point = Point.new(a,b)
res =  Float::INFINITY
eps = 10**-6
gets.to_i.times do |n|
  a,b,v =  gets.split.map{|x| x.to_f}
  car_point = Point.new(a,b)
  car = Car.new(car_point, user_point, v)
  if ((res - car.res) > eps)
    res = car.res
  end
end

puts res

a,b=gets.split.map(&:to_i)
n=gets.to_i
time=10000000
n.times do
  xi,yi,vi=gets.split.map(&:to_i)
  x=(xi-a).abs
  y=(yi-b).abs
  t=Math.sqrt(x**2+y**2)/vi
  if(t<time)
    time=t
  end
end
puts time

x,y=gets.split.map{|e| e.to_f}
n=gets.to_i
ans=0
n.times{|i|
	x1,y1,z1=gets.split.map{|e| e.to_f}
	t=Math.hypot(x-x1,y-y1)/z1
	if i==0 || ans>t then
		ans=t
	end
}
puts ans

ab = gets.chomp.split.map(&:to_i)
n = gets.chomp.to_i
arr = []
d = []
for i in (0..n-1)
	arr << gets.chomp.split.map(&:to_i)
	d << Math.sqrt((arr[i][0] - ab[0])**2 + (arr[i][1] - ab[1])**2)/arr[i][2]
end

print d.min

result = 1000000.0
my_x, my_y = gets.split.map(&:to_i)
n = gets.chomp.to_i

1.upto(n) do
	x, y, v = gets.split.map(&:to_i)

	d = Math.sqrt((my_x-x)**2 + (my_y-y)**2)/v

	result = [d, result].min
end

puts result.round(8)

a,b = gets.split.map &:to_f
n = gets.to_i
puts (1..n).map{|_|
  x,y,v=gets.split.map &:to_f
  Math.sqrt((x-a)**2+(y-b)**2)/v
}.min

def dist x1, x2, y1, y2
	((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
end

charX, charY = gets.chomp.split(' ').map(&:to_i)

taxiNum = gets.chomp.to_i
distArr = []

taxiNum.times do
	taxiX, taxiY, velocity = gets.chomp.split(' ').map(&:to_i)
	value = dist charX, taxiX, charY, taxiY
	distArr << value / velocity
end

puts distArr.min

a,b=gets.split.map(&:to_f)
p gets.to_i.times.map{
x,y,z=gets.split.map(&:to_f)
((a-x).abs+(b-y).abs)/z
}.min

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

arr = []
n.times do
  x2, y2, v = gets.chomp.split.map(&:to_f)
  arr << ((x2 - x).abs + (y2 - y).abs) / v
end
puts arr.min


You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \le x \le r$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the number of segments and the upper bound for coordinates. The next $$$n$$$ lines contain two integers each $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — the endpoints of the $$$i$$$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $$$l_i=r_i$$$, i.e. a segment can degenerate to a point.

In the first line print one integer $$$k$$$ — the number of points that don't belong to any segment. In the second line print exactly $$$k$$$ integers in any order — the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the point $$$1$$$ belongs to the second segment, the point $$$2$$$ belongs to the first and the second segments and the point $$$5$$$ belongs to the third segment. The points $$$3$$$ and $$$4$$$ do not belong to any segment.In the second example all the points from $$$1$$$ to $$$7$$$ belong to the first segment.

a,b=gets.split.map &:to_i
r=[*1..b]
a.times{x,y=gets.split.map &:to_i;r-=[*x..y]}
p r.size
puts r*' '

N, M = gets.chomp.split(/ /)
range = *(1..M.to_i)

N.to_i.times do |i|
  u, l = gets.chomp.split(/ /)

  (u.to_i..l.to_i).each do |i|
    if range.include? i
      range.delete(i)
    end
  end
end

p range.length

if range.length > 0
  range.each{|i| print "#{i} "}
end

def solution
  n, m = read_ints

  starts = Hash.new { |h, k| h[k] = 0 }
  ends   = Hash.new { |h, k| h[k] = 0 }

  n.times do
    l, r = read_ints
    starts[l] += 1
    ends[r] += 1
  end

  crt = 0

  alone = []

  1.upto(m) do |i|
    crt += starts[i]
    alone << i if crt == 0
    crt -= ends[i]
  end

  puts alone.size
  puts alone.join(' ')

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N, M = gets.split.map(&:to_i)
imos = Array.new(M+2, 0)
N.times do
    l, r = gets.split.map(&:to_i)
    imos[l] += 1
    imos[r+1] -= 1
end
(1..M).each do |i|
    imos[i] += imos[i-1]
end
ans = (1..M).select{|i|imos[i] == 0}
puts ans.length
puts ans.join(' ') if ans.length > 0

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

ary = Array.new(m+1, 0)
n.times do
  l, r = gets.strip.split.map(&:to_i)
  l.upto(r).each {|i| ary[i]=1}
end

ans=[]
1.upto(m).each {|i| ans << i if ary[i]==0 }

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

n, m = gets.split.map(&:to_i)
ans = []
lrs = []
n.times do
  l, r = gets.split.map(&:to_i)
  lrs << (l..r).to_a
end

(1..m).each do |i|
  inclusive = false
  lrs.each do |lr|
    if lr.to_a.include?(i)
      inclusive = true
    end
  end
  ans << i unless inclusive
end
puts ans.size
puts ans.join(" ")

def solution(m, segments)
  o = {}
  c = {}

  segments.each do |segment|
    o[segment[0]] = o.fetch(segment[0], 0) + 1
    c[segment[1]] = c.fetch(segment[1], 0) + 1
  end

  s = []
  x = 0
  (1..m).each do |i|
    x += o.fetch(i, 0)
    s << i if x == 0
    x -= c.fetch(i, 0)
  end
  return s
end

n, m = gets.chomp.split(" ").map(&:to_i)
segments = []
n.times { segments << gets.chomp.split(" ").map(&:to_i) }

s = solution(m, segments)

puts s.length
puts s.join(" ")

n, m = gets.split.map{|x| x.to_i}
segs = []
n.times{segs << gets.split.map{|x| x.to_i}}
points = []
(1..m).each do
    |x| points << x if segs.inject(true) do |s, y|
        s &&= !x.between?(y[0], y[1])
    end
end
puts(points.size, points.join(' '))

N, M = gets.chomp.split(/ /)
range = *(1..5)
am = 0

N.to_i.times do |i|
  u, l = gets.chomp.split(/ /)

  (u.to_i..l.to_i).each do |i|
    if range.include? i
      range.delete(i)
    end
  end
end

if range.length > 0
  p range.length
  p range
end

N, M = gets.chomp.split(/ /)
range = *(1..M.to_i)
am = 0

N.to_i.times do |i|
  u, l = gets.chomp.split(/ /)

  (u.to_i..l.to_i).each do |i|
    if range.include? i
      range.delete(i)
    end
  end
end

if range.length > 0
  p range.length
  range.each{|i| print "#{i} "}
end


A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

n,m=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
g=Array.new(n){Array.new(n,0)}
m.times{
        p,q=gets.split.map(&:to_i)
        g[p-1][q-1]=g[q-1][p-1]=1
}
ans=9999999999
0.upto(n-1){|i|
        (i+1).upto(n-1){|j|
                if g[i][j]==0 then
                        next
                end
                (j+1).upto(n-1){|k|
                        if g[i][k]==0 || g[j][k]==0 then
                                next
                        end
                        ans=[ans,a[i]+a[j]+a[k]].min
                }
        }
}
puts (ans>=999999999)?-1:ans

n, m = gets.split("\s").map(&:to_i)
cost = gets.split("\s").map(&:to_i)
arr = Array.new(111) { Array.new }
m.times do
	u, v = gets.split("\s").map(&:to_i)
	arr[u] << v
	arr[v] << u
end

res = 1e10
for i in 1..n
	for j in (i+1)..n
		for k in (j+1)..n
			res = [res, cost[i-1]+cost[j-1]+cost[k-1]].min if arr[i].include?(j) && arr[j].include?(k) && arr[k].include?(i)
		end
	end
end

res = -1 if res == 1e10
puts res

sn, sm = gets.chop.split(/\s+/)

count = sn.to_i
countRelation = sm.to_i

costs = Array.new(0)
scosts = gets.chop.split(/\s+/)
(0..count-1).each { |i|
  costs[i] = scosts[i].to_i
}

relations = Array.new()
(0..count-1).each { |i|
  relations[i] = Array.new()
  (0..count-1).each { |j|
    relations[i][j] = false
  }
}

(0..countRelation-1).each { |i|
  su, sv = gets.chop.split(/\s+/)
  u = su.to_i - 1;
  v = sv.to_i - 1;
  relations[u][v] = true
  relations[v][u] = true
}

solves = Array.new(0)

#(0..count-2).each { |row|
##  (row..count-2).each { |col|
#    if (relations[row][col] == true and relations[row][col+1] == true and relations[row+1][col+1] == true)
#      solves[solves.length] =  costs[row] + costs[col] + costs[col+1]
#    end
#  }
#}

(0..count-1).each { |i|
  (0..count-1).each { |j|
    (0..count-1).each { |k|
      if (relations[i][j] == true and relations[j][k] == true and relations[i][k] == true)
        solves[solves.length] =  costs[i] + costs[j] + costs[k]
      end
    }
  }
}

if (solves.length > 0)
  puts solves.min
else
  puts "-1"
end

sn, sm = gets.chop.split(/\s+/)

count = sn.to_i
countRelation = sm.to_i

costs = Array.new(0)
scosts = gets.chop.split(/\s+/)
(0..count-1).each { |i|
  costs[i] = scosts[i].to_i
}

relations = Array.new()
(0..count-1).each { |i|
  relations[i] = Array.new()
  (0..count-1).each { |j|
    relations[i][j] = false
  }
}

(0..countRelation-1).each { |i|
  su, sv = gets.chop.split(/\s+/)
  u = su.to_i - 1;
  v = sv.to_i - 1;
  relations[u][v] = true
  relations[v][u] = true
}

solves = Array.new(0)

(0..count-2).each { |row|
  (row..count-2).each { |col|
    if (relations[row][col] == true and relations[row][col+1] == true and relations[row+1][col+1] == true)
      solves[solves.length] =  costs[row] + costs[col] + costs[col+1]
    end
  }
}

if (solves.length > 0)
  puts solves.min
else
  puts "-1"
end


Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 \le n \le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$\mathbf{1 \le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree:   A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a,b,c \le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$\mathbf{1 \leq m < n}$$$), representing the size of the tree and the number of restrictions. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ ($$$1 \le a_i, b_i, c_i \le n$$$, $$$a$$$, $$$b$$$, $$$c$$$ are distinct), signifying that node $$$b_i$$$ cannot lie on the simple path between nodes $$$a_i$$$ and $$$c_i$$$.  It is guaranteed that the sum of $$$n$$$ across all test cases will not exceed $$$10^5$$$.

For each test case, output $$$n-1$$$ lines representing the $$$n-1$$$ edges in the tree. On each line, output two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) signifying that there is an edge between nodes $$$u$$$ and $$$v$$$. Given edges have to form a tree that satisfies Omkar's restrictions.

NoteThe output of the first sample case corresponds to the following tree:    For the first restriction, the simple path between $$$1$$$ and $$$3$$$ is $$$1, 3$$$, which doesn't contain $$$2$$$. The simple path between $$$3$$$ and $$$5$$$ is $$$3, 5$$$, which doesn't contain $$$4$$$. The simple path between $$$5$$$ and $$$7$$$ is $$$5, 3, 1, 2, 7$$$, which doesn't contain $$$6$$$. The simple path between $$$6$$$ and $$$4$$$ is $$$6, 7, 2, 1, 3, 4$$$, which doesn't contain $$$5$$$. Thus, this tree meets all of the restrictions.The output of the second sample case corresponds to the following tree:

gets.to_i.times do
	n, m = gets.split.map(&:to_i)
	vec = Array.new(n+1) { 0 }
	for i in 0..m-1 do
		x, y, z = gets.split.map(&:to_i)
		vec[y] = 1
	end
	pos = 0
	for i in 1..n do
		if vec[i] == 0
			pos = i
			break
		end
	end
	for i in 1..n do
		if pos == i
			next
		end
		puts "#{pos} #{i}"
	end
end

gets.to_i.times do
	n, m = gets.split.map(&:to_i)
	vec = Array.new(n+1) { 0 }
	for i in 0..m-1 do
		x, y, z = gets.split.map(&:to_i)
		vec[y] = 1
	end
	pos = 1;
	for i in 1..n do
		if vec[i] == 0
			pos = 1
			break
		end
	end
	for i in 1..n do
		if pos == i
			next
		end
		puts "#{pos} #{i}"
	end
end


This is an easier version of the problem. In this version, $$$n \le 2000$$$.There are $$$n$$$ distinct points in three-dimensional space numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th point has coordinates $$$(x_i, y_i, z_i)$$$. The number of points $$$n$$$ is even.You'd like to remove all $$$n$$$ points using a sequence of $$$\frac{n}{2}$$$ snaps. In one snap, you can remove any two points $$$a$$$ and $$$b$$$ that have not been removed yet and form a perfectly balanced pair. A pair of points $$$a$$$ and $$$b$$$ is perfectly balanced if no other point $$$c$$$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$.Formally, point $$$c$$$ lies within the axis-aligned minimum bounding box of points $$$a$$$ and $$$b$$$ if and only if $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$, and $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Note that the bounding box might be degenerate. Find a way to remove all points in $$$\frac{n}{2}$$$ snaps.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ is even), denoting the number of points. Each of the next $$$n$$$ lines contains three integers $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$), denoting the coordinates of the $$$i$$$-th point. No two points coincide.

Output $$$\frac{n}{2}$$$ pairs of integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting the indices of points removed on snap $$$i$$$. Every integer between $$$1$$$ and $$$n$$$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them.

NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $$$z = 0$$$ plane). Note that order of removing matters: for example, points $$$5$$$ and $$$1$$$ don't form a perfectly balanced pair initially, but they do after point $$$3$$$ is removed.

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
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 kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
datas = []
n.times do
  datas << inp
end
used = na(n,false)
n.times do |i|
  next if used[i]
  r = 0
  min = 1e20
  a,b,c = datas[i]
  ((i+1)...n).each do |j|
    next if used[j]
    s = ((a-datas[j][0]).abs+(b-datas[j][1]).abs+(c-datas[j][2]).abs)
    if(s < min)
      min = s
      r = j
    end
  end
  puts "#{r+1} #{i+1}"
  used[i] = true
  used[r] = true
end

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
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 kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
datas = []
n.times do
  datas << inp
end
used = na(n,false)
n.times do |i|
  next if used[i]
  r = 0
  min = 1e20
  a,b,c = datas[i]
  ((i+1)...n).each do |j|
    next if used[j]
    s = ((a-datas[j][0])+(b-datas[j][1])+(c-datas[j][2])).abs
    if(s < min)
      min = s
      r = j
    end
  end
  puts "#{r+1} #{i+1}"
  used[i] = true
  used[r] = true
end

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
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 kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
datas = []
n.times do
  datas << inp
end
used = na(n,false)
n.times do |i|
  next if used[i]
  r = 0
  min = 1e20
  a,b,c = datas[i]
  ((i+1)...n).each do |j|
    next if used[j]
    s = ((a-datas[j][0]+1e-20)*(b-datas[j][1]+1e-20)*(c-datas[j][2]+1e-20)).abs
    if(s < min)
      min = s
      r = j
    end
  end
  puts "#{r+1} #{i+1}"
  used[i] = true
  used[r] = true
end