There are $$$n$$$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The value of the line is the sum of each person's count.For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $$$[0, 3, 2, 3, 4]$$$, and the value is $$$0+3+2+3+4=12$$$.You are given the initial arrangement of people in the line. For each $$$k$$$ from $$$1$$$ to $$$n$$$, determine the maximum value of the line if you can change the direction of at most $$$k$$$ people.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the line. The following line contains a string consisting of $$$n$$$ characters, each of which is either L or R, representing a person facing left or right, respectively — the description of the line. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$. Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

For each test case, output $$$n$$$ space-separated non-negative integers — the maximum value of the line if you can change the direction of at most $$$k$$$ people for each $$$k$$$ from $$$1$$$ to $$$n$$$, inclusive.

6

3

LLR

5

LRRLL

1

L

12

LRRRLLLRLLRL

10

LLLLLRRRRR

9

LRLRLRLRL

NoteIn the first test case:   $$$k=1$$$: change the direction of $$$1$$$ person to make the line RLR. The total value is $$$2+1+0=3$$$.  $$$k=2$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$.  $$$k=3$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$. Note that you have to change the direction of at most $$$k$$$ people. In the second test case, it is optimal to only change the direction of the first person for all $$$k$$$ from $$$1$$$ to $$$5$$$ (that is, make the line RRRLL).

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp
  dxs = []
  sum = s.chars.zip(0..).map do |c, i|
    x = c == "L" ? i : n - i - 1
    dxs << [i, n - i - 1].max - x
    x
  end.sum
  answer = []
  dxs.sort.reverse.each do |dx|
    sum += dx
    answer << sum
  end
  puts answer.join(" ")
end


Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.

The first line of input contains integers n, k and m (1 ≤ k ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively. The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct. The third line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the cost of sending the i-th word. The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≤ x ≤ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group. The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.

The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.

5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

NoteIn the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.

def min(*values)
 values.min
end
input_str = gets.chomp
input_array = input_str.split(" ")
n = Integer(input_array[0])
k = Integer(input_array[1])
m = Integer(input_array[2])
input_str = gets.chomp
words = input_str.split(" ")
input_str = gets.chomp
score = input_str.split(" ")
for i in 0...n do
	score[i] = Integer(score[i])
end
min_score = Array.new(k)
group = Hash.new
for i in 0...k do
	input_str = gets.chomp
	input_array = input_str.split(" ")
	input_array.shift
	input_array.each{ |input|
		temp = Integer(input)-1
		if min_score[i] == nil
			min_score[i] = score[temp]
		else
			min_score[i] = min(min_score[i],score[temp])
		end
		group[words[temp]] = i
	}
end
input_str = gets.chomp
input_array = input_str.split(" ")
result = 0
input_array.each{ |input|
	result+=min_score[group[input]]
}
puts result

def min(*values)
 values.min
end
input_str = gets.chomp
input_array = input_str.split(" ")
n = Integer(input_array[0])
k = Integer(input_array[1])
m = Integer(input_array[2])
input_str = gets.chomp
words = input_str.split(" ")
input_str = gets.chomp
score = input_str.split(" ").map(&:to_i)
min_score = Array.new(k)
group = Hash.new
for i in 0...k do
	input_str = gets.chomp
	input_array = input_str.split(" ")
	input_array.shift
	input_array.each{ |input|
		temp = Integer(input)-1
		if min_score[i] == nil
			min_score[i] = score[temp]
		else
			min_score[i] = min(min_score[i],score[temp])
		end
		group[words[temp]] = i
	}
end
input_str = gets.chomp
input_array = input_str.split(" ")
result = 0
input_array.each{ |input|
	result+=min_score[group[input]]
}
puts result


You are playing a computer game, where you lead a party of $$$m$$$ soldiers. Each soldier is characterised by his agility $$$a_i$$$.The level you are trying to get through can be represented as a straight line segment from point $$$0$$$ (where you and your squad is initially located) to point $$$n + 1$$$ (where the boss is located).The level is filled with $$$k$$$ traps. Each trap is represented by three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$. $$$l_i$$$ is the location of the trap, and $$$d_i$$$ is the danger level of the trap: whenever a soldier with agility lower than $$$d_i$$$ steps on a trap (that is, moves to the point $$$l_i$$$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $$$r_i$$$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.You have $$$t$$$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions:  if your location is $$$x$$$, you may move to $$$x + 1$$$ or $$$x - 1$$$. This action consumes one second;  if your location is $$$x$$$ and the location of your squad is $$$x$$$, you may move to $$$x + 1$$$ or to $$$x - 1$$$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $$$d_i$$$ greater than agility of some soldier from the squad). This action consumes one second;  if your location is $$$x$$$ and there is a trap $$$i$$$ with $$$r_i = x$$$, you may disarm this trap. This action is done instantly (it consumes no time). Note that after each action both your coordinate and the coordinate of your squad should be integers.You have to choose the maximum number of soldiers such that they all can be brought from the point $$$0$$$ to the point $$$n + 1$$$ (where the boss waits) in no more than $$$t$$$ seconds.

The first line contains four integers $$$m$$$, $$$n$$$, $$$k$$$ and $$$t$$$ ($$$1 \le m, n, k, t \le 2 \cdot 10^5$$$, $$$n < t$$$) — the number of soldiers, the number of integer points between the squad and the boss, the number of traps and the maximum number of seconds you may spend to bring the squad to the boss, respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the agility of the $$$i$$$-th soldier. Then $$$k$$$ lines follow, containing the descriptions of traps. Each line contains three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$1 \le d_i \le 2 \cdot 10^5$$$) — the location of the trap, the location where the trap can be disarmed, and its danger level, respectively.

Print one integer — the maximum number of soldiers you may choose so that you may bring them all to the boss in no more than $$$t$$$ seconds.

NoteIn the first example you may take soldiers with agility $$$3$$$, $$$4$$$ and $$$5$$$ with you. The course of action is as follows:  go to $$$2$$$ without your squad;  disarm the trap $$$2$$$;  go to $$$3$$$ without your squad;  disartm the trap $$$3$$$;  go to $$$0$$$ without your squad;  go to $$$7$$$ with your squad. The whole plan can be executed in $$$13$$$ seconds.

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

require 'prime'

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

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

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

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

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

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

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

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

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

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

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

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

m,n,k,time = inp
mob = inp.sort.reverse!
t = []
k.times{t<<inp}
t.sort_by!{|u|u[2]*-1}
pt = na(n+1,false)
pl = na(m+5,0)
qt = copy(t)

trap_i = 0
m.times do |mob_i|
  mob[mob_i]
  pl[mob_i] = pl[mob_i-1]
  while t[trap_i] != nil and t[trap_i][2] > mob[mob_i]
    t[trap_i]
    paint_i = t[trap_i][0]
    while paint_i <= t[trap_i][1]
      if pt[paint_i]
        paint_i = pt[paint_i]
      else
        pt[paint_i] = t[trap_i][1]
        pl[mob_i] += 1
      end
      paint_i += 1
    end
    trap_i += 1
  end
end
time -= (n+1)
pl.each.with_index do |d,i|
  if(d+d > time)
    p i
    exit
  end
end
p m

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

require 'prime'

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

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

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

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

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

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

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

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

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

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

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

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

m,n,k,time = inp
mob = inp.sort.reverse!
t = []
k.times{t<<inp}
t.sort_by!{|u|u[2]*-1}
pt = na(n+1,false)
pl = na(m+5,0)
qt = copy(t)

trap_i = 0
m.times do |mob_i|
  mob[mob_i]
  pl[mob_i] = pl[mob_i-1]
  while t[trap_i] != nil and t[trap_i][2] > mob[mob_i]
    t[trap_i]
    (t[trap_i][0]..t[trap_i][1]).each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    (t[trap_i][0]..t[trap_i][1]).reverse_each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    trap_i += 1
  end
end
time -= (n+1)
pl.each.with_index do |d,i|
  if(d+d > time)
    p i
    exit
  end
end
p m

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

require 'prime'

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

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

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

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

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

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

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

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

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

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

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

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

m,n,k,time = inp
mob = inp.sort.reverse!
t = []
k.times{t<<inp}
t.sort_by!{|u|u[2]*-1}
pt = na(n+1,false)
pl = na(m,0)
qt = copy(t)

trap_i = 0
m.times do |mob_i|
  mob[mob_i]
  pl[mob_i] = pl[mob_i-1]
  while t[trap_i] != nil and t[trap_i][2] > mob[mob_i]
    t[trap_i]
    (t[trap_i][0]..t[trap_i][1]).each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    (t[trap_i][0]..t[trap_i][1]).reverse_each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    trap_i += 1
  end
end
time -= (n+1)
pl.each.with_index do |d,i|
  if(d+d > time)
    p i
    exit
  end
end
p m

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

require 'prime'

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

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

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

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

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

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

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

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

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

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

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

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

m,n,k,time = inp
mob = inp.sort.reverse!
t = []
k.times{t<<inp}
t.sort_by!{|u|u[2]*-1}
pt = na(n+1,false)
pl = na(m,0)
qt = copy(t)

trap_i = 0
m.times do |mob_i|
  mob[mob_i]
  pl[mob_i] = pl[mob_i-1]
  while t[trap_i] != nil and t[trap_i][2] > mob[mob_i]
    t[trap_i]
    (t[trap_i][0]..t[trap_i][1]).each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    (t[trap_i][0]..t[trap_i][1]).reverse_each do |paint_i|
      if pt[paint_i]
        break
      else
        pt[paint_i] = true
        pl[mob_i] += 1
      end
    end
    trap_i += 1
  end
end
p time -= (n+1)
pl.each.with_index do |d,i|
  if(d+d > time)
    p i
    exit
  end
end
p n


Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic:  The following matrices are not palindromic because they change after the order of rows is reversed:  The following matrices are not palindromic because they change after the order of columns is reversed:  You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".

The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.

If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.

NoteNote that there exist multiple answers for the first two examples.

n = gets.to_i
a = gets.split.map(&:to_i)
cnt = a.tally.map { |k, v| [v, k] }

ans = Array.new(n) { [-1] * n }

set = lambda do |i, j|
	count =
		if n.even?
			4
		else
			f1, f2 = i == n / 2, j == n / 2
			if f1 && f2
				1
			elsif !f1 && !f2
				4
			else
				2
			end
		end
	cnt = cnt.sort.reverse
	cnt[0][0] -= count
	puts('NO') + exit if cnt[0][0] < 0
	val = cnt[0][1]
	ans[i][j] = val
	ans[i][~j] = val
	ans[~i][j] = val
	ans[~i][~j] = val
end

if n.even?
	(0...n / 2).each { |i| (0...n / 2).each { |j| set[i, j] } }
