This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size $$$n \times m$$$. This table consists of symbols $$$0$$$ and $$$1$$$.You can make such operation: select $$$3$$$ different cells that belong to one $$$2 \times 2$$$ square and change the symbols in these cells (change $$$0$$$ to $$$1$$$ and $$$1$$$ to $$$0$$$).Your task is to make all symbols in the table equal to $$$0$$$. You are allowed to make at most $$$3nm$$$ operations. You don't need to minimize the number of operations.It can be proved that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n, m \leq 100$$$). Each of the next $$$n$$$ lines contains a binary string of length $$$m$$$, describing the symbols of the next row of the table. It is guaranteed that the sum of $$$nm$$$ for all test cases does not exceed $$$20000$$$.

For each test case print the integer $$$k$$$ ($$$0 \leq k \leq 3nm$$$) — the number of operations. In the each of the next $$$k$$$ lines print $$$6$$$ integers $$$x_1, y_1, x_2, y_2, x_3, y_3$$$ ($$$1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m$$$) describing the next operation. This operation will be made with three cells $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$. These three cells should be different. These three cells should belong into some $$$2 \times 2$$$ square.

NoteIn the first test case, it is possible to make only one operation with cells $$$(1, 1)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After that, all symbols will be equal to $$$0$$$.In the second test case:  operation with cells $$$(2, 1)$$$, $$$(3, 1)$$$, $$$(3, 2)$$$. After it the table will be: 011001000  operation with cells $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$. After it the table will be: 000000000 In the fifth test case:  operation with cells $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$. After it the table will be: 010110  operation with cells $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After it the table will be: 000000

def apply(x1, x2, x3, x4, op)
  op.each do |el|
    x1 = 1 - x1 if el.include?([1, 1])
    x2 = 1 - x2 if el.include?([1, 2])
    x3 = 1 - x3 if el.include?([2, 1])
    x4 = 1 - x4 if el.include?([2, 2])
  end
  return [x1, x2, x3, x4]
end

def fix_sq(xs, op)
  num_o = xs.sum
  xs_z = xs.zip [[1, 1], [1, 2], [2, 1], [2, 2]]
  case
  when num_o == 0
    return op
  when num_o == 4
    new_op = [[2, 1], [1, 2], [1, 1]]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 3
    new_op = xs_z.filter {|el| el[0] == 1}.map {|el| el[1]}
    op << new_op
    return op
  when num_o == 2
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 1
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}.first(2)
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = []
  n.times do
    arr << gets.chomp.split('').map(&:to_i)
  end
  res = []
  row = 0
  while row < n
    col = 0
    row = [row + 2, n].min
    while col < m
      col = [col + 2, m].min
      temp = fix_sq(
        [
          arr[row - 2][col - 2],
          arr[row - 2][col - 1],
          arr[row - 1][col - 2],
          arr[row - 1][col - 1]
        ],[])
      res += temp.map{|op| op.map{|el| [el[0] + row - 2, el[1] + col - 2]}}
      arr[row - 2][col - 2] =
        arr[row - 2][col - 1] =
        arr[row - 1][col - 2] =
        arr[row - 1][col - 1] = 0
    end
  end
  puts res.size
  res.each do |el|
    puts el.flatten.join(' ')
  end
end

def apply(x1, x2, x3, x4, op)
  op.each do |el|
    x1 = 1 - x1 if el.include?([1, 1])
    x2 = 1 - x2 if el.include?([1, 2])
    x3 = 1 - x3 if el.include?([2, 1])
    x4 = 1 - x4 if el.include?([2, 2])
  end
  return [x1, x2, x3, x4]
end

def fix_sq(xs, op)
  num_o = xs.sum
  xs_z = xs.zip [[1, 1], [1, 2], [2, 1], [2, 2]]
  case
  when num_o == 0
    return op
  when num_o == 4
    new_op = [[2, 1], [1, 2], [1, 1]]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 3
    new_op = xs_z.filter {|el| el[0] == 1}.map {|el| el[1]}
    op << new_op
    return op
  when num_o == 2
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 1
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}.first(2)
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = []
  n.times do
    arr << gets.chomp.split('').map(&:to_i)
  end
  res = []
  row = 0
  while row < n
    col = 0
    row = [row + 2, n].min
    while col < m
      col = [col + 2, m].min
      temp = fix_sq(
        [
          arr[row - 2][col - 2],
          arr[row - 2][col - 1],
          arr[row - 1][col - 2],
          arr[row - 1][col - 1]
        ],[])
      res += temp.map{|op| op.map{|el| [el[0] + row - 2, el[1] + col - 2]}}
    end
  end
  puts res.size
  res.each do |el|
    puts el.flatten.join(' ')
  end
end

def apply(x1, x2, x3, x4, op)
  op.each do |el|
    x1 = 1 - x1 if el.include?([1, 1])
    x2 = 1 - x2 if el.include?([2, 1])
    x3 = 1 - x3 if el.include?([1, 2])
    x4 = 1 - x4 if el.include?([2, 2])
  end
  return [x1, x2, x3, x4]
end

def fix_sq(xs, op)
  num_o = xs.sum
  xs_z = xs.zip [[1, 1], [2, 1], [1, 2], [2, 2]]
  case
  when num_o == 0
    return op
  when num_o == 4
    new_op = [[2, 1], [1, 2], [1, 1]]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 3
    new_op = xs_z.filter {|el| el[0] == 1}.map {|el| el[1]}
    op << new_op
    return op
  when num_o == 2
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  when num_o == 1
    new_op = xs_z.filter {|el| el[0] == 0}.map {|el| el[1]}.first(2)
    new_op << xs_z.find {|el| el[0] == 1}[1]
    op << new_op
    return fix_sq(apply(*xs, [new_op]), op)
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = []
  n.times do
    arr << gets.chomp.split('').map(&:to_i)
  end
  res = []
  row = 0
  while row < n
    col = 0
    row = [row + 2, n].min
    while col < m
      col = [col + 2, m].min
      temp = fix_sq(
        [
          arr[row - 2][col - 2],
          arr[row - 2][col - 1],
          arr[row - 1][col - 2],
          arr[row - 1][col - 1]
        ],[])
      res += temp.map{|op| op.map{|el| [el[0] + row - 2, el[1] + col - 2]}}
    end
  end
  puts res.size
  res.each do |el|
    puts el.flatten.join(' ')
  end
end


Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof. The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**. The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T *  is always equal to T.Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands. All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.

For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.

5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv

17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c

void*
void**
void
void**
errtype
void
errtype
errtype
errtype

NoteLet's look at the second sample.After the first two queries typedef the b type is equivalent to void*, and с — to void**.The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.Then the b type is again redefined as &void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.

def parse(type, values)
  type =~ /^(\&*)(.*?)(\**)$/
  amp = $1
  base = $2
  star = $3
  if base == 'errtype'
    return 'errtype'
  elsif base != 'void'
    if !values[base]
      return 'errtype'
    end
    type = "#{amp}#{values[base]}#{star}"
    type =~ /^(\&*)(.*?)(\**)$/
    amp = $1
    base = $2
    star = $3

    if base == 'errtype'
      return 'errtype'
    end
  end

  s = star.size - amp.size
  if s < 0
    return 'errtype'
  else
    return base + "*" * s
  end
end

values = {}

gets.to_i.times{
  l = gets.chomp
  if l =~ /typedef (\S+) (\S+)/
    type = $1
    name = $2
    values[name] = parse(type, values)
  elsif l =~ /typeof (\S+)/
    type = $1
    puts parse(type, values)
  else
    raise
  end
}

