According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of buttons on the jacket. The second line contains n integers ai (0 ≤ ai ≤ 1). The number ai = 0 if the i-th button is not fastened. Otherwise ai = 1.

In the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".

def fastened?(n, line)
  return if line.length != n || (n < 1 || n > 1000)
  if n > 1 && n <= 1000
    list0 = []
    for i in 0..(line.length - 1)
      if line[i].to_i == 0
        list0 << line[i]
      end
    end
    puts list0.length == 1 ? "YES" : "NO"
  else
    puts line[0].to_i == 1 ? "YES" : "NO"
  end
end

buttons_length = gets.chomp.to_i
list_integers = gets.chomp.split

fastened?(buttons_length, list_integers)

def fastened?(n, line)
  return "WRONG INPUT" if line.length != n
  if n > 1 && n <= 1000
    list0 = []
    for i in 0..(line.length - 1)
      if line[i].to_i == 0
        list0 << line[i]
      end
    end
    puts list0.length == 1 ? "YES" : "NO"
  else
    puts line[0].to_i == 1 ? "YES" : "NO"
  end
end

buttons_length = gets.chomp.to_i
list_integers = gets.chomp.split

fastened?(buttons_length, list_integers)

def valid?(number_button, buttons)
  # special case
  if number_button.to_i == 1
    return buttons == "1"
  end

  @count = 0
  buttons.split(' ').each do |button|
    @count += 1 if button == '0'
  end

  if @count == 1
    return true
  else
    return false
  end
end

def execute(number_button, buttons)
  if valid?(number_button, buttons)
    puts 'YES'
  else
    puts 'NO'
  end
end

number_button = gets.chomp
buttons = gets.chomp

execute(number_button, buttons)

z=gets.to_i==1?:none?: :one?;puts gets.split.send(z){|e|e==?0}?:YES: :NO

def checks(quality_buttons, buttons)
  return puts 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split(' ').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  return puts 'YES' if quality_buttons.to_i == 1 && not_install == 0
  r = if quality_buttons.to_i > 1 && not_install == 1
    'YES'
  else
    'NO'
  end

  puts r
end

checks(gets.chomp, gets.chomp)

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

num = 0

mas.each {|x| num+=1 if x==0}

if (n==1 and num==0) or (num==1 and n!=1)
    puts "YES"
else
    puts "NO"
end

jacket_number = gets.to_i
# jacket_number = '3'.to_i
jacket_list = gets.split(' ').map(&:to_i)
# jacket_list = '1 0 1'.split(' ').map(&:to_i)

def fastened?(jacket_list)
  unFastened = []
  jacket_list.each do |j|
    unFastened << 0 if j.zero?
    return false if unFastened.count > 1
  end
  unFastened.count == 1
end

if jacket_number == 1
  puts jacket_list[0] == 1 ? 'YES' : 'NO'
else
  puts fastened?(jacket_list) ? 'YES' : 'NO'
end

n = gets.strip.to_i
buttons = gets.strip.split.map(&:to_i)
count_fastened = 0
(0...n).each do |i|
    button = buttons[i]
    count_fastened += 1 if button == 1
end
if (n > 1 && n - 1 == count_fastened) || (count_fastened == n && n == 1)
    puts "YES"
else
    puts "NO"
end

a=gets.chomp.to_i
b=gets.chomp.split(" ")
if a==1
if b.count('1')==0
puts "NO"
else
puts "YES"
end
else
if b.count('1')!=a-1
puts "NO"
else
puts "YES"
end
end

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

if arr.size == 1
  puts arr.first == 1 ? 'YES' : 'NO'
else
  puts arr.count { |v| v.zero? } == 1 ? 'YES' : 'NO'
end

n = gets.to_i
sum = 0
gets.split(" ").map{|s| s.to_i }.each do |i|
	sum += i
end
if n == 1
    n = 2
end
puts sum==n-1?"YES":"NO"

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

=begin
something = 0

for i in nums
	if nums[i] == 0
		something += 1
	end
end
=end

if (nums.count(0) == 1 && nums.length > 1) || (nums.length == 1 && nums[0] == 1)
	puts "YES"
else
	puts "NO"
end

n = gets.to_i
arr = gets.split.map(&:to_i)
if arr.length == 1
	puts arr.first == 0 ? "NO" : "YES"
else
	cnt = 0
	arr.each do |num|
		cnt += 1 if num == 0
	end
	puts cnt == 1 ? "YES" : "NO"
end

#!/usr/bin/env ruby

n = ARGF.gets.to_i

buttons = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

closed = buttons.reduce(:+)

if n == 1
    if closed == 1
        puts "YES"
    else
        puts "NO"
    end
elsif closed + 1 == n
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
buttons = gets.split.map(&:to_i)
if n == 1
  puts buttons[0] == 1 ? 'YES' : 'NO'
else
  not_fastened = 0
  buttons.each do |b|
    not_fastened += 1 if b == 0
  end
  puts not_fastened == 1  ?  'YES' : 'NO'
end

n = gets.chomp.to_i
buttons = gets.split.map(&:to_i)
not_fastened = 0
buttons.each do |b|
  not_fastened += 1 if b == 0
end
(not_fastened == 1  || buttons.size == 1) ? 'YES' : 'NO'

$stdout.sync = true
def valid?(number_button, buttons)
  return false if buttons.to_s.split(' ').size > number_button.to_i

  @count = 0

  buttons.split(' ').each do |button|
    @count += 1 if button == '0'
    return false if @count >= 2
  end

  if @count == 0
    return false
  else
    return true
  end

end

def execute(number_button, buttons)
  if valid?(number_button, buttons)
    puts 'YES'
  else
    puts 'NO'
  end
end

number_button = gets.chomp
buttons = gets.chomp

execute(number_button, buttons)

def valid?(number_button, buttons)
  return false if buttons.to_s.split(' ').size > number_button.to_i

  @count = 0

  buttons.split(' ').each do |button|
    @count += 1 if button == '0'
    return false if @count >= 2
  end

  return true
end

def execute(number_button, buttons)
  if valid?(number_button, buttons)
    puts 'YES'
  else
    puts 'NO'
  end
end

number_button = gets.chomp
buttons = gets.chomp

execute(number_button, buttons)

def valid?(number_button, buttons)
  # special case
  if number_button.to_i == 1
    return buttons == "1"
  else
    return false
  end

  @count = 0
  buttons.split(' ').each do |button|
    @count += 1 if button == '0'
    return false if @count >= 2
  end

  if @count == 1
    return true
  else
    return false
  end
end

def execute(number_button, buttons)
  if valid?(number_button, buttons)
    puts 'YES'
  else
    puts 'NO'
  end
end

number_button = gets.chomp
buttons = gets.chomp

execute(number_button, buttons)

def checks(quality_buttons, buttons)
  return puts 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split(' ').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  r = if ( quality_buttons.to_i == 1 && not_install >= 1 )
    'NO'
  elsif not_install == 1
    'YES'
  elsif not_install == 0
    'YES'
  else
    'NO'
  end

  puts r
end

checks(gets.chomp, gets.chomp)

def checks(quality_buttons, buttons)
  return p 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split('').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  r = if ( quality_buttons.to_i == 1 && not_install == 1 )
    'NO'
  elsif not_install <= 1
    'YES'
  else
    'NO'
  end

  p r
end

checks(gets.chomp, gets.chomp)

def checks(quality_buttons, buttons)
  return puts 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split(' ').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  return puts 'YES' if quality_buttons.to_i == 1 && not_install == 0
  p not_install
  r = if quality_buttons.to_i > 1 && not_install == 1
    'YES'
  else
    'NO'
  end

  puts r
end

checks(gets.chomp, gets.chomp)

def checks(quality_buttons, buttons)
  return puts 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split(' ').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  r = if ( quality_buttons.to_i == 1 && not_install == 1 )
    'NO'
  elsif not_install <= 1
    'YES'
  else
    'NO'
  end

  puts r
end

checks(gets.chomp, gets.chomp)

def checks(quality_buttons, buttons)
  return puts 'NO' unless quality_buttons.to_i <= 1000 && quality_buttons.to_i >= 1
  not_install = 0
  buttons.split(' ').each do |b|
    not_install += 1 if b.to_i == 0 || b.to_i > 1 || b.to_i < 0
  end

  r = if ( quality_buttons.to_i == 1 && not_install == 1 )
    'NO'
  elsif not_install == 1
    'YES'
  else
    'NO'
  end

  puts r
end

checks(gets.chomp, gets.chomp)

jacket_number = gets.to_i
# jacket_number = '3'.to_i
jacket_list = gets.split(' ').map(&:to_i)
# jacket_list = '1 0 1'.split(' ').map(&:to_i)

def fastened?(jacket_list)
  unFastened = []
  jacket_list.each do |j|
    unFastened << 0 if j.zero?
    return false if unFastened.count > 1
  end
  true
end

if jacket_number == 1
  puts jacket_list[0] == 1 ? 'YES' : 'NO'
else
  puts fastened?(jacket_list) ? 'YES' : 'NO'
end

jacket_number = gets.to_i
jacket_list = gets.split(' ').map(&:to_i)

def fastened?(jacket_list)
  unFastened = []
  jacket_list.each do |j|
    unFastened << 0 if j.zero?
    return false if unFastened.count > 1
  end
  return true
end

if jacket_number == 1
  puts jacket_list[0] == 1 ? 'YES' : 'NO'
else
  puts fastened?(jacket_list) ? 'YES' : 'NO'
end

n = gets.strip.to_i
buttons = gets.strip.split.map(&:to_i)
count_fastened = 0
(0...n).each do |i|
    button = buttons[i]
    count_fastened += 1 if button == 1
end
if n - 1 == count_fastened || (count_fastened == n && count_fastened == 1)
    puts "YES"
else
    puts "NO"
end

n = gets.strip.to_i
buttons = gets.strip.split.map(&:to_i)
ans = "YES"
count_open = 0
(0...n).each do |i|
    button = buttons[i]
    count_open += 1 if button == 0
end
if n == 1 && count_open == n
    ans = "NO"
elsif count_open > 1
    ans = "NO"
end
puts ans

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

if arr.size == 1
  puts arr.first.zero? ? 'YES' : 'NO'
else
  puts arr.count { |v| v.zero? } == 1 ? 'YES' : 'NO'
end

n = gets.to_i
sum = 0
gets.split(" ").map{|s| s.to_i }.each do |i|
	sum += i
end
puts sum==n-1?"YES":"NO"

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

=begin
something = 0

for i in nums
	if nums[i] == 0
		something += 1
	end
end
=end

if nums.count(0) == 1 || nums.length == 1
	puts "YES"
else
	puts "NO"
end

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

=begin
something = 0

for i in nums
	if nums[i] == 0
		something += 1
	end
end
=end

if nums.count(0) == 1
	puts "YES"
else
	puts "NO"
end

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

=begin
something = 0