else
	(0...n / 2).each { |i| (0...n / 2).each { |j| set[i, j] } }
	(0...n / 2).each do |i|
		set[n / 2, i]
		set[i, n / 2]
	end
	set[n / 2, n / 2]
end
puts 'YES'
puts ans.map { _1.join(' ') }.join("\n")

n = gets.to_i
cnt = gets.split.map(&:to_i).tally.map { [_2, _1] }
ans = Array.new(n) { [-1] * n }

set = lambda do |i, j|
	f1, f2 = n.odd? && i == n / 2, n.odd? && j == n / 2
	cnt.sort!.reverse!
	cnt[0][0] -=
		if f1 && f2
			1
		elsif !f1 && !f2
			4
		else
			2
		end
	puts('NO') + exit if cnt[0][0] < 0
	ans[i][j] = ans[i][~j] = ans[~i][j] = ans[~i][~j] = cnt[0][1]
end

(0...n / 2).each { |i| (0...n / 2).each { |j| set[i, j] } }
if n.odd?
	(0...n / 2).each do |i|
		set[n / 2, i]
		set[i, n / 2]
	end
	set[n / 2, n / 2]
end
puts 'YES', ans.map { _1.join(' ') }.join("\n")

def print_even(n, r4)
  puts "YES"
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i<n/2 && j<n/2
        x = i
        y = j
      end

      if i>=n/2 && j<n/2
        x = i%h
        x = h-x-1
        y = j
      end

      if i<n/2 && j>=n/2
        x = i
        y = j%h
        y = h-y-1
      end

      if i>=n/2 && j>=n/2
        x = i%h
        x = h-x-1
        y = j%h
        y = h-y-1
      end

      print(r4[x*h+y].to_s)
      print(" ") unless j == n-1
    end
    puts
  end
end

def print_odd(n, r4, r2, r1)
  puts "YES"
  c = n/2
  h = n/2

  r2_1 = r2[0..n/2-1]
  r2_2 = r2[n/2..-1]
  for i in 0..n-1
    for j in 0..n-1
      if i == c || j == c
        if i == c && j == c
          print r1
        elsif i == c
          if j < c
            print r2_1[j]
          else
            y = (j-1)%h
            y = h-y-1
            print r2_1[y]
          end

        elsif j == c
          if i < c
            print r2_2[i]
          else
            y = (i-1)%h
            y = h-y-1
            print r2_2[y]
          end
        end
      else

        if i<c && j<c
          x = i
          y = j
        end

        if i>c && j<c
          x = (i-1)%h
          x = h-x-1
          y = j
        end

        if i<c && j>c
          x = i
          y = (j-1)%h
          y = h-y-1
        end

        if i>c && j>c
          x = (i-1)%h
          x = h-x-1
          y = (j-1)%h
          y = h-y-1
        end

        print(r4[x*h+y].to_s)
      end
      print(" ") unless j == n-1
    end
    puts
  end
end

def main()
  n = STDIN.gets.to_i
  aa = STDIN.gets.strip.split.map(&:to_i)
  counts = {}
  aa.each do |a|
    counts[a] ||= 0;
    counts[a] += 1;
  end

  center = nil
  if n%2 == 0
    unless counts.all? { |k, v| v%4==0 }
      return puts "NO"
    end

    r4 = []
    counts.each do |k, v|
      (v/4).times do
        r4.push(k)
      end
    end
    print_even(n, r4)
  else
    # (4*n-1) + 2*(n-1) + 1
    r1 = counts.keys.select { |k| counts[k] % 2 == 1 }
    unless r1.size == 1
      puts "NO"
      return
    end
    r1 = r1[0]
    counts[r1] -= 1

    # すべて偶数
    unless counts.all? { |k, v| v%2==0 }
      return puts "NO"
    end

    r4_num = ((n-1)/2) ** 2
    r4 = []
    r2 = []

    keys = counts.keys.sort_by { |k| counts[k] }.reverse
    idx = 0
    while idx <= keys.length-1 do
      k = keys[idx]
      if counts[k] == 0
        idx+=1
        next
      end

      if r4.length < r4_num
        if counts[k]%4==0
          counts[k] -= 4
          r4.push(k)
          next
        end
      end

      counts[k] -= 2
      r2.push(k)
    end

    if r4.length < r4_num
      puts "NO"
      return
    end
    print_odd(n, r4, r2, r1)
  end
end

main

$n = Integer(gets)
$ans = []
def setans(key, val)
    $ans[key[0]][key[1]] = val
    $ans[$n-key[0]-1][key[1]] = val
    $ans[key[0]][$n-key[1]-1] = val
    $ans[$n-key[0]-1][$n-key[1]-1] = val
end
for i in 1..$n
    $ans.push(Array.new($n))
end
hsh = Hash.new()
gets.split().each do |y|
    x = Integer(y)
    hsh[x] = 0 unless hsh[x]
    hsh[x] += 1
end
fours = []
for i in 0...$n/2
    for j in 0...$n/2
        fours.push([i, j])
    end
end
twos = []
ones = []
if $n % 2 == 1
    for i in 0...$n/2
        twos.push([i, $n/2])
        twos.push([$n/2, i])
    end
    ones.push([$n/2, $n/2])
end
able = true
begin
    hsh.each do |num, cnt|
        if cnt%2 == 1
            setans(ones.pop(), num)
            cnt-=1
        end
        if cnt%4 == 2
            setans(twos.pop(), num)
            cnt-=2
        end
        until cnt == 0 or fours.empty?
            setans(fours.pop(), num)
            cnt-=4
        end
        until cnt == 0 or twos.empty?
            setans(twos.pop(), num)
            cnt-=2
        end
        until cnt == 0 or ones.empty?
            setans(ones.pop(), num)
            cnt-=1
        end
        raise "jizz" if cnt != 0
    end
    puts "YES"
    $ans.each do |x|
        puts x.join(" ")
    end
rescue
    puts "NO"
end

DBG = !true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
h = {}
for x in a
  if h.has_key?(x)
    h[x] += 1
  else
    h[x] = 1
  end
end
s4 = {}
s2 = {}
s1 = {}
h.each{ |k,v|
  if v%4 == 0
    s4[k] = v
  elsif v%2 == 0
    if n%2 == 0
      puts "NO"
      exit 0
    end
    s4[k] = v-2 if v>=6
    s2[k] = 2
  else
    if n%2 == 0 || s1.size > 0
      puts "NO"
      exit 0
    end
    if v>=4
      s4[k] = v-v%4
      v = v%4
    end
    if v>=2  # must be 3
      s2[k] = v-1
    end
    s1[k] = 1
  end
}
if n%2 == 1
  m = n/2
  if DBG
    print s4
    puts "- s4"
  end
  sum4 = s4.values.inject(:+)
  sum4 = 0 if sum4.nil?
  if sum4 < 4*m*m
    puts "NO"
    exit 0
  end
end

if DBG
  puts "n #{n}"
  print s4
  puts ""
  print s2
  puts ""
  print s1
  puts ""
end

t = Array.new(n)
t.map!{Array.new(n)}
i = 0
j = 0

m = n/2
if n%2 == 0
  s4.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  for i in 0...m
    for j in 0...m
      t[2*m-1-i][j] = t[i][j]
      t[i][2*m-1-j] = t[i][j]
      t[2*m-1-i][2*m-1-j] = t[i][j]
    end
  end

else # n%2 == 1
  s4.each { |k,v|
    while v>0 && i<m
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  s4.each{|k,v|
    if s2.has_key?(k)
      s2[k] += v
    else
      s2[k] = v
    end
  }
  if DBG
    puts "s2 now"
    print s2
    puts ""
  end

  i = m
  j = 0
  vert = true
  s2.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 2
      if j==m-1
        i = 0
        j = m
        vert = false
      elsif vert
        j += 1
      else
        i += 1
      end
    end
  }

  s1.each { |k,v|
    t[m][m] = k
  }

  if DBG
    puts "after mm"
    for i in 0..m
      for j in 0..m
        print "#{t[i][j] }"
      end
      puts ""
    end
    puts ""
  end

  for i in 0...m
    for j in 0...m
      t[2*m-i][2*m-j] = t[i][j]
      t[i][2*m-j] = t[i][j]
      t[2*m-i][j] = t[i][j]
    end
    t[2*m-i][m] = t[i][m]
    t[m][2*m-i] = t[m][i]
  end
end

puts "YES"
for i in 0...n
  for j in 0...n
    print "#{t[i][j]} "
  end
  puts ""
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = Hash.new(0)
a.each do |i|
    b[i] += 1
end
c = d = 0
b.values.each do |i|
    c += 1 if i.odd?
    d += 1 if i%4 > 1
end
if (n.odd? && (c != 1 || d > n-1)) || (n.even? && (c != 0 || d != 0))
    puts "NO"
    exit
end
ans = Array.new(n).map{Array.new(n,0)}
if n.odd?
    b.keys.each do |k|
        if b[k].odd?
            ans[n/2][n/2] = k
            b[k] -= 1
            break
        end
    end
    for i in 0..n/2-1
        b.keys.each do |k|
            if b[k]%4 == 2
                ans[i][n/2] = ans[n-i-1][n/2] = k
                b[k] -= 2
                break
            end
        end
    end
    for i in 0..n/2-1
        b.keys.each do |k|
            if b[k]%4 == 2
                ans[n/2][i] = ans[n/2][n-i-1] = k
                b[k] -= 2
                break
            end
        end
    end
    for i in 0..n/2-1
        b.keys.each do |k|
            if ans[i][n/2] == 0 && b[k] != 0
                ans[i][n/2] = ans[n-i-1][n/2] = k
                b[k] -= 2
                break
            end
        end
    end
    for i in 0..n/2-1
        b.keys.each do |k|
            if ans[n/2][i] == 0 && b[k] != 0
                ans[n/2][i] = ans[n/2][n-i-1] = k
                b[k] -= 2
                break
            end
        end
    end
end
for i in 0..n/2-1
    for j in 0..n/2-1
        b.keys.each do |k|
            if b[k] != 0
                ans[i][j] = ans[i][n-1-j] = ans[n-1-i][j] = ans[n-1-i][n-1-j] = k
                b[k] -= 4
                break
            end
        end
    end
end
puts "YES"
ans.each do |arr|
    puts arr.join(" ")
end

def print_even(n, r4)
  puts "YES"
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i<n/2 && j<n/2
        x = i
        y = j
      end

      if i>=n/2 && j<n/2
        x = i%h
        x = h-x-1
        y = j
      end

      if i<n/2 && j>=n/2
        x = i
        y = j%h
        y = h-y-1
      end

      if i>=n/2 && j>=n/2
        x = i%h
        x = h-x-1
        y = j%h
        y = h-y-1
      end

      print(r4[x*h+y].to_s)
      print(" ") unless j == n-1
    end
    puts
  end