h = {void: "void", errtype: "errtype"}
gets.to_i.times do
  s = gets.split
  if s[0] == "typeof"
    s[1].match(/(&*)([^&*]+)(\**)/)
    a, b, c = $1.size, $2.to_sym, $3.size
    if h[b].nil? || h[b] == "errtype" || a > c + h[b].scan(/\*/).size
      puts :errtype
    else
      if a >= c
        puts h[b][0..-(a - c + 1)]
      else
        puts h[b] + "*" * (c - a)
      end
    end
  else
    s[2] = s[2].to_sym
    s[1].match(/(&*)([^&*]+)(\**)/)
    a, b, c = $1.size, $2.to_sym, $3.size
    if h[b].nil? || h[b] == "errtype" || a > c + h[b].scan(/\*/).size
      h[s[2]] = "errtype"
    else
      if a >= c
        h[s[2]] = h[b][0..-(a - c + 1)]
      else
        h[s[2]] = h[b] + "*" * (c - a)
      end
    end
  end
end

n = STDIN.readline.to_i
regex = /^(&*)(.+?)(\**)$/
dict = Hash.new
dict['void'] = 0
n.times do
  s = STDIN.readline.split ' '
  array = regex.match(s[1])
  head = array[1].length
  body = array[2]
  tail = array[3].length
  if s[0] == "typedef" then
    base = if dict.include? body then
             dict[body]
           else
             nil
           end
    dict[s[2]] = if base == nil or base + tail - head < 0 then
                   nil
                 else
                   base + tail - head
                 end
  else
    if (!dict.include? body) || (!dict[body]) then
      puts 'errtype'
    else
      len = dict[body] + tail - head
      if len >= 0 then
        puts 'void' + ('*' * len)
      else
        puts 'errtype'
      end
    end
  end
end

h = {void: "void", errtype: "errtype"}
gets.to_i.times do
  s = gets.split
  if s[0] == "typeof"
    if s[1].match(/(&*)(#{h.keys.join(?|)})(\**)/)
      a, b, c = $1.size, $2.to_sym, $3.size
      if h[b].nil? || h[b] == "errtype" || a > c + h[b].scan(/\*/).size
        puts :errtype
      else
        if a >= c
          puts h[b][0..-(a - c + 1)]
        else
          puts h[b] + "*" * (c - a)
        end
      end
    else
      puts :errtype
    end
  else
    s[2] = s[2].to_sym
    if s[1].match(/(&*)(#{h.keys.join(?|)})(\**)/)
      a, b, c = $1.size, $2.to_sym, $3.size
      if h[b].nil? || h[b] == "errtype" || a > c + h[b].scan(/\*/).size
        h[s[2]] = "errtype"
      else
        if a >= c
          h[s[2]] = h[b][0..-(a - c + 1)]
        else
          h[s[2]] = h[b] + "*" * (c - a)
        end
      end
    else
      h[s[2]] = "errtype"
    end
  end
end

n = STDIN.readline.to_i
regex = /^(&*)(.+?)(\**)$/
dict = Hash.new
n.times do
  s = STDIN.readline.split ' '
  if s[0] == "typedef" then
    array = regex.match(s[1])
    base = if array[2] == 'void' then 0
           elsif dict.include?(array[2]) then dict[array[2]]
           else nil
           end
    if base == nil then
      dict[s[2]] = nil
    elsif base + array[3].length - array[1].length < 0 then
      dict[s[2]] = nil
    else
      dict[s[2]] = base + array[3].length - array[1].length
    end
  else
    array = regex.match(s[1])
    if !dict.include?(array[2]) || !dict[array[2]] then
      puts 'errtype'
    else
#      p array
      len = dict[array[2]] + array[3].length - array[1].length
      if len >= 0 then
        puts 'void' + ('*' * len)
      else
        puts 'errtype'
      end
    end
  end
end


One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

require 'set'

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
s = []
for i in 0..n-1
	s << gets.chomp
end
ret = 1
for i in 0..m-1
	ws = Set.new
	for j in 0..n-1
		ws.add(s[j][i])
	end
	ret *= ws.length
end
ret %= 1000000007
puts ret

n, m = gets.split.map(&:to_i)
p Array.new(m).zip(*(n.times.map{gets.chars.to_a})).map{|_| _.uniq.size - 1}.inject(&:*) % 1000000007

n, m = gets.split.map(&:to_i)
p n.times.map{gets.chars.to_a}.transpose.map{|_| _.uniq.size}.inject(&:*) % 1000000007

n,m=gets.split.map(&:to_i)
ans=1
input=[]
n.times{input+=[gets.split[0]]}
m.times{|i|
	a=Hash.new
	n.times{|j|
		a[input[j][i]]=true
	}
	ans*=a.size
	ans%=1000000007
}
p ans

#!/usr/bin/env ruby

MOD = 1000000007
n, m = gets.split.map(&:to_i)
transpose = Array.new(m) { {} }
n.times do
  gets.chomp.each_char.to_a.each_with_index do |ch, idx|
    transpose[idx][ch] = 1
  end
end

cnt = 1
transpose.each do |set|
  cnt *= set.size
  cnt %= MOD
end

p cnt

a=gets.chomp.split(' ')
a.length.times {|x| a[x]=a[x].to_i}
b=[]
c=[]
a[0].times do |x|
  b<<gets.chomp
  a[1].times do |y|
   if c[y].nil?
   c[y]=b[x][y]
  elsif !c[y].nil? && !c[y].include?(b[x][y])
  c[y]+=b[x][y]
  end
  end
end
res=1
c.length.times do |x|
 res*=c[x].length
end
puts res%(10**9+7)

n,m = gets.split.map(&:to_i)
a = []
n.times{ a << gets.strip.split(//) }
p a.transpose.map{|s| s.uniq.size}.inject(:*) % 1000000007

n,m = gets.split(" ").map(&:to_i)
arr = []
n.times do
	arr << gets.chomp
end
ans = []
(0...m).each do |j|
	count = 0
	h = {}
	(0...n).each do |i|
		letter = arr[i][j]
		unless h[letter]
			h[letter] =  true
			count += 1
		end
	end
	ans << count
end
s = 1
ans.each do |i|
	s = (s * i) % 1000000007
end
puts s

inp = gets.split(" ")
n = inp[0].to_i
m = inp[1].to_i
l = Array.new(m){[]}
for i in 0..(n-1)
  inp = gets
  for j in 0..(m-1)
    l[j] << inp[j]
  end
end

count = 1
l.each do |arr|
  arr.sort!
  #p arr
  unq = 1
  curr = 0
  while curr < (n - 1)
    if arr[curr] != arr[curr+1]
      unq += 1
	end
	curr += 1
  end
  #puts unq
  count *= unq
end

puts count % 1000000007


Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 10^9$$$) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$, $$$a_i > b_i$$$) — the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.

If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.

NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$.

def solution

  n, m = read_ints

  sum = 0
  sum_comp = 0

  diffs = []

  n.times do
    a, b = read_ints
    sum += a
    sum_comp += b
    diffs << (a - b)
  end

  diffs = diffs.sort.reverse

  if sum_comp > m
    puts -1
    return
  end

  i = 0

  while sum > m
    sum -= diffs[i]
    i += 1
  end

  puts i

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)
as, bs = [], []
N.times do |i|
    as[i], bs[i] = gets.split.map(&:to_i)
end

sum = as.inject(:+)
gains = [0] + N.times.map{|i| as[i] - bs[i]}.sort.reverse
(N+1).times do |i|
    sum -= gains[i]
    if sum <= M
        puts i; exit
    end
end
puts -1

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

sum = 0
ary = []
n.times do
  a, b = gets.strip.split.map(&:to_i)
  ary << [a,b]
  sum += a
end

ary = ary.sort_by{|x| x[1]-x[0]}
i = 0
ans = 0
while sum > m && i<n do
  sum -= (ary[i][0] - ary[i][1])
  i += 1
  ans += 1
end

if sum > m
  puts "-1"
else
  puts ans
end

n= Array.new
n = gets.chomp.split(" ").each.map(&:to_i)

a= Array.new
b= Array.new
c=0
sum=0

while n[0]>0
    a = gets.chomp.split(" ").each.map(&:to_i)
    sum+=a[0]
    b.push((a[0]-a[1]))
    n[0]-=1
end

b= b.sort

while n[1]<sum && !b.empty?
    sum-=b.pop
    c+=1
end

if(sum>n[1])
    print(-1)
else
    print(c)
end

Song = Struct.new(:a, :b) do
  def diff
    self.a - self.b
  end
end

def solution

  n, m = read_ints

  songs = []

  sum = 0

  n.times do
    a, b = read_ints
    sum += a
    songs << Song.new(a, b)
  end

  songs = songs.sort_by(&:diff).reverse

  i = 0

  while sum > m && i < songs.size
    sum -= songs[i].diff
    i += 1
  end

  if sum > m
    puts -1
  else
    puts i
  end

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

Song = Struct.new(:a, :b) do
  def diff
    self.a - self.b
  end
end

def solution

  n, m = read_ints

  songs = []

  sum = 0

  n.times do
    a, b = read_ints
    sum += a
    songs << Song.new(a, b)
  end

  songs = songs.sort_by(&:diff)

  i = 0

  while sum > m && i < songs.size
    sum -= songs[i].diff
    i += 1
  end

  if sum > m
    puts -1
  else
    puts i - 1
  end

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']


You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).

For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  x, y, z = b * 10 ** 9 + a, b, c
  puts "#{x} #{y} #{z}"
end


A median in an array with the length of n is an element which occupies position number  after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression  as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.

The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.

Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.

NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.

n,xx = gets.chomp.split(/ /).map!{|x| x.to_i}
a = gets.chomp.split(/ /).map!{|x| x.to_i}
ret = 0
if not a.include?(xx)
  ret = 1
  a << xx
end
a.sort!
m = (a.length() + 1)/2

minxx = a.index(xx)
maxxx = a.rindex(xx)
if minxx > (m-1)
  ret += (minxx - (a.length() - (minxx+1)))
elsif maxxx < (m-1)
  ret += ((a.length() - (maxxx+1)) - maxxx - 1)
end
puts ret

n, x = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
unless a.include?(x)
  a.push(x)
  ans += 1
end
a.sort!
m = (a.size()+1)/2-1

while a[m]>x
  a.unshift(-1000)
  m = (a.size()+1)/2-1
  ans+=1
end

while a[m]<x
  a.push(10000000)
  m = (a.size()+1)/2-1
  ans+=1
end

p ans

#!/usr/bin/ruby

n, x = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i).sort

cnt = 0
if arr.index(x).nil?
  arr << x
  cnt += 1
  arr.sort!
end

median = (arr.size+1) / 2 - 1
ni = arr.index(x)
ri = arr.rindex(x)

if arr[median] == x
  p cnt
  exit
end

# right adjustment
rcnt = n*100
if ni > median
  rcnt = 0
  target = ni

  if arr.size.even?
    rcnt += 1
    target -= 1
  end
  rcnt += (target-median) * 2
end

# left adjustment
lcnt = n*100
if ri < median
  lcnt = 0
  target = ri

  if arr.size.odd?
    lcnt += 1
    target += 1
  end
  lcnt += (median-target) * 2
end

p [rcnt,lcnt].min + cnt

def mid(x)
	(x-1)/2
end
n, x = gets.split(/\s+/).map(&:to_i)
a = gets.split(/\s+/).map(&:to_i).sort
res = []
1000.times do |i|
	res << i if a[mid(a.size)] == x
	a << x
	a.sort!
end
p res.min

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

$a = gets.split().map(&:to_i)
$a.sort!
def gg()
  return 0 if $a[$a.length/2] == $m
  ls = 0
  gt = 0
  eq = 0
 $a.each do |i|
    if i < $m
      ls = ls + 1
    elsif i == $m
      eq = eq + 1
    else
      gt = gt + 1
    end
  end

  return 1 if ls == gt
  if ls < gt
    ls = ls + eq
    return gt - ls
  else
    gt = gt + eq
    return ls - gt + 1
  end

end

ans = gg
puts ans

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort
  end

  def run
    median_position = calculate_median(size)
    median_number = array[median_position]

    if number == median_number
      0
    elsif array.include?(number)
      index = array.rindex(number)
      if index > median_position
        index = array.index(number)
        revert_median_calculation(index) - size
      elsif index < median_position
        (median_position - index) * 2 - size % 2
      end
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      new_median_position = calculate_median(size + 1)
      if index > new_median_position
        revert_median_calculation(index) - size
      elsif index < new_median_position
        (new_median_position - index) * 2 - (size + 1) % 2 + 1
      else
        1
      end
    end
  end

  private

  def calculate_median(array_size)
    (array_size + 1)/2 - 1
  end

  def revert_median_calculation(median)
    (median + 1) * 2 - 1
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

# ProblemC

n, x = gets.split().map! {|s| s.to_i}

ary = gets.split().map! {|s| s.to_i}

res = 0
unless ary.index(x)
  ary << x
  res += 1
end

ary = ary.sort

while true
  n = (ary.size)
  m = ((n + 1) / 2) - 1
  break if ary[m] == x
  if ary[m] > x
    ary.unshift(1)
  else
    ary << (10 ** 5)
  end
  res += 1
end

puts res

a = gets.chomp.split(" ").map{|i| i.to_i}
b = gets.chomp.split(" ").map{|i| i.to_i}

b.sort!
n = a[0]
k = a[1]

if k > b[n-1]
    puts n+1
else
    if k < b[0]
        puts n
    else
        x = (n+1)/2 - 1
        if k == b[x]
            puts 0
        else
            if k < b[x]
                i = 0
                while b[i+1] <= k do
                    i += 1
                end
                find = n -2*i -2
                puts find
            else
                i = n-1
                while b[i-1] >= k do
                    i -= 1
                end
                find = 2*i + 1 - n
                puts find
            end
        end
    end
end

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).sort
ans=0
unless a.include?(k)
	a<<k
	a.sort!
	ans+=1
	n+=1