for i in nums
	if nums[i] == 0
		something += 1
	end
end
=end

if nums.count(0) == 1 || (nums.length == 1 && nums[0] == 1)
	puts "YES"
else
	puts "NO"
end

n = gets.to_i
arr = gets.split.map(&:to_i)
if arr.length == 1
	arr.first == 0 ? "NO" : "YES"
else
	cnt = 0
	arr.each do |num|
		cnt += 1 if num == 0
	end
	cnt == 1 ? "YES" : "NO"
end

n = gets.chomp.to_i
buttons = gets.split.map(&:to_i)
not_fastened = 0
buttons.each do |b|
  not_fastened += 1 if b == 0
end
puts (not_fastened == 1  || buttons.size == 1) ?  'YES' : 'NO'

def check_fastened
  n = gets.chomp.to_i
  buttons = gets.split.map(&:to_i)
  return 'YES' if buttons.size == 1
  not_fastened = 0
  buttons.each do |b|
    not_fastened += 1 if b == 0
  end
  not_fastened > 1 ? 'NO' : 'YES'

end

n = gets.chomp.to_i
buttons = gets.split.map(&:to_i)
return 'YES' if buttons.size == 1
not_fastened = 0
buttons.each do |b|
  not_fastened += 1 if b == 0
end
not_fastened == 1 ? 'YES' : 'NO'


You know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.For example, d(35047) = d((3 + 5 + 0 + 4)7) = d(157) = d((1 + 5)7) = d(67) = 67. In this sample the calculations are performed in the 7-base notation.If a number's digital root equals b, the Martians also call this number lucky.You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.Note that substring s[i... j] of the string s = a1a2... an (1 ≤ i ≤ j ≤ n) is the string aiai + 1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1 ≠ i2 or j1 ≠ j2.

The first line contains three integers k, b and n (2 ≤ k ≤ 109, 0 ≤ b < k, 1 ≤ n ≤ 105). The second line contains string s as a sequence of n integers, representing digits in the k-base notation: the i-th integer equals ai (0 ≤ ai < k) — the i-th digit of string s. The numbers in the lines are space-separated.

Print a single integer — the number of substrings that are lucky numbers. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the following substrings have the sought digital root: s[1... 2] = "3 2", s[1... 3] = "3 2 0", s[3... 4] = "0 5", s[4... 4] = "5" and s[2... 6] = "2 0 5 6 1".

a=Hash.new 0;a[0]=1;k,b,n=gets.split.map &:to_i;s=t=c=z=0;k-=1
(gets.split.map &:to_i).each{|i|s=(s+i)%k;z+=a[(s-b)%k];a[s]+=1;if i>0 then c=0;else t+=c+=1 end}
if b==0 then z=t elsif b==k then z-=t end;p z

a=Hash.new 0;a[0]=1;k,b,n=gets.split.map &:to_i;s=t=c=z=0;k-=1
(gets.split.map &:to_i).each{|i|s=(s+i)%k;z+=a[(s-b)%k];a[s]+=1;if i>0 then c=0;else t+=c+=1 end}
if b==0 then z=t elsif b==k-1 then z-=t end;p z


People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:  every integer from 1 to n2 appears in the table exactly once;  in each row numbers are situated in increasing order;  the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.

n, k = gets.split.map(&:to_i)
ans = Array.new(n){Array.new(n)}
n2 = n*n
for i in 0...n
  for j in 0..(n - k)
    ans[i][n - 1 - j] = n2
    n2 -= 1
  end
end
a = 1
for i in 0...n
  for j in 0...(k-1)
    ans[i][j] = a
    a += 1
  end
end
sum = 0
n.times do |i|
  sum += ans[i][k-1]
end
puts sum
n.times do |i|
  puts "#{ans[i].join(' ')}"
end

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

as = Array.new(n) { Array.new(n, 0) }
s = 0
m = 1
for i in 0...n
  for j in 0...k - 1
    as[i][j] = m
    m += 1
  end
end

for i in 0...n
  as[i][k - 1] = m
  s += m
  m += 1
  for j in k...n
    as[i][j] = m
    m += 1
  end
end

puts s
as.map { |a| puts a.*' ' }

n, k = gets.split(' ').map &:to_i
min = (k-1)*n + 1
sum = 0

g = []
ic = 1
oc = min
for i in 0...n
  g[i] = []
  for j in 0...n
    if j < k-1
      g[i][j] = ic
      ic += 1
    else
      g[i][j] = oc
      oc += 1
    end
  end
  sum += g[i][k-1]
end

puts sum
for r in g
  puts r.join(' ')
end

n, k = gets.split(' ').map &:to_i
min = (k-1)*n + 1
sum = min
for i in 1...n
  sum += min + i*k
end

g = []
ic = 1
oc = min
puts sum
for i in 0...n
  g[i] = []
  for j in 0...n
    if j < k-1
      g[i][j] = ic
      ic += 1
    else
      g[i][j] = oc
      oc += 1
    end
  end
  puts g[i].join(' ')
end


In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.

In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.

n = gets.to_i

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

b = a.dup
b.sort!

res = []
0.upto(a.size-1) do |i|
	if a[i]!= b[i]
		j = a.rindex b[i]
		a[j] = a[i]
		res << "#{i} #{j}"
	end
end
puts res.size
puts res

n = STDIN.readline.to_i
data = STDIN.readline.split.each_with_index.map {|s, i| [s.to_i, i] }
sorted = data.sort
index = {}
data.each_with_index {|pair, i| index[pair] = i }
moves = []
sorted.each_with_index do |p, i|
	next if index[p] == i
	q, j = data[i], index[p]
	data[i], index[p] = p, i
	data[j], index[q] = q, j
	moves.push([i, j])
end
puts moves.length
puts moves.map {|a, b| '%d %d' % [a, b] }.join "\n" if moves.length != 0

#$stdin = File.open "input.txt"

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

puts n - 1
(n - 1).times do |i|
	m = a[i...n].min
	j = i + a[i...n].index(m)

	puts "#{i} #{j}"
	a[i], a[j] = a[j], a[i]
end

#!/usr/bin/ruby

n = gets.to_i
l = gets.chomp.split(' ').map { |i| i.to_i }
s = 0
sw = []
(0..n-2).each do |i|
  im = l[i..n-1].index(l[i..n-1].min) + i
  if im != i
    temp = l[i]
    l[i] = l[im]
    l[im] = temp
    s += 1
    sw << "#{i} #{im}"
  end
end

p s
puts sw

n = gets.to_i

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

b = a.dup
b.sort!

res = []
0.upto(a.size-1) do |i|
	if a[i]!= b[i]
		j = a.index b[i]
		a[j] = a[i]
		res << "#{i} #{j}"
	end
end
puts res.size
puts res

n = STDIN.readline.to_i
data = STDIN.readline.split.each_with_index.map {|s, i| [s.to_i, i] }
sorted = data.sort
index = {}
data.each_with_index {|pair, i| index[pair] = i }
moves = []
sorted.each_with_index do |pair, i|
	next if index[pair] == i
	moves.push([i, index[pair]])
	index[data[i]] = index[pair]
	index[pair] = i
end
puts moves.length
puts moves.map {|a, b| '%d %d' % [a, b] }.join "\n" if moves.length != 0

#$stdin = File.open "input.txt"

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

puts n - 1
(n - 1).times do |i|
	m = a[i + 1...n].min
	j = a.index(m)

	puts "#{i} #{j}"
	a[i], a[j] = a[j], a[i]
end

#$stdin = File.open "input.txt"

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

(1...n).each do |i|
	j = i
	while (j > 0) && (a[j] < a[j - 1])
		a[j], a[j - 1] = a[j - 1], a[j]
		b[j], b[j - 1] = b[j - 1], b[j]
		j -= 1
	end
end

swaps = []
n.times { |i| swaps << [i, b[i]] if b[i] > i }

puts swaps.size
swaps.each { |s| puts "#{s[0]} #{s[1]}" }


By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:  For given numbers xi and vi assign value vi to element axi.  For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2.  For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.

The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type:    if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105);  if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n);  if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105).  The input limits for scoring 30 points are (subproblem E1):    It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.  The input limits for scoring 70 points are (subproblems E1+E2):    It is guaranteed that there will be queries of the 1-st and 2-nd type only.  The input limits for scoring 100 points are (subproblems E1+E2+E3):    No extra limitations.

For each query print the calculated sum modulo 1000000000 (109).

t = STDIN.gets
a1 = t.split
n = a1[0].to_i
m = a1[1].to_i

t = STDIN.gets
a = t.split
@a = []
a.count.times do |i|
  @a[i] = a[i].to_i
end
@f = []
@f[0] = 1
@f[1] = 1
def operation1(x,v)
  @a[x] = v % 1000000000
end
def f(x)
  @f[x] if x < @f.count
  fcount = @f.count
  (x - fcount + 1).times do |j|
    @f[fcount + j] = (@f[fcount + j - 2] + @f[fcount + j - 1]) % 1000000000
  end
  @f[x]
end

def sum(x,l,r)
  f(x)*@a[l + x] % 1000000000
end

def operation2(l,r)
  s = 0
  (r - l + 1).times do |x|
    s = (s + sum(x, l, r)) % 1000000000
  end
  puts (s % 1000000000)
end

def operation3(l,r,d)

  ( r-l + 1).times do |x|
    @a[l + x] = (@a[l + x] + d) % 1000000000
  end
end

m.times do |i|
  t = STDIN.gets
  operation = t.split
  if operation[0] == '1'
    operation1(operation[1].to_i - 1, operation[2].to_i)
  end

  if operation[0] == '2'
    operation2(operation[1].to_i - 1, operation[2].to_i - 1)
  end

  if operation[0] == '3'
    operation3(operation[1].to_i - 1, operation[2].to_i - 1 , operation[3].to_i)
  end
end


The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.

Print a single integer — the number of ways you can choose the c prisoners.

n, t, c = gets.strip.split.map(&:to_i)
a = gets.strip.split.map(&:to_i)
a = a.chunk{ |i| i <= t }.to_a.map{|t, a| a if t}.compact
sum = a.inject(0){|s, arr| s + ([arr.count - c + 1, 0].max)}
puts sum

n,t,c=gets.split.map &:to_i
p=gets.split.map &:to_i
w,r=0,0
p.each{|l|r=l>t ?0:r+1;r>=c&&w+=1}
puts w

n, t, c  = gets.split(' ').map(&:to_i)
arr = gets.split(' ').map(&:to_i)
last = -1
possible = 0
(0..n-1).each do |index|
  if arr[index] > t
    last = index
  elsif index - last >= c
    possible += 1
  end
end
puts possible

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

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

x = 0
y = t

sev = 0
count = 0

for i in 0...t
  if a[i] > c
    sev += 1
  end
end

if sev == 0
  count += 1
end

for i in 0...n-t
  if a[x+i] > c
    sev -= 1
  end
  if a[y+i] > c
    sev += 1
  end
  if sev == 0
    count += 1
  end