end

def print_odd(n, r4, r2, r1)
  puts "YES"
  c = n/2
  h = n/2

  r2_1 = r2[0..n/2-1]
  r2_2 = r2[n/2..-1]
  for i in 0..n-1
    for j in 0..n-1
      if i == c || j == c
        if i == c && j == c
          print r1
        elsif i == c
          if j < c
            print r2_1[j]
          else
            y = j%h
            print r2_1[y]
          end

        elsif j == c
          if i < c
            print r2_2[i]
          else
            x = i%h
            print r2_2[x]
          end
        end
      else

        if i<c && j<c
          x = i
          y = j
        end

        if i>c && j<c
          x = (i-1)%h
          x = h-x-1
          y = j
        end

        if i<c && j>c
          x = i
          y = (j-1)%h
          y = h-y-1
        end

        if i>c && j>c
          x = (i-1)%h
          x = h-x-1
          y = (j-1)%h
          y = h-y-1
        end

        print(r4[x*h+y].to_s)
      end
      print(" ") unless j == n-1
    end
    puts
  end
end

def main()
  n = STDIN.gets.to_i
  aa = STDIN.gets.strip.split.map(&:to_i)
  counts = {}
  aa.each do |a|
    counts[a] ||= 0;
    counts[a] += 1;
  end

  center = nil
  if n%2 == 0
    unless counts.all? { |k, v| v%4==0 }
      return puts "NO"
    end

    r4 = []
    counts.each do |k, v|
      (v/4).times do
        r4.push(k)
      end
    end
    print_even(n, r4)
  else
    # (4*n-1) + 2*(n-1) + 1
    r1 = counts.keys.select { |k| counts[k] % 2 == 1 }
    unless r1.size == 1
      puts "NO"
      return
    end
    r1 = r1[0]
    counts[r1] -= 1

    # すべて偶数
    unless counts.all? { |k, v| v%2==0 }
      return puts "NO"
    end

    r4_num = ((n-1)/2) ** 2
    r4 = []
    r2 = []

    keys = counts.keys.sort_by { |k| counts[k] }.reverse
    idx = 0
    while idx <= keys.length-1 do
      k = keys[idx]
      if counts[k] == 0
        idx+=1
        next
      end

      if r4.length < r4_num
        if counts[k]%4==0
          counts[k] -= 4
          r4.push(k)
          next
        end
      end

      counts[k] -= 2
      r2.push(k)
    end

    if r4.length < r4_num
      puts "NO"
      return
    end
    print_odd(n, r4, r2, r1)
  end
end

main

def print_even(n, r4)
  puts "YES"
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i<n/2 && j<n/2
        x = i
        y = j
      end

      if i>=n/2 && j<n/2
        x = i%h
        x = h-x-1
        y = j
      end

      if i<n/2 && j>=n/2
        x = i
        y = j%h
        y = h-y-1
      end

      if i>=n/2 && j>=n/2
        x = i%h
        x = h-x-1
        y = j%h
        y = h-y-1
      end

      print(r4[x*h+y].to_s)
      print(" ") unless j == n-1
    end
    puts
  end
end

def print_odd(n, r4, r2, r1)
  puts "YES"
  c = n/2
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i == c || j == c
        if i == c && j == c
          print r1
        elsif i == c
          if j < c
            print r2[j]
          else
            print r2[n-j-1]
          end

        elsif j == c
          if i < c
            print r2[i]
          else
            print r2[n-i-1]
          end
        end
      else

        if i<c && j<c
          x = i
          y = j
        end

        if i>c && j<c
          x = (i-1)%h
          x = h-x-1
          y = j
        end

        if i<c && j>c
          x = i
          y = (j-1)%h
          y = h-y-1
        end

        if i>c && j>c
          x = (i-1)%h
          x = h-x-1
          y = (j-1)%h
          y = h-y-1
        end

        print(r4[x*h+y].to_s)
      end
      print(" ") unless j == n-1
    end
    puts
  end
end

def main()
  n = STDIN.gets.to_i
  aa = STDIN.gets.strip.split.map(&:to_i)
  counts = {}
  aa.each do |a|
    counts[a] ||= 0;
    counts[a] += 1;
  end

  center = nil
  if n%2 == 0
    unless counts.all? { |k, v| v%4==0 }
      return puts "NO"
    end

    r4 = []
    counts.each do |k, v|
      (v/4).times do
        r4.push(k)
      end
    end
    print_even(n, r4)
  else
    # (4*n-1) + 2*(n-1) + 1
    r1 = counts.keys.select { |k| counts[k] % 4 == 1 }
    unless r1.size == 1
      puts "NO"
      return
    end
    r1 = r1[0]
    counts[r1] -= 1

    # すべて偶数
    unless counts.all? { |k, v| v%2==0 }
      return puts "NO"
    end

    r4_num = ((n-1)/2) ** 2
    r4 = []
    r2 = []

    keys = counts.keys.sort_by { |k| counts[k] }.reverse
    idx = 0
    while idx <= keys.length-1 do
      k = keys[idx]
      if counts[k] == 0
        idx+=1
        next
      end

      if r4.length < r4_num
        if counts[k]%4==0
          counts[k] -= 4
          r4.push(k)
          next
        end
      end

      counts[k] -= 2
      r2.push(k)
    end

    if r4.length < r4_num
      puts "NO"
      return
    end
    print_odd(n, r4, r2, r1)
  end
end

main

def print_even(n, r4)
  puts "YES"
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i<n/2 && j<n/2
        x = i
        y = j
      end

      if i>=n/2 && j<n/2
        x = i%h
        x = h-x-1
        y = j
      end

      if i<n/2 && j>=n/2
        x = i
        y = j%h
        y = h-y-1
      end

      if i>=n/2 && j>=n/2
        x = i%h
        x = h-x-1
        y = j%h
        y = h-y-1
      end

      print(r4[x*h+y].to_s)
      print(" ") unless j == n-1
    end
    puts
  end
end

def print_odd(n, r4, r2, r1)
  puts "YES"
  c = n/2
  h = n/2
  for i in 0..n-1
    for j in 0..n-1
      if i == c || j == c
        if i == c && j == c
          print r1
        elsif i == c
          if j < c
            print r2[j]
          else
            print r2[n-j-1]
          end

        elsif j == c
          if i < c
            print r2[i]
          else
            print r2[n-i-1]
          end
        end
      else

        if i<c && j<c
          x = i
          y = j
        end

        if i>c && j<c
          x = (i-1)%h
          x = h-x-1
          y = j
        end

        if i<c && j>c
          x = i
          y = (j-1)%h
          y = h-y-1
        end

        if i>c && j>c
          x = (i-1)%h
          x = h-x-1
          y = (j-1)%h
          y = h-y-1
        end

        print(r4[x*h+y].to_s)
      end
      print(" ") unless j == n-1
    end
    puts
  end
end

def main()
  n = STDIN.gets.to_i
  aa = STDIN.gets.strip.split.map(&:to_i)
  counts = {}
  aa.each do |a|
    counts[a] ||= 0;
    counts[a] += 1;
  end

  center = nil
  if n%2 == 0
    unless counts.all? { |k, v| v%4==0 }
      return puts "NO"
    end

    r4 = []
    counts.each do |k, v|
      (v/4).times do
        r4.push(k)
      end
    end
    print_even(n, r4)
  else
    # (4*n-1) + 2*(n-1) + 1
    r1 = counts.keys.select { |k| counts[k] % 2 == 1 }
    unless r1.size == 1
      puts "NO"
      return
    end
    r1 = r1[0]
    counts[r1] -= 1

    # すべて偶数
    unless counts.all? { |k, v| v%2==0 }
      return puts "NO"
    end

    r4_num = ((n-1)/2) ** 2
    r4 = []
    r2 = []

    keys = counts.keys.sort_by { |k| counts[k] }.reverse
    idx = 0
    while idx <= keys.length-1 do
      k = keys[idx]
      if counts[k] == 0
        idx+=1
        next
      end

      if r4.length < r4_num
        if counts[k]%4==0
          counts[k] -= 4
          r4.push(k)
          next
        end
      end

      counts[k] -= 2
      r2.push(k)
    end

    if r4.length < r4_num
      puts "NO"
      return
    end
    print_odd(n, r4, r2, r1)
  end
end

main

DBG = !true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
h = {}
for x in a
  if h.has_key?(x)
    h[x] += 1
  else
    h[x] = 1
  end
end
s4 = {}
s2 = {}
s1 = {}
h.each{ |k,v|
  if v%4 == 0
    s4[k] = v
  elsif v%2 == 0
    if n%2 == 0
      puts "NO"
      exit 0
    end
    s4[k] = v-2 if v>=6
    s2[k] = 2
  else
    if n%2 == 0 || s1.size > 0
      puts "NO"
      exit 0
    end
    if v>=4
      s4[k] = v-v%4
      v = v%4
    end
    if v>=2  # must be 3
      s2[k] = v-1
    end
    s1[k] = 1
  end
}
if n%2 == 1
  m = n/2
  print s4 if DBG
  sum4 = s4.values.inject(:+)
  sum4 = 0 if sum4.nil?
  if sum4 < m*m
    puts "NO"
    exit 0
  end
end

if DBG
  puts "n #{n}"
  print s4
  puts ""
  print s2
  puts ""
  print s1
  puts ""
end

t = Array.new(n)
t.map!{Array.new(n)}
i = 0
j = 0

m = n/2
if n%2 == 0
  s4.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  for i in 0...m
    for j in 0...m
      t[2*m-1-i][j] = t[i][j]
      t[i][2*m-1-j] = t[i][j]
      t[2*m-1-i][2*m-1-j] = t[i][j]
    end
  end

else # n%2 == 1
  s4.each { |k,v|
    while v>0 && i<m
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  s4.each{|k,v|
    if s2.has_key?(k)
      s2[k] += v
    else
      s2[k] = v
    end
  }
  if DBG
    puts "s2 now"
    print s2
    puts ""
  end

  i = m
  j = 0
  vert = true
  s2.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 2
      if j==m-1
        i = 0
        j = m
        vert = false
      elsif vert
        j += 1
      else
        i += 1
      end
    end
  }

  s1.each { |k,v|
    t[m][m] = k
  }

  if DBG
    puts "after mm"
    for i in 0..m
      for j in 0..m
        print "#{t[i][j] }"
      end
      puts ""
    end
    puts ""
  end

  for i in 0...m
    for j in 0...m
      t[2*m-i][2*m-j] = t[i][j]
      t[i][2*m-j] = t[i][j]
      t[2*m-i][j] = t[i][j]
    end
    t[2*m-i][m] = t[i][m]
    t[m][2*m-i] = t[m][i]
  end
end

puts "YES"
for i in 0...n
  for j in 0...n
    print "#{t[i][j]} "
  end
  puts ""