end

if a[(n+1)/2-1]<k
	until a[(n+1)/2-1]==k
		ans+=1
		n+=1
		a<<10**5
	end
elsif a[(n+1)/2-1]>k
	until a[(n+1)/2-1]==k
		ans+=1
		n+=1
		a.unshift 1
	end
end
p ans

#!/usr/bin/ruby

n, x = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i).sort

cnt = 0
if arr.index(x).nil?
  arr << x
  cnt += 1
  arr.sort!
end

median = (arr.size+1) / 2 - 1
ni = arr.index(x)
ri = arr.rindex(x)

if arr[median] == x
  p 0
  exit
end

# right adjustment
rcnt = n*100
if ri > median
  rcnt = 0
  target = ri
  target = ni if ni > median

  if arr.size.even?
    rcnt += 1
    target -= 1
  end
  rcnt += (target-median) * 2
end

# left adjustment
lcnt = n*100
if ni < median
  lcnt = 0
  target = ni
  target = ri if ri < median

  if arr.size.odd?
    lcnt += 1
    target += 1
  end
  lcnt += (median-target) * 2
end

p [rcnt,lcnt].min + cnt

#!/usr/bin/ruby

n, x = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i).sort

cnt = 0
if arr.index(x).nil?
  arr << x
  cnt += 1
  arr.sort!
end

median = (arr.size+1) / 2 - 1
ni = arr.index(x)
ri = arr.rindex(x)

# right adjustment
rcnt = n*100
if ri > median
  rcnt = 0
  target = ri
  target = ni if ni > median

  if arr.size.even?
    rcnt += 1
    target -= 1
  end
  rcnt += (target-median) * 2
end

# left adjustment
lcnt = n*100
if ni < median
  lcnt = 0
  target = ni
  target = ri if ri < median

  if arr.size.odd?
    lcnt += 1
    target += 1
  end
  lcnt += (median-target) * 2