end

print count

n, t, c = gets.strip.split(" ").map(&:to_i)
a = gets.strip.split(" ").map(&:to_i)
i = 0
num = 0
count = 0
while i < n do
  if a[i] <= t then
    num += 1
  elsif num >= c then
    count += num - c + 1
    num = 0
  else
    num = 0
  end
  i += 1
end
if num >= c then
  count += num - c + 1
end
puts count

n,t,c = gets.split(' ').map(&:to_i)
p = gets.split(' ').map(&:to_i)
l,ans=0,0
p.each do |i|
  if i > t
    l=0
  else
    l+=1
  end
  if l>=c
    ans+=1
  end
 end
  puts ans

n,t,c = gets.split(' ').map(&:to_i)
p = gets.split(' ').map(&:to_i)
l, ans=0, 0
p.each do |i|
  if i > t
    l=0
  else
    l+=1
  end
  if l>=c
    ans+=1
  end
 end
  puts ans

n, t, c = gets.split
n = Integer n
t = Integer t
c = Integer c

nums = gets.split
for i in 0...n
  nums[i] = Integer nums[i]
end

# how many t have we found ?
count_t = 0
# the answer/count
count = 0

for i in 0...n
  if nums[i] > t
    count_t += 1
  end

  if i >= c && nums[i-c] > t
    count_t -= 1
  end

  if i >= c - 1 && count_t == 0
    count += 1
  end
end

puts count

n, t, c = gets.split
n = Integer n
t = Integer t
c = Integer c

nums = gets.split
for i in 0...n
  nums[i] = Integer nums[i]
end
nums[n] = t + 1

# what's the position of last number > t found?
last_t_found = -1
# the answer/count
count = 0

for i in 0..n
  if nums[i] > t
    if i - last_t_found > c
      count += i - last_t_found - c
    end
    last_t_found = i
  end
end

puts count

n, t, c = gets.split
n = Integer n
t = Integer t
c = Integer c

nums = gets.split
for i in 0...n
  nums[i] = Integer nums[i]
end

# what's the position of last number > t found?
last_t_found = -1
# what's the last position we've checked?
last_checked = -1
# the answer/count
count = 0

# loop through all possible i
for i in 0..n-c
  # if no t appears after i by now
  if i > last_t_found
    # check all the number between i and i+c
    for j in last_checked+1...i+c
      # find a t after i
      if nums[j] > t
        # record what we've seen
        last_t_found = j
        last_checked = j
        break
      end
    end

    # no t found after i?
    if last_t_found < i
      last_checked = i + c - 1
      count += 1
    end
  end
end

puts count

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

ans = 0
cnt = a[0...c-1].count { |p| p > t }
a[c-1...n].each_with_index { |p, idx|
  cnt += 1 if p > t
  ans += 1 if cnt == 0
  cnt -= 1 if a[idx] > t
}

puts ans

# Read input
n, t, c = gets.strip.split.map(&:to_i)
a = gets.strip.split.map(&:to_i)

# Grab the locations of elements > t
spoilerloc = a.each_index.select{|i| a[i] > t}.unshift(-1).push(n)

# Spot dead segments
rsum = 0

for i in 1..(spoilerloc.length - 1) do
    m = spoilerloc[i] - spoilerloc[i-1] - 1
    rsum = rsum + [m - c + 1, 0].max
end

puts rsum

def num_ways(n, k)
    count = 1
    for i in 0...(n-k)
        count += 1
    end
    count
end

data = gets.split.map(&:to_i)
n = data[0]
t = data[1]
c = data[2]
arr = gets.split.map(&:to_i)
aarr = []
sub = []
for i in 0...n
    if arr[i] <= t
        sub << arr[i]
    else
        aarr << sub
        sub = []
    end
end

aarr << sub

count = 0
for arr in aarr do
    if arr.length < c
        next
    end
    count += num_ways(arr.length, c)
end

puts count

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

ans = 0
cnt = a[0...c-1].count { |p| p > t }
a[c-1...n].each_with_index { |p, idx|
  cnt += 1 if p > t
  ans += 1 if cnt == 0
  cnt -= 1 if a[idx-c+1] > t
}

puts ans

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

ans = 0
cnt = a[0...c-1].count { |p| p >= t }
a[c-1...n].each_with_index { |p, idx|
  cnt += 1 if p >= t
  ans += 1 if cnt == 0
  cnt -= 1 if a[idx-c+1] >= t
}

puts ans

# Read input
n, t, c = gets.strip.split.map(&:to_i)
a = gets.strip.split.map(&:to_i)

# Grab the locations of elements > t
spoilerloc = a.each_index.select{|i| a[i] > t}

# Create mask
mask = (-1 * c + 1 .. c - 1).to_a - [0]
mask = [0] if c == 1

# Spot dead segments
out = []
for i in spoilerloc
    masked = mask.map{|j| j + i}
    out = out | masked
end

puts n - c + 1 - out.length


Michael and Joe are playing a game. The game is played on a grid with $$$n$$$ rows and $$$m$$$ columns, filled with distinct integers. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$.Michael starts by saying two numbers $$$h$$$ ($$$1\le h \le n$$$) and $$$w$$$ ($$$1\le w \le m$$$). Then Joe picks any $$$h\times w$$$ subrectangle of the board (without Michael seeing).Formally, an $$$h\times w$$$ subrectangle starts at some square $$$(a,b)$$$ where $$$1 \le a \le n-h+1$$$ and $$$1 \le b \le m-w+1$$$. It contains all squares $$$(i,j)$$$ for $$$a \le i \le a+h-1$$$ and $$$b \le j \le b+w-1$$$.    Possible move by Joe if Michael says $$$3\times 2$$$ (with maximum of $$$15$$$). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $$$h \cdot w$$$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose $$$h, w$$$ for which he can ensure that he wins.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 40$$$)  — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-10^9 \le a_{ij} \le 10^9$$$)  — the element in the cell $$$(i, j)$$$. It is guaranteed that all the numbers are distinct (that is, if $$$a_{i_1j_1} = a_{i_2j_2}$$$, then $$$i_1 = i_2, j_1 = j_2$$$).

For each test case print a single positive integer  — the minimum possible area the subrectangle can have while still ensuring that Michael can guarantee the victory.

NoteIn the first test case, the grid is $$$1\times 1$$$, so the only possible choice for $$$h, w$$$ is $$$h = 1, w = 1$$$, giving an area of $$$h\cdot w = 1$$$.The grid from the second test case is drawn in the statement. It can be shown that with $$$h = 3, w = 3$$$ Michael can guarantee the victory and that any choice with $$$h\cdot w \le 8$$$ doesn't.

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  a = Array.new(n){gets.split.map(&:to_i)}
  x = 0
  y = 0
  n.times do |i|
    m.times do |j|
      if a[y][x] < a[i][j]
        x = j
        y = i
      end
    end
  end

  x = [x+1, m-x].max
  y = [y+1, n-y].max
  puts x*y
end

t = gets.to_i
t.times {
  n, m = gets.split.map &:to_i
  g = []
  for i in (1..n)
    g += [gets.split.map(&:to_i)]
  end
  big = -2000000000
  big_i = -1
  big_j = -1
  for i in (0...n)
    for j in (0...m)
      if g[i][j] > big
        big = g[i][j]
        big_i = i
        big_j = j
      end
    end
  end
  h = [big_i + 1, n - big_i].max
  w = [big_j + 1, m - big_j].max
  puts h * w
}

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  a = Array.new(n){gets.split.map(&:to_i)}
  x = 0
  y = 0
  n.times do |i|
    m.times do |j|
      if a[y][x] < a[i][j]
        x = j
        y = i
      end
    end
  end

  x = [x+1, n-x].max
  y = [y+1, m-y].max
  puts x*y
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  a = Array.new(n){gets.split.map(&:to_i)}
  max_n = 0
  x = 0
  y = 0
  n.times do |i|
    m.times do |j|
      if max_n < a[i][j]
        max_n = a[i][j]
        x = j+1
        y = i+1
      end
    end
  end
  x = [x, n-x+1].max
  y = [y, m-y+1].max
  puts x*y
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  a = Array.new(n){gets.split.map(&:to_i)}
  max_n = 0
  x = 0
  y = 0
  n.times do |i|
    m.times do |j|
      if max_n < a[i][j]
        max_n = a[i][j]
        x = j+1
        y = i+1
      end
    end
  end
  puts [x*y, (m-x+1)*y, x*(n-y+1), (m-x+1)*(n-y+1)].max
end


$$$n$$$ towns are arranged in a circle sequentially. The towns are numbered from $$$1$$$ to $$$n$$$ in clockwise order. In the $$$i$$$-th town, there lives a singer with a repertoire of $$$a_i$$$ minutes for each $$$i \in [1, n]$$$.Each singer visited all $$$n$$$ towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the $$$i$$$-th singer got inspired and came up with a song that lasts $$$a_i$$$ minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.Hence, for the $$$i$$$-th singer, the concert in the $$$i$$$-th town will last $$$a_i$$$ minutes, in the $$$(i + 1)$$$-th town the concert will last $$$2 \cdot a_i$$$ minutes, ..., in the $$$((i + k) \bmod n + 1)$$$-th town the duration of the concert will be $$$(k + 2) \cdot a_i$$$, ..., in the town $$$((i + n - 2) \bmod n + 1)$$$ — $$$n \cdot a_i$$$ minutes.You are given an array of $$$b$$$ integer numbers, where $$$b_i$$$ is the total duration of concerts in the $$$i$$$-th town. Reconstruct any correct sequence of positive integers $$$a$$$ or say that it is impossible.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 10^3$$$) — the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^4$$$) — the number of cities. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^{9}$$$) — the total duration of concerts in $$$i$$$-th city. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the answer as follows: If there is no suitable sequence $$$a$$$, print NO. Otherwise, on the first line print YES, on the next line print the sequence $$$a_1, a_2, \dots, a_n$$$ of $$$n$$$ integers, where $$$a_i$$$ ($$$1 \le a_i \le 10^{9}$$$) is the initial duration of repertoire of the $$$i$$$-th singer. If there are multiple answers, print any of them.