end

DBG = !true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
h = {}
for x in a
  if h.has_key?(x)
    h[x] += 1
  else
    h[x] = 1
  end
end
s4 = {}
s2 = {}
s1 = {}
h.each{ |k,v|
  if v%4 == 0
    s4[k] = v
  elsif v%2 == 0
    if n%2 == 0
      puts "NO"
      exit 0
    end
    s4[k] = v-2 if v>=6
    s2[k] = 2
  else
    if n%2 == 0 || s1.size > 0
      puts "NO"
      exit 0
    end
    if v>=4
      s4[k] = v-v%4
      v = v%4
    end
    if v>=2  # must be 3
      s2[k] = v-1
    end
    s1[k] = 1
  end
}

if DBG
  puts "n #{n}"
  print s4
  puts ""
  print s2
  puts ""
  print s1
  puts ""
end

t = Array.new(n)
t.map!{Array.new(n)}
i = 0
j = 0

m = n/2
if n%2 == 0
  s4.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  for i in 0...m
    for j in 0...m
      t[2*m-1-i][j] = t[i][j]
      t[i][2*m-1-j] = t[i][j]
      t[2*m-1-i][2*m-1-j] = t[i][j]
    end
  end

else # n%2 == 1
  s4.each { |k,v|
    while v>0 && i<m
      t[i][j] = k
      v -= 4
      s4[k] -= 4
      if j==m-1
        i += 1
        j = 0
      else
        j += 1
      end
    end
  }
  s4.each{|k,v|
    if s2.has_key?(k)
      s2[k] += v
    else
      s2[k] = v
    end
  }
  if DBG
    puts "s2 now"
    print s2
    puts ""
  end

  i = m
  j = 0
  vert = true
  s2.each { |k,v|
    while v>0
      t[i][j] = k
      v -= 2
      if j==m-1
        i = 0
        j = m
        vert = false
      elsif vert
        j += 1
      else
        i += 1
      end
    end
  }

  s1.each { |k,v|
    t[m][m] = k
  }

  if DBG
    puts "after mm"
    for i in 0..m
      for j in 0..m
        print "#{t[i][j] }"
      end
      puts ""
    end
    puts ""
  end

  for i in 0...m
    for j in 0...m
      t[2*m-i][2*m-j] = t[i][j]
      t[i][2*m-j] = t[i][j]
      t[2*m-i][j] = t[i][j]
    end
    t[2*m-i][m] = t[i][m]
    t[m][2*m-i] = t[m][i]
  end
end

puts "YES"
for i in 0...n
  for j in 0...n
    print "#{t[i][j]} "
  end
  puts ""
end

n = gets.to_i
a = gets.split.map(&:to_i)
b = Hash.new(0)
a.each do |i|
    b[i] += 1
end
c = 0
b.values.each do |i|
    c += 1 if i%4 != 0
end
if (n.odd? && c != 1) || (n.even? && c != 0)
    puts "NO"
    exit
end
ans = Array.new(n).map{Array.new(n,0)}
if n.odd?
    b.keys.each do |k|
        if b[k].odd?
            ans[n/2][n/2] = k
            b[k] -= 1
            break
        end
    end
    for i in 0..n/2-1
        b.keys.each do |k|
            if b[k] != 0
                ans[i][n/2] = ans[n-i-1][n/2] = ans[n/2][i] = ans[n/2][n-i-1] = k
                b[k] -= 4
                break
            end
        end
    end
end
for i in 0..n/2-1
    for j in 0..n/2-1
        b.keys.each do |k|
            if b[k] != 0
                ans[i][j] = ans[i][n-1-j] = ans[n-1-i][j] = ans[n-1-i][n-1-j] = k
                b[k] -= 4
                break
            end
        end
    end
end
puts "YES"
ans.each do |arr|
    puts arr.join(" ")
end


Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $$$n$$$ friends, numbered from $$$1$$$ to $$$n$$$.Recall that a permutation of size $$$n$$$ is an array of size $$$n$$$ such that each integer from $$$1$$$ to $$$n$$$ occurs exactly once in this array.So his recent chat list can be represented with a permutation $$$p$$$ of size $$$n$$$. $$$p_1$$$ is the most recent friend Polycarp talked to, $$$p_2$$$ is the second most recent and so on.Initially, Polycarp's recent chat list $$$p$$$ looks like $$$1, 2, \dots, n$$$ (in other words, it is an identity permutation).After that he receives $$$m$$$ messages, the $$$j$$$-th message comes from the friend $$$a_j$$$. And that causes friend $$$a_j$$$ to move to the first position in a permutation, shifting everyone between the first position and the current position of $$$a_j$$$ by $$$1$$$. Note that if the friend $$$a_j$$$ is in the first position already then nothing happens.For example, let the recent chat list be $$$p = [4, 1, 5, 3, 2]$$$:   if he gets messaged by friend $$$3$$$, then $$$p$$$ becomes $$$[3, 4, 1, 5, 2]$$$;  if he gets messaged by friend $$$4$$$, then $$$p$$$ doesn't change $$$[4, 1, 5, 3, 2]$$$;  if he gets messaged by friend $$$2$$$, then $$$p$$$ becomes $$$[2, 4, 1, 5, 3]$$$. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$) — the number of Polycarp's friends and the number of received messages, respectively. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$) — the descriptions of the received messages.

Print $$$n$$$ pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.

NoteIn the first example, Polycarp's recent chat list looks like this:   $$$[1, 2, 3, 4, 5]$$$  $$$[3, 1, 2, 4, 5]$$$  $$$[5, 3, 1, 2, 4]$$$  $$$[1, 5, 3, 2, 4]$$$  $$$[4, 1, 5, 3, 2]$$$ So, for example, the positions of the friend $$$2$$$ are $$$2, 3, 4, 4, 5$$$, respectively. Out of these $$$2$$$ is the minimum one and $$$5$$$ is the maximum one. Thus, the answer for the friend $$$2$$$ is a pair $$$(2, 5)$$$.In the second example, Polycarp's recent chat list looks like this:   $$$[1, 2, 3, 4]$$$  $$$[1, 2, 3, 4]$$$  $$$[2, 1, 3, 4]$$$  $$$[4, 2, 1, 3]$$$

class BIT
  def initialize(size)
    @arr = Array.new(size+1, 0)
  end

  def update(p, v)
    while p < @arr.length
      @arr[p] += v
      p += (p&-p)
    end
  end

  def pquery(p)
    ans = 0
    while p > 0
      ans += @arr[p]
      p -= (p&-p)
    end
    ans
  end

  def query(l, r)
    l <= r ? pquery(r) - pquery(l-1) : 0
  end
end

n, m = gets.chomp.split(' ').map(&:to_i)
arr = gets.chomp.split(' ').map(&:to_i)
lastpos = Array.new(n+1, -1)
maxpos = (0..n).to_a
bit_m = BIT.new(m)
bit_n = BIT.new(n)

(1..m).each do |i|
  x = arr[i-1]
  if lastpos[x] == -1
    curr = x + bit_n.query(x+1, n)
  else
    curr = 1 + bit_m.query(lastpos[x]+1, i)
    bit_m.update(lastpos[x], -1)
  end
  maxpos[x] = curr if curr > maxpos[x]

  lastpos[x] = i
  bit_m.update(i, 1)
  bit_n.update(x, 1) if bit_n.query(x, x) == 0
end

(1..n).each do |x|
  if lastpos[x] == -1
    curr = x + bit_n.query(x+1, n)
  else
    curr = 1 + bit_m.query(lastpos[x]+1, m)
  end
  maxpos[x] = curr if curr > maxpos[x]
end

minpos = (0..n).map {|x| lastpos[x] == -1 ? x : 1}
answer = minpos.zip(maxpos).map {|a, b| "#{a} #{b}"}
puts answer[1..n]

class BIT
  def initialize(size)
    @arr = Array.new(size+1, 0)
  end

  def update(p, v)
    while p < @arr.length
      @arr[p] += v
      p += (p&-p)
    end
  end

  def pquery(p)
    ans = 0
    while p > 0
      ans += @arr[p]
      p -= (p&-p)
    end
    ans
  end

  def query(l, r)
    l <= r ? pquery(r) - pquery(l-1) : 0
  end
end

n, m = gets.chomp.split(' ').map(&:to_i)
arr = gets.chomp.split(' ').map(&:to_i)
lastpos = Array.new(n+1, -1)
maxpos = (0..n).to_a
bit_m = BIT.new(m)
bit_n = BIT.new(n)

(1..m).each do |i|
  x = arr[i-1]
  if lastpos[x] == -1
    curr = x + bit_n.query(x+1, n)
  else
    curr = 1 + bit_m.query(lastpos[x]+1, i)
    bit_m.update(lastpos[x], -1)
  end
  maxpos[x] = curr if curr > maxpos[x]

  lastpos[x] = i
  bit_m.update(i, 1)
  bit_n.update(x, 1) if bit_n.query(x, x) == 0
end

final_bit_m = (1..m).map {|x| bit_m.query(x, x) }
puts final_bit_m.join(' ')

(1..n).each do |x|
  if lastpos[x] == -1
    curr = x + bit_n.query(x+1, n)
  else
    curr = 1 + bit_m.query(lastpos[x]+1, m)
  end
  maxpos[x] = curr if curr > maxpos[x]
end

minpos = (0..n).map {|x| lastpos[x] == -1 ? x : 1}
answer = minpos.zip(maxpos).map {|a, b| "#{a} #{b}"}
puts answer[1..n]

class BIT
  def initialize(size)
    @arr = Array.new(size+1, 0)
  end

  def update(p, v)
    while p < @arr.length
      @arr[p] += v
      p += (p&-p)
    end
  end

  def pquery(p)
    ans = 0
    while p > 0
      ans += @arr[p]
      p -= (p&-p)
    end
    ans
  end

  def query(l, r)
    l <= r ? pquery(r) - pquery(l-1) : 0
  end
end

n, m = gets.chomp.split(' ').map(&:to_i)
arr = gets.chomp.split(' ').map(&:to_i)
lastpos = Array.new(n+1, -1)
maxpos = (0..n).to_a
bit_m = BIT.new(m)
bit_n = BIT.new(n)

(1..m).each do |i|
  x = arr[i-1]
  if lastpos[x] == -1
    curr = x + bit_n.query(x+1, n)
  else
    curr = 1 + bit_m.query(lastpos[x]+1, i-1)
    bit_m.update(i, -1)
  end
  maxpos[x] = curr if curr > maxpos[x]
  lastpos[x] = i
  bit_m.update(i, 1)
  bit_n.update(x, 1) if bit_n.query(x, x) == 0
end