end

p [rcnt,lcnt].min + cnt

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

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

def gg()
  return 0 if $a[$a.length/2] == $m
  ls = 0
  gt = 0
  eq = 0
 $a.each do |i|
    if i < $m
      ls = ls + 1
    elsif i == $m
      eq = eq + 1
    else
      gt = gt + 1
    end
  end

  return 1 if ls == gt
  if ls < gt
    ls = ls + eq
    return gt - ls
  else
    gt = gt + eq
    return ls - gt + 1
  end

end

ans = gg
puts ans

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort.reverse
  end

  def run
    median_position = (size + 1)/2 - 1
    if array.include?(number)
      index = array.index(number)
      (median_position - index).abs
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      (median_position - index).abs * 2
    end
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort
  end

  def run
    median_position = (size + 1)/2 - 1
    median_number = array[median_position]

    if number == median_number
      0
    elsif array.include?(number)
      index = array.index(number)
      (median_position - index).abs
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      new_median_position = (size + 2)/2 - 1
      if index > new_median_position
        index * 2 - size + 1
      elsif index < new_median_position
        size - index + 1
      else
        1
      end
    end
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort
  end

  def run
    median_position = calculate_median(size)
    median_number = array[median_position]

    if number == median_number
      0
    elsif array.include?(number)
      index = array.index(number)
      if index > median_position
        revert_median_calculation(index) - size
      elsif index < median_position
        median_position - index
      end
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      new_median_position = calculate_median(size + 1)
      if index > new_median_position
        revert_median_calculation(index) - size
      elsif index < new_median_position
        median_position - index + 1
      else
        1
      end
    end
  end

  private

  def calculate_median(array_size)
    (array_size + 1)/2 - 1
  end

  def revert_median_calculation(median)
    (median + 1) * 2 - 1
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort
  end

  def run
    median_position = calculate_median(size)
    median_number = array[median_position]

    if number == median_number
      0
    elsif array.include?(number)
      index = array.rindex(number)
      if index > median_position
        revert_median_calculation(index) - size
      elsif index < median_position
        (median_position - index) * 2 - size % 2
      end
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      new_median_position = calculate_median(size + 1)
      if index > new_median_position
        revert_median_calculation(index) - size
      elsif index < new_median_position
        (new_median_position - index) * 2 - (size + 1) % 2 + 1
      else
        1
      end
    end
  end

  private

  def calculate_median(array_size)
    (array_size + 1)/2 - 1
  end

  def revert_median_calculation(median)
    (median + 1) * 2 - 1
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

#!/usr/bin/env ruby

class Main
  attr_reader :size, :number, :array

  def initialize(size, number, array)
    @size = size
    @number = number
    @array = array.sort
  end

  def run
    median_position = (size + 1)/2 - 1
    median_number = array[median_position]

    if number == median_number
      0
    elsif array.include?(number)
      index = array.index(number)
      (median_position - index).abs
    else
      median_number = array[median_position]
      new_array = (array + [number]).sort
      index = new_array.index(number)
      (median_position - index).abs * 2
    end
  end
end

size, number = gets.split(" ")
array = gets.split(" ")
puts Main.new(size.to_i, number.to_i, array.map(&:to_i)).run

a = gets.chomp.split(" ").map{|i| i.to_i}
b = gets.chomp.split(" ").map{|i| i.to_i}

b.sort!
n = a[0]
k = a[1]

if k > b[n-1]
    puts n+1
else
    if k < b[0]
        puts n
    else
        x = (n+1)/2 - 1
        if k == b[x]
            puts 0
        else
            if k < b[x]
                i = 0
                while b[i] < k do
                    i += 1
                end
                i -= 1 if b[i] != k
                find = n -2*i -2
                puts find
            else
                i = n-1
                while b[i] > k do
                    i -= 1
                end
                i -= 1 if b[i] != k
                find = 2*i + 2 - n
                puts find
            end
        end
    end
end

a = gets.chomp.split(" ").map{|i| i.to_i}
b = gets.chomp.split(" ").map{|i| i.to_i}

b.sort!
n = a[0]
k = a[1]

if k > b[n-1]
    puts n+1
else
    if k < b[0]
        puts n
    else
        x = (n+1)/2 - 1
        if k == b[x]
            puts 0
        else
            if k < b[x]
                i = 0
                while b[i] < k do
                    i += 1
                end
                i -= 1 if b[i] != k
                find = n -2*i -2
                puts find
            else
                i = n-1
                while b[i] > k do
                    i -= 1
                end
                i += 1 if b[i] != k
                find = 2*i + 1 - n
                puts find
            end
        end
    end
end

a = gets.chomp.split(" ").map{|i| i.to_i}
b = gets.chomp.split(" ").map{|i| i.to_i}

b.sort!
n = a[0]
k = a[1]

if k > b[n-1]
    puts n+1
else
    if k < b[0]
        puts n
    else
        x = (n+1)/2
        if k == b[x]
            puts 0
        else
            if k < b[x]
                i = 0
                while b[i] < k do
                    i += 1
                end
                i -= 1 if b[i] != k
                find = n -2*i -2
                puts find
            else
                i = n-1
                while b[i] > k do
                    i -= 1
                end
                i -= 1 if b[i] != k
                find = 2*i + 2 - n
                puts find
            end
        end
    end
end


A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.

The first line consists of two integers n and m . Then m lines follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n. It is guaranteed that every pair of cities will appear at most once in the input.

You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi. If there are several solutions, you may print any of them.

NoteThis is one possible solution of the example:   These are examples of wrong solutions:   The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair.   The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads.   Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.

args = gets.split(" ").map{ |i| i.to_i}
n = args[0]
m = args[1]

prohib = Array.new(n) { |i| 0 }
for i in 0...m
  args = gets.split(" ").map{ |i| i.to_i}
  prohib[args[0]-1] += 1
  prohib[args[1]-1] += 1
end
center = prohib.each_with_index.min[1] + 1
puts n - 1
(1..n).to_a.select{ |a| a != center }.each{ |b| puts "#{b} #{center}"}

n,m=gets.split.map(&:to_i)
g=[]
m.times do
  a,b=gets.split.map(&:to_i)
  g<<a<<b
end
g=((1..n).to_a-g).first
p n-1
(1..n).each{|i|puts "#{g} #{i}" if g!=i}

n, m = gets.split(' ').map(&:to_i)
cannot = Array.new(n + 1){Array.new}
m.times do
  a, b = gets.split(' ').map(&:to_i)
  a, b = b, a if a > b
  cannot[a] << b
  cannot[b] << a
end
center = 1
for i in 1..n
  if cannot[i].size < cannot[center].size
    center = i
  end
end
link = Array.new(n + 1){Array.new(n + 1, false)}
road = []
for i in 1..n
  next if i == center
  if cannot[center].include? i
    for j in 1..n
      next if i == j
      next if cannot[i].include? j
      link[i][j] = link[j][i] = true
      road << [i, j]
      for k in 1...j
        next if link[j][k]
        link[i][k] = link[k][i] = true
        road << [i, k]
      end
      break
    end
  else
    link[center][i] = link[i][center] = true
    road << [center, i]
  end
end
puts road.size
road.each do |r|
  puts r.join(' ')
end

n,m=gets.chomp.split.map(&:to_i)
a=Array.new(1000,0)
m.times do
	i,j=gets.chomp.split.map(&:to_i)
	a[i],a[j]=1,1
end
i,j=1,1
while i<=n
	break if a[i]==0
	i+=1
end
puts n-1
while j<=n
	puts "#{i} #{j}" if j!=i
	j+=1
end