NoteLet's consider the $$$1$$$-st test case of the example:  the $$$1$$$-st singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd — for $$$6$$$ minutes, in the $$$3$$$-rd — for $$$9$$$ minutes;  the $$$2$$$-nd singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd — for $$$1$$$ minute, in the $$$3$$$-rd - for $$$2$$$ minutes;  the $$$3$$$-rd singer in the $$$1$$$-st city will give a concert for $$$6$$$ minutes, in the $$$2$$$-nd — for $$$9$$$ minutes, in the $$$3$$$-rd — for $$$3$$$ minutes.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  b = gets.chomp.split(" ").map(&:to_i)
  x = b.sum
  if x % (n * (n+1) / 2) != 0
    ans << ["NO"]
    next
  end
  a = []
  x /= (n * (n+1) / 2)
  f = true
  n.times do |i|
    f = false if (x - (b[i%n] - b[(i-1)%n])) % n != 0
    v = (x - (b[i%n] - b[(i-1)%n])) / n
    f = false if v <= 0
    a << v
  end
  if f
    ans << ["YES"]
    ans << a
  else
    ans << ["NO"]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  b = gets.chomp.split(" ").map(&:to_i)
  x = b.sum
  if x % (n * (n+1) / 2) != 0
    ans << ["NO"]
    next
  end
  a = []
  x /= (n * (n+1) / 2)
  f = true
  n.times do |i|
    v = (x - (b[i%n] - b[(i-1)%n])) / n
    f = false if v <= 0
    a << v
  end
  if f
    ans << ["YES"]
    ans << a
  else
    ans << ["NO"]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  b = gets.chomp.split(" ").map(&:to_i)
  x = b.sum
  if x % (n * (n+1) / 2) != 0
    ans << ["NO"]
    next
  end
  a = []
  x /= (n * (n+1) / 2)
  f = true
  n.times do |i|
    f = false if (x - (b[i%n] - b[(i-1)%n])) % n != 0
    v = (x - (b[i%n] - b[(i-1)%n])) / n
    f = false if v == 0
    a << v
  end
  if f
    ans << ["YES"]
    ans << a
  else
    ans << ["NO"]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  b = gets.chomp.split(" ").map(&:to_i)
  x = b.sum
  if x % (n * (n+1) / 2) != 0
    ans << ["NO"]
    next
  end
  a = []
  x /= (n * (n+1) / 2)
  f = true
  n.times do |i|
    v = (x - (b[i%n] - b[(i-1)%n])) / n
    f = false if v == 0
    a << v
  end
  if f
    ans << ["YES"]
    ans << a
  else
    ans << ["NO"]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end


Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n + 2n + 3n + 4n) mod 5for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).

The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn't contain any leading zeroes.

Print the value of the expression without leading zeros.

NoteOperation x mod y means taking remainder after division x by y.Note to the first sample:

num = gets.chomp

count  = 0
count += num[-1].to_i + num[-2].to_i*10

if count%4==0
    puts "4"
else
    puts "0"
end

n = gets.to_s
if n.length > 3
  n = n[-3..-1]
end
n = n.to_i
if n % 4 == 0
  p 4
else
  p 0
end

# Read Input
s = gets.strip

# Take the last two digits
n = s.length > 2 ? s[-2..-1].to_i : s.to_i

# Return result
puts (n % 4) == 0 ? 4 : 0

n = ('00' + gets.chomp)[-2, 2].to_i

if n % 4 == 0
	puts 4
else
	puts 0
end

sum=0
f=gets.chomp
f.each_char do |i|
sum+=i.to_i
end

if((f[f.length-1]+f[f.length-2]).to_i)%4==3
ans=(1+3+3+4)%5
puts "#{ans}"
elsif((f[f.length-1]+f[f.length-2]).to_i)%4==0
ans=(1+1+1+1)%5
puts "#{ans}"
elsif((f[f.length-1]+f[f.length-2]).to_i)%4==2
ans=(1+4+4+1)%5
puts "#{ans}"
else
ans=(1+2+3+4)%5
puts "#{ans}"
end

n = gets.strip.to_i

a = 5 ** (n * Math.log(2, 5)).modulo(1).floor
b = 5 ** (n * Math.log(3, 5)).modulo(1).floor
c = 5 ** (n * Math.log(4, 5)).modulo(1).floor

puts (1 + (a % 5) + (b % 5) + (c % 5)) % 5

# Read Input
s = gets.strip

# Take the last two digits
n = s.length > 2 ? s[-2..-1].to_i : n.to_i

# Return result
puts (n % 4) == 0 ? 4 : 0

n = ('00' + gets)[-2, 2].to_i

if n % 4 == 0
	puts 4
else
	puts 0
end


Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".Help Polycarp find out if his teacher might be suspicious.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of days during which Polycarp solved tasks. The second line contains a string of length $$$n$$$, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.

For each test case output:    "YES", if the teacher cannot be suspicious;  "NO", otherwise.  You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB

def destructed(str, n)
  mp = {}
  str.chars.each_with_index do |v, i|
    if mp.key?(str[i])
      mp[v] = mp[v] << i
    else
      mp[v] = [i]
    end
  end
  # found = true
  mp.each_pair do |k, v|
    len = v.length
    (0..len-2).each do |i|
      if v[i+1] - v[i] != 1
        return false
      end
    end
  end
  return true
end

t = gets.to_i
inputs = []
(0...t).each do
  n = gets.to_i
  str = gets.chomp
  inputs<<[str, n]
end

inputs.each do |input|
  str = input[0]
  n = input[1]
  res = destructed(str, n)
  if res
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times {
  gets
  s = gets.strip
  ('A'..'Z').each { s.gsub!(/(#{_1})+/, _1) }
  h = Hash.new 0
  s.each_char { h[_1] += 1 }
  ans = h.values.any? { _1 > 1 }
  puts(ans ? "NO" : "YES")
}

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	tasks = gets.chomp.split('')
	no_f = true
	tasks.each_with_index do |let, idx|
		next if let == tasks[idx+1]

		if tasks[idx+1..-1].include? let
			results.push("NO")
			no_f = false
			break
		end
	end
	results.push("YES") if no_f
end
results.each do |res|
	puts res
end

t = gets.chomp.to_i

while t != 0

  n   = gets.chomp.to_i
  str = gets.chomp

  mp = {} # map of indices
  for i in 0...n
    mp[ str[i] ] = i
  end

  y = true
  for i in 0...n

    for j in i...mp[str[i]]
      if str[i] != str[j]
        y = false
        break
      end
    end

      if y == false
        break
      end
  end

  if y == true
    puts("YES")
  else
    puts("NO")
  end

  t = t-1
end

require 'set'

t = gets.chomp.to_i

def cannot_be_sus
  _ = gets
  # @type [String]
  input = gets.chomp

  last_seen_char = nil
  seen = Set.new
  input.each_char do |c|
    if c == last_seen_char
      # do nothing
    elsif seen.include? c
      return false
    else
      seen.add c
    end
    last_seen_char = c
  end
  true
end

(1..t).each do
  cannot_be_sus ? (puts 'YES') : (puts 'NO')
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.strip.split("")
  seen = {}
  seen[a[0]] = true
  prev = a[0]
  bad = false
  1.upto(n - 1) do |i|
    next if prev == a[i]
    if seen[a[i]]
      bad = true
      break
    end
    seen[a[i]] = true
    prev = a[i]
  end
  printf("%s\n", bad ? "NO" : "YES")
end


Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.

The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10.

Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom.

8
alina
maria
ekaterina
darya
darya
ekaterina
maria
alina

NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows:   alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows:  ivan  alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows:  roman  ivan  alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows:  ivan  roman  alex

require 'set'
n = gets.to_i
chats = []
n.times do
    chats.push(gets.chomp)
end
s = Set.new
chats.reverse.each do |name|
    if !s.include?(name)
        puts name
        s << name
    end
end


There are $$$n$$$ logs, the $$$i$$$-th log has a length of $$$a_i$$$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into $$$2$$$ pieces. If the length of the chosen log is $$$x$$$, and the lengths of the resulting pieces are $$$y$$$ and $$$z$$$, then $$$y$$$ and $$$z$$$ have to be positive integers, and $$$x=y+z$$$ must hold. For example, you can chop a log of length $$$3$$$ into logs of lengths $$$2$$$ and $$$1$$$, but not into logs of lengths $$$3$$$ and $$$0$$$, $$$2$$$ and $$$2$$$, or $$$1.5$$$ and $$$1.5$$$.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?

Each test contains multiple test cases. The first line contains a single 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 a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$)  — the number of logs. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$)  — the lengths of the logs. Note that there is no bound on the sum of $$$n$$$ over all test cases.

For each test case, print "errorgorn" if errorgorn wins or "maomao90" if maomao90 wins. (Output without quotes).

NoteIn the first test case, errorgorn will be the winner. An optimal move is to chop the log of length $$$4$$$ into $$$2$$$ logs of length $$$2$$$. After this there will only be $$$4$$$ logs of length $$$2$$$ and $$$1$$$ log of length $$$1$$$.After this, the only move any player can do is to chop any log of length $$$2$$$ into $$$2$$$ logs of length $$$1$$$. After $$$4$$$ moves, it will be maomao90's turn and he will not be able to make a move. Therefore errorgorn will be the winner.In the second test case, errorgorn will not be able to make a move on his first turn and will immediately lose, making maomao90 the winner.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  puts xs.map { |x| x - 1 }.sum.even? ? "maomao90" : "errorgorn"
end

gets.to_i.times do
  puts ['maomao90', 'errorgorn'][(gets.to_i+gets.chomp.split.map(&:to_i).inject(:+))&1]
end


Nikolay lives in a two-storied house. There are $$$n$$$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $$$1$$$ and $$$n$$$). If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $$$i$$$ and $$$i+1$$$ on each floor are neighbouring, for all $$$1 \leq i \leq n - 1$$$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $$$x$$$ on the first floor and the room $$$x$$$ on the second floor, then Nikolay can use it to move from one room to another.     The picture illustrates a house with $$$n = 4$$$. There is a staircase between the room $$$2$$$ on the first floor and the room $$$2$$$ on the second floor, and another staircase between the room $$$4$$$ on the first floor and the room $$$4$$$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string "0101" in the input.  Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been). Calculate the maximum number of rooms Nikolay can visit during his tour, if:  he can start in any room on any floor of his choice,  and he won't visit the same room twice.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of two lines. The first line contains one integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of rooms on each floor. The second line contains one string consisting of $$$n$$$ characters, each character is either a '0' or a '1'. If the $$$i$$$-th character is a '1', then there is a staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. If the $$$i$$$-th character is a '0', then there is no staircase between the room $$$i$$$ on the first floor and the room $$$i$$$ on the second floor. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

For each test case print one integer — the maximum number of rooms Nikolay can visit during his tour, if he can start in any room on any floor, and he won't visit the same room twice.

NoteIn the first test case Nikolay may start in the first room of the first floor. Then he moves to the second room on the first floor, and then — to the third room on the first floor. Then he uses a staircase to get to the third room on the second floor. Then he goes to the fourth room on the second floor, and then — to the fifth room on the second floor. So, Nikolay visits $$$6$$$ rooms.There are no staircases in the second test case, so Nikolay can only visit all rooms on the same floor (if he starts in the leftmost or in the rightmost room).In the third test case it is possible to visit all rooms: first floor, first room $$$\rightarrow$$$ second floor, first room $$$\rightarrow$$$ second floor, second room $$$\rightarrow$$$ first floor, second room $$$\rightarrow$$$ first floor, third room $$$\rightarrow$$$ second floor, third room $$$\rightarrow$$$ second floor, fourth room $$$\rightarrow$$$ first floor, fourth room $$$\rightarrow$$$ first floor, fifth room $$$\rightarrow$$$ second floor, fifth room.In the fourth test case it is also possible to visit all rooms: second floor, third room $$$\rightarrow$$$ second floor, second room $$$\rightarrow$$$ second floor, first room $$$\rightarrow$$$ first floor, first room $$$\rightarrow$$$ first floor, second room $$$\rightarrow$$$ first floor, third room.