(1..n).each do |x|
  if lastpos[x] != -1
    curr = 1 + bit_m.query(lastpos[x]+1, m)
  else
    curr = x + bit_n.query(x+1, n)
  end
  maxpos[x] = curr if curr > maxpos[x]
end

minpos = (0..n).map {|x| lastpos[x] == -1 ? x : 1}
answer = minpos.zip(maxpos).map {|a, b| "#{a} #{b}"}
puts answer[1..n]


Recently, your friend discovered one special operation on an integer array $$$a$$$:   Choose two indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$);  Set $$$a_i = a_j = |a_i - a_j|$$$. After playing with this operation for a while, he came to the next conclusion:   For every array $$$a$$$ of $$$n$$$ integers, where $$$1 \le a_i \le 10^9$$$, you can find a pair of indices $$$(i, j)$$$ such that the total sum of $$$a$$$ will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer $$$n$$$. Can you find such counterexample and prove him wrong?In other words, find an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) such that for all pairs of indices $$$(i, j)$$$ performing the operation won't decrease the total sum (it will increase or not change the sum).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first and only line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the length of array $$$a$$$.

For each test case, if there is no counterexample array $$$a$$$ of size $$$n$$$, print NO. Otherwise, print YES followed by the array $$$a$$$ itself ($$$1 \le a_i \le 10^9$$$). If there are multiple counterexamples, print any.

NoteIn the first test case, the only possible pairs of indices are $$$(1, 2)$$$ and $$$(2, 1)$$$.If you perform the operation on indices $$$(1, 2)$$$ (or $$$(2, 1)$$$), you'll get $$$a_1 = a_2 = |1 - 337| = 336$$$, or array $$$[336, 336]$$$. In both cases, the total sum increases, so this array $$$a$$$ is a counterexample.

main = -> {
  t = int
  pow3 = [1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489]
  len = pow3.size
  t.times do
    n = int
    if n <= len
      puts "YES"
      puts pow3[0, n].join(" ")
    else
      puts "NO"
    end
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri ( - 4000 ≤ beforei, afteri ≤ 4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters. It is guaranteed that all handles are distinct.

Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise.

3
Burunduk1 2526 2537
BudAlNik 2084 2214
subscriber 2833 2749

3
Applejack 2400 2400
Fluttershy 2390 2431
Pinkie_Pie -2500 -2450

NoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.

n = gets.to_i

n.times do
	s, b, a = gets.split
	bi = b.to_i
	if 2400 <= bi && bi < a.to_i then
		puts "YES"
		exit 0
	end
end

puts "NO"

#!/usr/bin/ruby
puts gets.to_i.times.any?{
	e=gets.split.map(&:to_i)
	2400<=e[1] && e[1]<e[2]
} ? :YES : :NO

def color(n)
  (n >= 2400) ? "red" : "other"
end

n = gets.chomp.to_i
arr = [].tap do |out|
  n.times do
    out << gets.chomp.split
  end
end

puts arr.any? { |n, a, b| color(a.to_i) == "red" && b.to_i > a.to_i } ? "YES" : "NO"

n = gets.to_i
ans = 'NO'
n.times do
  name, b, a = gets.split
  if b.to_i >= 2400 && b.to_i < a.to_i
    ans = 'YES'
  end
end
puts ans

n = gets.strip.to_i
ans = "NO"
n.times do
    line = gets.strip.split(/ /)
    before = line[1].to_i
    after = line[2].to_i
    ans = "YES" if before >= 2400 && after > before
end
puts ans

n = gets.to_i
q = []

(1..n).each do |i|
  a, b, c = gets.split
  b, c = b.to_i, c.to_i
  q << [a,b,c]
end

q.delete_if { |e| e[1] < 2400 || e[1] >= e[2] }

puts q.empty? ? 'NO' : 'YES'

n = gets.to_i
n.times do |i|
    a, b, c = gets.split
    if b.to_i >= 2400 && c.to_i - b.to_i > 0
        puts "YES"
        exit
    end
end
puts "NO"

n = gets.chomp.to_i
f = false
n.times do
  name, before, after = gets.chomp.split
  if 2400 <= before.to_i and before.to_i < after.to_i
    f = true
  end
end

puts f ? "YES" : "NO"

n = gets.chomp.to_i
a = []
count = 0
for i in (0..n-1)
	a << gets.chomp.split
	if a[i][1].to_i >= 2400 && a[i][2].to_i > a[i][1].to_i
		count += 1
	end
end
if count > 0
	print "YES"
else
	print "NO"
end

puts gets.to_i.times.map{gets.split.map(&:to_i)}.any?{|*,a,b| a>=2400 && b>a} ? "YES" : "NO"

n = gets.to_i
ans = false
n.times do
  _, s1, s2 = gets.split.map(&:to_i)
  ans = true if s1 >= 2400 && s2 > s1
end
puts ans ? 'YES' : 'NO'

n = gets.to_i

out = 'NO'
for i in 1..n
  user = gets.split
  pre = user[1].to_i
  if pre >= 2400
    if user[2].to_i > pre
      out = 'YES'
    end
  end
end

puts out

n=gets.to_i
ans=false;
n.times{
	buf=gets.split(' ');
	name,before,after = buf[0], buf[1].to_i, buf[2].to_i
	ans=true if before>=2400&&after>before
}
puts ans==true ? "YES" : "NO"

n = gets.to_i
n.times do
  _, before, after = gets.split.map &:to_i
  if 2400 <= before and before < after
    puts 'YES'
    exit
  end
end
puts 'NO'

POINT_VALUE = 2400

time = gets.chomp.to_i

result = false
time.times do |n|
	line = gets.chomp
	_, before, after = line.split(' ').map &:to_i

	result = true if before >= POINT_VALUE and after > before
end

puts result ? 'YES' : 'NO'

good = false

n = gets.chomp.to_i
n.times do
  name, prev_score, after_score = gets.chomp.split
  if(prev_score.to_i >= 2400 && after_score.to_i > prev_score.to_i)
    good = true
    break
  end
end

if good
  puts "YES"
else
  puts "NO"
end

peopleNum = gets.chomp.to_i
peoples = []

peopleNum.times do
    people = gets.chomp.split(' ')
    people[1] = people[1].to_i
    people[2] = people[2].to_i

    peoples << people
end

red = []

peoples.each do |people|
    red << people if people[1] >= 2400 && people[2] > people[1]
end

ans = if red.length > 0
    "YES"
else
    "NO"
end

puts ans

n = gets.chomp.to_i
a = []
for i in (0..n-1)
	a << gets.chomp.split
	count = 0
	if a[i][1].to_i >= 2400 && a[i][2].to_i > a[i][1].to_i
		count += 1
	end
end
if count > 0
	print "YES"
else
	print "NO"
end

n = gets.chomp.to_i
a = []
for i in (0..n-1)
	a << gets.chomp.split
	count = 0
	if a[i][1].to_i >= 2400 && a[i][2].to_i != a[i][1].to_i && a[i][2].to_i >= 2400
		count += 1
	end
end
if count > 0
	print "YES"
else
	print "NO"
end

p gets.to_i.times.map{gets.split.map(&:to_i)}.any?{|*,a,b| a>=2400 && b>a} ? "YES" : "NO"

POINT_VALUE = 2400

time = gets.chomp.to_i

result = false
time.times do |n|
	line = gets.chomp
	_, before, after = line.split(' ').map &:to_i

	result = true if before > POINT_VALUE and after > before
end

puts result ? 'YES' : 'NO'


Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:  Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.

The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.

Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p.

NotePicture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.In the second test case, we can put all four small boxes into a box with side length 2.

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
sizes = []
n.times do
	k, a = STDIN.readline.split.collect {|s| s.to_i }
	p = (Math.log2(a)/2).ceil
	p = 1 if p == 0
	sizes.push(k+p)
end

puts sizes.sort[n-1]

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
ka = []
n.times do
	k, a = STDIN.readline.split.collect {|s| s.to_i }
	ka.push([k, a])
end
#ka.sort!

sizes = []
ka.each do |k, a|
	p = (Math.log2(a)/2).ceil
	p = 1 if p == 0
	sizes.push(k+p)
end

puts sizes.sort[n-1]

n = gets.to_i
max = 0;
n.times{
    k,x = gets.split(" ").map(&:to_i)
    d = (Math.log2(Math.sqrt(x)) + k.to_f).ceil
    if ( d == k ) then
        d = d+1
    end
    if( d > max) then
        max = d
    end
}
if max>0 then
puts max
else
puts "0"
end

def run
  n = ARGF.readline.to_i

  ret = 0
  ARGF.readlines.each do |line|
    k, a = line.split.map(&:to_i)

    cur = k + [(Math.log(a, 4)).ceil, 1].max
    ret = [cur, ret].max
  end

  puts ret
end

run if $0 == __FILE__

#!/usr/bin/env ruby

n = gets.to_i
p = 0
n.times do
	k, a = gets.split.map(&:to_i)
	if a == 1
		p = [p, k + 1].max
	else
		p = [p, k + Math.log(a, 4).ceil].max
	end
end
puts p

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
ka = []
n.times do
	k, a = STDIN.readline.split.collect {|s| s.to_i }
	ka.push([k, a])
end
ka.sort!

sizes = []
ka.each do |k, a|
	p = (Math.log2(a)/2).ceil
	sizes.push(k+p)
end

puts sizes.sort[n-1]

n = gets.to_i
max = 0;
n.times{
    k,x = gets.split(" ").map(&:to_i)
    d = (Math.log2(x) + k.to_f).ceil
    if ( d == k ) then
        d = d+1
    end
    if( d > max) then
        max = d
    end
}
if max>0 then
puts max
else
puts "0"
end

n = gets.to_i
max = 0;
n.times{
	k,x = gets.split(" ").map(&:to_i)
	t = ((2**(k))**2) * x
	if( t > max) then
		max = t
	end
}
if max>0 then
puts Math.log2(Math.sqrt(max)).ceil
else
puts "0"
end

n = gets.to_i
max = 0;
n.times{
	k,x = gets.split(" ").map(&:to_i)
	t = ((2**(k))**2) * x
	if( t > max) then
		max = t
	end
}
puts Math.log2(Math.sqrt(max)).ceil

n = gets.to_i
max = 0;
n.times{
    k,x = gets.split(" ").map(&:to_i)
    d = k + Math.log2(x).ceil
    if ( d == k ) then
        d = d+1
    end
    if( d > max) then
        max = d
    end
}
if max>0 then
puts max
else
puts "0"
end

def run
  n = ARGF.readline.to_i

  ret = 0
  ARGF.readlines.each do |line|
    k, a = line.split.map(&:to_i)

    cur = k + [(Math.log(a, 4)).ceil, 1].min
    ret = [cur, ret].max
  end

  puts ret
end

run if $0 == __FILE__


According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.

The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.

Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.

n, d = gets.split.map{|i| i.to_i}

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

res = 0
n.times do |i|
    n.times do |j|
        if (solds[i] - solds[j]).abs <= d then
            res += 1
        end
    end
end

puts res-n

s = gets.chomp
ns,ds = s.split(/ /)
n = ns.to_i
d = ds.to_i
s = gets.chomp
ss = s.split(/ /)

a = Array.new
for i in 0..n-1
	a[i] = ss[i].to_i
end

sum = 0
for i in 0..n-2
	for j in i+1..n-1
		if (a[i]-a[j]).abs <= d
			sum += 2
		end
	end
end
puts sum

n,d=gets.split.map &:to_i
a=gets.split.map &:to_i
ans=0
n.times do |i|
    n.times do |j|
        if i!=j && (a[i]-a[j]).abs<=d
            ans+=1
        end
    end
end
p ans

#!/usr/bin/ruby
d,a=$<.map{|l|l.split.map(&:to_i)}
r=0
a.size.times{|i|(i+1).step(a.size-1){|j|r+=2 if (a[i]-a[j]).abs<=d[1]}}
p r

d=gets.split[1].to_i
ans=0
i=gets.split.map(&:to_i)
i.each{|a|
    i.each{|b|
        ans=ans+(((a-b).abs<=d)?1:0)
    }
}
puts ans-i.length

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

ans = 0
(0..n-2).each do |i|
  ((i+1)..n-1).each do |j|
    if (as[i] - as[j]).abs <= d
      ans += 1
    end
  end
end

puts ans * 2

ma = gets.split(" ").map{|i| i.to_i}
mas = gets.split(" ").map{|i| i.to_i}
mas = mas.sort
ans = 0
mas.each{|a|
    mas.each{|b|
    	if (a - b).abs <= ma[1]
    		ans = ans + 1
    	end
    }
}
puts ans - ma[0]

def main()
	n,d=gets.chomp.split(" ").map{|i| i.to_i}
	har=gets.chomp.split(" ").map{|i| i.to_i}
	ans=0
	for i in 0...n
		for j in 0...n
			if i==j
				next;
			end
			if (har[i]-har[j]).abs<=d
				ans+=1
			end
		end
	end
	puts ans
end
main()

s = gets.chomp!.split(" ")
n = s[0].to_i
d = s[1].to_i

s = gets.chomp!.split(" ")
mas = Array.new
for i in 1..n
  mas[i] = s[i-1].to_i
end

count = 0
for i in 1..n
  for j in 1..n
    if (i != j && (mas[i] - mas[j]).abs <= d)
      count += 1
    end
  end
end

puts(count)

n=gets(" ").chomp.to_i
d=gets.chomp.to_i
data=gets.chomp.split(/ /)
sol=[]
for i in 0..(n-1)
	sol.push(data[i].to_i)
end
#puts sol
sol=sol.sort{|a,b|
	a<=>b
}
#puts sol

ans=0
for i in 0..(n-1)
	j=1
	while (i+j)<n
		if sol[i+j]-sol[i]<=d then
			ans+=2
		else	break
		end
		j+=1
	end
end
puts ans

# To change this template, choose Tools | Templates
# and open the template in the editor.

cond = gets.split.map{ |s| s.to_i}
n=cond[0]
d=cond[1]
heights = gets.split.map { |s| s.to_i }.sort

if n != heights.length
  puts "ERROR!"
  exit
end
count = 0
heights.each_with_index do |h, i|
  heights[(i+1)..-1].each do |hh|
    if hh-h<=d
      count+=1
    else
      break
    end
  end

end
puts count*2


You are given an array $$$a_1, a_2 \dots a_n$$$. Calculate the number of tuples $$$(i, j, k, l)$$$ such that:   $$$1 \le i < j < k < l \le n$$$;  $$$a_i = a_k$$$ and $$$a_j = a_l$$$;

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$4 \le n \le 3000$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the array $$$a$$$. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$3000$$$.

For each test case, print the number of described tuples.

NoteIn the first test case, for any four indices $$$i < j < k < l$$$ are valid, so the answer is the number of tuples.In the second test case, there are $$$2$$$ valid tuples:   $$$(1, 2, 4, 6)$$$: $$$a_1 = a_4$$$ and $$$a_2 = a_6$$$;  $$$(1, 3, 4, 6)$$$: $$$a_1 = a_4$$$ and $$$a_3 = a_6$$$.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  arr = Array.new(n*(n+1)+1,0)
  cnt = 0
  (n-3).downto(1) do |j|
    k = j+1
    for l in k+1..n-1
      arr[a[k]*n+a[l]] += 1
    end
    for i in 0..j-1
      cnt += arr[a[i]*n+a[j]]
    end
  end
  ans << cnt
end
ans.each do |x|
  puts x
end


Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.

The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le n + m$$$, $$$1 \le t_a, t_b \le 10^9$$$) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \le a_1 < a_2 < \ldots < a_n \le 10^9$$$) — the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \le b_1 < b_2 < \ldots < b_m \le 10^9$$$) — the times the flights from B to C depart.