n,m=gets.split.map(&:to_i)
x=[true]*n
m.times {
    gets.split.map(&:to_i).each {|v|
        x[v-1]=false
    }
}
c=x.index(true)+1
p n-1
1.upto(n) {|v|
    puts "#{c} #{v}" if c != v
}

require "Set"

n,m = gets.split(" ").map(&:to_i)
not_connecting = Set.new
not_connecting_pair = []
m.times do
	a,b = gets.split(" ").map(&:to_i)
	not_connecting.add(a)
	not_connecting.add(b)
	not_connecting_pair << [a,b]
end
candidate = (1..n).to_a - not_connecting.to_a
node = candidate.first

puts n - 1
(1..n).each do |i|
	puts "#{node} #{i}" if node != i
end

require 'set'
n, m = gets.split.collect{|i| i.to_i}
mark = Set.new
for i in 0...m
    gets.split.collect{|i| i.to_i}.each{|i| mark.add(i)}
end
if not (Set.new(1..n)-mark).empty?
    puts n-1
    c = (Set.new(1..n)-mark).to_a[0]
    for i in 1..n
        print c, " ", i, "\n" if i!=c
    end
end

require 'set'

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

n, m = read_next_line
all = Set.new(1..n)
for _ in 1..m
  all -= read_next_line
end

center = all.first
puts n - 1
for i in 1..n
  puts "#{center} #{i}" if i != center
end

n, m = gets.split(' ').map(&:to_i)
ab = m.times.map {|i| gets.split(' ').map(&:to_i).sort }
center = (1..n).select{|i| ab.flatten.uniq.all?{|p| i != p } }
puts n.pred
(1..n).each{|i|
  unless i == center.first
    puts [center.first,i].join ' '
  end
}

n,m=gets.split.map(&:to_i)
x=[true]*n
m.times {
    gets.split.map(&:to_i).each {|v|
        x[v-1]=false
    }
}
c=x.index(true)+1
1.upto(n) {|v|
    puts "#{c} #{v}" if c != v
}


You are given a positive integer $$$n$$$, it is guaranteed that $$$n$$$ is even (i.e. divisible by $$$2$$$).You want to construct the array $$$a$$$ of length $$$n$$$ such that:   The first $$$\frac{n}{2}$$$ elements of $$$a$$$ are even (divisible by $$$2$$$);  the second $$$\frac{n}{2}$$$ elements of $$$a$$$ are odd (not divisible by $$$2$$$);  all elements of $$$a$$$ are distinct and positive;  the sum of the first half equals to the sum of the second half ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the array. It is guaranteed that that $$$n$$$ is even (i.e. divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — "NO" (without quotes), if there is no suitable answer for the given test case or "YES" in the first line and any suitable array $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) satisfying conditions from the problem statement on the second line.

gets.to_i.times do
	n = gets.to_i
	if n % 4 == 0
		a = (1..n / 2).map { _1 * 2 }
		a.concat((1...n / 2).map { _1 * 2 - 1 } + [n + n / 2 - 1])
		puts 'YES', a.join(' ')
	else
		puts 'NO'
	end
end

# frozen_string_literal: true

class Result
  def print_result
    n = gets.to_i
    return puts 'NO' if (n / 2).odd?

    puts 'YES'

    (n / 2).times do |i|
      print (i + 1) * 2, ' '
    end
    (n / 2).times do |i|
      print (i * 2) + 1 + (i + 1 == n / 2 ? n / 2 : 0), ' '
    end
    puts
  end
end

gets.to_i.times do
  Result.new.print_result
end

1.upto(gets.chomp.to_i) do
  n = gets.chomp.to_i
  if n % 4 != 0
    puts 'NO'
  else
    puts 'YES'
    k = n/2
    (1..k).each {|x| print "#{2*x} "; }
    (1..k-1).each {|x| print "#{2*x-1} "; }
    puts 3*k-1
  end
end

number_of_testcases = gets.to_s.to_i

number_of_testcases.times do |i|

  n = gets.to_s.to_i
  h = n/2

  if h.odd?
    puts "No"
    next
  else
    puts "Yes"
  end

  2.step(n,  2){ |i| print "#{i} " }
  1.step(n-3,2){ |i| print "#{i} " }
  puts 2 + 2 * (h-1) + (h-1)
end

module Enumerable
  def sum
    inject :+
  end
end

gets.to_i.times do
  n = gets.to_i
  if n%4 != 0
    puts 'NO'
    next
  end
  puts 'YES'
  a, b = [], []
  (0...n/4).each{|i| a[2*i..2*i+1] = [4*i + 2, 4*i + 4]}
  (0...a.size-1).each{|i| b[i] = 2*i + 1}
  b << a.sum - b.sum
  puts a.join(' ') + ' ' + b.join(' ')
end

module Enumerable
  def sum
    inject :+
  end
end

gets.to_i.times do
  n = gets.to_i
  if n%4 != 0
    puts 'NO'
    next
  end
  puts 'YES'
  a, b = [], []
  (0...n/4).each{|i| a[2*i..2*i+1] = 4*i + 2, 4*i + 4}
  (0...a.size-1).each{|i| b[i] = 2*i + 1}
  b << a.sum - b.sum
  puts a.join(' ') + ' ' + b.join(' ')
end

module Enumerable
  def sum
    inject :+
  end
end

gets.to_i.times do
  n = gets.to_i
  if n%4 != 0
    puts 'NO'
    next
  end
  puts 'YES'
  a, b = []*(n/2), []*(n/2)
  (0...n/4).each{|i| a[2*i, 2*i + 1] = [4*i + 2, 4*i + 4]}
  (0...a.size-1).each{|i| b[i] = 2*i + 1}
  b << a.sum - b.sum
  puts a.join(' ') + ' ' + b.join(' ')
end

module Enumerable
  def sum
    inject :+
  end
end

gets.to_i.times do
  n = gets.to_i
  if n%4 != 0
    puts 'NO'
    next
  end
  puts 'YES'
  a, b = []*(n/4), []*(n/4)
  (0...n/4).each{|i| a[2*i, 2*i + 1] = [4*i + 2, 4*i + 4]}
  (0...a.size-1).each{|i| b[i] = 2*i + 1}
  b << a.sum - b.sum
  puts a.join(' ') + ' ' + b.join(' ')
end

t = gets.to_i

1.upto(t) do
  n = gets.to_i
  result = 2.step(n, 2).to_a + 1.step(n, 2).to_a

  result[n-1] += result[0, n/2].inject(&:+) - result[n/2, n/2].inject(&:+)

  if result.last.odd?
    puts 'YES'
    puts result.join(' ')
  else
    puts 'NO'
  end
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  n>>=1
  if(n&1)==1
    puts "NO"
    next
  end
  puts "YES"
  sum =0
  (1).upto(n) do |i|
    print "#{i*2} "
    sum+=i*2
  end

  (1).upto(n-1) do |i|
    sum-=i*2-1
    print "#{i*2-1} "
  end
  puts sum
end

gets.to_i.times do
  n = gets.to_i
  if n%4 != 0
    puts 'NO'
    next
  end
  puts 'YES'
  a = []
  (0...n/4).each{|i| a += [4*i + 2, 4*i + 4]}
  (0...n/4).each{|i| a += [4*i + 1, 4*i + 7]}
  puts a.join ' '
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  n>>=1
  if(n&1)==1
    puts "NO"
    next
  end
  puts "YES"
  (1).upto(n) do
    print "2 "
  end
  (1).upto(n) do |i|
    x=i&1
    x<<=1
    x+=1
    print "#{x} "
  end
  puts ""
end

t=gets.to_i
(1).upto(t) do
  n=gets.to_i
  n>>=1
  if(n&1)==1
    puts "NO"
    next
  end
  puts "YES"
  (1).upto(n) do |i|
    print "#{i*2} "
  end
  (1).upto(n) do |i|
    print "#{i*2-1} "
  end
  puts ""