readline.to_i.times do
  n = readline.to_i
  s = readline.chomp
  z = [n + s.count("1")]
  if z[0] > n then
    l,r = s.index("1"), s.rindex("1")
    z << 2*(r+1)
    z << 2*(n-l)
  end
  p z.max
end

T = gets.to_i
T.times do
  n = gets.to_i
  s = gets.chomp
  if !s.include?("1")
    p n
  else
    l,r = 0,n-1
    l += 1 while s[l] == "0"
    r -= 1 while s[r] == "0"
    p [n-l,r+1].max*2
  end
end

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
t=gi
ans=[]

t.times do |i|
  n=gi
  s=gs

  i1 = s.index("1")
  i2 = s.reverse.index("1")
  if i1.nil?
    ans << n
  else
    d = n - min(i1,i2)
    ans << (d*2)
  end

end

puts ans


Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point (i + 1, yi + 1). For any even i (2 ≤ i ≤ 2n) the following condition holds: yi - 1 < yi and yi > yi + 1. We shall call a vertex of a polyline with an even x coordinate a mountain peak.   The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2.  Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1, r1), (2, r2), ..., (2n + 1, r2n + 1).Given Bolek's final picture, restore the initial one.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100). The next line contains 2n + 1 space-separated integers r1, r2, ..., r2n + 1 (0 ≤ ri ≤ 100) — the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.

Print 2n + 1 integers y1, y2, ..., y2n + 1 — the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.

n,k = gets.chomp.split(/ /).map!{|x| x.to_i}
ra = gets.chomp.split(/ /).map!{|x| x.to_i}
k2 = k
for i in 0..n-1
    pr = 2*i
    pe = 2*i+1
    nx = 2*i+2
    if (ra[pe] - ra[pr] > 1) && (ra[pe] - ra[nx] > 1)
        ra[pe] -= 1
        k2 -= 1
    end
    break if k2 <= 0
end
puts ra.join(" ")

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

i = 1; while (true)
	if (a[i] - a[i-1] > 1 && a[i] - a[i+1] > 1)
		a[i] -= 1; k -= 1
		break if (k.zero?)
	end
	i += 2
end

puts a*' '

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

n.times do |i|
	ii = 2 * i + 1
	if (a[ii] - a[ii-1] > 1 && a[ii] - a[ii+1] > 1)
		a[ii] -= 1; k -= 1
	end
	break if k.zero?
end

puts a.join(' ')

I =->{gets.split.map &:to_i}

n, k = I[]; a = I[]
i = 1; while (true)
	if a[i] - a[i-1] > 1 && a[i] - a[i+1] > 1
		a[i] -= 1; k -= 1; break if (k.zero?)
	end
	i += 2
end

puts a*' '

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

i = 1; while (true)
	if (a[i] - a[i-1] > 1 && a[i] - a[i+1] > 1)
		a[i] -= 1; k -= 1
		break if (k.zero?)
	end
	i += 2
end

puts a.join(' ')

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
picks = (0...2*n+1).find_all {|x| x.odd? }
mordor = []
k.times do
  n.times do |p|
    i = picks[p]
    if a[i-1] < a[i]-1 and a[i]-1 > a[i+1]
      mordor.push i
      picks.delete i
      break
    end
  end
end

mordor.each {|j| a[j]-=1 }
puts a*' '

n, k = gets.chomp.split.map{|e|e.to_i}
a = 2*n+1
y = Array.new(a){}
y = gets.chomp.split.map{|e|e.to_i}
c = 0
a.times do |i|
  if i+1 < a && i % 2 == 1 && y[i]-1 > y[i-1] && y[i]-1 > y[i+1]
    y[i] -=1
    c += 1
    break if c == k
  end
end
puts y.join(" ")

#!/usr/bin/ruby
n,k = gets.chomp.split(' ').map{|x| x.to_i}
line = gets.chomp.split(' ').map{|x| x.to_i}
ktmp=0
for i in 0..(2*n)
  if i%2==1
    if line[i]-1>line[i-1] && line[i]-1 > line[i+1] && ktmp < k
      ktmp+=1
      line[i]-=1;
    end
  end
  print line[i].to_s + " " if i < 2*n
end
puts line[2*n]

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

while m > 0
	i = 1
	while i < ar.length
		if ar[i] > ar[i-1] + 1 and ar[i] > ar[i+1] + 1
			ar[i] -= 1
			m -= 1
			break if m == 0
		end
		i += 2
	end
end

for x in ar
	print x.to_s + " "
end

#!/usr/bin/ruby
include Math

n,k = gets.split.map(&:to_i)
pic = gets.split.map(&:to_i)
dec = 0
n.times do |i|
  if pic[2*i+1] - pic[2*i] > 1 && pic[2*i+1] - pic[2*i+2] > 1
    pic [2*i+1] -= 1
    dec += 1
  end
  break if dec >= k
end
puts pic.join(' ')

n, k = gets.split.map(&:to_i)
r = gets.split.map(&:to_i)
1.upto(2*n) do |i|
  next if i%2==0
  break if k==0
  if r[i-1] < r[i]-1 && r[i+1]< r[i]-1 && k>0
    r[i]-=1
    k-=1
  end
end

r.each do |rr|
  print "#{rr} "
end

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

n, k = read_next_line
a = read_next_line
for i in (1...2 * n).step(2)
  v = a[i] - 1
  if a[i - 1] < v && a[i + 1] < v
    a[i] = v
    k -= 1
    break if k == 0
  end
end
puts a * ' '

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

n.times do |i|
	ii = 2 * i + 1
	if (a[ii] - a[ii-1] > 1 && a[ii] - a[ii+1] > 1)
		--a[ii]; --k
	end
	break if k.zero?
end

puts a.join(' ')

#!/usr/bin/ruby
include Math
str = gets
str.gsub! /(WUB)+/, ' '
str.gsub! /^\s*/,''
str.gsub! /\s*$/,''
puts str

n, k = gets.split.map(&:to_i)
r = gets.split.map(&:to_i)
1.upto(n) do |i|
  next if i%2==0
  break if k==0
  if r[i-1] < r[i]-1 && r[i+1]< r[i]-1 && k>0
    r[i]-=1
    k-=1
  end
end

r.each do |rr|
  print "#{rr} "
end


You are given $$$n$$$ points with integer coordinates on a coordinate axis $$$OX$$$. The coordinate of the $$$i$$$-th point is $$$x_i$$$. All points' coordinates are distinct and given in strictly increasing order.For each point $$$i$$$, you can do the following operation no more than once: take this point and move it by $$$1$$$ to the left or to the right (i..e., you can change its coordinate $$$x_i$$$ to $$$x_i - 1$$$ or to $$$x_i + 1$$$). In other words, for each point, you choose (separately) its new coordinate. For the $$$i$$$-th point, it can be either $$$x_i - 1$$$, $$$x_i$$$ or $$$x_i + 1$$$.Your task is to determine if you can move some points as described above in such a way that the new set of points forms a consecutive segment of integers, i. e. for some integer $$$l$$$ the coordinates of points should be equal to $$$l, l + 1, \ldots, l + n - 1$$$.Note that the resulting points should have distinct coordinates.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points in the set $$$x$$$. The second line of the test case contains $$$n$$$ integers $$$x_1 < x_2 < \ldots < x_n$$$ ($$$1 \le x_i \le 10^6$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th point. It is guaranteed that the points are given in strictly increasing order (this also means that all coordinates are distinct). It is also guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — if the set of points from the test case can be moved to form a consecutive segment of integers, print YES, otherwise print NO.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  dxs = xs.each_cons(2).map { |a, b| b - a }.sort.reverse
  if dxs.empty? || dxs[0] == 1 || dxs[0] == 2 && dxs.count(2) <= 2 || dxs[0] == 3 && (dxs[1] == nil || dxs[1] == 1)
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.chomp.split.map(&:to_i)
  c = 0
  1.upto(n-1) do |i|
    c += a[i] - a[i-1] - 1
  end
  puts c > 2 ? "NO":"YES"
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  dxs = xs.each_cons(2).map { |a, b| b - a }.sort.reverse
  if dxs.empty? || dxs[0] == 1 || dxs[0] == 2 && dxs.count(2) <= 2 || dxs[0] == 3 && dxs.count(3) == 1
    puts "YES"
  else
    puts "NO"
  end
end


God's Blessing on This PermutationForces!A Random PebbleYou are given a permutation $$$p_1,p_2,\ldots,p_n$$$ of length $$$n$$$ and a positive integer $$$k \le n$$$. In one operation you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i < j \le n$$$) and swap $$$p_i$$$ with $$$p_j$$$.Find the minimum number of operations needed to make the sum $$$p_1 + p_2 + \ldots + p_k$$$ as small as possible.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ integers $$$p_1,p_2,\ldots,p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the given numbers form a permutation of length $$$n$$$.

For each test case print one integer — the minimum number of operations needed to make the sum $$$p_1 + p_2 + \ldots + p_k$$$ as small as possible.

NoteIn the first test case, the value of $$$p_1 + p_2 + \ldots + p_k$$$ is initially equal to $$$2$$$, but the smallest possible value is $$$1$$$. You can achieve it by swapping $$$p_1$$$ with $$$p_3$$$, resulting in the permutation $$$[1, 3, 2]$$$.In the second test case, the sum is already as small as possible, so the answer is $$$0$$$.

gets.to_i.times do
    n,k = gets.split.map(&:to_i)
    inputs = gets.split.map(&:to_i)
    puts inputs[...k].count { |x| x>k }
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  ps = gets.split.map(&:to_i)
  p ps[..k - 1].count { |p| p > k }
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  p=gets.split.map(&:to_i)
  puts p[0...k].count {|i| i>k}
end


Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:           0        0 1 0      0 1 2 1 0    0 1 2 3 2 1 0  0 1 2 3 4 3 2 1 00 1 2 3 4 5 4 3 2 1 0  0 1 2 3 4 3 2 1 0    0 1 2 3 2 1 0      0 1 2 1 0        0 1 0          0Your task is to determine the way the handkerchief will look like by the given n.

The first line contains the single integer n (2 ≤ n ≤ 9).

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