If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.

NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.

def bsearch(arr,t)
  ok,ng = arr.length-1,-1
  while (ng - ok).abs > 1
    mid = (ok+ng)/2
    if arr[mid] >= t
      ok = mid
    else
      ng = mid
    end
  end
  return ok
end

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

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

if n <= k || m <= k
  p -1
  exit
end
ans = 0
0.upto(k) do |i|
  ib = bsearch(b,a[i]+ta)
  if ib+k-i > m-1 || a[i]+ta > b[ib]
    p -1
    exit
  end
#p [i,ib]
  ans = b[ib+k-i] if ans < b[ib+k-i]
end
p ans+tb

def bsearch(arr,t)
  ok,ng = arr.length-1,-1
  while (ng - ok).abs > 1
    mid = (ok+ng)/2
    if arr[mid] >= t
      ok = mid
    else
      ng = mid
    end
  end
  return ok
end

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

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

ia = 0

if n <= k
  p -1
  exit
end
ans = 0
1.upto(k) do |i|
  ib = bsearch(b,a[i]+ta)
  if ib+k-i > m-1 || a[i]+ta > b[ib]
    p -1
    exit
  end
#p [i,ib]
  ans = b[ib+k-i] if ans < b[ib+k-i]
end
p ans+tb

def bsearch(arr,t)
  ok,ng = arr.length-1,-1
  while (ng - ok).abs > 1
    mid = (ok+ng)/2
    if arr[mid] >= t
      ok = mid
    else
      ng = mid
    end
  end
  return ok
end

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

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

ia = 0
ib = bsearch(b,a[0]+ta)

t = b[ib] + tb
ans = []

if n <= k
  p -1
  exit
end
ans = 0
1.upto(k) do |i|
  ib = bsearch(b,a[i]+ta)
  if ib+k-i > m-1
    p -1
    exit
  end
#p [i,ib]
  ans = b[ib+k-i] if ans < b[ib+k-i]
end
p ans+tb


You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.The decoding of the lever description is given below.  If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.  If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.  If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.

The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar. To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.

Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.

NoteAs you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.The pictures to the examples:

a=gets.chomp.split('')
s=0
len=a.length
for i in 0..len-1
	if a[i]=='^'
		break
	end
end
for j in 0..len-1
	if a[j]!='='
		s+=a[j].to_i*(i-j)
	end
end
puts s>0? "left" : s==0? "balance" : "right"

s = gets.chomp
mid = s.index "^"
left = 0
right = 0
(0...mid).each do |i|
    left += (mid - i) * s[i].to_i if s[i] != '='
end
((mid + 1)...s.length).each do |i|
    right += (i - mid) * s[i].to_i if s[i] != '='
end
ans = right <=> left
case ans
when 0
    puts "balance"
when 1
    puts "right"
else
    puts "left"
end

class Weights
  attr_accessor :string, :balance

  def initialize(value)
    raise "Node value shouldn't be nil or empty" if value.nil?
    @string = value

  end

  def balance
    left, right = @string.split("^")
    left = left.reverse

    left_weight = weigh(left)
    right_weight = weigh(right)

    if left_weight > right_weight
      return "left"
    elsif left_weight < right_weight
      return "right"
    else
      return "balance"
    end

  end

  private

  def weigh(input)
    w = 0
    input.split("").each_with_index do |element, index|
      w += element.to_i * (index + 1) unless element == "="
    end
    w
  end

end

str = gets
puts Weights.new(str).balance

left,right = gets.split("^")
left.reverse!
sum_arr = []
i = 1
sum = 0
left.each_char do |l|
	sum += l.to_i * i if l != '='
	i += 1
end

sum_arr << sum

i = 1
sum = 0
right.each_char do |r|
	sum += r.to_i * i if r != '='
	i += 1
end
sum_arr << sum
# puts "#{sum_arr}"

if sum_arr[0] == sum_arr[1]
	ans = "balance"
elsif sum_arr[0] > sum_arr[1]
	ans = "left"
else
	ans = "right"
end
puts ans

s = gets.chomp
fulcrum = s.index('^')
left = 0
right = 0
i = 1
while fulcrum-i >= 0
    if s[fulcrum-i].to_i.to_s == s[fulcrum-i]
        left += i*s[fulcrum-i].to_i
    end
    i += 1
end
i = 1
while fulcrum+i < s.size
    if s[fulcrum+i].to_i.to_s == s[fulcrum+i]
        right += i*s[fulcrum+i].to_i
    end
    i += 1
end
case left <=> right
when 1
    puts 'left'
when -1
    puts 'right'
when 0
    puts 'balance'
end

s = gets.chomp
fulcrum = s.index('^')
left = 0
right = 0
i = 1
while fulcrum-i >= 0
    left += i*s[fulcrum-i].to_i if s[fulcrum-i].to_i.to_s == s[fulcrum-i]
    i += 1
end
i = 1
while fulcrum+i < s.size
    right += i*s[fulcrum+i].to_i if s[fulcrum+i].to_i.to_s == s[fulcrum+i]
    i += 1
end
case left <=> right
when 1
    puts 'left'
when -1
    puts 'right'
when 0
    puts 'balance'
end

bar = gets
pivot = bar.index("^")

left_weight = 0
right_weight = 0

(0...bar.length).each do |index|
  piece = bar[index].chr
  if piece =~ /[[:digit:]]/
    if index < pivot
      left_weight += (pivot - index) * piece.to_i
    else
      right_weight += (index - pivot) * piece.to_i
    end
  end
end

if left_weight > right_weight
  puts "left"
elsif right_weight > left_weight
  puts "right"
else
  puts "balance"
end

s=gets.chomp
x=s.index '^'
i=1
z=0
while x-i>=0
  c=s[x-i].to_i
  z+=c*i if c>0
  i+=1
end
i=1
while x+i<s.size
  c=s[x+i].to_i
  z-=c*i if c>0
  i+=1