end


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output:    the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way;  "-1" if no such value $$$k$$$ exists.

for t in 0...gets.to_i
	n = gets.to_i
	a = gets.split.map(&:to_i)
	sum = a.sum
	ans = 0;
	if sum % n > 0
		puts -1
	elsif
		(0...n).each do |i|
			if a[i] * n > sum
				ans += 1
			end
		end
		puts ans
	end
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i)
  s=a.sum
  if s%n!=0
    puts "-1"
    next
  end
  c=0
  z=s/n
  a.each do |aa|
    if aa>z
      c+=1
    end
  end
  puts c
end


Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.

The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.

Print a single integer — the answer to the problem.

NoteIn the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7.In the second sample you need to add numbers 20, 21, 22.

def update_hash hash, num
  return hash[num] = true if hash[num].nil?
  hash.delete(num)
  update_hash(hash, num.next)
end

gets

hash = {}
b = gets.chomp.split(" ").map(&:to_i).each{|num| update_hash(hash, num)}

puts hash.keys.max - hash.keys.count + 1

MAX=(2*10**9)*(10**5)+1
n=gets.to_i
a=gets.split.map(&:to_i)
a<<MAX
a.reverse!
ans=0
i=0
until a.last==MAX
  b=a.pop
  num=1
  while b==a.last
    a.pop
    num+=1
  end
  if num%2==1
    ans+=b-i
    i=b+1
  end
  (num/2).times{a.push(b+1)}
end
puts ans

gets

b = gets.chomp.split(" ").map(&:to_i).map{|a|2 **a}.inject(:*)

puts b.to_s(2).count('0')


Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n,k \leq 10^5$$$) — the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$) — Bob's questions.

Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.

NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios.

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

appeared = [0]*(n+1)
cnt = [0]*(n+1)
x.each do |v|
  appeared[v] = 1
  cnt[v] = appeared[v]
  cnt[v] += appeared[v-1] if v-1 >= 0
  cnt[v] += appeared[v+1] if v+1 <= n
end
ans = 3*n-2
cnt.each do |v|
  ans -= v
end
#p cnt
p ans


We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).

The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings. Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.

Print any suitable string s, or -1 if such string doesn't exist.

NoteIn the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.In the third example it's impossible to obtain given strings by aforementioned operations.

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

aaa=s[0]
if s.any?{|s| s.chars.sort != aaa.chars.sort}
puts -1
exit(0)
end

if n>=5
    k.times do |j|
  diff = []
  n.times do |i|
    diff << i if s[0][i] != s[j][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); ((ex_id && sz == 0) || sz == 2)}
      puts org
      exit(0)
    end
  end
    end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

aaa=s[0]
if s.any?{|s| s.chars.sort != aaa.chars.sort}
puts -1
exit(0)
end

if n>=5
  diff = []
    k.times do |j|
  n.times do |i|
    diff << i if s[0][i] != s[j][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); ((ex_id && sz == 0) || sz == 2)}
      puts org
      exit(0)
    end
  end
    end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

if n>=5
  diff = []
  n.times do |i|
    diff << i if s[0][i] != s[1][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

aaa=s[0]
if s.any?{|s| s.chars.sort != aaa.chars.sort}
puts -1
exit(0)
end

if n>=5
  diff = []
  n.times do |i|
    diff << i if s[0][i] != s[1][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s[1,s.size].all? {|s| sz = diffsz(s,org); ((ex_id && sz == 0) || sz == 2)}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s[1,s.size].all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

aaa=s[0]
if s.any?{|s| s.chars.sort != aaa.chars.sort}
puts -1
exit(0)
end

if n>=5
  diff = []
  n.times do |i|
    diff << i if s[0][i] != s[1][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); ((ex_id && sz == 0) || sz == 2)}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)

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

def diffsz(x,y)
  x.chars.zip(y.chars).reject{|x,y|x==y}.size
end

s = []
k.times{s << gets.chomp}

if k==1
  s=s[0]
  s[0], s[1] = s[1], s[0]
  puts s
  exit(0)
end

ex_id = s[0].size != s[0].chars.uniq.size

if n>=5
  diff = []
  n.times do |i|
    diff << i if s[0][i] != s[1][i]
  end

  if diff.size>4
    puts -1
    exit(0)
  end

  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); ((ex_id && sz == 0) || sz == 2) && (s.chars == org.chars)}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)
end

diff = n.times.to_a
  diff.permutation(diff.size).each do |p|
    org = s[0].dup
    p.each_with_index{|a,i| org[a] = s[0][diff[i]]}

    if s.all? {|s| sz = diffsz(s,org); (ex_id && sz == 0) || sz == 2 && (s.chars == org.chars)}
      puts org
      exit(0)
    end
  end

  puts -1
  exit(0)


Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen.

Print a single integer — the number of entrance that Allen will use.

NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$.

N = gets.to_i
as = gets.split.map(&:to_i)
N.times do |i|
    as[i] = ((as[i]-i-1)/N + 1) * N + i
    as[i] = i if as[i] < i
end
puts N.times.min_by{|i| as[i]} + 1

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

minv = ary.min
sq = minv % n
exitq = sq
ary.map!{|x| x-minv}
sq.upto(sq+n-1).each do |i|
  aryi = i % n
  if ary[aryi]<=(i-sq)
    exitq = aryi
    break
  end
end

puts exitq+1

number_of_entrances = gets.to_i
min_time = 1000000000
min_time_index = 0
ppl_in_each_entrance = gets.split(' ').map(&:to_i)

def ceiling(num, den)
  (num/den) + (num % den == 0 ? 0 : 1)
end

0.upto(number_of_entrances - 1) do |entrance|
  no_of_ppl = ppl_in_each_entrance[entrance]

  x = [0, no_of_ppl - entrance].max
  value = ceiling(x, number_of_entrances)

  if min_time > value
    min_time = value
    min_time_index = entrance
  end
end

p min_time_index + 1

number_of_entrances = gets.to_i
min_time = 1000000000
min_time_index = 0

def ceiling(num, den)
  (num/den) + (num % den == 0 ? 0 : 1)
end

0.upto(number_of_entrances - 1) do |entrance|
  no_of_ppl = gets.to_i

  x = [0, no_of_ppl - entrance].max
  value = ceiling(x, number_of_entrances)

  if min_time > value
    min_time = value
    min_time_index = entrance
  end
end

p min_time_index + 1


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

t = gets.to_i
t.times do
	r,l = gets.split.map(&:to_i)
	puts "#{r} #{r*2}"
end

gets.to_i.times do
  l, r = gets.split.map(&:to_i)
  puts "#{l} #{l*2}"
end

n = gets().to_i
(1..n).each do
  l, r = gets().split.map(&:to_i)
  puts "#{l} #{l * 2}"
end

gets.to_i.times do
    l,r = gets.split.map(&:to_i)
    puts "#{l} #{l*2}"
end

def lscan; gets.split.map(&:to_i); end

gets.to_i.times do
    l, r = lscan
    x = l
    y = l*2
    puts "#{x} #{y}"
end

t = gets.to_i
t.times do
    l, r = gets.split.map &:to_i
    print l, ' ', 2*l, "\n"
end

n = gets().to_i
(1..n).each do
  l, r = gets().split.map(&:to_i)
  (l..r).each do |x|
    i = 2
    if (x * 2 < r)
      puts "#{x} #{x * 2}"
      break
    end
  end
end


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')

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

if 2*k>=n
	puts -1
else
	puts n*k
	(1..n).each do |ind|
		(1..k).each do |ind2|
			puts "#{ind} #{(ind+ind2-1)%n+1}"
		end
	end
end

n,k=gets.split.map &:to_i
if k > (n-1) / 2
  puts "-1"
  exit
else
  puts n*k
  n.times do |cmdW|
    k.times do |cmdL|
      puts "#{cmdW+1} #{(cmdW+1+cmdL)%n + 1}"
    end
  end