class Euler
  a=gets.to_i;
  b=2*a+1;
  pr=2*a;
  allpr=2*b-1;
  (1..pr).each do
      print(" ");
    end
  puts("0");
  (2..b-1).each do |i|
    if (i<=a+1)
      c=2*i-1;
    else
      c=b-2*(i-a-1)
    end
    s=2*(a-(c/2));
    (1..s).each do
      print(" ");
    end
    l=c/2+1;
    (1..l).each do |j|
      print(j-1);
      print(" ");
    end
   (1..l-2).each do |j|
     k=(c-1)/2;
      print(k-j);
      print(" ");
    end
    if (l>1)
      print("0");
      end
    print("\n");
  end
  (1..pr).each do
      print(" ");
    end
  puts("0");
 end

n = gets.to_i
x = 0
while (x <= n)
    c = n - x
    i = 0
    s = ''
    while (i < c)
        s += '  '
        i+=1
    end
    i = 0
    fst = true
    while (i <= x)
        if (!fst) then s += ' ' end
        fst = false
        s += i.to_s
        i+=1
    end
    i = x-1
    while (i >= 0)
        s += ' ' + i.to_s
        i-=1
    end
    puts s
    x+=1
end
x = n-1
while (x >= 0)
    c = n - x
    i = 0
    s = ''
    while (i < c)
        s += '  '
        i+=1
    end
    i = 0
    fst = true
    while (i <= x)
        if (!fst) then s += ' ' end
        fst = false
        s += i.to_s
        i+=1
    end
    i = x-1
    while (i >= 0)
        s += ' ' + i.to_s
        i-=1
    end
    puts s
    x-=1
end

def present
  n = gets.to_i + 1

  #print  "  "

  n.times do |i|
    line = ""
    line += "  " * (n - i - 1)
    0.upto(i) do |j|
      line += "#{j} "
    end

    (i - 1).downto(0) do |l|
      line += "#{l} "
    end
    line[line.size - 1] = "\n"
    print line
  end

  (n - 2).downto(0) do |i|
    line = ""
    line += "  " * (n - i - 1)
    0.upto(i) do |j|
      line += "#{j} "
    end

    (i - 1).downto(0) do |l|
      line += "#{l} "
    end
    line[line.size - 1] = "\n"
    print line
  end
end

present

#!/usr/bin/ruby -Ks

INPUT_NUMBER = $stdin.gets.chomp.to_i

output = Array.new

0.upto(INPUT_NUMBER) do |i|
  output[i] = ""
  (INPUT_NUMBER - i).times do |j|
    output[i] += " " + " "
  end
  0.upto(i) do |j|
    output[i] += j.to_s + " "
  end
end

output.each_with_index do |str, idx|
  output_string = str + str.reverse.slice(3, (str.size - 3)).rstrip
  puts output_string.rstrip
end

output.reverse.each_with_index do |str, idx|
  next if idx == 0
  output_string = str + str.reverse.slice(3, (str.size - 3))
  puts output_string.rstrip
end

# EOF

input = gets.to_i

top = ""

(0..input).each do |x|

  top += "  " * (input - x)

  l = (0..x).to_a
  r = l.reverse
  r.shift

  top += (l + r).join " "
  top += "\n"

end

bot = top.split("\n")
bot.pop

print top + bot.reverse.join("\n")

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    line = ""
    (elem[space] - 1).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
#elem = Array.new()
#elem.push 1

elem = 1.upto(lines - 1).inject([1]) {|res, i| res[i] = res[i - 1] + (i <= n ? 2 : -2); res}
# 1.upto(lines - 1) do |i|
    # if i <= n
        # elem[i] = elem[i - 1] + 2
    # else
        # elem[i] = elem[i - 1] - 2
    # end
# end
space = n
elem.each do |i|
    line = " " * (elem[space] - 1)
    # (elem[space] - 1).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1

elem = 1.upto(lines - 1).inject([1]) {|res, i| res[i] = res[i - 1] + (i <= n ? 2 : -2); res}
space = n
elem.each do |i|
    line = " " * (elem[space] - 1)
    space -= (space == 0) ? 2 : 1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        num += (j < i/2) ? 1: -1
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
#elem = Array.new()
#elem.push 1

elem = 1.upto(lines - 1).inject([1]) {|res, i| res[i] = i <= n ? res[i - 1] + 2 : res[i - 1] - 2; res}
# 1.upto(lines - 1) do |i|
    # if i <= n
        # elem[i] = elem[i - 1] + 2
    # else
        # elem[i] = elem[i - 1] - 2
    # end
# end
space = n
elem.each do |i|
    line = " " * (elem[space] - 1)
    # (elem[space] - 1).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = 1.upto(lines - 1).inject([1]) {|res, i| res[i] = res[i - 1] + (i <= n ? 2 : -2); res}
space = n
elem.each do |i|
    line = " " * (elem[space] - 1)
    space -= (space == 0) ? 2 : 1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        num += (j < i / 2) ? 1: -1
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    line = " " * (elem[space] - 1)
    # (elem[space] - 1).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.rstrip
end

n = gets.chomp.to_i

for i in 0..2*n
  spn = 0
  pn = 2*n+1
  if i < n then
    spn = 2*(n - i)
    pn = 2*i+1
  elsif i > n then
    spn = 2*(i - n )
    pn = 2*(2*n-i) + 1
  end
  for j in 0..spn-1
    print " "
  end
  nn = 0
  for j in 0..pn-1
    print " " if j > 0
    print nn
    if j >= (pn-1).div(2)
      nn -= 1
    else
      nn += 1
    end
  end
  puts ""
end

n = gets.to_i
a = Array.new(2 * n + 1){Array.new(2 * n + 1){' '}}
(-n .. n).each do |i|
	k = n - i.abs
	(-k .. k).each do |j|
		a[i + n][j + n] = (k - j.abs).to_s
	end
end
puts a.map{|_| (_ * ' ').rstrip} * "\n"

n = STDIN.readline.to_i

a = n + 1
result = []
(0..n).each do |i|
    line = []
    (-(n)..i).each do |j|
        if i - j.abs < 0
            line << ' '
        else
            line << (i - j.abs)
        end
    end
    result << line.join(' ')
end
result << result[0..-2].reverse
puts result

n=gets.to_i
k=1
q=n
for i in 0..n
        (q).times{
                print "  "
        }
        for j in 0..(k/2)
                if j>0 then
                        print " "
                end
                print j
        end
        (k/2-1).downto(0){|j|
                print " "+j.to_s
        }
        puts
        k+=2
        q-=1
end
q+=2
k-=4
n.downto(1){|i|
        (q).times{
                print "  "
        }
        for j in 0..(k/2)
                if j>0 then
                        print " "
                end
                print j
        end
        (k/2-1).downto(0){|j|
                print " "+j.to_s
        }
        puts
        k-=2
        q+=1
}

def line(a, n)
  space = Array.new(n-a){"  "}.join("")
  str = "#{a}"
  while a > 0
    a -= 1
    str = "#{a} #{str} #{a}"
  end
  puts space + str
end

n = gets.to_i
i = 0
while i <= n do
  line(i, n)
  i += 1
end
i = n-1
while i >= 0 do
  line(i, n)
  i -= 1
end

n = gets.to_i

(0..2 * n).each do |y|
    s = ""
    (0..2 * n).each do |x|
        t = n - (x - n).abs - (y - n).abs
        s += (t >= 0 ? t.to_s : " ")
        s += " "
    end
    puts s.rstrip
end

x = gets.chomp.to_i

arr = []

0.upto(x) do |ind|
  arr << ""
  arr.last << 0.upto(ind).to_a.join(' ')
  line_end = (ind-1).downto(0).to_a.join(' ')
  arr.last << ' ' + line_end if line_end.size > 0
end

largest_len = arr.last.length

arr.each do |s|
  puts " "*((largest_len-s.length)/2) + s
end

arr.reverse.drop(1).each do |s|
  puts " "*((largest_len-s.length)/2) + s
end

#!/usr/bin/ruby

def readNextValues
  arr = gets.chomp.split
  return arr.collect {|x| x.to_i }
end

#######################

def nums(toNum)
  0.upto(toNum) do |i|
    print "#{i}"
    if toNum != 0
      print ' '
    end
  end
  (toNum-1).downto(0) do |i|
    print "#{i}"
    if i != 0
      print ' '
    end
  end
end

n = gets.to_i

0.upto(n) do |i|
  print '  ' * (n-i)
  nums(i)
  puts
end
(n-1).downto(0) do |i|
  print '  ' * (n-i)
  nums(i)
  puts
end

n=gets.to_i
arr=[]
(n+1).times{|i|
	str=""
	c1=i-n
	d=1
	f=true
	0.upto(n+i){
		if (d==1) && (c1==i-n) then
		else
			str<<" "
		end
		if c1<0 then
			str<<" "
		else
			str<<c1.to_s
		end
		c1+=d
		d=-1 if c1==i
	}
	puts str
	arr<<str if n>i
}
arr.reverse.each{|e|
	puts e
}

#!/usr/bin/env ruby
def a2s( a )
  b = []
  a.each do |i|
    if i < 0
      b << " "
    else
      b << i.to_s
    end
  end
  return b.join( " " ).rstrip
end

n = gets.to_i
a = []
0.upto(n){ |i| a << i }
(n-1).downto(0){ |i| a << i }
a.map!{ |i| i-n }
n.times do |i|
  puts a2s(a)
  a.map!{ |i| i+1 }
end
n.times do |i|
  puts a2s(a)
  a.map!{ |i| i-1 }
end
puts a2s(a)

n = gets.to_i + 1

n.times do |i|
  (n-i-1).times do
print "  "
  end

  (i+1).times do |ii|
    print ii
    print " " unless i == 0
  end
  (i-1).downto(0) do |ii|
    print ii
    print " " unless ii == 0
  end

  print "\n"
end

(n-2).downto(0) do |i|
  (n-i-1).times do
    print "  "
  end

  (i+1).times do |ii|
    print ii
    print " " unless i == 0
  end
  (i-1).downto(0) do |ii|
    print ii
    print " " unless ii == 0
  end

  print "\n"
end

@n = gets.to_i
@w = @n*4+1

def gen(k)
  s = ' '
  (0..k).each do |i|
    s += i.to_s + ' '
  end
  (0...k).reverse_each do |i|
    s += i.to_s + ' '
  end
  puts s.strip.center(@w).rstrip
end

(0..@n).each do |i|
  gen(i)
end
(0...@n).reverse_each do |i|
  gen(i)
end

n = gets.chop.to_i
for y in 0..n
	for s in 1..(n-y)+(n-y)
		print " "
	end
	for x in 0..y-1
		print x
			print " "
	end
	y.downto(0){ |x|
		print x
		if x > 0
			print " "
		end
	}
	puts ""
end
#pts n
(n-1).downto(0){ |y|
   for s in 1..n-y+n-y
                print " "
        end
        for x in 0..y-1
                print x
		print " "
        end
        y.downto(0){ |x|
		print x
		if x > 0
			print " "
		end
        }
        puts ""

}

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

n = gets.chop.to_i

size = 2*n + 1