end
if z>0
  puts 'left'
elsif z==0
  puts 'balance'
else
  puts 'right'
end

puts (->(x){ x.first > x.last ? 'left' : (x.first < x.last ? 'right' : 'balance')}.call(->(x) {[x.first.reverse, x.last] }.call((STDIN.readline.chomp).split('^').map{|p| p.scan(/./)}).map{|x| x.each_with_index.inject(0){|s,p| s = s + p.first.to_i  * (p.last + 1) }}))

s = gets.chomp
mid = s.index "^"
left = []
right = []
(0...mid).each do |i|
    if s[i] != '='
        left << s[i].to_i
    else
        left << 0
    end
end
((mid + 1)...s.length).each do |i|
    if s[i] != '='
        right << s[i].to_i
    else
        right << 0
    end
end
left.delete 0
right.delete 0
ans = 0
if left.length == right.length
    left.length.times do |i|
        l = left[left.length - 1 - i]
        r = right[i]
        ans += r <=> l
    end
else
    ans = left.inject(:+) <=> right.inject(:+)
end
case ans
when 0
    puts "balance"
when 1
    puts "right"
else
    puts "left"
end

s = gets.chomp
mid = s.index "^"
left = 0
right = 0
(0...mid).each do |i|
    left += (mid - 1) * s[i].to_i if s[i] != '='
end
((mid + 1)...s.length).each do |i|
    right += (i - mid) * s[i].to_i if s[i] != '='
end
ans = right <=> left
case ans
when 0
    puts "balance"
when 1
    puts "right"
else
    puts "left"
end

->(x){ x.first > x.last ? 'left' : (x.first < x.last ? 'right' : 'balance')}.call(->(x) {[x.first.reverse, x.last] }.call((STDIN.readline.chomp).split('^').map{|p| p.scan(/./)}).map{|x| x.each_with_index.map{|p,i| [p, i+1]}}.map{|x| x.map{|t|[t.first.to_i, t.last]}}.map{|x| x.inject(0){|s, t| s = s + t.first * t.last }})

puts (->(x){ x.first > x.last ? 'left' : (x.first < x.last ? 'right' : 'balance')}.call(->(x) {[x.first.reverse, x.last] }.call((STDIN.readline.chomp).split('^').map{|p| p.scan(/./)}).map{|x| x.each_with_index.inject(0){|s,p| s = s + p.first.to_i * p.last}}))


A positive integer $$$x$$$ is called a power of two if it can be represented as $$$x = 2^y$$$, where $$$y$$$ is a non-negative integer. So, the powers of two are $$$1, 2, 4, 8, 16, \dots$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to represent $$$n$$$ as the sum of exactly $$$k$$$ powers of two.

The only line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le k \le 2 \cdot 10^5$$$).

If it is impossible to represent $$$n$$$ as the sum of $$$k$$$ powers of two, print NO. Otherwise, print YES, and then print $$$k$$$ positive integers $$$b_1, b_2, \dots, b_k$$$ such that each of $$$b_i$$$ is a power of two, and $$$\sum \limits_{i = 1}^{k} b_i = n$$$. If there are multiple answers, you may print any of them.

# Utility
def digits(num, base)
  num.to_s(base).split("").reverse!.map { |c| c.to_i }
end

# Input
n, k = *(gets.split.map { |s| s.to_i })

# Processing
b = digits(n, 2)
#p b
decomposition = b.map.with_index { |e, i| e * 2**i }
decomposition = decomposition.reject { |e| e == 0 }
decomposition.reverse!
# decomposition is sorted so largest element is first
#p decomposition

if decomposition.length > k || k > n
  puts "NO"
else
  # Will be splitting numbers until we get enough
  while decomposition.length != k
    num = decomposition.shift
    if num == 1
      decomposition.push(num)
    else
      decomposition.push(num / 2, num / 2)
    end
  end

  puts "YES"
  puts decomposition.join(" ")
end

N,K = gets.split.map(&:to_i)
bs = []
n = N
while n > 0
  bs << (n&1)
  n >>= 1
end

t = bs.count(1)
if K < t || N < K
  puts "NO"; exit
end

(1...bs.size).reverse_each{ |b|
  if K - t <= bs[b]
    bs[b] -= K-t
    bs[b-1] += 2*(K-t)
    break
  end
  bs[b-1] += 2*bs[b]
  t += bs[b]
  bs[b] = 0
}

puts "YES"
b = 1
puts bs.map.with_index{ |b,i| [1 << i] * b }.flatten.join(" ")

nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]

n = n.to_s(2)

mink = n.count("1")
maxk = 0
len = n.length

n.each_char.with_index do |ch,i|
  pos = len-i-1
  maxk += 2**pos if ch == "1"
end

if k < mink or k > maxk
  puts "NO"
  exit
end

def myprint(narr,k)
  sum = narr.inject(:+)
  while sum < k
    narr[0] -= 1
    narr[1] += 2
    sum += 1
    if narr[0] == 0
      narr.shift
    end
  end

  len = narr.length
  narr.each_with_index do |x,i|
    x.times do
      print 2**(len-i-1)
      print " "
    end
  end
end

puts "YES"
myprint(n.each_char.to_a.map(&:to_i),k)
puts

# Utility
def digits(num, base)
  num.to_s(base).split("").map { |c| c.to_i }
end

# Input
n, k = *(gets.split.map { |s| s.to_i })

# Processing
b = digits(n, 2)
decomposition = b.map.with_index { |e, i| e * 2**i }
decomposition = decomposition.reject { |e| e == 0 }
decomposition.reverse!
# decomposition is sorted so largest element is first

if decomposition.length > k || k > n
  puts "NO"
else
  # Will be splitting numbers until we get enough
  while decomposition.length != k
    num = decomposition.shift
    if num == 1
      decomposition.push(num)
    else
      decomposition.push(num / 2, num / 2)
    end
  end

  puts "YES"
  puts decomposition.join(" ")
end


You have $$$n$$$ rectangular wooden blocks, which are numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th block is $$$1$$$ unit high and $$$\lceil \frac{i}{2} \rceil$$$ units long.Here, $$$\lceil \frac{x}{2} \rceil$$$ denotes the result of division of $$$x$$$ by $$$2$$$, rounded up. For example, $$$\lceil \frac{4}{2} \rceil = 2$$$ and $$$\lceil \frac{5}{2} \rceil = \lceil 2.5 \rceil = 3$$$.For example, if $$$n=5$$$, then the blocks have the following sizes: $$$1 \times 1$$$, $$$1 \times 1$$$, $$$1 \times 2$$$, $$$1 \times 2$$$, $$$1 \times 3$$$.  The available blocks for $$$n=5$$$ Find the maximum possible side length of a square you can create using these blocks, without rotating any of them. Note that you don't have to use all of the blocks.  One of the ways to create $$$3 \times 3$$$ square using blocks $$$1$$$ through $$$5$$$

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of blocks.

For each test case, print one integer — the maximum possible side length of a square you can create.

NoteIn the first test case, you can create a $$$1 \times 1$$$ square using only one of the blocks.In the second test case, one of the possible ways to create a $$$3 \times 3$$$ square is shown in the statement. It is impossible to create a $$$4 \times 4$$$ or larger square, so the answer is $$$3$$$.


You are given a special jigsaw puzzle consisting of $$$n\cdot m$$$ identical pieces. Every piece has three tabs and one blank, as pictured below.  The jigsaw puzzle is considered solved if the following conditions hold:  The pieces are arranged into a grid with $$$n$$$ rows and $$$m$$$ columns.  For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.

The test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$).

For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteFor the first test case, this is an example solution:   For the second test case, we can show that no solution exists.For the third test case, this is an example solution:

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN
t = file.gets.chomp.to_i
t.times do
  n, m = file.gets.chomp.split.map(&:to_i)
  if (n == 1 || m == 1) || (n==2 && m == 2)
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.to_i
0.upto t-1 do
  t1, t2 = gets.split.map(&:to_i)
  if t1 == 1 or t2 == 1
    puts "YES"
  elsif t1 == 2 and t2 == 2
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.to_i
t.times do
 a ,b =gets.split.map(&:to_i)
 if a==1 or b==1 or a+b==4
    puts "YES"
 else
    puts"NO"
 end
end

1.upto(gets.chomp.to_i) do
  a, b = gets.chomp.split.map(&:to_i)
  if (a == 1 || b == 1 || (a <= 2 && b <= 2))
    puts 'YES'
  else
    puts 'NO'
  end
end


Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

n=gets.chomp.to_i
memo=gets.chomp.split.map{|i| i.to_i}.sort!
min=memo[0]
n.times do |i|
  if min!=memo[i]
    puts(memo[i])
    exit
  end
end
puts("NO")

n = gets.to_i
a = gets.split(' ')[0...n].map { |s| s.to_i }
puts a.sort.uniq[1] || 'NO'

num = gets.chomp
data = gets.chomp

array = data.split(/\s* \s*/).uniq.sort{|a, b| a.to_i <=> b.to_i}

if array.length > 1
  puts array[1]
else
  puts "NO"
end

amount = gets.to_i
elements = gets.split(' ').map { |e| e.to_i }
elements = elements.to_a.sort
answer = min = elements[0]
(0...amount).each do |i|
  if elements[i] > min
    answer = elements[i]
    break
  end
end
if answer == min
  print "NO"
else
  print answer
end

gets
k=gets.split.map(&:to_i).sort.uniq
puts k.size<=1 ?"NO":k[1]

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
ans = nil
amin = a.min
a.each{|aa| ans = aa if aa > amin and (ans == nil or aa < ans)}
if ans == nil
    puts "NO"
else
    puts ans
end

gets
nums = gets.chomp.split.map(&:to_i)

min = nums.min
res = nums.sort.detect{ |x| x > min }
puts res.nil? ? "NO" : res

gets.chomp # Skip the first line
puts((seq = gets.chomp.split.map { |x| x.to_i }.uniq).size > 1 ? seq.sort[1] : 'NO')

n = gets.to_i

a = gets.split.collect{|x| x.to_i}

min = a.min
a.delete(min)

answer = a.min

if answer == nil
	puts 'NO'
else
	puts answer
end

STDIN.readlines.drop(1).join.split.map(&:to_i).uniq.sort.tap { |x| puts(x.length < 2 ? "NO" : x[1])}

gets
values = gets.split.map { |v| v.to_i }.sort.uniq
result = values.size >= 2 ? values[1] : "NO"
puts result

n = gets.to_i

s = gets.split.map{|i| i.to_i}.sort

if s[0]  == s[-1] then
    result = "NO"
else
    i = 1
    while s[i] == s[0] && i < n do
        i += 1
    end
    result = s[i]
end

puts result