end

n, k = gets.split.map {|x| Integer x}
if k * n > n * (n - 1) / 2
  puts -1
  exit
end
am = Array.new(n)
cnt = Array.new(n, n - 1)
for i in 0...n
  am[i] = Array.new(n)
end
for i in 0...n
  c = 0
  for j in 0...n
    if cnt[j] == k || i == j || am[i][j] != nil
      next
    end
    am[i][j] = true
    am[j][i] = false
    c += 1
    if c == k
      break
    end
  end
end
ans = []
for i in 0...n
  for j in 0...n
    if am[i][j]
      ans.push((i + 1).to_s + ' ' + (j + 1).to_s)
    end
  end
end
puts ans.length
puts ans

#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')

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

if k*(n/2)>=n
	puts -1
else
	puts n*k
	(1..n).each do |ind|
		(1..k).each do |ind2|
			puts "#{ind} #{(ind+ind2-1)%n+1}"
		end
	end
end

n, k = gets.split.map {|x| Integer x}
if k > n * (n - 1) / 4
  puts -1
  exit
end
am = Array.new(n)
cnt = Array.new(n, n - 1)
for i in 0...n
  am[i] = Array.new(n)
end
for i in 0...n
  c = 0
  for j in 0...n
    if cnt[j] == k || i == j || am[i][j] != nil
      next
    end
    am[i][j] = true
    am[j][i] = false
    c += 1
    if c == k
      break
    end
  end
end
for i in 0...n
  for j in 0...n
    if am[i][j]
      puts (i + 1).to_s + ' ' + (j + 1).to_s
    end
  end
end

n, k = gets.split.map {|x| Integer x}
if k > n * (n - 1) / 4
  puts -1
  exit
end
am = Array.new(n)
cnt = Array.new(n, n - 1)
for i in 0...n
  am[i] = Array.new(n)
end
for i in 0...n
  c = 0
  for j in 0...n
    if cnt[j] == k || i == j || am[i][j] != nil
      next
    end
    am[i][j] = true
    am[j][i] = false
    c += 1
    if c == k
      break
    end
  end
end
ans = []
for i in 0...n
  for j in 0...n
    if am[i][j]
      ans.push((i + 1).to_s + ' ' + (j + 1).to_s)
    end
  end
end
puts ans.length
puts ans


You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$n \le m \le 10^9$$$, $$$1 \le k \le n$$$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \ldots < b_n$$$.

Print the minimum total length of the pieces.

NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$.

n,m,k = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
ans = 0
a = []
for i in 1..n-1
    a << b[i]-b[i-1]
end
a.sort!
for i in 0..n-k-1
    ans += a[i]
end
puts ans+k

DBG = !true
n,m,k = gets.split.map{|z| z.to_i}
b = gets.split.map{|z| z.to_i}
sd = []
for i in 1...n
  sd << [i, b[i]-b[i-1]]
end
sd.sort_by!{|z| -z[1]}
print sd if DBG

d = sd[0,k-1].map{|z| z[0]}
d.sort!
print d if DBG

prev = 0
sum = 0
for x in d
  sum += b[x-1] - b[prev] + 1
  prev = x
end
sum += b[-1] - b[prev] + 1
puts "#{sum}"


This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise. You can print each letter in any case (upper or lower).

4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

NoteIn the first test case, Ujan can swap characters $$$s_1$$$ and $$$t_4$$$, obtaining the word "house".In the second test case, it is not possible to make the strings equal using exactly one swap of $$$s_i$$$ and $$$t_j$$$.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  noeqc = nil
  f = false
  n.times do |i|
    if (s[i] != t[i])
      if(noeqc == nil)
        noeqc = i
      elsif(noeqc == false)
        f = false
        break
      else
        if(s[i] == s[noeqc] and t[noeqc] == t[i])
          f = true
          noeqc = false
        else
          f = false
          break
        end
      end
    end
  end
  puts (f)? "Yes" : "No"
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 kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  noeqc = nil
  f = false
  n.times do |i|
    if (s[i] != t[i])
      if(noeqc == nil)
        noeqc = i
      elsif(noeqc == false)
        f = false
        break
      else
        if(s[i] == s[noeqc] and t[noeqc] == t[i])
          f = true
        else
          f = false
          break
        end
      end
    end
  end
  puts (f)? "Yes" : "No"
end


You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times:  Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \,\bmod\, k = j \,\bmod\, k$$$ ($$$1 \le i < j \le n$$$).  Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$) — the number of test cases. Each test case consists of two lines.  The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the length of the array and the number in the statement above. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)  — the array itself.

For each test case, print the maximum score you can get, one per line.

NoteIn the first test case, we can get a score of $$$11$$$ if we select $$$a_1, a_2$$$ without performing any operations.In the third test case, we can get a score of $$$15$$$ if we first swap $$$a_1$$$ with $$$a_4$$$ and then select $$$a_3, a_4, a_5$$$.

def main
  t = inp.to_i
  t.times do
    n, k = mapint(inarr)
    a = mapint(inarr)

    md = Array.new(k, 0)
    n.times do |i|
      md[i % k ] = [md[i %k], a[i]].max
    end
    sum = 0
    md.each do |i|
      sum += i
    end
    puts sum

  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

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

main

def main
  t = inp.to_i
  t.times do
    n, k = mapint(inarr)
    a = mapint(inarr)

    left = 0
    ans = 0
    while(left + k <= n)
      sum = 0
      left.upto(left + k - 1) do |i|
        m = a[i]
        if i - k >= 0 && left + k - 1 != i
          m = [a[i], a[i - k]].max
        end
        if i + k < n && i != left
          m = [a[i], a[i + k]].max
        end
        sum += m
      end
      ans = [ans, sum].max
      left+=1
    end
    puts ans
  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

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

main

def main
  t = inp.to_i
  t.times do
    n, k = mapint(inarr)
    a = mapint(inarr)

    left = 0
    ans = 0
    while(left + k <= n)
      sum = 0
      left.upto(left + k - 1) do |i|
        m = a[i]
        if i - k >= 0
          m = [a[i], a[i - k]].max
        end
        if i + k < n && i != left
          m = [a[i], a[i + k]].max
        end
        sum += m
      end
      ans = [ans, sum].max
      left+=1
    end
    puts ans
  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

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

main


General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.

The first line contains two integers n, k (1 ≤ n ≤ 50; 1 ≤ k ≤  ) — the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.

Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≤ ci ≤ n) — the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i — the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.

a = ARGF.read.split.map &:to_i
n, k = a.shift(2)
dp = Array.new(n+1) { Hash.new }
dp[0][0] = true
(1..n).each do |i|
  dp[i-1].each_key do |val|
    dp[i][val] = dp[i][val + a[i-1]] = true
  end
  (n = i; break) if dp[i].size > k
end
dfs = ->(arr, i, j) {
  if i > 0
    if dp[i-1].has_key?(j-a[i-1]) then arr << a[i-1]; dfs.(arr, i-1, j-a[i-1])
    else dfs.(arr, i-1, j) end
  end
}
ks = dp[n].keys.select! { |k| k != 0 }
k.times do
  arr = []
  dfs.(arr, n, ks.shift)
  $stdout.puts "#{arr.size} #{arr.map(&:to_i).join(' ')}"
end

a = ARGF.read.split.map &:to_i
n, k = a.shift(2)
dp = Array.new(n+1) { Hash.new }
dp[0][0] = true
(1..n).each do |i|
  dp[i-1].each_key do |val|
    dp[i][val] = dp[i][val + a[i-1]] = true
  end
end
dfs = ->(arr, i, j) {
  if i > 0
    if dp[i-1].has_key?(j-a[i-1]) then arr << i; dfs.(arr, i-1, j-a[i-1])
    else dfs.(arr, i-1, j) end
  end
}
ks = dp[n].keys.select! { |k| k != 0 }
k.times do
  arr = []
  dfs.(arr, n, ks.shift)
  $stdout.puts "#{arr.size} #{arr.map(&:to_i).join(' ')}"