for i in -n..n
  line = ""
  for j in -n..n
    val = (n - (i.abs + j.abs))
    if (val >= 0)
      line += "#{val} "
    else
      line += "  "
    end

  end
  puts line.rstrip
end

input = $stdin.readline.chop.to_i
n = input
i = 0
while n>=0
  (n*2).times do
    print " "
  end

  for j in 0..(i-1)
    print "#{j} "
  end

  print "#{i}"
  print " " if i!=0

  j = i - 1
  while j>=0
    print j
    print " " if j!=0
    j-=1
  end

  print "\n"
  n-=1
  i+=1
end

n = 1
i = input-1
while n<=input
  (n*2).times do
    print " "
  end

  for j in 0..(i-1)
    print "#{j} "
  end

  print "#{i}"
  print " " if i!=0

  j = i - 1
  while j>=0
    print j
    print " " if j!=0
    j-=1
  end

  print "\n"
  n+=1
  i-=1
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
lines = []
for i in (0..n).to_a + (0...n).to_a.reverse
    pads = n - i
    buf = []
    pads.times { buf << ' ' }
    lines << buf + (0..i).to_a + (0...i).to_a.reverse
end

for line in lines
    puts line.join(' ')
end

n = Integer(gets)
line = 2 * n + 1
a = Array.new
for i in 0...line
    a[i] = Array.new
end

for i in 0...line
    if i <= n
        for j in 0...n+i+1
            a[i][j] = " "
        end
    else
        for j in 0...3*n+1-i
            a[i][j] = " "
        end
    end
end

for m in 0...n

    for i in 0...line
        for j in 0...line
            if m == 0
                if i + j == n
                    a[i][j] = 0
                    a[i][2*n-j] = 0
                    a[2*n-i][j] = 0
                    a[2*n-i][2*n-j]= 0
                end
            else
                if i + j == n + m && i >= m && j >= m

                            a[i][j] = m
                            a[i][2*n-j] = m
                            a[2*n-i][j] = m
                            a[2*n-i][2*n-j]= m

                end
            end

        end
    end
end

a[n][n] = n
for i in 0...line
    if i <= n
        for j in 0...n+i+1
            if j != 0
                print " "
            end
            print a[i][j]
        end
    else
        for j in 0...3*n+1-i
            if j!= 0
                print " "
            end
            print a[i][j]
        end
    end

    puts
end

n = gets.chomp.to_i
space = n*2
for i in (1..n)
	for x in (i..space)
		print " "
	end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		if x < line
			print count
			print " "
			if x <= line/2
				count += 1
			else
				count -= 1
			end
		else
			puts count
		end
	end
	space -= 1
end
count = 0
for i in (1..(n*2) + 1)
	if i < (n*2) + 1
		print count
		print " "
		if i <= ((n*2)+1)/2
			count += 1
		else
			count -= 1
		end
	else
		puts count
	end
end
i = n
space = n+1
while i >= 1
		for x in (i..space)
			print " "
		end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		if x < line
			print count
			print " "
			if x <= line/2
				count += 1
			else
				count -= 1
			end
		else
			puts count
		end
	end
	i -= 1
	space += 1
end

n = STDIN.gets.chomp.to_i

def line(from, to)
  left = ""
  for i in from...to
    left += (if i >= 0 then i.to_s else " "; end) + " "
  end
  result = (left + to.to_s + left.reverse).rstrip
end

top_lines = []
for i in 0...n
  top_lines << line(i - n, i)
end
top_lines.each { |line| puts line }
puts line(0, n)
top_lines.reverse.each { |line| puts line }

def present
  n = gets.to_i

  #print  "  "

  n.times do |i|
    line = ""
    line += "  " * (n - i - 1)
    0.upto(i) do |j|
      line += "#{j} "
    end

    (i - 1).downto(0) do |l|
      line += "#{l} "
    end
    line[line.size - 1] = "\n"
    print line
  end

  (n - 2).downto(0) do |i|
    line = ""
    line += "  " * (n - i - 1)
    0.upto(i) do |j|
      line += "#{j} "
    end

    (i - 1).downto(0) do |l|
      line += "#{l} "
    end
    line[line.size - 1] = "\n"
    print line
  end
end

present

#!/usr/bin/ruby -Ks

INPUT_NUMBER = $stdin.gets.chomp.to_i

output = Array.new

0.upto(INPUT_NUMBER) do |i|
  output[i] = ""
  (INPUT_NUMBER - i).times do |j|
    output[i] += " " + " "
  end
  0.upto(i) do |j|
    output[i] += j.to_s + " "
  end
end

output.each do |str|
  print str
  puts str.reverse.slice(3, (str.size - 3)).rstrip
end

output.reverse.each_with_index do |str, idx|
  next if idx == 0
  print str
  puts str.reverse.slice(3, (str.size - 3)).rstrip
end