n = gets.chomp.to_i
a = gets.chomp.split(/ /)
an = Hash.new(n)
a.each{|aa| an[aa.to_i] = 0 }
ann = an.keys.sort
if ann.count <= 1
	puts "NO"
else
	puts ann[1]
end

gets
a=gets.split.map(&:to_i).uniq.sort[1]
puts a ?a:"NO"

gets
puts gets.split.map(&:to_i).sort.uniq[1] || 'NO'

gets
x = gets.split.map(&:to_i).uniq.sort
puts (x[1] || 'NO')

gets
arr = gets.split.map(&:to_i).sort
for i in arr
  if not i == arr[0]
    puts i
    exit 0
  end
end
puts 'NO'

n=gets.to_i
i=gets.split.map(&:to_i)
i.sort!
m=i[0]
ans="NO"
i.each{|j|
        if j>m then
                ans=j.to_s
                break
        end
}

puts ans

n=gets.chomp.to_i
memo=gets.chomp.split.map{|i| i.to_i}.sort!
min=memo[0]
n.times do |i|
  if min!=memo[i]
    puts(memo[i])
    exit
  end
end
puts(-1)

amount = gets.to_i
elements = gets.split(' ').sort.map { |e| e.to_i }
min = elements[0]
(0...amount).each do |i|
  if elements[i] > min
    min = elements[i]
    break
  end
end
print min

amount = gets.to_i
elements = gets.split(' ').sort.map { |e| e.to_i }
answer = min = elements[0]
(0...amount).each do |i|
  if elements[i] > min
    answer = elements[i]
    break
  end
end
if answer == min
  print "NO"
else
  print answer
end

gets
k=gets.split.map(&:to_i).sort.uniq
puts k[1]

gets
nums = gets.chomp.split.map(&:to_i)

min = nums.min
res = nums.detect{ |x| x > min }
puts res.nil? ? "NO" : res

gets
arr = gets.split.map(&:to_i).sort
for i in arr
  if not i == arr[0]
    puts i
    exit 0
  end
end
puts arr[0]

gets
arr = gets.split.map(&:to_i).sort
for i in arr
  if not i == arr[0]
    puts i
    break
  end
end
puts arr[0]


Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 104) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≤ aij ≤ 104).

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

n,m,d=gets.chomp.split.map(&:to_i)
a,flag=[],1
n.times { |j| gets.chomp.split.map(&:to_i).each {|i| a<<i} }
a.sort!
mid,ans=a[n*m/2],0
a.each do |i|
	x=(mid-i).abs
	(x%d!=0) ? flag=0 : ans+=x/d
end
puts (flag==0) ? "-1" : ans

class B
  def initialize
    n, m, d = $stdin.gets.chomp.split(' ').map(&:to_i)

    array = []
    n.times do
      array += $stdin.gets.chomp.split(' ').map(&:to_i)
    end

    array.sort!
    pipo = array[array.size/2]

    count = 0

    array.each do |num|
      diff = (pipo-num).abs
      if diff % d == 0
        count += diff/d
      else
        puts -1
        exit
      end
    end

    puts count
  end
end

b = B.new

require "Set"

n,m,d = gets.split(" ").map(&:to_i)
arr = []

n.times do
	arr << gets.split(" ").map(&:to_i)
end
arr.flatten!
arr.sort!
mid = arr[(arr.length)/2]
# puts "#{mid}"
rem = Set.new
sum = 0
arr.each do |a|
	rem.add(a%d)
	sum += (a - mid).abs
end
if rem.length > 1
	puts "-1"
else
	puts sum / d
end

# (0..(n-1)).each do |i|
# 	(0..(m-1)).each do |j|
# 		val = gcd(val,arr[i][j])
# 	end
# end

n, m, d = gets.split.map(&:to_i)
xs = n.times.map { gets.split.map(&:to_i) }.flatten.sort
mod = xs[0] % d
if xs.all? { |x| x % d == mod }
  median = xs[xs.size / 2]
  if median % d != mod
    median += median % d + mod
  end
  p xs.map { |x| (x - median).abs / d }.reduce(:+)
else
  p -1
end

n, m, d = gets.split(" ").collect{|x| x.to_i}

arr = []
n.times do
  gets.split(" ").collect{|x| arr << x.to_i}
end

rem = arr[0] % d
inv = 0
arr.each{|num|
  if num % d != rem
    inv = 1
    break
  end
}

if inv == 1
  puts -1
else
  arr.sort!
  target = arr[n * m / 2]

  mods = 0
  arr.each{|num|
    mods += (num - target).abs / d
  }

  puts mods
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless (x % d) == mod_d
  end
  true
end

def trace(vars={})
  vars.each do |x,y|
    puts "#{x} => #{y}"
  end
end

def get_count(matrix, c, d)
  matrix.map{|x| (c-x).abs/d}.inject :+
end

if possible?(matrix, d)
  matrix.sort!
  c = matrix[matrix.length/2]
  puts get_count(matrix, c, d)
else
  puts -1
end

require "Set"

n,m,d = gets.split(" ").map(&:to_i)
arr = []

n.times do
	arr << gets.split(" ").map(&:to_i)
end
arr.flatten!
arr.sort!
mid = arr[(arr.length-1)/2 + 1]
# puts "#{mid}"
rem = Set.new
sum = 0
arr.each do |a|
	rem.add(a%d)
	sum += (a - mid).abs
end
if rem.length > 1
	puts "-1"
else
	puts sum / d
end

# (0..(n-1)).each do |i|
# 	(0..(m-1)).each do |j|
# 		val = gcd(val,arr[i][j])
# 	end
# end

n, m, d = gets.split.map(&:to_i)
matrix = n.times.map { gets.split.map(&:to_i) }
mod = matrix[0][0] % d
if matrix.all? { |row| row.all? { |el| el % d == mod } }
  sum = matrix.map { |row| row.reduce(:+) }.reduce(:+)
  target = sum / (n * m)
  target += target % d + mod if target % d != mod
  p matrix.map { |row| row.map { |el| (el - target).abs / d }.reduce(:+) }.reduce(:+)
else
  p -1
end

n, m, d = gets.split.map(&:to_i)
matrix = n.times.map { gets.split.map(&:to_i) }
if matrix.all? { |row| row.all? { |el| el % d == 0 } }
  sum = matrix.map { |row| row.reduce(:+) }.reduce(:+)
  target = sum / (n * m)
  target += target % d if target % d != 0
  p matrix.map { |row| row.map { |el| (el - target).abs / d }.reduce(:+) }.reduce(:+)
else
  p -1
end

n, m, d = gets.split.map(&:to_i)
matrix = n.times.map { gets.split.map(&:to_i) }
if matrix.all? { |row| row.all? { |el| el % d == 0 } }
  sum = matrix.map { |row| row.reduce(:+) }.reduce(:+)
  avg = sum / (n * m)
  p matrix.map { |row| row.map { |el| (el - avg).abs / d }.reduce(:+) }.reduce(:+)
else
  p -1
end

n, m, d = gets.split(" ").collect{|x| x.to_i}

arr = []
n.times do
  gets.split(" ").collect{|x| arr << x.to_i}
end

rem = arr[0] % d
sum = 0
inv = 0
arr.each{|num|
  if num % d != rem
    inv = 1
    break
  end

  sum += num
}

if inv == 1
  puts -1
else
  avg = sum.to_f / (n * m)
  ce = arr[0]
  diff = (arr[0] - avg).abs

  arr.each{|num|
    if (num - avg).abs < diff
      ce = num
      diff = (num - avg).abs
    end
  }

  mods = 0
  arr.each{|num|
    mods += (num - ce).abs / d
  }

  puts mods
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless (x % d) == mod_d
  end
  true
end

def trace(vars={})
  vars.each do |x,y|
    puts "#{x} => #{y}"
  end
end

if possible?(matrix, d)
  mod_d = matrix[0] % d
  sum = matrix.inject(:+)
  avg = (( (sum.to_f / (n*m)).round - mod_d ) / d).round.to_i * d + mod_d

  #avg1 = ((avg - mod_d) / d).floor.to_i * d + mod_d
  #avg2 = ((avg - mod_d) / d).ceil.to_i * d + mod_d
  #trace avg1: avg1, avg2: avg2
  #
  #n1 = matrix.map{|x| (avg1 - x).abs / d}.inject(:+)
  #n2 = matrix.map{|x| (avg2 - x).abs / d}.inject(:+)
  #puts [n1,n2].min

  puts matrix.map{|x| (avg - x).abs / d}.inject(:+)

else
  puts -1
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless x % d == mod_d
  end
  true
end

if possible?(matrix, d)
  mod_d = matrix[0] % d
  sum = matrix.inject(:+)
  avg = sum / (n*m)
  avg1 = ((avg - mod_d) / d) * d + mod_d
  avg2 = ((avg - mod_d) / d + 1) * d + mod_d
  n1 = matrix.map{|x| (x - avg1).abs / d}.inject(:+)
  n2 = matrix.map{|x| (x - avg2).abs / d}.inject(:+)
  puts [n1,n2].min
else
  puts -1
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless (x % d) == mod_d
  end
  true
end

def trace(vars={})
  vars.each do |x,y|
    puts "#{x} => #{y}"
  end
end

def get_count(matrix, c)
  matrix.map{|x| (c-x).abs}.inject :+
end

if possible?(matrix, d)
  matrix.sort!
  min = matrix.first
  max = matrix.last
  c = min
  n = nil
  while c <= max
    count = get_count(matrix, c)
    n = count if n.nil? || count < n
    c += d
  end
  puts n
else
  puts -1
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless x % d == mod_d
  end
  true
end

if possible?(matrix, d)
  sum = matrix.inject(:+)
  avg = sum.to_f / (n*m)
  avg1 = (avg / d).to_i * d
  avg2 = ((avg / d).to_i + 1) * d
  n1 = matrix.map{|x| (x - avg1).abs / d}.inject(:+)
  n2 = matrix.map{|x| (x - avg2).abs / d}.inject(:+)
  puts [n1,n2].min
else
  puts -1
end

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

matrix = []
n.times do
  matrix += gets.strip.split.map(&:to_i)[0...m]
end

$stderr.puts n,m,d, matrix.inspect

def possible?(matrix, d)
  mod_d = matrix[0] % d
  matrix.each do |x|
    return false unless (x % d) == mod_d
  end
  true
end

if possible?(matrix, d)
  mod_d = matrix[0] % d
  sum = matrix.inject(:+)
  avg = sum.to_f / (n*m)

  avg1 = ((avg - mod_d) / d).to_i * d + mod_d
  avg2 = (((avg - mod_d) / d).to_i + 1) * d + mod_d
  n1 = matrix.map{|x| (x - avg1).abs / d}.inject(:+)
  n2 = matrix.map{|x| (x - avg2).abs / d}.inject(:+)
  puts [n1,n2].min
else
  puts -1
end