end


You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers.Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then:$$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$The sum of an empty array is $$$0$$$.Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.

Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).

NoteIn the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$.In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$.In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.

def solution
  n = read_int
  xs = read_ints

  max = 0

  prefs = Hash.new

  sum = 0
  xs.each.with_index do |x, i|
    # p x
    sum += x
    prefs[sum] = i
  end

  sum = 0
  (n-1).downto(0) do |j|
    x = xs[j]
    sum += x

    if prefs[sum] && prefs[sum] < j
      max = sum
    end

  end

  puts  max

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N = gets.to_i
as = gets.split.map(&:to_i)
total = as.inject(:+)
h1, h2 = {}, {}
sum = 0
N.times do |i|
    h1[sum] = true
    sum += as[i]
    break if sum*2 > total
end
sum = 0
(N-1).downto(0) do |i|
    h2[sum] = true
    sum += as[i]
    break if sum*2 > total
end
h1.keys.sort.reverse.each do |sum|
    if h2[sum]
        puts sum
        exit
    end
end


Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. Using each of them exactly at once, you're to make such sequence $$$b_1, b_2, \dots, b_n$$$ that sequence $$$c_1, c_2, \dots, c_n$$$ is lexicographically maximal, where $$$c_i=GCD(b_1,\dots,b_i)$$$ - the greatest common divisor of the first $$$i$$$ elements of $$$b$$$. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$)  — the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$)  — the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case output the answer in a single line  — the desired sequence $$$b$$$. If there are multiple answers, print any.

NoteIn the first test case of the example, there are only two possible permutations $$$b$$$  — $$$[2, 5]$$$ and $$$[5, 2]$$$: for the first one $$$c=[2, 1]$$$, for the second one $$$c=[5, 1]$$$.In the third test case of the example, number $$$9$$$ should be the first in $$$b$$$, and $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, so the second number of $$$b$$$ should be $$$3$$$.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $$$b$$$.

require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map.with_index { |(base, k), i|
      s = i.zero? ? 0 : 1
      (s..k).map { |n| base ** n }
    }.inject { |res, e| res + res.flat_map { |t| e.map { |v| t * v } } }.sort
  end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.prime_division.each do |e, _|
      primes[e] << x
    end
  end

  ans = []
  s = a.max
  g = s

  loop {
    ans << s
    counter[s] -= 1
    cand = -1
    max_v = -Float::INFINITY

    s.prime_division.map(&:first).reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        next_gcd = g.gcd(num)

        if max_v < next_gcd
          max_v = next_gcd
          cand = num
        end
      end
    end

    break if cand == -1
    g = g.gcd(cand)
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = [a.max]
  g = a.max
  max_idx = a.index(g)
  vis = a.map.with_index {|_, a_i| a_i == max_idx ? true : false}

  (n - 1).times do
    max_v = -1
    max_i = -1
    a.each_with_index do |a_i, i|
      next if vis[i]

      if g.gcd(a_i) > max_v
        max_i = i
        max_v = g.gcd(a_i)
      end
    end

    b << a[max_i]
    vis[max_i] = true
    g = max_v
  end

  puts b.join(' ')
end

require 'prime'

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.prime_division.each do |e, cnt|
      primes[e] << x
    end
  end

  ans = []
  s = a.max

  loop {
    ans << s
    counter[s] -= 1
    cand = -1

    s.prime_division.map(&:first).reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        cand = num
        break
      end

      break if cand != -1
    end

    break if cand == -1
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map.with_index { |(base, k), i|
      s = i.zero? ? 0 : 1
      (s..k).map { |n| base ** n }
    }.inject { |res, e| res + res.flat_map { |t| e.map { |v| t * v } } }.sort
  end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.prime_division.each do |e, _|
      primes[e] << x
    end
  end

  ans = []
  s = a.max
  gcd = s

  loop {
    ans << s
    counter[s] -= 1
    cand = -1
    max_v = -Float::INFINITY

    s.prime_division.reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        next_gcd = gcd.gcd(num)

        if max_v < next_gcd
          max_v = next_gcd
          cand = num
        end
      end
    end

    break if cand == -1
    gcd = gcd.gcd(cand)
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map.with_index { |(base, k), i|
      s = i.zero? ? 0 : 1
      (s..k).map { |n| base ** n }
    }.inject { |res, e| res + res.flat_map { |t| e.map { |v| t * v } } }.sort
  end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.prime_division.each do |e, _|
      primes[e] << x
    end
  end

  ans = []
  s = a.max
  gcd = s

  loop {
    ans << s
    counter[s] -= 1
    cand = -1
    max_v = -Float::INFINITY

    s.prime_division.map(&:first).reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        next_gcd = gcd.gcd(num)

        if max_v < next_gcd
          max_v = next_gcd
          cand = num
        end
      end
    end

    break if cand == -1
    gcd = s.gcd(cand)
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map.with_index { |(base, k), i|
      s = i.zero? ? 0 : 1
      (s..k).map { |n| base ** n }
    }.inject { |res, e| res + res.flat_map { |t| e.map { |v| t * v } } }.sort
  end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.divisor_list.each do |e, _|
      primes[e] << x
    end
  end

  ans = []
  s = a.max
  gcd = s

  loop {
    ans << s
    counter[s] -= 1
    cand = -1
    max_v = -Float::INFINITY

    s.divisor_list.reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        next_gcd = gcd.gcd(num)

        if max_v < next_gcd
          max_v = next_gcd
          cand = num
        end
      end
    end

    break if cand == -1
    gcd = s.gcd(cand)
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map.with_index { |(base, k), i|
      s = i.zero? ? 0 : 1
      (s..k).map { |n| base ** n }
    }.inject { |res, e| res + res.flat_map { |t| e.map { |v| t * v } } }.sort
  end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)

  counter = Hash.new(0)
  primes = Hash.new { |h, k| h[k] = [] }

  a.each do |x|
    counter[x] += 1

    x.divisor_list.each do |e, cnt|
      primes[e] << x
    end
  end

  ans = []
  s = a.max

  loop {
    ans << s
    counter[s] -= 1
    cand = -1

    s.divisor_list.reverse_each do |e|
      primes[e].each do |num|
        next if counter[num] <= 0

        cand = num
        break
      end

      break if cand != -1
    end

    break if cand == -1
    s = cand
  }

  counter.each do |num, cnt|
    next if cnt <= 0

    cnt.times do
      ans << num
    end
  end

  puts ans.join(' ')
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = [a.max]
  g = a.max
  vis = a.map {|a_i| a_i == g ? true : false}

  (n - 1).times do
    max_v = -1
    max_i = -1
    a.each_with_index do |a_i, i|
      next if vis[i]

      if g.gcd(a_i) > max_v
        max_i = i
        max_v = g.gcd(a_i)
      end
    end

    b << a[max_i]
    vis[max_i] = true
    g = max_v
  end

  puts b.join(' ')
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = [a.max]
  g = a.max
  vis = a.map {|a_i| a_i == g ? true : false}

  (n - 1).times do
    max_v = -1
    max_i = -1
    max_ai = -1
    a.each_with_index do |a_i, i|
      next if vis[i]

      if g.gcd(a_i) > max_v || (g.gcd(a_i) == max_v && a_i > max_ai)
        max_i = i
        max_v = g.gcd(a_i)
        max_ai = a_i
      end
    end

    b << a[max_i]
    vis[max_i] = true
    g = max_v
  end

  puts b.join(' ')
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  max_v = a.max
  b = a.map {|a_i| [a_i, a_i.gcd(max_v)]}.sort_by {|av, gv| [-gv, -av]}.map(&:first)
  puts b.join(' ')
end