# EOF

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    print " "
    elem[space].times {|i| print " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        print num, " ";
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    line = ""
    (elem[space]).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.chomp
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    line = ""
    (elem[space]).times {|i| line += " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        line += (num.to_s + " ");
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts line.rstrip
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    print " "
    (elem[space] - 1).times {|i| print " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        print " ", num;
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts
end

n = STDIN.gets.chomp.to_i
lines = ((n + 1) * 2) - 1
elem = Array.new()
elem.push 1
1.upto(lines - 1) do |i|
    if i <= n
        elem[i] = elem[i - 1] + 2
    else
        elem[i] = elem[i - 1] - 2
    end
end
space = n
elem.each do |i|
    elem[space].times {|i| print " "}
    space -= 1
    space -= 1 if space == -1
    num = 0
    i.times do |j|
        print num, " ";
        if j < i / 2
            num += 1
        else
            num -= 1
        end
    end
    puts
end

n = STDIN.readline.to_i

a = n + 1
result = []
(0..n).each do |i|
	line = []
	(-(n)..(n)).each do |j|
		if i - j.abs < 0
			line << ' '
		else
			line << (i - j.abs)
		end
	end
	result << line.join(' ')
end
result << result[0..-2].reverse
puts result

n=gets.to_i
k=1
q=n
for i in 0..n
        q.times{
                print "  "
        }
        for j in 0..(k/2)
                if j then
                        print " "
                end
                print j
        end
        (k/2-1).downto(0){|j|
                print " "+j.to_s
        }
        puts
        k+=2
        q-=1
end
q+=2
k-=4
n.downto(1){|i|
        q.times{
                print "  "
        }
        for j in 0..(k/2)
                if j then
                        print " "
                end
                print j
        end
        (k/2-1).downto(0){|j|
                print " "+j.to_s
        }
        puts
        k-=2
        q+=1
}

x = gets.chomp.to_i

arr = []

0.upto(x) do |ind|
  arr << ""
  arr.last << 0.upto(ind).to_a.join(' ')
  line_end = (ind-1).downto(0).to_a.join(' ')
  arr.last << ' ' + line_end if line_end.size > 0
end

puts largest_len = arr.last.length

arr.each do |s|
  puts " "*((largest_len-s.length)/2) + s
end

arr.reverse.drop(1).each do |s|
  puts " "*((largest_len-s.length)/2) + s
end

#!/usr/bin/ruby

def readNextValues
  arr = gets.chomp.split
  return arr.collect {|x| x.to_i }
end

#######################

def nums(toNum)
  0.upto(toNum) do |i|
    print "#{i} "
  end
  (toNum-1).downto(0) do |i|
    print "#{i}"
    if i != 0
      print ' '
    end
  end
end

n = gets.to_i

0.upto(n) do |i|
  print '  ' * (n-i)
  nums(i)
  puts
end
(n-1).downto(0) do |i|
  print '  ' * (n-i)
  nums(i)
  puts
end

#!/usr/bin/env ruby
def a2s( a )
  b = []
  a.each do |i|
    if i < 0
      b << " "
    else
      b << i.to_s
    end
  end
  return b.join( " " )
end

n = gets.to_i
a = []
0.upto(n){ |i| a << i }
(n-1).downto(0){ |i| a << i }
a.map!{ |i| i-n }
n.times do |i|
  puts a2s(a)
  a.map!{ |i| i+1 }
end
n.times do |i|
  puts a2s(a)
  a.map!{ |i| i-1 }
end
puts a2s(a)

n = gets.to_i + 1

n.times do |i|
  (n-i-1).times do
    print "  "
  end

  (i+1).times do |ii|
    print ii
    print " "
  end
  (i-1).downto(0) do |ii|
    print ii
    print " "
  end

  print "\n"
end

(n-2).downto(0) do |i|
  (n-i-1).times do
    print "  "
  end

  (i+1).times do |ii|
    print ii
    print " "
  end
  (i-1).downto(0) do |ii|
    print ii
    print " "
  end

  print "\n"
end

@n = gets.to_i
@w = @n*4+1

def gen(k)
  s = ' '
  (0..k).each do |i|
    s += i.to_s + ' '
  end
  (0...k).reverse_each do |i|
    s += i.to_s + ' '
  end
  puts s.strip.center(@w)
end

(0..@n).each do |i|
  gen(i)
end
(0...@n).reverse_each do |i|
  gen(i)
end

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

n = gets.chop.to_i

size = 2*n + 1

for i in -n..n
  line = ""
  for j in -n..n
    val = (n - (i.abs + j.abs))
    if (val >= 0)
      line += "#{val} "
    else
      line += "  "
    end

  end
  puts line.chop
end

input = $stdin.readline.chop.to_i
n = input
i = 0
while n>=0
  (n*2).times do
    print " "
  end

  for j in 0..(i-1)
    print "#{j} "
  end

  print "#{i} "

  j = i - 1
  while j>=0
    print j
    print " " if j!=0
    j-=1
  end

  print "\n"
  n-=1
  i+=1
end

n = 1
i = input-1
while n<=input
  (n*2).times do
    print " "
  end

  for j in 0..(i-1)
    print "#{j} "
  end

  print "#{i} "

  j = i - 1
  while j>=0
    print j
    print " " if j!=0
    j-=1
  end

  print "\n"
  n+=1
  i-=1
end

n = Integer(gets)
line = 2 * n + 1
a = Array.new
for i in 0...line
    a[i] = Array.new
end

for i in 0...line
    if i <= n
        for j in 0...n+i+1
            a[i][j] = " "
        end
    else
        for j in 0...3*n+1-i
            a[i][j] = " "
        end
    end
end

for m in 0...n

    for i in 0...line
        for j in 0...line
            if m == 0
                if i + j == n
                    a[i][j] = 0
                    a[i][2*n-j] = 0
                    a[2*n-i][j] = 0
                    a[2*n-i][2*n-j]= 0
                end
            else
                if i + j == n + m && i >= m && j >= m

                            a[i][j] = m
                            a[i][2*n-j] = m
                            a[2*n-i][j] = m
                            a[2*n-i][2*n-j]= m

                end
            end

        end
    end
end

a[n][n] = n
for i in 0...line
    for j in 0...line
     print a[i][j]
     if j != i + 3
        print " "
     end

    end
    puts
end

n = Integer(gets)
line = 2 * n + 1
a = Array.new
for i in 0...line
	a[i] = Array.new
end

for i in 0...line
	if i <= n
		for j in 0...n+i+1
			a[i][j] = " "
		end
	else
		for j in 0...3*n+1-i
			a[i][j] = " "
		end
	end
end

for m in 0...n

	for i in 0...line
		for j in 0...line
			if m == 0
				if i + j == n
					a[i][j] = 0
					a[i][2*n-j] = 0
					a[2*n-i][j] = 0
					a[2*n-i][2*n-j]= 0
				end
			else
				if i + j == n + m && i >= m && j >= m

							a[i][j] = m
							a[i][2*n-j] = m
							a[2*n-i][j] = m
							a[2*n-i][2*n-j]= m

				end
			end

		end
	end
end

a[n][n] = n
for i in 0...line
	for j in 0...line
	 print a[i][j]
	end
	puts
end

n = gets.chomp.to_i
space = n*2
for i in (1..n)
	for x in (i..space)
		print " "
	end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		print count
		print " "
		if x <= line/2
			count += 1
		else
			count -= 1
		end
	end
	puts " "
	space -= 1
end
count = 0
for i in (1..(n*2) + 1)
	if i < (n*2) + 1
		print count
		print " "
		if i <= ((n*2)+1)/2
			count += 1
		else
			count -= 1
		end
	else
		puts count
	end
end
i = n
space = n+1
while i >= 1
		for x in (i..space)
			print " "
		end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		print count
		print " "
		if x <= line/2
			count += 1
		else
			count -= 1
		end
	end
	puts " "
	i -= 1
	space += 1
end

n = gets.chomp.to_i

for i in (1..n)
	for x in (i..n)
		print " "
	end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		print count
		if x <= line/2
			count += 1
		else
			count -= 1
		end
	end
	for x in (i..n-1)
		print " "
	end
	puts " "
end
count = 0
for i in (1..(n*2) + 1)
	if i < (n*2) + 1
		print count
		if i <= ((n*2)+1)/2
			count += 1
		else
			count -= 1
		end
	else
		puts count
	end
end
i = n
while i >= 1
	for x in (i..n)
		print " "
	end
	line = (n*2) + 1 - (((n + 1 - i) * 2)).abs
	count = 0
	for x in (1..line)
		print count
		if x <= line/2
			count += 1
		else
			count -= 1
		end
	end
	for x in (i..n-1)
		print " "
	end
	puts " "
	i -= 1
end

n = STDIN.gets.chomp.to_i

def line(from, to)
  left = ""
  for i in from...to
    left += (if i >= 0 then i.to_s else " "; end) + " "
  end
  result = left + to.to_s + left.reverse
end

top_lines = []
for i in 0...n
  top_lines << line(i - n, i)
end
top_lines.each { |line| puts line }
puts line(0, n)
top_lines.reverse.each { |line| puts line }

class Euler
  a=gets.to_i;
  b=2*a+1;
  pr=2*a;
  allpr=2*b-1;

  (1..b).each do |i|
    if (i<=a+1)
      c=2*i-1;
    else
      c=b-2*(i-a-1)
    end
    s=2*(a-(c/2));
    (1..s).each do
      print(" ");
    end
    l=c/2+1;
    (1..l).each do |j|
      print(j-1);
      print(" ");
    end
   (1..l-2).each do |j|
     k=(c-1)/2;
      print(k-j);
      print(" ");
    end
    if (l>1)
      print("0");
      end
    print("\n");
  end
 end


You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?

The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.

If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.

4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc

NoteIn the first test case, you can do the following:   Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.

gets.to_i.times do
    n = gets.to_i
    s = []
    n.times do
        s << gets.chomp!
    end
    cnt = [0] * 26
    s.each do |i|
        i.each_char do |c|
            cnt[c.ord - 'a'.ord] += 1
        end
    end
    ok = true
    cnt.each do |i|
        ok &= i % n == 0
    end
    puts ok ? "YES" : "NO"
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  hash = Hash.new(0)
  n.times do
    s = gets.chomp.split("")
    s.each do |x|
      hash[x] += 1
    end
  end
  str = "YES"
  hash.each_value do |v|
    if v % n != 0
      str = "NO"
    end
  end
  ans << str
end
ans.each do |x|
  puts x
end

gets.to_i.times do
  l = gets.to_i
  h = Hash.new(0)
  l.times do
    gets.split('').each { |i|  h[i] += 1 }
  end
  r = h.values.all? { |i| i % l == 0 }  ? 'YES' : 'NO'
  puts r
end


You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold:  For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \neq a_j$$$.  The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq n$$$).  If there are multiple solutions, print any of them.

NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$.

n = gets.to_i
m = 0
arr=Array.new(n)
for i in 2..n
	j = i
	while(j <= n)
		if(arr[j-1] == nil)
			if(j == i)
				m += 1
			end
			arr[j-1] = m
		end
		j += i
	end
end
for ele in arr[1...n]
	print("#{ele} ")
end

n = gets.to_i

arr=Array.new(n)
for i in 2..n
	j = i
	while(j <= n)
		if(arr[j-1] == nil)
			arr[j-1] = i-1
		end
		j += i
	end
end
for ele in arr[1...n]
	print("#{ele} ")
end


There is a matrix A of size x × y filled with integers. For every ,  Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x;  (i, j + 1) — only if j < y;  (i - 1, j) — only if i > 1;  (i, j - 1) — only if j > 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.

If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.

NoteThe matrix and the path on it in the first test looks like this:  Also there exist multiple correct answers for both the first and the third examples.

n = gets.to_i
a = gets.split.map &:to_i
d = (1...n).map { |i| (a[i] - a[i - 1]).abs } .uniq.reject { |v| v == 1 }
if d.size > 1 || d.include?(0)
  puts :NO
else
  ok = d.empty? || (1...n).all? do |i|
    x = a[i - 1]
    y = a[i]
    x, y = y, x if x > y
    case y - x
    when 1 then x % d[0] > 0
    else true
    end
  end
  puts case ok
  when false then :NO
  else [:YES, [1e9.to_i, d[0] || 1].join(' ')]
  end
end

n = gets.to_i
a = gets.split.map &:to_i
d = (1...n).map { |i| (a[i] - a[i - 1]).abs } .uniq.reject { |v| v == 1 }
if d.size > 1 || d.include?(0)
  puts :NO
else
  ok = d.empty? || (1...n).all? do |i|
    x = a[i - 1]
    y = a[i]
    x, y = y, x if x > y
    case y - x
    when 1 then x % d[0] > 0
    else true
    end
  end
  puts case ok
  when false then :NO
  else [:YES, [1e9.to_i, d[0]].join(' ')]
  end
end


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

n = gets.to_i
ar = gets.split(' ',n-1).map(&:to_i).insert(0,0)
a, b = gets.split(' ').map(&:to_i)
puts ar[a...b].inject(:+)

n = gets.to_i
d = gets.split.map{|i| i.to_i}
a,b = gets.split.map{|i| i.to_i}
i = a
res = 0
while i < b do
    res += d[i-1]
    i += 1
end

p res

n = gets.chomp.to_i
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
sum = 0
for i in a-1..b-2
	sum += ar[i]
end
puts sum

n = gets.to_i
d = gets.split.map(&:to_i)
i = gets.split.map(&:to_i)
sum = 0
d[i[0]-1..i[1]-2].each{|e| sum+= e}
print sum

a=gets(p).split.map &:to_i;p eval a[a[-2]...a[-1]]*?+

n = gets.to_i
try = gets.split().map(&:to_i)
a,b = gets.split().map(&:to_i)
t = 0

for i in a...b
	t += try[i-1]
end

puts t

n=gets.chomp.to_i
j=gets.chomp.split(' ').map(&:to_i)
sum=0
a,b=gets.chomp.split(' ').map(&:to_i)
i=a-1
while i<(b-1)
	sum+=j[i]
	i+=1
end
puts sum

gets
d = gets.split.map(&:to_i)
a, b = gets.split.map { |x| x.to_i - 1}
puts (a...b).map {|i| d[i]}.inject(:+)

t = gets.chomp.to_i
arr = gets.split.map(&:to_i)
a,b = gets.split.map(&:to_i)
res = 0
while a<b
  res+=arr[a-1]
  a+=1
end
puts res

n=gets.to_i
x=gets.split.map{|e| e.to_i}
y,z=gets.split.map{|e| e.to_i-1}
ans=0

y.upto(z-1){|i|
	ans+=x[i]
}
puts ans

n=gets.to_i
c=gets.split.map(&:to_i)
a,b=gets.split.map(&:to_i)
p c[a-1...b-1].inject(:+)

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

ans=0
for i in a...b
	ans+=d[i-1]
end

puts ans

n = gets.to_i
years = gets.split(' ').map { |e| e.to_i }
ranks = gets.split(' ').map { |e| e.to_i }
total = 0
(ranks[0]...ranks[1]).each do |i|
  total += years[i-1]
end
puts total

gets;mas=gets.split.map &:to_i;a,b=gets.split.map &:to_i;c=0;(a-1).upto(b-2){|x| c+=mas[x]};puts c

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

s = gets.split(" ")
start = s[0].to_i
finish = s[1].to_i
sum = 0
for i in start-1..finish-2
  sum += rank[i]
end

puts sum

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

years = 0

(a - 1).times { d.shift }
(b - a).times { years += d.shift }

puts years

n = gets.to_i
d = gets.split.map &:to_i
a, b = gets.split.map &:to_i
p d[a-1...b-1].inject(0){|s, x| s + x}

gets;a=gets.split.map(&:to_i)
x,y=gets.split.map(&:to_i)
res=0
while x < y do
  res += a[x-1]
  x += 1
end
p res

n=gets.to_i;
mas=gets.to_s.split(" ");
mas2=gets.to_s.split(" ");
a=mas2[0].to_i-1;
b=mas2[1].to_i-2;
sum=0;
(a..b).each { |i| sum+=mas[i].to_i }
puts sum;

n = gets.to_i
d_i = gets.split(' ').map(&:to_i)
d_i.unshift(0)
a, b = gets.split(' ').map(&:to_i)

res = d_i[a..b-1].reduce(:+)

p res

gets.chomp # Skip the first line
d = gets.chomp.split.map { |x| x.to_i }
a, b = gets.chomp.split.map { |x| x.to_i }
puts d[a - 1..b - 2].inject(:+)

class Array
  def sum
    self.inject { |r, v| r + v }
  end
end

n = gets.to_i
d = gets.split.map { |v| v.to_i }
a, b = gets.split.map { |v| v.to_i }
puts d[a - 1, b - a].sum

n = gets.to_i
d = gets.split.map(&:to_i)
i = gets.split.map(&:to_i)
sum = 0
d[i[0]-1..d[1]-1].each{|e| sum+= e}
print sum